[
  {
    "path": ".github/workflows/linter.yml",
    "content": "name: Linter\n\non: [push, pull_request]\n\njobs:\n  linter:\n    runs-on: ubuntu-latest\n    steps:\n    - uses: actions/checkout@v5\n    - name: Use Node.js\n      uses: actions/setup-node@v6\n    - name: Install Dependencies\n      run: npm install\n    - run: npm run eslint\n"
  },
  {
    "path": ".github/workflows/tester.yml",
    "content": "name: Tester\n\non: [push, pull_request]\n\njobs:\n  tester:\n    runs-on: ${{ matrix.os }}\n    strategy:\n      matrix:\n        os: [ubuntu-latest, windows-latest, macos-latest]\n      fail-fast: false\n    steps:\n      - uses: actions/checkout@v5\n        with:\n          repository: hexojs/hexo-starter\n      - name: Use Node.js\n        uses: actions/setup-node@v6\n      - name: Install Dependencies\n        run: npm install\n      - name: Test\n        run: npm run build\n"
  },
  {
    "path": ".gitignore",
    "content": "package-lock.json\nnode_modules/\n.DS_Store\n.idea/\n.vscode/\nbackup/\nsrc/CubismSdkForWeb-*/\nbuild/CubismSdkForWeb-*/\n"
  },
  {
    "path": ".prettierignore",
    "content": "node_modules\ndist\n"
  },
  {
    "path": ".prettierrc.yaml",
    "content": "tabWidth: 2\nsemi: true\nsingleQuote: true\njsxSingleQuote: true\ntrailingComma: all\nendOfLine: crlf\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.en.md",
    "content": "# Live2D Widget\n\n![](https://forthebadge.com/images/badges/built-with-love.svg)\n![](https://forthebadge.com/images/badges/made-with-typescript.svg)\n![](https://forthebadge.com/images/badges/uses-css.svg)\n![](https://forthebadge.com/images/badges/contains-cat-gifs.svg)\n![](https://forthebadge.com/images/badges/powered-by-electricity.svg)\n![](https://forthebadge.com/images/badges/makes-people-smile.svg)\n\n[中文](README.md)\n\n## Features\n\n- Add Live2D widget to web page\n- Lightweight, with no runtime dependencies other than Live2D Cubism Core\n- Core code is written in TypeScript, making it easy to integrate\n\n<img src=\"demo/screenshots/screenshot-2.png\" width=\"280\"><img src=\"demo/screenshots/screenshot-3.png\" width=\"280\"><img src=\"demo/screenshots/screenshot-1.png\" width=\"270\">\n\n*Note: The character models above are for demonstration purposes only and are not included in this repository.*\n\nYou can also check out example web pages:\n\n- Check the effect in the lower left corner of [Mimi's Blog](https://zhangshuqiao.org)\n- [demo/demo.html](https://live2d-widget.pages.dev/demo/demo) to demonstrate basic functionality\n- [demo/login.html](https://live2d-widget.pages.dev/demo/login) to imitate the login interface of NPM\n\n## Usage\n\nIf you are a beginner or only need the basic functionality, you can simply add the following line of code to the `head` or `body` of your HTML page to load the widget:\n\n```html\n<script src=\"https://fastly.jsdelivr.net/npm/live2d-widgets@1.0.0/dist/autoload.js\"></script>\n```\n\nThe placement of the code depends on how your website is built. For example, if you are using [Hexo](https://hexo.io), you need to add the above code to the template file of your theme. The modification process is similar for pages generated using various template engines.  \nIf your website uses PJAX, since the widget does not need to be refreshed on every page, make sure to place the script outside the PJAX refresh area.\n\n**However, we strongly recommend configuring the widget yourself to make it more suitable for your website!**  \nIf you are interested in customizing the widget, please refer to the detailed instructions below.\n\n## Configuration\n\nYou can refer to the source code of `dist/autoload.js` to see the available configuration options. `autoload.js` will automatically load two files: `waifu.css` and `waifu-tips.js`. `waifu-tips.js` creates the `initWidget` function, which is the main function for loading the widget. The `initWidget` function accepts an object-type parameter as the configuration for the widget. The following are the available options:\n\n| Option | Type | Default Value | Description |\n| ------ | ---- | ------------- | ----------- |\n| `waifuPath` | `string` | `https://fastly.jsdelivr.net/npm/live2d-widgets@1/dist/waifu-tips.json` | Path to the widget resources, can be modified |\n| `cdnPath` | `string` | `https://fastly.jsdelivr.net/gh/fghrsh/live2d_api/` | CDN path |\n| `cubism2Path` | `string` | `https://fastly.jsdelivr.net/npm/live2d-widgets@1/dist/live2d.min.js` | Path to Cubism 2 Core |\n| `cubism5Path` | `string` | `https://cubism.live2d.com/sdk-web/cubismcore/live2dcubismcore.min.js` | Path to Cubism 5 Core |\n| `modelId` | `number` | `0` | Default model id |\n| `tools` | `string[]` | see `autoload.js` | Buttons of the loaded tools |\n| `drag` | `boolean` | `false` | Make the widget draggable |\n| `logLevel` | `string` | `error` | Log level: `error`, `warn`, `info`, `trace` |\n\n## Model Repository\n\nThis repository does not include any models. You need to configure a separate model repository and set it via the `cdnPath` option.  \nOlder versions of the `initWidget` function supported the `apiPath` parameter, which required users to set up their own backend. You can refer to [live2d_api](https://github.com/fghrsh/live2d_api) for details. The backend interface would integrate model resources and dynamically generate JSON description files. Since version 1.0, these features have been implemented on the frontend, so a dedicated `apiPath` is no longer required. All model resources can be provided statically. As long as `model_list.json` and the corresponding `textures.cache` for each model exist, features such as outfit changing are supported.\n\n## Development\n\nIf the options provided in the \"Configuration\" section above are not enough to meet your needs, you can make modifications yourself. The directory structure of this repository is as follows:\n\n- `src` directory contains the TypeScript code for each component, e.g. the button and dialog box.\n- `build` directory contains files generated from the source code in `src` (please do not modify them directly!)\n- `dist` directory contains the files that can be directly used on web pages after packaging, including:\n  - `autoload.js` is used to automatically load other resources such as style sheets.\n  - `waifu-tips.js` is automatically generated by `build/waifu-tips.js` and it is not recommended to modify it directly.\n  - `waifu.css` is the style sheet for the widget.\n  - `waifu-tips.json` defines the triggering conditions (`selector`, CSS selector) and the displayed text when triggered (`text`).  \n    By default, the CSS selector rules in `waifu-tips.json` are effective for the Hexo [NexT theme](https://github.com/next-theme/hexo-theme-next), but you may need to modify or add new content to make it suitable for your own website.  \n    **Warning: The content in `waifu-tips.json` may not be suitable for all age groups or appropriate to access during work. Please ensure their suitability when using them.**\n\nTo deploy the development testing environment of this project locally, you need to install Node.js and npm, then execute the following commands:\n\n```bash\ngit clone https://github.com/stevenjoezhang/live2d-widget.git\nnpm install\n```\n\nIf you need to use Cubism 3 or newer models, please download and extract the Cubism SDK for Web separately into the `src` directory, for example, `src/CubismSdkForWeb-5-r.4`. Due to Live2D license agreements (including the Live2D Proprietary Software License Agreement and Live2D Open Software License Agreement), this project cannot include the source code of Cubism SDK for Web.  \nIf you only need to use Cubism 2 models, you can skip this step. The code in this repository complies with the Redistributable Code terms of the Live2D license agreements.  \nOnce completed, use the following command to compile and bundle the project.\n\n\n```bash\nnpm run build\n```\n\nThe TypeScript code in the `src` directory is compiled into the `build` directory, and the code in the `build` directory is further bundled into the `dist` directory.  \nTo support both Cubism 2 and Cubism 3 (and newer) models while minimizing code size, Cubism Core and related code are loaded dynamically based on the detected model version.\n\n## Deploy\n\nAfter making modifications locally, you can deploy the modified project on a server or load it via a CDN. To make it easier to customize, you can fork this repository and push your modified content to your own repository using `git push`.\n\n### Using jsDelivr CDN\n\nTo load forked repository via jsDelivr, the usage method becomes:\n\n```html\n<script src=\"https://fastly.jsdelivr.net/gh/username/live2d-widget@latest/autoload.js\"></script>\n```\n\nReplace `username` with your GitHub username. To ensure the content of the CDN is refreshed correctly, you need to create a new git tag and push it to the GitHub repository. Otherwise, `@latest` in the URL will still point to the previous version. Additionally, CDN itself has caching, so the changes may take some time to take effect.\n\n### Using Cloudflare Pages\n\nYou can also deploy using Cloudflare Pages. Create a new project in Cloudflare Pages and select your forked repository. Then, set the build command to `npm run build`. Once configured, Cloudflare Pages will automatically build and deploy your project.\n\n### Self-host\n\nAlternatively, you can directly host these files on your server instead of loading them via CDN.\n\n- Clone the forked repository onto your server, or upload the local files to the website directory on the server using `ftp` or similar methods.\n- If you are deploying a static blog using Hexo or similar tools, place the code of this project in the blog's source file directory (e.g., the `source` directory). When redeploying the blog, the relevant files will be automatically uploaded to the corresponding paths. To prevent these files from being incorrectly modified by Hexo plugins, you may need to set `skip_render`.\n\nAfterwards, the entire project can be accessed through your domain name. You can try opening the `autoload.js` and `live2d.min.js` files in your browser and confirm that their content is complete and correct.\nIf everything is normal, you can proceed to modify the constant `live2d_path` in `autoload.js` to the URL of the `dist` directory. For example, if you can access `live2d.min.js` through the following URL:\n\n```\nhttps://example.com/path/to/live2d-widget/dist/live2d.min.js\n```\n\nthen modify the value of `live2d_path` to:\n\n```\nhttps://example.com/path/to/live2d-widget/dist/\n```\n\nMake sure to include the trailing `/` in the path.\nOnce done, add the following code to the interface where you want to add the live2d-widget:\n\n```html\n<script src=\"https://example.com/path/to/live2d-widget/dist/autoload.js\"></script>\n```\n\nThis will load the widget.\n\n## Thanks\n\n<a href=\"https://www.browserstack.com/\">\n  <picture>\n    <source media=\"(prefers-color-scheme: dark)\" height=\"80\" srcset=\"https://d98b8t1nnulk5.cloudfront.net/production/images/layout/logo-header.png?1469004780\">\n    <source media=\"(prefers-color-scheme: light)\" height=\"80\" srcset=\"https://live.browserstack.com/images/opensource/browserstack-logo.svg\">\n    <img alt=\"BrowserStack Logo\" height=\"80\" src=\"https://live.browserstack.com/images/opensource/browserstack-logo.svg\">\n  </picture>\n</a>\n\n> Thanks to [BrowserStack](https://www.browserstack.com/) for providing the infrastructure that allows us to test in real browsers!\n\n<a href=\"https://www.jsdelivr.com\">\n  <picture>\n    <source media=\"(prefers-color-scheme: dark)\" height=\"80\" srcset=\"https://raw.githubusercontent.com/jsdelivr/jsdelivr-media/master/white/svg/jsdelivr-logo-horizontal.svg\">\n    <source media=\"(prefers-color-scheme: light)\" height=\"80\" srcset=\"https://raw.githubusercontent.com/jsdelivr/jsdelivr-media/master/default/svg/jsdelivr-logo-horizontal.svg\">\n    <img alt=\"jsDelivr Logo\" height=\"80\" src=\"https://raw.githubusercontent.com/jsdelivr/jsdelivr-media/master/default/svg/jsdelivr-logo-horizontal.svg\">\n  </picture>\n</a>\n\n> Thanks to jsDelivr for providing public CDN service.\n\nThanks fghrsh for providing API service.\n\nThanks to [Hitokoto](https://hitokoto.cn) for providing the sentence API.\n\nWhen you click on the paper airplane button of the virtual assistant, a hidden surprise will appear. This feature is from [WebsiteAsteroids](http://www.websiteasteroids.com).\n\n## More\n\nThe code is modified based on this blog post:  \nhttps://www.fghrsh.net/post/123.html\n\nFor more information, you can refer to the following links:  \nhttps://nocilol.me/archives/lab/add-dynamic-poster-girl-with-live2d-to-your-blog-02  \nhttps://github.com/guansss/pixi-live2d-display\n\nFor more models:  \nhttps://github.com/zenghongtu/live2d-model-assets\n\nIn addition to that, there are desktop versions available:  \nhttps://github.com/TSKI433/hime-display  \nhttps://github.com/amorist/platelet  \nhttps://github.com/akiroz/Live2D-Widget  \nhttps://github.com/zenghongtu/PPet  \nhttps://github.com/LikeNeko/L2dPetForMac\n\nAnd also Wallpaper Engine:  \nhttps://github.com/guansss/nep-live2d\n\nOfficial Live2D websites:  \nhttps://www.live2d.com/en/\n\n## License\n\nThis repository does not contain any models. The copyrights of all Live2D models, images, and motion data used for demonstration purposes belong to their respective original authors. They are provided for research and learning purposes only and should not be used for commercial purposes.\n\nThe code in this repository (excluding parts covered by the Live2D Proprietary Software License and the Live2D Open Software License) is released under the GNU General Public License v3  \nhttp://www.gnu.org/licenses/gpl-3.0.html\n\nPlease comply with the relevant licenses when using any Live2D-related code:\n\nLicense for Live2D Cubism SDK 2.1:  \n[Live2D SDK License Agreement (Public)](https://docs.google.com/document/d/10tz1WrycskzGGBOhrAfGiTSsgmyFy8D9yHx9r_PsN8I/)\n\nLicense for Live2D Cubism SDK 5:  \nLive2D Cubism Core is provided under the Live2D Proprietary Software License.  \nhttps://www.live2d.com/eula/live2d-proprietary-software-license-agreement_en.html  \nLive2D Cubism Components are provided under the Live2D Open Software License.  \nhttps://www.live2d.com/eula/live2d-open-software-license-agreement_en.html\n\n## Update Log\n\nStarting from January 1, 2020, this project no longer depends on jQuery.\n\nStarting from November 1, 2022, this project no longer requires users to separately load Font Awesome.\n"
  },
  {
    "path": "README.md",
    "content": "# Live2D Widget\n\n![](https://forthebadge.com/images/badges/built-with-love.svg)\n![](https://forthebadge.com/images/badges/made-with-typescript.svg)\n![](https://forthebadge.com/images/badges/uses-css.svg)\n![](https://forthebadge.com/images/badges/contains-cat-gifs.svg)\n![](https://forthebadge.com/images/badges/powered-by-electricity.svg)\n![](https://forthebadge.com/images/badges/makes-people-smile.svg)\n\n[English](README.en.md)\n\n## 特性\n\n- 在网页中添加 Live2D 看板娘\n- 轻量级，除 Live2D Cubism Core 外无其他运行时依赖\n- 核心代码由 TypeScript 编写，易于集成\n\n<img src=\"demo/screenshots/screenshot-2.png\" width=\"280\"><img src=\"demo/screenshots/screenshot-3.png\" width=\"280\"><img src=\"demo/screenshots/screenshot-1.png\" width=\"270\">\n\n*注：以上人物模型仅供展示之用，本仓库并不包含任何模型。*\n\n你也可以查看示例网页：\n\n- 在 [米米的博客](https://zhangshuqiao.org) 的左下角可查看效果\n- [demo/demo.html](https://live2d-widget.pages.dev/demo/demo)，展现基础功能\n- [demo/login.html](https://live2d-widget.pages.dev/demo/login)，仿 NPM 的登陆界面\n\n## 使用\n\n如果你是小白，或者只需要最基础的功能，那么只用将这一行代码加入 html 页面的 `head` 或 `body` 中，即可加载看板娘：\n\n```html\n<script src=\"https://fastly.jsdelivr.net/npm/live2d-widgets@1.0.0/dist/autoload.js\"></script>\n```\n\n添加代码的位置取决于你的网站的构建方式。例如，如果你使用的是 [Hexo](https://hexo.io)，那么需要在主题的模版文件中添加以上代码。对于用各种模版引擎生成的页面，修改方法类似。  \n如果网站启用了 PJAX，由于看板娘不必每页刷新，需要注意将该脚本放到 PJAX 刷新区域之外。\n\n**但是！我们强烈推荐自己进行配置，让看板娘更加适合你的网站！**  \n如果你有兴趣自己折腾的话，请看下面的详细说明。\n\n## 配置\n\n你可以对照 `dist/autoload.js` 的源码查看可选的配置项目。`autoload.js` 会自动加载两个文件：`waifu.css` 和 `waifu-tips.js`。`waifu-tips.js` 会创建 `initWidget` 函数，这就是加载看板娘的主函数。`initWidget` 函数接收一个 Object 类型的参数，作为看板娘的配置。以下是配置选项：\n\n| 选项 | 类型 | 默认值 | 说明 |\n| - | - | - | - |\n| `waifuPath` | `string` | `https://fastly.jsdelivr.net/npm/live2d-widgets@1/dist/waifu-tips.json` | 看板娘资源路径，可自行修改 |\n| `cdnPath` | `string` | `https://fastly.jsdelivr.net/gh/fghrsh/live2d_api/` | CDN 路径 |\n| `cubism2Path` | `string` | `https://fastly.jsdelivr.net/npm/live2d-widgets@1/dist/live2d.min.js` | Cubism 2 Core 路径 |\n| `cubism5Path` | `string` | `https://cubism.live2d.com/sdk-web/cubismcore/live2dcubismcore.min.js` | Cubism 5 Core 路径 |\n| `modelId` | `number` | `0` | 默认模型 id |\n| `tools` | `string[]` | 见 `autoload.js` | 加载的小工具按钮 |\n| `drag` | `boolean` | `false` | 支持拖动看板娘 |\n| `logLevel` | `string` | `error` | 日志等级，支持 `error`，`warn`，`info`，`trace` |\n\n## 模型仓库\n\n本仓库中并不包含任何模型，需要单独配置模型仓库，并通过 `cdnPath` 选项进行设置。  \n旧版本的 `initWidget` 函数支持 `apiPath` 参数，这要求用户自行搭建后端，可以参考 [live2d_api](https://github.com/fghrsh/live2d_api)。后端接口会对模型资源进行整合并动态生成 JSON 描述文件。自 1.0 版本起，相关功能已通过前端实现，因此不再需要专门的 `apiPath`，所有模型资源都可通过静态方式提供。只要存在 `model_list.json` 和模型对应的 `textures.cache`，即可支持换装等功能。\n\n## 开发\n\n如果以上「配置」部分提供的选项还不足以满足你的需求，那么你可以自己进行修改。本仓库的目录结构如下：\n\n- `src` 目录下包含了各个组件的 TypeScript 源代码，例如按钮和对话框等；\n- `build` 目录下包含了基于 `src` 中源代码构建后的文件（请不要直接修改！）；\n- `dist` 目录下包含了进一步打包后网页直接可用的文件，其中：\n  - `autoload.js` 用于自动加载其它资源，例如样式表等；\n  - `waifu-tips.js` 是由 `build/waifu-tips.js` 自动打包生成的，不建议直接修改；\n  - `waifu.css` 是看板娘的样式表；\n  - `waifu-tips.json` 中定义了触发条件（`selector`，CSS 选择器）和触发时显示的文字（`text`）。  \n    `waifu-tips.json` 中默认的 CSS 选择器规则是对 Hexo 的 [NexT 主题](https://github.com/next-theme/hexo-theme-next) 有效的，为了适用于你自己的网页，可能需要自行修改，或增加新内容。  \n    **警告：`waifu-tips.json` 中的内容可能不适合所有年龄段，或不宜在工作期间访问。在使用时，请自行确保它们是合适的。**\n\n要在本地部署本项目的开发测试环境，你需要安装 Node.js 和 npm，然后执行以下命令：\n\n```bash\ngit clone https://github.com/stevenjoezhang/live2d-widget.git\nnpm install\n```\n\n如果需要使用 Cubism 3 及更新的模型，请单独下载并解压 Cubism SDK for Web 到 `src` 目录下，例如 `src/CubismSdkForWeb-5-r.4`。受 Live2D 许可协议（包括 Live2D Proprietary Software License Agreement 和 Live2D Open Software License Agreement）限制，本项目无法包含 Cubism SDK for Web 的源码。  \n如果只需要使用 Cubism 2 版本的模型，可以跳过此步骤。本仓库使用的代码满足 Live2D 许可协议中 Redistributable Code 相关条款。  \n完成后，使用以下命令进行编译和打包。\n\n```bash\nnpm run build\n```\n\n`src` 目录中的 TypeScript 代码会被编译到 `build` 目录中，`build` 目录中的代码会被进一步打包到 `dist` 目录中。  \n为了能够兼容 Cubism 2 和 Cubism 3 及更新的模型，并减小代码体积，Cubism Core 及相关的代码会根据检测到的模型版本动态加载。\n\n## 部署\n\n在本地完成了修改后，你可以将修改后的项目部署在自己的服务器上，或者通过 CDN 加载。为了方便自定义有关内容，可以把这个仓库 Fork 一份，然后把修改后的内容通过 git push 到你的仓库中。\n\n### 使用 jsDelivr CDN\n\n如果要通过 jsDelivr 加载 Fork 后的仓库，使用方法对应地变为\n\n```html\n<script src=\"https://fastly.jsdelivr.net/gh/username/live2d-widget@latest/autoload.js\"></script>\n```\n\n将此处的 `username` 替换为你的 GitHub 用户名。为了使 CDN 的内容正常刷新，需要创建新的 git tag 并推送至 GitHub 仓库中，否则此处的 `@latest` 仍然指向更新前的文件。此外 CDN 本身存在缓存，因此改动可能需要一定的时间生效。\n\n### 使用 Cloudflare Pages\n\n也可以使用 Cloudflare Pages 来部署。在 Cloudflare Pages 中创建一个新的项目，选择你 Fork 的仓库。接下来，设置构建命令为 `npm run build`。完成后，Cloudflare Pages 会自动构建并部署你的项目。\n\n### Self-host\n\n你也可以直接把这些文件放到服务器上，而不是通过 CDN 加载。\n\n- 可以把修改后的代码仓库克隆到服务器上，或者通过 `ftp` 等方式将本地文件上传到服务器的网站的目录下；\n- 如果你是通过 Hexo 等工具部署的静态博客，请把本项目的代码放在博客源文件目录下（例如 `source` 目录）。重新部署博客时，相关文件就会自动上传到对应的路径下。为了避免这些文件被 Hexo 插件错误地修改，可能需要设置 `skip_render`。\n\n这样，整个项目就可以通过你的域名访问了。不妨试试能否正常地通过浏览器打开 `autoload.js` 和 `live2d.min.js` 等文件，并确认这些文件的内容是完整和正确的。  \n一切正常的话，接下来修改 `autoload.js` 中的常量 `live2d_path` 为 `dist` 目录的 URL 即可。比如说，如果你能够通过\n\n```\nhttps://example.com/path/to/live2d-widget/dist/live2d.min.js\n```\n\n访问到 `live2d.min.js`，那么就把 `live2d_path` 的值修改为\n\n```\nhttps://example.com/path/to/live2d-widget/dist/\n```\n\n路径末尾的 `/` 一定要加上。  \n完成后，在你要添加看板娘的界面加入\n\n```html\n<script src=\"https://example.com/path/to/live2d-widget/dist/autoload.js\"></script>\n```\n\n就可以加载了。\n\n## 鸣谢\n\n<a href=\"https://www.browserstack.com/\">\n  <picture>\n    <source media=\"(prefers-color-scheme: dark)\" height=\"80\" srcset=\"https://d98b8t1nnulk5.cloudfront.net/production/images/layout/logo-header.png?1469004780\">\n    <source media=\"(prefers-color-scheme: light)\" height=\"80\" srcset=\"https://live.browserstack.com/images/opensource/browserstack-logo.svg\">\n    <img alt=\"BrowserStack Logo\" height=\"80\" src=\"https://live.browserstack.com/images/opensource/browserstack-logo.svg\">\n  </picture>\n</a>\n\n> 感谢 BrowserStack 容许我们在真实的浏览器中测试此项目。  \n> Thanks to [BrowserStack](https://www.browserstack.com/) for providing the infrastructure that allows us to test in real browsers!\n\n<a href=\"https://www.jsdelivr.com\">\n  <picture>\n    <source media=\"(prefers-color-scheme: dark)\" height=\"80\" srcset=\"https://raw.githubusercontent.com/jsdelivr/jsdelivr-media/master/white/svg/jsdelivr-logo-horizontal.svg\">\n    <source media=\"(prefers-color-scheme: light)\" height=\"80\" srcset=\"https://raw.githubusercontent.com/jsdelivr/jsdelivr-media/master/default/svg/jsdelivr-logo-horizontal.svg\">\n    <img alt=\"jsDelivr Logo\" height=\"80\" src=\"https://raw.githubusercontent.com/jsdelivr/jsdelivr-media/master/default/svg/jsdelivr-logo-horizontal.svg\">\n  </picture>\n</a>\n\n> 感谢 jsDelivr 提供的 CDN 服务。  \n> Thanks jsDelivr for providing public CDN service.\n\n感谢 fghrsh 提供的 API 服务。\n\n感谢 [一言](https://hitokoto.cn) 提供的语句接口。\n\n点击看板娘的纸飞机按钮时，会出现一个彩蛋，这来自于 [WebsiteAsteroids](http://www.websiteasteroids.com)。\n\n## 更多\n\n代码自这篇博文魔改而来：  \nhttps://www.fghrsh.net/post/123.html\n\n更多内容可以参考：  \nhttps://nocilol.me/archives/lab/add-dynamic-poster-girl-with-live2d-to-your-blog-02  \nhttps://github.com/guansss/pixi-live2d-display\n\n更多模型仓库：  \nhttps://github.com/zenghongtu/live2d-model-assets\n\n除此之外，还有桌面版本：  \nhttps://github.com/TSKI433/hime-display  \nhttps://github.com/amorist/platelet  \nhttps://github.com/akiroz/Live2D-Widget  \nhttps://github.com/zenghongtu/PPet  \nhttps://github.com/LikeNeko/L2dPetForMac\n\n以及 Wallpaper Engine：  \nhttps://github.com/guansss/nep-live2d\n\nLive2D 官方网站：  \nhttps://www.live2d.com/en/\n\n## 许可证\n\n本仓库并不包含任何模型，用作展示的所有 Live2D 模型、图片、动作数据等版权均属于其原作者，仅供研究学习，不得用于商业用途。\n\n本仓库的代码（不包括受 Live2D Proprietary Software License 和 Live2D Open Software License 约束的部分）基于 GNU General Public License v3 协议开源  \nhttp://www.gnu.org/licenses/gpl-3.0.html\n\nLive2D 相关代码的使用请遵守对应的许可：\n\nLive2D Cubism SDK 2.1 的许可证：  \n[Live2D SDK License Agreement (Public)](https://docs.google.com/document/d/10tz1WrycskzGGBOhrAfGiTSsgmyFy8D9yHx9r_PsN8I/)\n\nLive2D Cubism SDK 5 的许可证：  \nLive2D Cubism Core は Live2D Proprietary Software License で提供しています。  \nhttps://www.live2d.com/eula/live2d-proprietary-software-license-agreement_cn.html  \nLive2D Cubism Components は Live2D Open Software License で提供しています。  \nhttps://www.live2d.com/eula/live2d-open-software-license-agreement_cn.html\n\n## 更新日志\n\n2020年1月1日起，本项目不再依赖于 jQuery。\n\n2022年11月1日起，本项目不再需要用户单独加载 Font Awesome。\n"
  },
  {
    "path": "build/cubism2/LAppDefine.d.ts",
    "content": "export default LAppDefine;\ndeclare namespace LAppDefine {\n    let VIEW_MAX_SCALE: number;\n    let VIEW_MIN_SCALE: number;\n    let VIEW_LOGICAL_LEFT: number;\n    let VIEW_LOGICAL_RIGHT: number;\n    let VIEW_LOGICAL_MAX_LEFT: number;\n    let VIEW_LOGICAL_MAX_RIGHT: number;\n    let VIEW_LOGICAL_MAX_BOTTOM: number;\n    let VIEW_LOGICAL_MAX_TOP: number;\n    let PRIORITY_NONE: number;\n    let PRIORITY_IDLE: number;\n    let PRIORITY_NORMAL: number;\n    let PRIORITY_FORCE: number;\n    let MOTION_GROUP_IDLE: string;\n    let MOTION_GROUP_TAP_BODY: string;\n    let MOTION_GROUP_FLICK_HEAD: string;\n    let MOTION_GROUP_PINCH_IN: string;\n    let MOTION_GROUP_PINCH_OUT: string;\n    let MOTION_GROUP_SHAKE: string;\n    let HIT_AREA_HEAD: string;\n    let HIT_AREA_BODY: string;\n}\n"
  },
  {
    "path": "build/cubism2/LAppDefine.js",
    "content": "const LAppDefine = {\n    VIEW_MAX_SCALE: 1.5,\n    VIEW_MIN_SCALE: 1,\n    VIEW_LOGICAL_LEFT: -1,\n    VIEW_LOGICAL_RIGHT: 1,\n    VIEW_LOGICAL_MAX_LEFT: -2,\n    VIEW_LOGICAL_MAX_RIGHT: 2,\n    VIEW_LOGICAL_MAX_BOTTOM: -2,\n    VIEW_LOGICAL_MAX_TOP: 2,\n    PRIORITY_NONE: 0,\n    PRIORITY_IDLE: 1,\n    PRIORITY_NORMAL: 2,\n    PRIORITY_FORCE: 3,\n    MOTION_GROUP_IDLE: 'idle',\n    MOTION_GROUP_TAP_BODY: 'tap_body',\n    MOTION_GROUP_FLICK_HEAD: 'flick_head',\n    MOTION_GROUP_PINCH_IN: 'pinch_in',\n    MOTION_GROUP_PINCH_OUT: 'pinch_out',\n    MOTION_GROUP_SHAKE: 'shake',\n    HIT_AREA_HEAD: 'head',\n    HIT_AREA_BODY: 'body',\n};\nexport default LAppDefine;\n"
  },
  {
    "path": "build/cubism2/LAppLive2DManager.d.ts",
    "content": "export default LAppLive2DManager;\ndeclare class LAppLive2DManager {\n    model: LAppModel;\n    reloading: boolean;\n    getModel(): LAppModel;\n    releaseModel(gl: any): void;\n    changeModel(gl: any, modelSettingPath: any): Promise<any>;\n    changeModelWithJSON(gl: any, modelSettingPath: any, modelSetting: any): Promise<void>;\n    setDrag(x: any, y: any): void;\n    maxScaleEvent(): void;\n    minScaleEvent(): void;\n    tapEvent(x: any, y: any): boolean;\n}\nimport LAppModel from './LAppModel.js';\n"
  },
  {
    "path": "build/cubism2/LAppLive2DManager.js",
    "content": "import { Live2DFramework } from './Live2DFramework.js';\nimport LAppModel from './LAppModel.js';\nimport PlatformManager from './PlatformManager.js';\nimport LAppDefine from './LAppDefine.js';\nimport logger from '../logger.js';\nclass LAppLive2DManager {\n    constructor() {\n        this.model = null;\n        this.reloading = false;\n        Live2D.init();\n        Live2DFramework.setPlatformManager(new PlatformManager());\n    }\n    getModel() {\n        return this.model;\n    }\n    releaseModel(gl) {\n        if (this.model) {\n            this.model.release(gl);\n            this.model = null;\n        }\n    }\n    async changeModel(gl, modelSettingPath) {\n        return new Promise((resolve, reject) => {\n            if (this.reloading)\n                return;\n            this.reloading = true;\n            const oldModel = this.model;\n            const newModel = new LAppModel();\n            newModel.load(gl, modelSettingPath, () => {\n                if (oldModel) {\n                    oldModel.release(gl);\n                }\n                this.model = newModel;\n                this.reloading = false;\n                resolve();\n            });\n        });\n    }\n    async changeModelWithJSON(gl, modelSettingPath, modelSetting) {\n        if (this.reloading)\n            return;\n        this.reloading = true;\n        const oldModel = this.model;\n        const newModel = new LAppModel();\n        await newModel.loadModelSetting(modelSettingPath, modelSetting);\n        if (oldModel) {\n            oldModel.release(gl);\n        }\n        this.model = newModel;\n        this.reloading = false;\n    }\n    setDrag(x, y) {\n        if (this.model) {\n            this.model.setDrag(x, y);\n        }\n    }\n    maxScaleEvent() {\n        logger.trace('Max scale event.');\n        if (this.model) {\n            this.model.startRandomMotion(LAppDefine.MOTION_GROUP_PINCH_IN, LAppDefine.PRIORITY_NORMAL);\n        }\n    }\n    minScaleEvent() {\n        logger.trace('Min scale event.');\n        if (this.model) {\n            this.model.startRandomMotion(LAppDefine.MOTION_GROUP_PINCH_OUT, LAppDefine.PRIORITY_NORMAL);\n        }\n    }\n    tapEvent(x, y) {\n        logger.trace('tapEvent view x:' + x + ' y:' + y);\n        if (!this.model)\n            return false;\n        if (this.model.hitTest(LAppDefine.HIT_AREA_HEAD, x, y)) {\n            logger.trace('Tap face.');\n            this.model.setRandomExpression();\n        }\n        else if (this.model.hitTest(LAppDefine.HIT_AREA_BODY, x, y)) {\n            logger.trace('Tap body.');\n            this.model.startRandomMotion(LAppDefine.MOTION_GROUP_TAP_BODY, LAppDefine.PRIORITY_NORMAL);\n        }\n        return true;\n    }\n}\nexport default LAppLive2DManager;\n"
  },
  {
    "path": "build/cubism2/LAppModel.d.ts",
    "content": "export default LAppModel;\ndeclare class LAppModel extends L2DBaseModel {\n    modelHomeDir: string;\n    modelSetting: ModelSettingJson;\n    tmpMatrix: any[];\n    loadJSON(callback: any): void;\n    loadModelSetting(modelSettingPath: any, modelSetting: any): Promise<void>;\n    load(gl: any, modelSettingPath: any, callback: any): void;\n    release(gl: any): void;\n    preloadMotionGroup(name: any): void;\n    update(): void;\n    setRandomExpression(): void;\n    startRandomMotion(name: any, priority: any): void;\n    startMotion(name: any, no: any, priority: any): void;\n    setFadeInFadeOut(name: any, no: any, priority: any, motion: any): void;\n    setExpression(name: any): void;\n    draw(gl: any): void;\n    hitTest(id: any, testX: any, testY: any): boolean;\n}\nimport { L2DBaseModel } from './Live2DFramework.js';\nimport ModelSettingJson from './utils/ModelSettingJson.js';\n"
  },
  {
    "path": "build/cubism2/LAppModel.js",
    "content": "import { L2DBaseModel, Live2DFramework, L2DEyeBlink } from './Live2DFramework.js';\nimport ModelSettingJson from './utils/ModelSettingJson.js';\nimport LAppDefine from './LAppDefine.js';\nimport MatrixStack from './utils/MatrixStack.js';\nimport logger from '../logger.js';\nclass LAppModel extends L2DBaseModel {\n    constructor() {\n        super();\n        this.modelHomeDir = '';\n        this.modelSetting = null;\n        this.tmpMatrix = [];\n    }\n    loadJSON(callback) {\n        const path = this.modelHomeDir + this.modelSetting.getModelFile();\n        this.loadModelData(path, model => {\n            for (let i = 0; i < this.modelSetting.getTextureNum(); i++) {\n                const texPaths = this.modelHomeDir + this.modelSetting.getTextureFile(i);\n                this.loadTexture(i, texPaths, () => {\n                    if (this.isTexLoaded) {\n                        if (this.modelSetting.getExpressionNum() > 0) {\n                            this.expressions = {};\n                            for (let j = 0; j < this.modelSetting.getExpressionNum(); j++) {\n                                const expName = this.modelSetting.getExpressionName(j);\n                                const expFilePath = this.modelHomeDir +\n                                    this.modelSetting.getExpressionFile(j);\n                                this.loadExpression(expName, expFilePath);\n                            }\n                        }\n                        else {\n                            this.expressionManager = null;\n                            this.expressions = {};\n                        }\n                        if (this.eyeBlink == null) {\n                            this.eyeBlink = new L2DEyeBlink();\n                        }\n                        if (this.modelSetting.getPhysicsFile() != null) {\n                            this.loadPhysics(this.modelHomeDir + this.modelSetting.getPhysicsFile());\n                        }\n                        else {\n                            this.physics = null;\n                        }\n                        if (this.modelSetting.getPoseFile() != null) {\n                            this.loadPose(this.modelHomeDir + this.modelSetting.getPoseFile(), () => {\n                                this.pose.updateParam(this.live2DModel);\n                            });\n                        }\n                        else {\n                            this.pose = null;\n                        }\n                        if (this.modelSetting.getLayout() != null) {\n                            const layout = this.modelSetting.getLayout();\n                            if (layout['width'] != null)\n                                this.modelMatrix.setWidth(layout['width']);\n                            if (layout['height'] != null)\n                                this.modelMatrix.setHeight(layout['height']);\n                            if (layout['x'] != null)\n                                this.modelMatrix.setX(layout['x']);\n                            if (layout['y'] != null)\n                                this.modelMatrix.setY(layout['y']);\n                            if (layout['center_x'] != null)\n                                this.modelMatrix.centerX(layout['center_x']);\n                            if (layout['center_y'] != null)\n                                this.modelMatrix.centerY(layout['center_y']);\n                            if (layout['top'] != null)\n                                this.modelMatrix.top(layout['top']);\n                            if (layout['bottom'] != null)\n                                this.modelMatrix.bottom(layout['bottom']);\n                            if (layout['left'] != null)\n                                this.modelMatrix.left(layout['left']);\n                            if (layout['right'] != null)\n                                this.modelMatrix.right(layout['right']);\n                        }\n                        for (let j = 0; j < this.modelSetting.getInitParamNum(); j++) {\n                            this.live2DModel.setParamFloat(this.modelSetting.getInitParamID(j), this.modelSetting.getInitParamValue(j));\n                        }\n                        for (let j = 0; j < this.modelSetting.getInitPartsVisibleNum(); j++) {\n                            this.live2DModel.setPartsOpacity(this.modelSetting.getInitPartsVisibleID(j), this.modelSetting.getInitPartsVisibleValue(j));\n                        }\n                        this.live2DModel.saveParam();\n                        this.preloadMotionGroup(LAppDefine.MOTION_GROUP_IDLE);\n                        this.mainMotionManager.stopAllMotions();\n                        this.setUpdating(false);\n                        this.setInitialized(true);\n                        if (typeof callback == 'function')\n                            callback();\n                    }\n                });\n            }\n        });\n    }\n    async loadModelSetting(modelSettingPath, modelSetting) {\n        this.setUpdating(true);\n        this.setInitialized(false);\n        this.modelHomeDir = modelSettingPath.substring(0, modelSettingPath.lastIndexOf('/') + 1);\n        this.modelSetting = new ModelSettingJson();\n        this.modelSetting.json = modelSetting;\n        await new Promise(resolve => this.loadJSON(resolve));\n    }\n    load(gl, modelSettingPath, callback) {\n        this.setUpdating(true);\n        this.setInitialized(false);\n        this.modelHomeDir = modelSettingPath.substring(0, modelSettingPath.lastIndexOf('/') + 1);\n        this.modelSetting = new ModelSettingJson();\n        this.modelSetting.loadModelSetting(modelSettingPath, () => {\n            this.loadJSON(callback);\n        });\n    }\n    release(gl) {\n        const pm = Live2DFramework.getPlatformManager();\n        gl.deleteTexture(pm.texture);\n    }\n    preloadMotionGroup(name) {\n        for (let i = 0; i < this.modelSetting.getMotionNum(name); i++) {\n            const file = this.modelSetting.getMotionFile(name, i);\n            this.loadMotion(file, this.modelHomeDir + file, motion => {\n                motion.setFadeIn(this.modelSetting.getMotionFadeIn(name, i));\n                motion.setFadeOut(this.modelSetting.getMotionFadeOut(name, i));\n            });\n        }\n    }\n    update() {\n        if (this.live2DModel == null) {\n            logger.error('Failed to update.');\n            return;\n        }\n        const timeMSec = UtSystem.getUserTimeMSec() - this.startTimeMSec;\n        const timeSec = timeMSec / 1000.0;\n        const t = timeSec * 2 * Math.PI;\n        if (this.mainMotionManager.isFinished()) {\n            this.startRandomMotion(LAppDefine.MOTION_GROUP_IDLE, LAppDefine.PRIORITY_IDLE);\n        }\n        this.live2DModel.loadParam();\n        const update = this.mainMotionManager.updateParam(this.live2DModel);\n        if (!update) {\n            if (this.eyeBlink != null) {\n                this.eyeBlink.updateParam(this.live2DModel);\n            }\n        }\n        this.live2DModel.saveParam();\n        if (this.expressionManager != null &&\n            this.expressions != null &&\n            !this.expressionManager.isFinished()) {\n            this.expressionManager.updateParam(this.live2DModel);\n        }\n        this.live2DModel.addToParamFloat('PARAM_ANGLE_X', this.dragX * 30, 1);\n        this.live2DModel.addToParamFloat('PARAM_ANGLE_Y', this.dragY * 30, 1);\n        this.live2DModel.addToParamFloat('PARAM_ANGLE_Z', this.dragX * this.dragY * -30, 1);\n        this.live2DModel.addToParamFloat('PARAM_BODY_ANGLE_X', this.dragX * 10, 1);\n        this.live2DModel.addToParamFloat('PARAM_EYE_BALL_X', this.dragX, 1);\n        this.live2DModel.addToParamFloat('PARAM_EYE_BALL_Y', this.dragY, 1);\n        this.live2DModel.addToParamFloat('PARAM_ANGLE_X', Number(15 * Math.sin(t / 6.5345)), 0.5);\n        this.live2DModel.addToParamFloat('PARAM_ANGLE_Y', Number(8 * Math.sin(t / 3.5345)), 0.5);\n        this.live2DModel.addToParamFloat('PARAM_ANGLE_Z', Number(10 * Math.sin(t / 5.5345)), 0.5);\n        this.live2DModel.addToParamFloat('PARAM_BODY_ANGLE_X', Number(4 * Math.sin(t / 15.5345)), 0.5);\n        this.live2DModel.setParamFloat('PARAM_BREATH', Number(0.5 + 0.5 * Math.sin(t / 3.2345)), 1);\n        if (this.physics != null) {\n            this.physics.updateParam(this.live2DModel);\n        }\n        if (this.lipSync == null) {\n            this.live2DModel.setParamFloat('PARAM_MOUTH_OPEN_Y', this.lipSyncValue);\n        }\n        if (this.pose != null) {\n            this.pose.updateParam(this.live2DModel);\n        }\n        this.live2DModel.update();\n    }\n    setRandomExpression() {\n        const tmp = [];\n        for (const name in this.expressions) {\n            tmp.push(name);\n        }\n        const no = parseInt(Math.random() * tmp.length);\n        this.setExpression(tmp[no]);\n    }\n    startRandomMotion(name, priority) {\n        const max = this.modelSetting.getMotionNum(name);\n        const no = parseInt(Math.random() * max);\n        this.startMotion(name, no, priority);\n    }\n    startMotion(name, no, priority) {\n        const motionName = this.modelSetting.getMotionFile(name, no);\n        if (motionName == null || motionName == '') {\n            return;\n        }\n        if (priority == LAppDefine.PRIORITY_FORCE) {\n            this.mainMotionManager.setReservePriority(priority);\n        }\n        else if (!this.mainMotionManager.reserveMotion(priority)) {\n            logger.trace('Motion is running.');\n            return;\n        }\n        let motion;\n        if (this.motions[name] == null) {\n            this.loadMotion(null, this.modelHomeDir + motionName, mtn => {\n                motion = mtn;\n                this.setFadeInFadeOut(name, no, priority, motion);\n            });\n        }\n        else {\n            motion = this.motions[name];\n            this.setFadeInFadeOut(name, no, priority, motion);\n        }\n    }\n    setFadeInFadeOut(name, no, priority, motion) {\n        const motionName = this.modelSetting.getMotionFile(name, no);\n        motion.setFadeIn(this.modelSetting.getMotionFadeIn(name, no));\n        motion.setFadeOut(this.modelSetting.getMotionFadeOut(name, no));\n        logger.trace('Start motion : ' + motionName);\n        if (this.modelSetting.getMotionSound(name, no) == null) {\n            this.mainMotionManager.startMotionPrio(motion, priority);\n        }\n        else {\n            const soundName = this.modelSetting.getMotionSound(name, no);\n            const snd = document.createElement('audio');\n            snd.src = this.modelHomeDir + soundName;\n            logger.trace('Start sound : ' + soundName);\n            snd.play();\n            this.mainMotionManager.startMotionPrio(motion, priority);\n        }\n    }\n    setExpression(name) {\n        var _b;\n        const motion = this.expressions[name];\n        logger.trace('Expression : ' + name);\n        (_b = this.expressionManager) === null || _b === void 0 ? void 0 : _b.startMotion(motion, false);\n    }\n    draw(gl) {\n        MatrixStack.push();\n        MatrixStack.multMatrix(this.modelMatrix.getArray());\n        this.tmpMatrix = MatrixStack.getMatrix();\n        this.live2DModel.setMatrix(this.tmpMatrix);\n        this.live2DModel.draw();\n        MatrixStack.pop();\n    }\n    hitTest(id, testX, testY) {\n        const len = this.modelSetting.getHitAreaNum();\n        if (len == 0) {\n            const hitAreasCustom = this.modelSetting.getHitAreaCustom();\n            if (hitAreasCustom) {\n                const x = hitAreasCustom[id + '_x'];\n                const y = hitAreasCustom[id + '_y'];\n                if (testX > Math.min(...x) && testX < Math.max(...x) &&\n                    testY > Math.min(...y) && testY < Math.max(...y)) {\n                    return true;\n                }\n            }\n        }\n        for (let i = 0; i < len; i++) {\n            if (id == this.modelSetting.getHitAreaName(i)) {\n                const drawID = this.modelSetting.getHitAreaID(i);\n                return this.hitTestSimple(drawID, testX, testY);\n            }\n        }\n        return false;\n    }\n}\nexport default LAppModel;\n"
  },
  {
    "path": "build/cubism2/Live2DFramework.d.ts",
    "content": "export class L2DBaseModel {\n    live2DModel: any;\n    modelMatrix: L2DModelMatrix;\n    eyeBlink: any;\n    physics: L2DPhysics;\n    pose: L2DPose;\n    initialized: boolean;\n    updating: boolean;\n    alpha: number;\n    accAlpha: number;\n    lipSync: boolean;\n    lipSyncValue: number;\n    accelX: number;\n    accelY: number;\n    accelZ: number;\n    dragX: number;\n    dragY: number;\n    startTimeMSec: any;\n    mainMotionManager: L2DMotionManager;\n    expressionManager: L2DMotionManager;\n    motions: {};\n    expressions: {};\n    isTexLoaded: boolean;\n    getModelMatrix(): L2DModelMatrix;\n    setAlpha(a: any): void;\n    getAlpha(): number;\n    isInitialized(): boolean;\n    setInitialized(v: any): void;\n    isUpdating(): boolean;\n    setUpdating(v: any): void;\n    getLive2DModel(): any;\n    setLipSync(v: any): void;\n    setLipSyncValue(v: any): void;\n    setAccel(x: any, y: any, z: any): void;\n    setDrag(x: any, y: any): void;\n    getMainMotionManager(): L2DMotionManager;\n    getExpressionManager(): L2DMotionManager;\n    loadModelData(path: any, callback: any): void;\n    loadTexture(no: any, path: any, callback: any): void;\n    loadMotion(name: any, path: any, callback: any): void;\n    loadExpression(name: any, path: any, callback: any): void;\n    loadPose(path: any, callback: any): void;\n    loadPhysics(path: any): void;\n    hitTestSimple(drawID: any, testX: any, testY: any): boolean;\n}\nexport class L2DViewMatrix extends L2DMatrix44 {\n    screenLeft: any;\n    screenRight: any;\n    screenTop: any;\n    screenBottom: any;\n    maxLeft: any;\n    maxRight: any;\n    maxTop: any;\n    maxBottom: any;\n    max: number;\n    min: number;\n    getMaxScale(): number;\n    getMinScale(): number;\n    setMaxScale(v: any): void;\n    setMinScale(v: any): void;\n    isMaxScale(): boolean;\n    isMinScale(): boolean;\n    adjustTranslate(shiftX: any, shiftY: any): void;\n    adjustScale(cx: any, cy: any, scale: any): void;\n    setScreenRect(left: any, right: any, bottom: any, top: any): void;\n    setMaxScreenRect(left: any, right: any, bottom: any, top: any): void;\n    getScreenLeft(): any;\n    getScreenRight(): any;\n    getScreenBottom(): any;\n    getScreenTop(): any;\n    getMaxLeft(): any;\n    getMaxRight(): any;\n    getMaxBottom(): any;\n    getMaxTop(): any;\n}\nexport class L2DEyeBlink {\n    nextBlinkTime: any;\n    stateStartTime: any;\n    blinkIntervalMsec: number;\n    eyeState: string;\n    closingMotionMsec: number;\n    closedMotionMsec: number;\n    openingMotionMsec: number;\n    closeIfZero: boolean;\n    eyeID_L: string;\n    eyeID_R: string;\n    calcNextBlink(): any;\n    setInterval(blinkIntervalMsec: any): void;\n    setEyeMotion(closingMotionMsec: any, closedMotionMsec: any, openingMotionMsec: any): void;\n    updateParam(model: any): void;\n}\nexport class Live2DFramework {\n    static getPlatformManager(): any;\n    static setPlatformManager(platformManager: any): void;\n}\nexport namespace Live2DFramework {\n    let platformManager: any;\n}\nexport class L2DMatrix44 {\n    static mul(a: any, b: any, dst: any): void;\n    tr: Float32Array<ArrayBuffer>;\n    identity(): void;\n    getArray(): Float32Array<ArrayBuffer>;\n    getCopyMatrix(): Float32Array<ArrayBuffer>;\n    setMatrix(tr: any): void;\n    getScaleX(): number;\n    getScaleY(): number;\n    transformX(src: any): number;\n    transformY(src: any): number;\n    invertTransformX(src: any): number;\n    invertTransformY(src: any): number;\n    multTranslate(shiftX: any, shiftY: any): void;\n    translate(x: any, y: any): void;\n    translateX(x: any): void;\n    translateY(y: any): void;\n    multScale(scaleX: any, scaleY: any): void;\n    scale(scaleX: any, scaleY: any): void;\n}\nexport class L2DTargetPoint {\n    EPSILON: number;\n    faceTargetX: number;\n    faceTargetY: number;\n    faceX: number;\n    faceY: number;\n    faceVX: number;\n    faceVY: number;\n    lastTimeSec: number;\n    setPoint(x: any, y: any): void;\n    getX(): number;\n    getY(): number;\n    update(): void;\n}\nexport namespace L2DTargetPoint {\n    let FRAME_RATE: number;\n}\ndeclare class L2DModelMatrix extends L2DMatrix44 {\n    constructor(w: any, h: any);\n    width: any;\n    height: any;\n    setPosition(x: any, y: any): void;\n    setCenterPosition(x: any, y: any): void;\n    top(y: any): void;\n    bottom(y: any): void;\n    left(x: any): void;\n    right(x: any): void;\n    centerX(x: any): void;\n    centerY(y: any): void;\n    setX(x: any): void;\n    setY(y: any): void;\n    setHeight(h: any): void;\n    setWidth(w: any): void;\n}\ndeclare class L2DPhysics {\n    static load(buf: any): L2DPhysics;\n    physicsList: any[];\n    startTimeMSec: any;\n    updateParam(model: any): void;\n}\ndeclare class L2DPose {\n    static load(buf: any): L2DPose;\n    lastTime: number;\n    lastModel: any;\n    partsGroups: any[];\n    updateParam(model: any): void;\n    initParam(model: any): void;\n    normalizePartsOpacityGroup(model: any, partsGroup: any, deltaTimeSec: any): void;\n    copyOpacityOtherParts(model: any, partsGroup: any): void;\n}\ndeclare class L2DMotionManager {\n    currentPriority: any;\n    reservePriority: any;\n    super: any;\n    getCurrentPriority(): any;\n    getReservePriority(): any;\n    reserveMotion(priority: any): boolean;\n    setReservePriority(val: any): void;\n    updateParam(model: any): any;\n    startMotionPrio(motion: any, priority: any): any;\n}\nexport {};\n"
  },
  {
    "path": "build/cubism2/Live2DFramework.js",
    "content": "import logger from '../logger.js';\nclass L2DBaseModel {\n    constructor() {\n        this.live2DModel = null;\n        this.modelMatrix = null;\n        this.eyeBlink = null;\n        this.physics = null;\n        this.pose = null;\n        this.initialized = false;\n        this.updating = false;\n        this.alpha = 1;\n        this.accAlpha = 0;\n        this.lipSync = false;\n        this.lipSyncValue = 0;\n        this.accelX = 0;\n        this.accelY = 0;\n        this.accelZ = 0;\n        this.dragX = 0;\n        this.dragY = 0;\n        this.startTimeMSec = null;\n        this.mainMotionManager = new L2DMotionManager();\n        this.expressionManager = new L2DMotionManager();\n        this.motions = {};\n        this.expressions = {};\n        this.isTexLoaded = false;\n    }\n    getModelMatrix() {\n        return this.modelMatrix;\n    }\n    setAlpha(a) {\n        if (a > 0.999)\n            a = 1;\n        if (a < 0.001)\n            a = 0;\n        this.alpha = a;\n    }\n    getAlpha() {\n        return this.alpha;\n    }\n    isInitialized() {\n        return this.initialized;\n    }\n    setInitialized(v) {\n        this.initialized = v;\n    }\n    isUpdating() {\n        return this.updating;\n    }\n    setUpdating(v) {\n        this.updating = v;\n    }\n    getLive2DModel() {\n        return this.live2DModel;\n    }\n    setLipSync(v) {\n        this.lipSync = v;\n    }\n    setLipSyncValue(v) {\n        this.lipSyncValue = v;\n    }\n    setAccel(x, y, z) {\n        this.accelX = x;\n        this.accelY = y;\n        this.accelZ = z;\n    }\n    setDrag(x, y) {\n        this.dragX = x;\n        this.dragY = y;\n    }\n    getMainMotionManager() {\n        return this.mainMotionManager;\n    }\n    getExpressionManager() {\n        return this.expressionManager;\n    }\n    loadModelData(path, callback) {\n        const pm = Live2DFramework.getPlatformManager();\n        logger.info('Load model : ' + path);\n        pm.loadLive2DModel(path, (l2dModel) => {\n            this.live2DModel = l2dModel;\n            this.live2DModel.saveParam();\n            const _err = Live2D.getError();\n            if (_err != 0) {\n                logger.error('Error : Failed to loadModelData().');\n                return;\n            }\n            this.modelMatrix = new L2DModelMatrix(this.live2DModel.getCanvasWidth(), this.live2DModel.getCanvasHeight());\n            this.modelMatrix.setWidth(2);\n            this.modelMatrix.setCenterPosition(0, 0);\n            callback(this.live2DModel);\n        });\n    }\n    loadTexture(no, path, callback) {\n        texCounter++;\n        const pm = Live2DFramework.getPlatformManager();\n        logger.info('Load Texture : ' + path);\n        pm.loadTexture(this.live2DModel, no, path, () => {\n            texCounter--;\n            if (texCounter == 0)\n                this.isTexLoaded = true;\n            if (typeof callback == 'function')\n                callback();\n        });\n    }\n    loadMotion(name, path, callback) {\n        const pm = Live2DFramework.getPlatformManager();\n        logger.trace('Load Motion : ' + path);\n        let motion = null;\n        pm.loadBytes(path, (buf) => {\n            motion = Live2DMotion.loadMotion(buf);\n            if (name != null) {\n                this.motions[name] = motion;\n            }\n            callback(motion);\n        });\n    }\n    loadExpression(name, path, callback) {\n        const pm = Live2DFramework.getPlatformManager();\n        logger.trace('Load Expression : ' + path);\n        pm.loadBytes(path, (buf) => {\n            if (name != null) {\n                this.expressions[name] = L2DExpressionMotion.loadJson(buf);\n            }\n            if (typeof callback == 'function')\n                callback();\n        });\n    }\n    loadPose(path, callback) {\n        const pm = Live2DFramework.getPlatformManager();\n        logger.trace('Load Pose : ' + path);\n        try {\n            pm.loadBytes(path, (buf) => {\n                this.pose = L2DPose.load(buf);\n                if (typeof callback == 'function')\n                    callback();\n            });\n        }\n        catch (e) {\n            logger.warn(e);\n        }\n    }\n    loadPhysics(path) {\n        const pm = Live2DFramework.getPlatformManager();\n        logger.trace('Load Physics : ' + path);\n        try {\n            pm.loadBytes(path, (buf) => {\n                this.physics = L2DPhysics.load(buf);\n            });\n        }\n        catch (e) {\n            logger.warn(e);\n        }\n    }\n    hitTestSimple(drawID, testX, testY) {\n        const drawIndex = this.live2DModel.getDrawDataIndex(drawID);\n        if (drawIndex < 0)\n            return false;\n        const points = this.live2DModel.getTransformedPoints(drawIndex);\n        let left = this.live2DModel.getCanvasWidth();\n        let right = 0;\n        let top = this.live2DModel.getCanvasHeight();\n        let bottom = 0;\n        for (let j = 0; j < points.length; j = j + 2) {\n            const x = points[j];\n            const y = points[j + 1];\n            if (x < left)\n                left = x;\n            if (x > right)\n                right = x;\n            if (y < top)\n                top = y;\n            if (y > bottom)\n                bottom = y;\n        }\n        const tx = this.modelMatrix.invertTransformX(testX);\n        const ty = this.modelMatrix.invertTransformY(testY);\n        return left <= tx && tx <= right && top <= ty && ty <= bottom;\n    }\n}\nlet texCounter = 0;\nclass L2DExpressionMotion extends AMotion {\n    constructor() {\n        super();\n        this.paramList = [];\n    }\n    static loadJson(buf) {\n        const ret = new L2DExpressionMotion();\n        const pm = Live2DFramework.getPlatformManager();\n        const json = pm.jsonParseFromBytes(buf);\n        ret.setFadeIn(parseInt(json.fade_in) > 0 ? parseInt(json.fade_in) : 1000);\n        ret.setFadeOut(parseInt(json.fade_out) > 0 ? parseInt(json.fade_out) : 1000);\n        if (json.params == null) {\n            return ret;\n        }\n        const params = json.params;\n        const paramNum = params.length;\n        ret.paramList = [];\n        for (let i = 0; i < paramNum; i++) {\n            const param = params[i];\n            const paramID = param.id.toString();\n            let value = parseFloat(param.val);\n            let calcTypeInt = L2DExpressionMotion.TYPE_ADD;\n            const calc = param.calc != null ? param.calc.toString() : 'add';\n            if (calc === 'add') {\n                calcTypeInt = L2DExpressionMotion.TYPE_ADD;\n            }\n            else if (calc === 'mult') {\n                calcTypeInt = L2DExpressionMotion.TYPE_MULT;\n            }\n            else if (calc === 'set') {\n                calcTypeInt = L2DExpressionMotion.TYPE_SET;\n            }\n            else {\n                calcTypeInt = L2DExpressionMotion.TYPE_ADD;\n            }\n            if (calcTypeInt == L2DExpressionMotion.TYPE_ADD) {\n                let defaultValue = param.def == null ? 0 : parseFloat(param.def);\n                value = value - defaultValue;\n            }\n            else if (calcTypeInt == L2DExpressionMotion.TYPE_MULT) {\n                let defaultValue = param.def == null ? 1 : parseFloat(param.def);\n                if (defaultValue == 0)\n                    defaultValue = 1;\n                value = value / defaultValue;\n            }\n            const item = new L2DExpressionParam();\n            item.id = paramID;\n            item.type = calcTypeInt;\n            item.value = value;\n            ret.paramList.push(item);\n        }\n        return ret;\n    }\n    updateParamExe(model, timeMSec, weight, motionQueueEnt) {\n        for (let i = this.paramList.length - 1; i >= 0; --i) {\n            const param = this.paramList[i];\n            if (param.type == L2DExpressionMotion.TYPE_ADD) {\n                model.addToParamFloat(param.id, param.value, weight);\n            }\n            else if (param.type == L2DExpressionMotion.TYPE_MULT) {\n                model.multParamFloat(param.id, param.value, weight);\n            }\n            else if (param.type == L2DExpressionMotion.TYPE_SET) {\n                model.setParamFloat(param.id, param.value, weight);\n            }\n        }\n    }\n}\nL2DExpressionMotion.EXPRESSION_DEFAULT = 'DEFAULT';\nL2DExpressionMotion.TYPE_SET = 0;\nL2DExpressionMotion.TYPE_ADD = 1;\nL2DExpressionMotion.TYPE_MULT = 2;\nfunction L2DExpressionParam() {\n    this.id = '';\n    this.type = -1;\n    this.value = null;\n}\nclass L2DEyeBlink {\n    constructor() {\n        this.nextBlinkTime = null;\n        this.stateStartTime = null;\n        this.blinkIntervalMsec = null;\n        this.eyeState = EYE_STATE.STATE_FIRST;\n        this.blinkIntervalMsec = 4000;\n        this.closingMotionMsec = 100;\n        this.closedMotionMsec = 50;\n        this.openingMotionMsec = 150;\n        this.closeIfZero = true;\n        this.eyeID_L = 'PARAM_EYE_L_OPEN';\n        this.eyeID_R = 'PARAM_EYE_R_OPEN';\n    }\n    calcNextBlink() {\n        const time = UtSystem.getUserTimeMSec();\n        const r = Math.random();\n        return time + r * (2 * this.blinkIntervalMsec - 1);\n    }\n    setInterval(blinkIntervalMsec) {\n        this.blinkIntervalMsec = blinkIntervalMsec;\n    }\n    setEyeMotion(closingMotionMsec, closedMotionMsec, openingMotionMsec) {\n        this.closingMotionMsec = closingMotionMsec;\n        this.closedMotionMsec = closedMotionMsec;\n        this.openingMotionMsec = openingMotionMsec;\n    }\n    updateParam(model) {\n        const time = UtSystem.getUserTimeMSec();\n        let eyeParamValue;\n        let t = 0;\n        switch (this.eyeState) {\n            case EYE_STATE.STATE_CLOSING:\n                t = (time - this.stateStartTime) / this.closingMotionMsec;\n                if (t >= 1) {\n                    t = 1;\n                    this.eyeState = EYE_STATE.STATE_CLOSED;\n                    this.stateStartTime = time;\n                }\n                eyeParamValue = 1 - t;\n                break;\n            case EYE_STATE.STATE_CLOSED:\n                t = (time - this.stateStartTime) / this.closedMotionMsec;\n                if (t >= 1) {\n                    this.eyeState = EYE_STATE.STATE_OPENING;\n                    this.stateStartTime = time;\n                }\n                eyeParamValue = 0;\n                break;\n            case EYE_STATE.STATE_OPENING:\n                t = (time - this.stateStartTime) / this.openingMotionMsec;\n                if (t >= 1) {\n                    t = 1;\n                    this.eyeState = EYE_STATE.STATE_INTERVAL;\n                    this.nextBlinkTime = this.calcNextBlink();\n                }\n                eyeParamValue = t;\n                break;\n            case EYE_STATE.STATE_INTERVAL:\n                if (this.nextBlinkTime < time) {\n                    this.eyeState = EYE_STATE.STATE_CLOSING;\n                    this.stateStartTime = time;\n                }\n                eyeParamValue = 1;\n                break;\n            case EYE_STATE.STATE_FIRST:\n            default:\n                this.eyeState = EYE_STATE.STATE_INTERVAL;\n                this.nextBlinkTime = this.calcNextBlink();\n                eyeParamValue = 1;\n                break;\n        }\n        if (!this.closeIfZero)\n            eyeParamValue = -eyeParamValue;\n        model.setParamFloat(this.eyeID_L, eyeParamValue);\n        model.setParamFloat(this.eyeID_R, eyeParamValue);\n    }\n}\nconst EYE_STATE = () => { };\nEYE_STATE.STATE_FIRST = 'STATE_FIRST';\nEYE_STATE.STATE_INTERVAL = 'STATE_INTERVAL';\nEYE_STATE.STATE_CLOSING = 'STATE_CLOSING';\nEYE_STATE.STATE_CLOSED = 'STATE_CLOSED';\nEYE_STATE.STATE_OPENING = 'STATE_OPENING';\nclass L2DMatrix44 {\n    constructor() {\n        this.tr = new Float32Array(16);\n        this.identity();\n    }\n    static mul(a, b, dst) {\n        const c = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n        const n = 4;\n        let i, j, k;\n        for (i = 0; i < n; i++) {\n            for (j = 0; j < n; j++) {\n                for (k = 0; k < n; k++) {\n                    c[i + j * 4] += a[i + k * 4] * b[k + j * 4];\n                }\n            }\n        }\n        for (i = 0; i < 16; i++) {\n            dst[i] = c[i];\n        }\n    }\n    identity() {\n        for (let i = 0; i < 16; i++)\n            this.tr[i] = i % 5 == 0 ? 1 : 0;\n    }\n    getArray() {\n        return this.tr;\n    }\n    getCopyMatrix() {\n        return new Float32Array(this.tr);\n    }\n    setMatrix(tr) {\n        if (this.tr == null || this.tr.length != this.tr.length)\n            return;\n        for (let i = 0; i < 16; i++)\n            this.tr[i] = tr[i];\n    }\n    getScaleX() {\n        return this.tr[0];\n    }\n    getScaleY() {\n        return this.tr[5];\n    }\n    transformX(src) {\n        return this.tr[0] * src + this.tr[12];\n    }\n    transformY(src) {\n        return this.tr[5] * src + this.tr[13];\n    }\n    invertTransformX(src) {\n        return (src - this.tr[12]) / this.tr[0];\n    }\n    invertTransformY(src) {\n        return (src - this.tr[13]) / this.tr[5];\n    }\n    multTranslate(shiftX, shiftY) {\n        const tr1 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, shiftX, shiftY, 0, 1];\n        L2DMatrix44.mul(tr1, this.tr, this.tr);\n    }\n    translate(x, y) {\n        this.tr[12] = x;\n        this.tr[13] = y;\n    }\n    translateX(x) {\n        this.tr[12] = x;\n    }\n    translateY(y) {\n        this.tr[13] = y;\n    }\n    multScale(scaleX, scaleY) {\n        const tr1 = [scaleX, 0, 0, 0, 0, scaleY, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];\n        L2DMatrix44.mul(tr1, this.tr, this.tr);\n    }\n    scale(scaleX, scaleY) {\n        this.tr[0] = scaleX;\n        this.tr[5] = scaleY;\n    }\n}\nclass L2DModelMatrix extends L2DMatrix44 {\n    constructor(w, h) {\n        super();\n        this.width = w;\n        this.height = h;\n    }\n    setPosition(x, y) {\n        this.translate(x, y);\n    }\n    setCenterPosition(x, y) {\n        const w = this.width * this.getScaleX();\n        const h = this.height * this.getScaleY();\n        this.translate(x - w / 2, y - h / 2);\n    }\n    top(y) {\n        this.setY(y);\n    }\n    bottom(y) {\n        const h = this.height * this.getScaleY();\n        this.translateY(y - h);\n    }\n    left(x) {\n        this.setX(x);\n    }\n    right(x) {\n        const w = this.width * this.getScaleX();\n        this.translateX(x - w);\n    }\n    centerX(x) {\n        const w = this.width * this.getScaleX();\n        this.translateX(x - w / 2);\n    }\n    centerY(y) {\n        const h = this.height * this.getScaleY();\n        this.translateY(y - h / 2);\n    }\n    setX(x) {\n        this.translateX(x);\n    }\n    setY(y) {\n        this.translateY(y);\n    }\n    setHeight(h) {\n        const scaleX = h / this.height;\n        const scaleY = -scaleX;\n        this.scale(scaleX, scaleY);\n    }\n    setWidth(w) {\n        const scaleX = w / this.width;\n        const scaleY = -scaleX;\n        this.scale(scaleX, scaleY);\n    }\n}\nclass L2DMotionManager extends MotionQueueManager {\n    constructor() {\n        super();\n        this.currentPriority = null;\n        this.reservePriority = null;\n        this.super = MotionQueueManager.prototype;\n    }\n    getCurrentPriority() {\n        return this.currentPriority;\n    }\n    getReservePriority() {\n        return this.reservePriority;\n    }\n    reserveMotion(priority) {\n        if (this.reservePriority >= priority) {\n            return false;\n        }\n        if (this.currentPriority >= priority) {\n            return false;\n        }\n        this.reservePriority = priority;\n        return true;\n    }\n    setReservePriority(val) {\n        this.reservePriority = val;\n    }\n    updateParam(model) {\n        const updated = MotionQueueManager.prototype.updateParam.call(this, model);\n        if (this.isFinished()) {\n            this.currentPriority = 0;\n        }\n        return updated;\n    }\n    startMotionPrio(motion, priority) {\n        if (priority == this.reservePriority) {\n            this.reservePriority = 0;\n        }\n        this.currentPriority = priority;\n        return this.startMotion(motion, false);\n    }\n}\nclass L2DPhysics {\n    constructor() {\n        this.physicsList = [];\n        this.startTimeMSec = UtSystem.getUserTimeMSec();\n    }\n    static load(buf) {\n        const ret = new L2DPhysics();\n        const pm = Live2DFramework.getPlatformManager();\n        const json = pm.jsonParseFromBytes(buf);\n        const params = json.physics_hair;\n        const paramNum = params.length;\n        for (let i = 0; i < paramNum; i++) {\n            const param = params[i];\n            const physics = new PhysicsHair();\n            const setup = param.setup;\n            const length = parseFloat(setup.length);\n            const resist = parseFloat(setup.regist);\n            const mass = parseFloat(setup.mass);\n            physics.setup(length, resist, mass);\n            const srcList = param.src;\n            const srcNum = srcList.length;\n            for (let j = 0; j < srcNum; j++) {\n                const src = srcList[j];\n                let id = src.id;\n                let type = PhysicsHair.Src.SRC_TO_X;\n                let typeStr = src.ptype;\n                if (typeStr === 'x') {\n                    type = PhysicsHair.Src.SRC_TO_X;\n                }\n                else if (typeStr === 'y') {\n                    type = PhysicsHair.Src.SRC_TO_Y;\n                }\n                else if (typeStr === 'angle') {\n                    type = PhysicsHair.Src.SRC_TO_G_ANGLE;\n                }\n                else {\n                    UtDebug.error('live2d', 'Invalid parameter:PhysicsHair.Src');\n                }\n                let scale = parseFloat(src.scale);\n                let weight = parseFloat(src.weight);\n                physics.addSrcParam(type, id, scale, weight);\n            }\n            const targetList = param.targets;\n            const targetNum = targetList.length;\n            for (let j = 0; j < targetNum; j++) {\n                const target = targetList[j];\n                let id = target.id;\n                let type = PhysicsHair.Target.TARGET_FROM_ANGLE;\n                let typeStr = target.ptype;\n                if (typeStr === 'angle') {\n                    type = PhysicsHair.Target.TARGET_FROM_ANGLE;\n                }\n                else if (typeStr === 'angle_v') {\n                    type = PhysicsHair.Target.TARGET_FROM_ANGLE_V;\n                }\n                else {\n                    UtDebug.error('live2d', 'Invalid parameter:PhysicsHair.Target');\n                }\n                let scale = parseFloat(target.scale);\n                let weight = parseFloat(target.weight);\n                physics.addTargetParam(type, id, scale, weight);\n            }\n            ret.physicsList.push(physics);\n        }\n        return ret;\n    }\n    updateParam(model) {\n        const timeMSec = UtSystem.getUserTimeMSec() - this.startTimeMSec;\n        for (let i = 0; i < this.physicsList.length; i++) {\n            this.physicsList[i].update(model, timeMSec);\n        }\n    }\n}\nclass L2DPose {\n    constructor() {\n        this.lastTime = 0;\n        this.lastModel = null;\n        this.partsGroups = [];\n    }\n    static load(buf) {\n        const ret = new L2DPose();\n        const pm = Live2DFramework.getPlatformManager();\n        const json = pm.jsonParseFromBytes(buf);\n        const poseListInfo = json.parts_visible;\n        const poseNum = poseListInfo.length;\n        for (let i_pose = 0; i_pose < poseNum; i_pose++) {\n            const poseInfo = poseListInfo[i_pose];\n            const idListInfo = poseInfo.group;\n            const idNum = idListInfo.length;\n            const partsGroup = [];\n            for (let i_group = 0; i_group < idNum; i_group++) {\n                const partsInfo = idListInfo[i_group];\n                const parts = new L2DPartsParam(partsInfo.id);\n                partsGroup[i_group] = parts;\n                if (partsInfo.link == null)\n                    continue;\n                const linkListInfo = partsInfo.link;\n                const linkNum = linkListInfo.length;\n                parts.link = [];\n                for (let i_link = 0; i_link < linkNum; i_link++) {\n                    const linkParts = new L2DPartsParam(linkListInfo[i_link]);\n                    parts.link.push(linkParts);\n                }\n            }\n            ret.partsGroups.push(partsGroup);\n        }\n        return ret;\n    }\n    updateParam(model) {\n        if (model == null)\n            return;\n        if (!(model == this.lastModel)) {\n            this.initParam(model);\n        }\n        this.lastModel = model;\n        const curTime = UtSystem.getUserTimeMSec();\n        let deltaTimeSec = this.lastTime == 0 ? 0 : (curTime - this.lastTime) / 1000.0;\n        this.lastTime = curTime;\n        if (deltaTimeSec < 0)\n            deltaTimeSec = 0;\n        for (let i = 0; i < this.partsGroups.length; i++) {\n            this.normalizePartsOpacityGroup(model, this.partsGroups[i], deltaTimeSec);\n            this.copyOpacityOtherParts(model, this.partsGroups[i]);\n        }\n    }\n    initParam(model) {\n        if (model == null)\n            return;\n        for (let i = 0; i < this.partsGroups.length; i++) {\n            const partsGroup = this.partsGroups[i];\n            for (let j = 0; j < partsGroup.length; j++) {\n                partsGroup[j].initIndex(model);\n                const partsIndex = partsGroup[j].partsIndex;\n                const paramIndex = partsGroup[j].paramIndex;\n                if (partsIndex < 0)\n                    continue;\n                const v = model.getParamFloat(paramIndex) != 0;\n                model.setPartsOpacity(partsIndex, v ? 1.0 : 0.0);\n                model.setParamFloat(paramIndex, v ? 1.0 : 0.0);\n                if (partsGroup[j].link == null)\n                    continue;\n                for (let k = 0; k < partsGroup[j].link.length; k++) {\n                    partsGroup[j].link[k].initIndex(model);\n                }\n            }\n        }\n    }\n    normalizePartsOpacityGroup(model, partsGroup, deltaTimeSec) {\n        let visibleParts = -1;\n        let visibleOpacity = 1.0;\n        const CLEAR_TIME_SEC = 0.5;\n        const phi = 0.5;\n        const maxBackOpacity = 0.15;\n        for (let i = 0; i < partsGroup.length; i++) {\n            let partsIndex = partsGroup[i].partsIndex;\n            const paramIndex = partsGroup[i].paramIndex;\n            if (partsIndex < 0)\n                continue;\n            if (model.getParamFloat(paramIndex) != 0) {\n                if (visibleParts >= 0) {\n                    break;\n                }\n                visibleParts = i;\n                visibleOpacity = model.getPartsOpacity(partsIndex);\n                visibleOpacity += deltaTimeSec / CLEAR_TIME_SEC;\n                if (visibleOpacity > 1) {\n                    visibleOpacity = 1;\n                }\n            }\n        }\n        if (visibleParts < 0) {\n            visibleParts = 0;\n            visibleOpacity = 1;\n        }\n        for (let i = 0; i < partsGroup.length; i++) {\n            let partsIndex = partsGroup[i].partsIndex;\n            if (partsIndex < 0)\n                continue;\n            if (visibleParts == i) {\n                model.setPartsOpacity(partsIndex, visibleOpacity);\n            }\n            else {\n                let opacity = model.getPartsOpacity(partsIndex);\n                let a1;\n                if (visibleOpacity < phi) {\n                    a1 = (visibleOpacity * (phi - 1)) / phi + 1;\n                }\n                else {\n                    a1 = ((1 - visibleOpacity) * phi) / (1 - phi);\n                }\n                const backOp = (1 - a1) * (1 - visibleOpacity);\n                if (backOp > maxBackOpacity) {\n                    a1 = 1 - maxBackOpacity / (1 - visibleOpacity);\n                }\n                if (opacity > a1) {\n                    opacity = a1;\n                }\n                model.setPartsOpacity(partsIndex, opacity);\n            }\n        }\n    }\n    copyOpacityOtherParts(model, partsGroup) {\n        for (let i_group = 0; i_group < partsGroup.length; i_group++) {\n            const partsParam = partsGroup[i_group];\n            if (partsParam.link == null)\n                continue;\n            if (partsParam.partsIndex < 0)\n                continue;\n            const opacity = model.getPartsOpacity(partsParam.partsIndex);\n            for (let i_link = 0; i_link < partsParam.link.length; i_link++) {\n                const linkParts = partsParam.link[i_link];\n                if (linkParts.partsIndex < 0)\n                    continue;\n                model.setPartsOpacity(linkParts.partsIndex, opacity);\n            }\n        }\n    }\n}\nclass L2DPartsParam {\n    constructor(id) {\n        this.paramIndex = -1;\n        this.partsIndex = -1;\n        this.link = null;\n        this.id = id;\n    }\n    initIndex(model) {\n        this.paramIndex = model.getParamIndex('VISIBLE:' + this.id);\n        this.partsIndex = model.getPartsDataIndex(PartsDataID.getID(this.id));\n        model.setParamFloat(this.paramIndex, 1);\n    }\n}\nclass L2DTargetPoint {\n    constructor() {\n        this.EPSILON = 0.01;\n        this.faceTargetX = 0;\n        this.faceTargetY = 0;\n        this.faceX = 0;\n        this.faceY = 0;\n        this.faceVX = 0;\n        this.faceVY = 0;\n        this.lastTimeSec = 0;\n    }\n    setPoint(x, y) {\n        this.faceTargetX = x;\n        this.faceTargetY = y;\n    }\n    getX() {\n        return this.faceX;\n    }\n    getY() {\n        return this.faceY;\n    }\n    update() {\n        const TIME_TO_MAX_SPEED = 0.15;\n        const FACE_PARAM_MAX_V = 40.0 / 7.5;\n        const MAX_V = FACE_PARAM_MAX_V / L2DTargetPoint.FRAME_RATE;\n        if (this.lastTimeSec == 0) {\n            this.lastTimeSec = UtSystem.getUserTimeMSec();\n            return;\n        }\n        const curTimeSec = UtSystem.getUserTimeMSec();\n        const deltaTimeWeight = ((curTimeSec - this.lastTimeSec) * L2DTargetPoint.FRAME_RATE) / 1000.0;\n        this.lastTimeSec = curTimeSec;\n        const FRAME_TO_MAX_SPEED = TIME_TO_MAX_SPEED * L2DTargetPoint.FRAME_RATE;\n        const MAX_A = (deltaTimeWeight * MAX_V) / FRAME_TO_MAX_SPEED;\n        const dx = this.faceTargetX - this.faceX;\n        const dy = this.faceTargetY - this.faceY;\n        if (Math.abs(dx) <= this.EPSILON && Math.abs(dy) <= this.EPSILON)\n            return;\n        const d = Math.sqrt(dx * dx + dy * dy);\n        const vx = (MAX_V * dx) / d;\n        const vy = (MAX_V * dy) / d;\n        let ax = vx - this.faceVX;\n        let ay = vy - this.faceVY;\n        let a = Math.sqrt(ax * ax + ay * ay);\n        if (a < -MAX_A || a > MAX_A) {\n            ax *= MAX_A / a;\n            ay *= MAX_A / a;\n            a = MAX_A;\n        }\n        this.faceVX += ax;\n        this.faceVY += ay;\n        {\n            const max_v = 0.5 *\n                (Math.sqrt(MAX_A * MAX_A + 16 * MAX_A * d - 8 * MAX_A * d) - MAX_A);\n            const cur_v = Math.sqrt(this.faceVX * this.faceVX + this.faceVY * this.faceVY);\n            if (cur_v > max_v) {\n                this.faceVX *= max_v / cur_v;\n                this.faceVY *= max_v / cur_v;\n            }\n        }\n        this.faceX += this.faceVX;\n        this.faceY += this.faceVY;\n    }\n}\nL2DTargetPoint.FRAME_RATE = 30;\nclass L2DViewMatrix extends L2DMatrix44 {\n    constructor() {\n        super();\n        this.screenLeft = null;\n        this.screenRight = null;\n        this.screenTop = null;\n        this.screenBottom = null;\n        this.maxLeft = null;\n        this.maxRight = null;\n        this.maxTop = null;\n        this.maxBottom = null;\n        this.max = Number.MAX_VALUE;\n        this.min = 0;\n    }\n    getMaxScale() {\n        return this.max;\n    }\n    getMinScale() {\n        return this.min;\n    }\n    setMaxScale(v) {\n        this.max = v;\n    }\n    setMinScale(v) {\n        this.min = v;\n    }\n    isMaxScale() {\n        return this.getScaleX() == this.max;\n    }\n    isMinScale() {\n        return this.getScaleX() == this.min;\n    }\n    adjustTranslate(shiftX, shiftY) {\n        if (this.tr[0] * this.maxLeft + (this.tr[12] + shiftX) > this.screenLeft)\n            shiftX = this.screenLeft - this.tr[0] * this.maxLeft - this.tr[12];\n        if (this.tr[0] * this.maxRight + (this.tr[12] + shiftX) < this.screenRight)\n            shiftX = this.screenRight - this.tr[0] * this.maxRight - this.tr[12];\n        if (this.tr[5] * this.maxTop + (this.tr[13] + shiftY) < this.screenTop)\n            shiftY = this.screenTop - this.tr[5] * this.maxTop - this.tr[13];\n        if (this.tr[5] * this.maxBottom + (this.tr[13] + shiftY) >\n            this.screenBottom)\n            shiftY = this.screenBottom - this.tr[5] * this.maxBottom - this.tr[13];\n        const tr1 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, shiftX, shiftY, 0, 1];\n        L2DMatrix44.mul(tr1, this.tr, this.tr);\n    }\n    adjustScale(cx, cy, scale) {\n        const targetScale = scale * this.tr[0];\n        if (targetScale < this.min) {\n            if (this.tr[0] > 0)\n                scale = this.min / this.tr[0];\n        }\n        else if (targetScale > this.max) {\n            if (this.tr[0] > 0)\n                scale = this.max / this.tr[0];\n        }\n        const tr1 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1];\n        const tr2 = [scale, 0, 0, 0, 0, scale, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];\n        const tr3 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -cx, -cy, 0, 1];\n        L2DMatrix44.mul(tr3, this.tr, this.tr);\n        L2DMatrix44.mul(tr2, this.tr, this.tr);\n        L2DMatrix44.mul(tr1, this.tr, this.tr);\n    }\n    setScreenRect(left, right, bottom, top) {\n        this.screenLeft = left;\n        this.screenRight = right;\n        this.screenTop = top;\n        this.screenBottom = bottom;\n    }\n    setMaxScreenRect(left, right, bottom, top) {\n        this.maxLeft = left;\n        this.maxRight = right;\n        this.maxTop = top;\n        this.maxBottom = bottom;\n    }\n    getScreenLeft() {\n        return this.screenLeft;\n    }\n    getScreenRight() {\n        return this.screenRight;\n    }\n    getScreenBottom() {\n        return this.screenBottom;\n    }\n    getScreenTop() {\n        return this.screenTop;\n    }\n    getMaxLeft() {\n        return this.maxLeft;\n    }\n    getMaxRight() {\n        return this.maxRight;\n    }\n    getMaxBottom() {\n        return this.maxBottom;\n    }\n    getMaxTop() {\n        return this.maxTop;\n    }\n}\nclass Live2DFramework {\n    static getPlatformManager() {\n        return Live2DFramework.platformManager;\n    }\n    static setPlatformManager(platformManager) {\n        Live2DFramework.platformManager = platformManager;\n    }\n}\nLive2DFramework.platformManager = null;\nexport { L2DBaseModel, L2DViewMatrix, L2DEyeBlink, Live2DFramework, L2DMatrix44, L2DTargetPoint };\n"
  },
  {
    "path": "build/cubism2/PlatformManager.d.ts",
    "content": "export default PlatformManager;\ndeclare class PlatformManager {\n    cache: {};\n    loadBytes(path: any, callback: any): any;\n    loadLive2DModel(path: any, callback: any): void;\n    loadTexture(model: any, no: any, path: any, callback: any): void;\n    jsonParseFromBytes(buf: any): any;\n}\n"
  },
  {
    "path": "build/cubism2/PlatformManager.js",
    "content": "import logger from '../logger.js';\nclass PlatformManager {\n    constructor() {\n        this.cache = {};\n    }\n    loadBytes(path, callback) {\n        if (path in this.cache) {\n            return callback(this.cache[path]);\n        }\n        fetch(path)\n            .then(response => response.arrayBuffer())\n            .then(arrayBuffer => {\n            this.cache[path] = arrayBuffer;\n            callback(arrayBuffer);\n        });\n    }\n    loadLive2DModel(path, callback) {\n        let model = null;\n        this.loadBytes(path, buf => {\n            model = Live2DModelWebGL.loadModel(buf);\n            callback(model);\n        });\n    }\n    loadTexture(model, no, path, callback) {\n        const loadedImage = new Image();\n        loadedImage.crossOrigin = 'anonymous';\n        loadedImage.src = path;\n        loadedImage.onload = () => {\n            const canvas = document.getElementById('live2d');\n            const gl = canvas.getContext('webgl2', { premultipliedAlpha: true, preserveDrawingBuffer: true });\n            let texture = gl.createTexture();\n            if (!texture) {\n                logger.error('Failed to generate gl texture name.');\n                return -1;\n            }\n            if (model.isPremultipliedAlpha() == false) {\n                gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);\n            }\n            gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);\n            gl.activeTexture(gl.TEXTURE0);\n            gl.bindTexture(gl.TEXTURE_2D, texture);\n            gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, loadedImage);\n            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);\n            gl.generateMipmap(gl.TEXTURE_2D);\n            model.setTexture(no, texture);\n            texture = null;\n            if (typeof callback == 'function')\n                callback();\n        };\n        loadedImage.onerror = () => {\n            logger.error('Failed to load image : ' + path);\n        };\n    }\n    jsonParseFromBytes(buf) {\n        let jsonStr;\n        const bomCode = new Uint8Array(buf, 0, 3);\n        if (bomCode[0] == 239 && bomCode[1] == 187 && bomCode[2] == 191) {\n            jsonStr = String.fromCharCode.apply(null, new Uint8Array(buf, 3));\n        }\n        else {\n            jsonStr = String.fromCharCode.apply(null, new Uint8Array(buf));\n        }\n        const jsonObj = JSON.parse(jsonStr);\n        return jsonObj;\n    }\n}\nexport default PlatformManager;\n"
  },
  {
    "path": "build/cubism2/index.d.ts",
    "content": "export default Cubism2Model;\ndeclare class Cubism2Model {\n    live2DMgr: LAppLive2DManager;\n    isDrawStart: boolean;\n    gl: any;\n    canvas: HTMLElement;\n    dragMgr: L2DTargetPoint;\n    viewMatrix: L2DViewMatrix;\n    projMatrix: L2DMatrix44;\n    deviceToScreen: L2DMatrix44;\n    oldLen: number;\n    _boundMouseEvent: any;\n    _boundTouchEvent: any;\n    initL2dCanvas(canvasId: any): void;\n    init(canvasId: any, modelSettingPath: any, modelSetting: any): Promise<void>;\n    destroy(): void;\n    _drawFrameId: number;\n    startDraw(): void;\n    draw(): void;\n    changeModel(modelSettingPath: any): Promise<void>;\n    changeModelWithJSON(modelSettingPath: any, modelSetting: any): Promise<void>;\n    modelScaling(scale: any): void;\n    modelTurnHead(event: any): void;\n    followPointer(event: any): void;\n    lookFront(): void;\n    mouseEvent(e: any): void;\n    touchEvent(e: any): void;\n    transformViewX(deviceX: any): number;\n    transformViewY(deviceY: any): number;\n    transformScreenX(deviceX: any): number;\n    transformScreenY(deviceY: any): number;\n}\nimport LAppLive2DManager from './LAppLive2DManager.js';\nimport { L2DTargetPoint } from './Live2DFramework.js';\nimport { L2DViewMatrix } from './Live2DFramework.js';\nimport { L2DMatrix44 } from './Live2DFramework.js';\n"
  },
  {
    "path": "build/cubism2/index.js",
    "content": "import { L2DMatrix44, L2DTargetPoint, L2DViewMatrix } from './Live2DFramework.js';\nimport LAppDefine from './LAppDefine.js';\nimport MatrixStack from './utils/MatrixStack.js';\nimport LAppLive2DManager from './LAppLive2DManager.js';\nimport logger from '../logger.js';\nfunction normalizePoint(x, y, x0, y0, w, h) {\n    const dx = x - x0;\n    const dy = y - y0;\n    let targetX = 0, targetY = 0;\n    if (dx >= 0) {\n        targetX = dx / (w - x0);\n    }\n    else {\n        targetX = dx / x0;\n    }\n    if (dy >= 0) {\n        targetY = dy / (h - y0);\n    }\n    else {\n        targetY = dy / y0;\n    }\n    return {\n        vx: targetX,\n        vy: -targetY\n    };\n}\nclass Cubism2Model {\n    constructor() {\n        this.live2DMgr = new LAppLive2DManager();\n        this.isDrawStart = false;\n        this.gl = null;\n        this.canvas = null;\n        this.dragMgr = null;\n        this.viewMatrix = null;\n        this.projMatrix = null;\n        this.deviceToScreen = null;\n        this.oldLen = 0;\n        this._boundMouseEvent = this.mouseEvent.bind(this);\n        this._boundTouchEvent = this.touchEvent.bind(this);\n    }\n    initL2dCanvas(canvasId) {\n        this.canvas = document.getElementById(canvasId);\n        if (this.canvas.addEventListener) {\n            this.canvas.addEventListener('mousewheel', this._boundMouseEvent, false);\n            this.canvas.addEventListener('click', this._boundMouseEvent, false);\n            document.addEventListener('mousemove', this._boundMouseEvent, false);\n            document.addEventListener('mouseout', this._boundMouseEvent, false);\n            this.canvas.addEventListener('contextmenu', this._boundMouseEvent, false);\n            this.canvas.addEventListener('touchstart', this._boundTouchEvent, false);\n            this.canvas.addEventListener('touchend', this._boundTouchEvent, false);\n            this.canvas.addEventListener('touchmove', this._boundTouchEvent, false);\n        }\n    }\n    async init(canvasId, modelSettingPath, modelSetting) {\n        this.initL2dCanvas(canvasId);\n        const width = this.canvas.width;\n        const height = this.canvas.height;\n        this.dragMgr = new L2DTargetPoint();\n        const ratio = height / width;\n        const left = LAppDefine.VIEW_LOGICAL_LEFT;\n        const right = LAppDefine.VIEW_LOGICAL_RIGHT;\n        const bottom = -ratio;\n        const top = ratio;\n        this.viewMatrix = new L2DViewMatrix();\n        this.viewMatrix.setScreenRect(left, right, bottom, top);\n        this.viewMatrix.setMaxScreenRect(LAppDefine.VIEW_LOGICAL_MAX_LEFT, LAppDefine.VIEW_LOGICAL_MAX_RIGHT, LAppDefine.VIEW_LOGICAL_MAX_BOTTOM, LAppDefine.VIEW_LOGICAL_MAX_TOP);\n        this.viewMatrix.setMaxScale(LAppDefine.VIEW_MAX_SCALE);\n        this.viewMatrix.setMinScale(LAppDefine.VIEW_MIN_SCALE);\n        this.projMatrix = new L2DMatrix44();\n        this.projMatrix.multScale(1, width / height);\n        this.deviceToScreen = new L2DMatrix44();\n        this.deviceToScreen.multTranslate(-width / 2.0, -height / 2.0);\n        this.deviceToScreen.multScale(2 / width, -2 / width);\n        this.gl = this.canvas.getContext('webgl2', { premultipliedAlpha: true, preserveDrawingBuffer: true });\n        if (!this.gl) {\n            logger.error('Failed to create WebGL context.');\n            return;\n        }\n        Live2D.setGL(this.gl);\n        this.gl.clearColor(0.0, 0.0, 0.0, 0.0);\n        await this.changeModelWithJSON(modelSettingPath, modelSetting);\n        this.startDraw();\n    }\n    destroy() {\n        if (this.canvas) {\n            this.canvas.removeEventListener('mousewheel', this._boundMouseEvent, false);\n            this.canvas.removeEventListener('click', this._boundMouseEvent, false);\n            document.removeEventListener('mousemove', this._boundMouseEvent, false);\n            document.removeEventListener('mouseout', this._boundMouseEvent, false);\n            this.canvas.removeEventListener('contextmenu', this._boundMouseEvent, false);\n            this.canvas.removeEventListener('touchstart', this._boundTouchEvent, false);\n            this.canvas.removeEventListener('touchend', this._boundTouchEvent, false);\n            this.canvas.removeEventListener('touchmove', this._boundTouchEvent, false);\n        }\n        if (this._drawFrameId) {\n            window.cancelAnimationFrame(this._drawFrameId);\n            this._drawFrameId = null;\n        }\n        this.isDrawStart = false;\n        if (this.live2DMgr && typeof this.live2DMgr.release === 'function') {\n            this.live2DMgr.release();\n        }\n        if (this.gl) {\n        }\n        this.canvas = null;\n        this.gl = null;\n        this.dragMgr = null;\n        this.viewMatrix = null;\n        this.projMatrix = null;\n        this.deviceToScreen = null;\n    }\n    startDraw() {\n        if (!this.isDrawStart) {\n            this.isDrawStart = true;\n            const tick = () => {\n                this.draw();\n                this._drawFrameId = window.requestAnimationFrame(tick, this.canvas);\n            };\n            tick();\n        }\n    }\n    draw() {\n        MatrixStack.reset();\n        MatrixStack.loadIdentity();\n        this.dragMgr.update();\n        this.live2DMgr.setDrag(this.dragMgr.getX(), this.dragMgr.getY());\n        this.gl.clear(this.gl.COLOR_BUFFER_BIT);\n        MatrixStack.multMatrix(this.projMatrix.getArray());\n        MatrixStack.multMatrix(this.viewMatrix.getArray());\n        MatrixStack.push();\n        const model = this.live2DMgr.getModel();\n        if (model == null)\n            return;\n        if (model.initialized && !model.updating) {\n            model.update();\n            model.draw(this.gl);\n        }\n        MatrixStack.pop();\n    }\n    async changeModel(modelSettingPath) {\n        await this.live2DMgr.changeModel(this.gl, modelSettingPath);\n    }\n    async changeModelWithJSON(modelSettingPath, modelSetting) {\n        await this.live2DMgr.changeModelWithJSON(this.gl, modelSettingPath, modelSetting);\n    }\n    modelScaling(scale) {\n        const isMaxScale = this.viewMatrix.isMaxScale();\n        const isMinScale = this.viewMatrix.isMinScale();\n        this.viewMatrix.adjustScale(0, 0, scale);\n        if (!isMaxScale) {\n            if (this.viewMatrix.isMaxScale()) {\n                this.live2DMgr.maxScaleEvent();\n            }\n        }\n        if (!isMinScale) {\n            if (this.viewMatrix.isMinScale()) {\n                this.live2DMgr.minScaleEvent();\n            }\n        }\n    }\n    modelTurnHead(event) {\n        var _b;\n        const rect = this.canvas.getBoundingClientRect();\n        const { vx, vy } = normalizePoint(event.clientX, event.clientY, rect.left + rect.width / 2, rect.top + rect.height / 2, window.innerWidth, window.innerHeight);\n        logger.trace('onMouseDown device( x:' +\n            event.clientX +\n            ' y:' +\n            event.clientY +\n            ' ) view( x:' +\n            vx +\n            ' y:' +\n            vy +\n            ')');\n        this.dragMgr.setPoint(vx, vy);\n        this.live2DMgr.tapEvent(vx, vy);\n        if ((_b = this.live2DMgr) === null || _b === void 0 ? void 0 : _b.model.hitTest(LAppDefine.HIT_AREA_BODY, vx, vy)) {\n            window.dispatchEvent(new Event('live2d:tapbody'));\n        }\n    }\n    followPointer(event) {\n        var _b;\n        const rect = this.canvas.getBoundingClientRect();\n        const { vx, vy } = normalizePoint(event.clientX, event.clientY, rect.left + rect.width / 2, rect.top + rect.height / 2, window.innerWidth, window.innerHeight);\n        logger.trace('onMouseMove device( x:' +\n            event.clientX +\n            ' y:' +\n            event.clientY +\n            ' ) view( x:' +\n            vx +\n            ' y:' +\n            vy +\n            ')');\n        this.dragMgr.setPoint(vx, vy);\n        if ((_b = this.live2DMgr) === null || _b === void 0 ? void 0 : _b.model.hitTest(LAppDefine.HIT_AREA_BODY, vx, vy)) {\n            window.dispatchEvent(new Event('live2d:hoverbody'));\n        }\n    }\n    lookFront() {\n        this.dragMgr.setPoint(0, 0);\n    }\n    mouseEvent(e) {\n        e.preventDefault();\n        if (e.type == 'mousewheel') {\n            if (e.wheelDelta > 0)\n                this.modelScaling(1.1);\n            else\n                this.modelScaling(0.9);\n        }\n        else if (e.type == 'click' || e.type == 'contextmenu') {\n            this.modelTurnHead(e);\n        }\n        else if (e.type == 'mousemove') {\n            this.followPointer(e);\n        }\n        else if (e.type == 'mouseout') {\n            this.lookFront();\n        }\n    }\n    touchEvent(e) {\n        e.preventDefault();\n        const touch = e.touches[0];\n        if (e.type == 'touchstart') {\n            if (e.touches.length == 1)\n                this.modelTurnHead(touch);\n        }\n        else if (e.type == 'touchmove') {\n            this.followPointer(touch);\n            if (e.touches.length == 2) {\n                const touch1 = e.touches[0];\n                const touch2 = e.touches[1];\n                const len = Math.pow(touch1.pageX - touch2.pageX, 2) +\n                    Math.pow(touch1.pageY - touch2.pageY, 2);\n                if (this.oldLen - len < 0)\n                    this.modelScaling(1.025);\n                else\n                    this.modelScaling(0.975);\n                this.oldLen = len;\n            }\n        }\n        else if (e.type == 'touchend') {\n            this.lookFront();\n        }\n    }\n    transformViewX(deviceX) {\n        const screenX = this.deviceToScreen.transformX(deviceX);\n        return this.viewMatrix.invertTransformX(screenX);\n    }\n    transformViewY(deviceY) {\n        const screenY = this.deviceToScreen.transformY(deviceY);\n        return this.viewMatrix.invertTransformY(screenY);\n    }\n    transformScreenX(deviceX) {\n        return this.deviceToScreen.transformX(deviceX);\n    }\n    transformScreenY(deviceY) {\n        return this.deviceToScreen.transformY(deviceY);\n    }\n}\nexport default Cubism2Model;\n"
  },
  {
    "path": "build/cubism2/utils/MatrixStack.d.ts",
    "content": "export default MatrixStack;\ndeclare class MatrixStack {\n    static reset(): void;\n    static loadIdentity(): void;\n    static push(): void;\n    static pop(): void;\n    static getMatrix(): number[];\n    static multMatrix(matNew: any): void;\n}\ndeclare namespace MatrixStack {\n    let depth: number;\n    let matrixStack: number[];\n    let currentMatrix: number[];\n    let tmp: any[];\n}\n"
  },
  {
    "path": "build/cubism2/utils/MatrixStack.js",
    "content": "class MatrixStack {\n    static reset() {\n        this.depth = 0;\n    }\n    static loadIdentity() {\n        for (let i = 0; i < 16; i++) {\n            this.currentMatrix[i] = i % 5 == 0 ? 1 : 0;\n        }\n    }\n    static push() {\n        const offset = this.depth * 16;\n        const nextOffset = (this.depth + 1) * 16;\n        if (this.matrixStack.length < nextOffset + 16) {\n            this.matrixStack.length = nextOffset + 16;\n        }\n        for (let i = 0; i < 16; i++) {\n            this.matrixStack[nextOffset + i] = this.currentMatrix[i];\n        }\n        this.depth++;\n    }\n    static pop() {\n        this.depth--;\n        if (this.depth < 0) {\n            this.depth = 0;\n        }\n        const offset = this.depth * 16;\n        for (let i = 0; i < 16; i++) {\n            this.currentMatrix[i] = this.matrixStack[offset + i];\n        }\n    }\n    static getMatrix() {\n        return this.currentMatrix;\n    }\n    static multMatrix(matNew) {\n        let i, j, k;\n        for (i = 0; i < 16; i++) {\n            this.tmp[i] = 0;\n        }\n        for (i = 0; i < 4; i++) {\n            for (j = 0; j < 4; j++) {\n                for (k = 0; k < 4; k++) {\n                    this.tmp[i + j * 4] +=\n                        this.currentMatrix[i + k * 4] * matNew[k + j * 4];\n                }\n            }\n        }\n        for (i = 0; i < 16; i++) {\n            this.currentMatrix[i] = this.tmp[i];\n        }\n    }\n}\nMatrixStack.matrixStack = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];\nMatrixStack.depth = 0;\nMatrixStack.currentMatrix = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];\nMatrixStack.tmp = new Array(16);\nexport default MatrixStack;\n"
  },
  {
    "path": "build/cubism2/utils/ModelSettingJson.d.ts",
    "content": "export default ModelSettingJson;\ndeclare class ModelSettingJson {\n    NAME: string;\n    ID: string;\n    MODEL: string;\n    TEXTURES: string;\n    HIT_AREAS: string;\n    HIT_AREAS_CUSTOM: string;\n    PHYSICS: string;\n    POSE: string;\n    EXPRESSIONS: string;\n    MOTION_GROUPS: string;\n    SOUND: string;\n    FADE_IN: string;\n    FADE_OUT: string;\n    LAYOUT: string;\n    INIT_PARAM: string;\n    INIT_PARTS_VISIBLE: string;\n    VALUE: string;\n    FILE: string;\n    json: {};\n    loadModelSetting(path: any, callback: any): void;\n    getTextureFile(n: any): any;\n    getModelFile(): any;\n    getTextureNum(): any;\n    getHitAreaNum(): any;\n    getHitAreaCustom(): any;\n    getHitAreaID(n: any): any;\n    getHitAreaName(n: any): any;\n    getPhysicsFile(): any;\n    getPoseFile(): any;\n    getExpressionNum(): any;\n    getExpressionFile(n: any): any;\n    getExpressionName(n: any): any;\n    getLayout(): any;\n    getInitParamNum(): any;\n    getMotionNum(name: any): any;\n    getMotionFile(name: any, n: any): any;\n    getMotionSound(name: any, n: any): any;\n    getMotionFadeIn(name: any, n: any): any;\n    getMotionFadeOut(name: any, n: any): any;\n    getInitParamID(n: any): any;\n    getInitParamValue(n: any): any;\n    getInitPartsVisibleNum(): any;\n    getInitPartsVisibleID(n: any): any;\n    getInitPartsVisibleValue(n: any): any;\n}\n"
  },
  {
    "path": "build/cubism2/utils/ModelSettingJson.js",
    "content": "import { Live2DFramework } from '../Live2DFramework.js';\nclass ModelSettingJson {\n    constructor() {\n        this.NAME = 'name';\n        this.ID = 'id';\n        this.MODEL = 'model';\n        this.TEXTURES = 'textures';\n        this.HIT_AREAS = 'hit_areas';\n        this.HIT_AREAS_CUSTOM = 'hit_areas_custom';\n        this.PHYSICS = 'physics';\n        this.POSE = 'pose';\n        this.EXPRESSIONS = 'expressions';\n        this.MOTION_GROUPS = 'motions';\n        this.SOUND = 'sound';\n        this.FADE_IN = 'fade_in';\n        this.FADE_OUT = 'fade_out';\n        this.LAYOUT = 'layout';\n        this.INIT_PARAM = 'init_param';\n        this.INIT_PARTS_VISIBLE = 'init_parts_visible';\n        this.VALUE = 'val';\n        this.FILE = 'file';\n        this.json = {};\n    }\n    loadModelSetting(path, callback) {\n        const pm = Live2DFramework.getPlatformManager();\n        pm.loadBytes(path, buf => {\n            const str = String.fromCharCode.apply(null, new Uint8Array(buf));\n            this.json = JSON.parse(str);\n            callback();\n        });\n    }\n    getTextureFile(n) {\n        if (this.json[this.TEXTURES] == null || this.json[this.TEXTURES][n] == null)\n            return null;\n        return this.json[this.TEXTURES][n];\n    }\n    getModelFile() {\n        return this.json[this.MODEL];\n    }\n    getTextureNum() {\n        if (this.json[this.TEXTURES] == null)\n            return 0;\n        return this.json[this.TEXTURES].length;\n    }\n    getHitAreaNum() {\n        if (this.json[this.HIT_AREAS] == null)\n            return 0;\n        return this.json[this.HIT_AREAS].length;\n    }\n    getHitAreaCustom() {\n        return this.json[this.HIT_AREAS_CUSTOM];\n    }\n    getHitAreaID(n) {\n        if (this.json[this.HIT_AREAS] == null ||\n            this.json[this.HIT_AREAS][n] == null)\n            return null;\n        return this.json[this.HIT_AREAS][n][this.ID];\n    }\n    getHitAreaName(n) {\n        if (this.json[this.HIT_AREAS] == null ||\n            this.json[this.HIT_AREAS][n] == null)\n            return null;\n        return this.json[this.HIT_AREAS][n][this.NAME];\n    }\n    getPhysicsFile() {\n        return this.json[this.PHYSICS];\n    }\n    getPoseFile() {\n        return this.json[this.POSE];\n    }\n    getExpressionNum() {\n        return this.json[this.EXPRESSIONS] == null\n            ? 0\n            : this.json[this.EXPRESSIONS].length;\n    }\n    getExpressionFile(n) {\n        if (this.json[this.EXPRESSIONS] == null)\n            return null;\n        return this.json[this.EXPRESSIONS][n][this.FILE];\n    }\n    getExpressionName(n) {\n        if (this.json[this.EXPRESSIONS] == null)\n            return null;\n        return this.json[this.EXPRESSIONS][n][this.NAME];\n    }\n    getLayout() {\n        return this.json[this.LAYOUT];\n    }\n    getInitParamNum() {\n        return this.json[this.INIT_PARAM] == null\n            ? 0\n            : this.json[this.INIT_PARAM].length;\n    }\n    getMotionNum(name) {\n        if (this.json[this.MOTION_GROUPS] == null ||\n            this.json[this.MOTION_GROUPS][name] == null)\n            return 0;\n        return this.json[this.MOTION_GROUPS][name].length;\n    }\n    getMotionFile(name, n) {\n        if (this.json[this.MOTION_GROUPS] == null ||\n            this.json[this.MOTION_GROUPS][name] == null ||\n            this.json[this.MOTION_GROUPS][name][n] == null)\n            return null;\n        return this.json[this.MOTION_GROUPS][name][n][this.FILE];\n    }\n    getMotionSound(name, n) {\n        if (this.json[this.MOTION_GROUPS] == null ||\n            this.json[this.MOTION_GROUPS][name] == null ||\n            this.json[this.MOTION_GROUPS][name][n] == null ||\n            this.json[this.MOTION_GROUPS][name][n][this.SOUND] == null)\n            return null;\n        return this.json[this.MOTION_GROUPS][name][n][this.SOUND];\n    }\n    getMotionFadeIn(name, n) {\n        if (this.json[this.MOTION_GROUPS] == null ||\n            this.json[this.MOTION_GROUPS][name] == null ||\n            this.json[this.MOTION_GROUPS][name][n] == null ||\n            this.json[this.MOTION_GROUPS][name][n][this.FADE_IN] == null)\n            return 1000;\n        return this.json[this.MOTION_GROUPS][name][n][this.FADE_IN];\n    }\n    getMotionFadeOut(name, n) {\n        if (this.json[this.MOTION_GROUPS] == null ||\n            this.json[this.MOTION_GROUPS][name] == null ||\n            this.json[this.MOTION_GROUPS][name][n] == null ||\n            this.json[this.MOTION_GROUPS][name][n][this.FADE_OUT] == null)\n            return 1000;\n        return this.json[this.MOTION_GROUPS][name][n][this.FADE_OUT];\n    }\n    getInitParamID(n) {\n        if (this.json[this.INIT_PARAM] == null ||\n            this.json[this.INIT_PARAM][n] == null)\n            return null;\n        return this.json[this.INIT_PARAM][n][this.ID];\n    }\n    getInitParamValue(n) {\n        if (this.json[this.INIT_PARAM] == null ||\n            this.json[this.INIT_PARAM][n] == null)\n            return NaN;\n        return this.json[this.INIT_PARAM][n][this.VALUE];\n    }\n    getInitPartsVisibleNum() {\n        return this.json[this.INIT_PARTS_VISIBLE] == null\n            ? 0\n            : this.json[this.INIT_PARTS_VISIBLE].length;\n    }\n    getInitPartsVisibleID(n) {\n        if (this.json[this.INIT_PARTS_VISIBLE] == null ||\n            this.json[this.INIT_PARTS_VISIBLE][n] == null)\n            return null;\n        return this.json[this.INIT_PARTS_VISIBLE][n][this.ID];\n    }\n    getInitPartsVisibleValue(n) {\n        if (this.json[this.INIT_PARTS_VISIBLE] == null ||\n            this.json[this.INIT_PARTS_VISIBLE][n] == null)\n            return NaN;\n        return this.json[this.INIT_PARTS_VISIBLE][n][this.VALUE];\n    }\n}\nexport default ModelSettingJson;\n"
  },
  {
    "path": "build/cubism5/index.d.ts",
    "content": "export class AppDelegate extends LAppDelegate {\n    _drawFrameId: number;\n    stop(): void;\n    transformOffset(e: any): {\n        x: number;\n        y: number;\n    };\n    onMouseMove(e: any): void;\n    onMouseEnd(e: any): void;\n    onTap(e: any): void;\n    mouseMoveEventListener: any;\n    mouseEndedEventListener: any;\n    tapEventListener: any;\n    changeModel(modelSettingPath: string): void;\n    get subdelegates(): import(\"@framework/type/csmvector.js\").csmVector<LAppSubdelegate>;\n}\nimport { LAppDelegate } from '@demo/lappdelegate.js';\nimport { LAppSubdelegate } from '@demo/lappsubdelegate.js';\n"
  },
  {
    "path": "build/cubism5/index.js",
    "content": "import { LAppDelegate } from '@demo/lappdelegate.js';\nimport { LAppSubdelegate } from '@demo/lappsubdelegate.js';\nimport * as LAppDefine from '@demo/lappdefine.js';\nimport { LAppModel } from '@demo/lappmodel.js';\nimport { LAppPal } from '@demo/lapppal';\nimport logger from '../logger.js';\nLAppPal.printMessage = () => { };\nclass AppSubdelegate extends LAppSubdelegate {\n    initialize(canvas) {\n        if (!this._glManager.initialize(canvas)) {\n            return false;\n        }\n        this._canvas = canvas;\n        if (LAppDefine.CanvasSize === 'auto') {\n            this.resizeCanvas();\n        }\n        else {\n            canvas.width = LAppDefine.CanvasSize.width;\n            canvas.height = LAppDefine.CanvasSize.height;\n        }\n        this._textureManager.setGlManager(this._glManager);\n        const gl = this._glManager.getGl();\n        if (!this._frameBuffer) {\n            this._frameBuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);\n        }\n        gl.enable(gl.BLEND);\n        gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);\n        this._view.initialize(this);\n        this._view._gear = {\n            render: () => { },\n            isHit: () => { },\n            release: () => { }\n        };\n        this._view._back = {\n            render: () => { },\n            release: () => { }\n        };\n        this._live2dManager._subdelegate = this;\n        this._resizeObserver = new window.ResizeObserver((entries, observer) => this.resizeObserverCallback.call(this, entries, observer));\n        this._resizeObserver.observe(this._canvas);\n        return true;\n    }\n    onResize() {\n        this.resizeCanvas();\n        this._view.initialize(this);\n    }\n    update() {\n        if (this._glManager.getGl().isContextLost()) {\n            return;\n        }\n        if (this._needResize) {\n            this.onResize();\n            this._needResize = false;\n        }\n        const gl = this._glManager.getGl();\n        gl.clearColor(0.0, 0.0, 0.0, 0.0);\n        gl.enable(gl.DEPTH_TEST);\n        gl.depthFunc(gl.LEQUAL);\n        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n        gl.clearDepth(1.0);\n        gl.enable(gl.BLEND);\n        gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);\n        this._view.render();\n    }\n}\nexport class AppDelegate extends LAppDelegate {\n    run() {\n        const loop = () => {\n            LAppPal.updateTime();\n            for (let i = 0; i < this._subdelegates.getSize(); i++) {\n                this._subdelegates.at(i).update();\n            }\n            this._drawFrameId = window.requestAnimationFrame(loop);\n        };\n        loop();\n    }\n    stop() {\n        if (this._drawFrameId) {\n            window.cancelAnimationFrame(this._drawFrameId);\n            this._drawFrameId = null;\n        }\n    }\n    release() {\n        this.stop();\n        this.releaseEventListener();\n        this._subdelegates.clear();\n        this._cubismOption = null;\n    }\n    transformOffset(e) {\n        const subdelegate = this._subdelegates.at(0);\n        const rect = subdelegate.getCanvas().getBoundingClientRect();\n        const localX = e.pageX - rect.left;\n        const localY = e.pageY - rect.top;\n        const posX = localX * window.devicePixelRatio;\n        const posY = localY * window.devicePixelRatio;\n        const x = subdelegate._view.transformViewX(posX);\n        const y = subdelegate._view.transformViewY(posY);\n        return {\n            x, y\n        };\n    }\n    onMouseMove(e) {\n        const lapplive2dmanager = this._subdelegates.at(0).getLive2DManager();\n        const { x, y } = this.transformOffset(e);\n        const model = lapplive2dmanager._models.at(0);\n        lapplive2dmanager.onDrag(x, y);\n        lapplive2dmanager.onTap(x, y);\n        if (model.hitTest(LAppDefine.HitAreaNameBody, x, y)) {\n            window.dispatchEvent(new Event('live2d:hoverbody'));\n        }\n    }\n    onMouseEnd(e) {\n        const lapplive2dmanager = this._subdelegates.at(0).getLive2DManager();\n        const { x, y } = this.transformOffset(e);\n        lapplive2dmanager.onDrag(0.0, 0.0);\n        lapplive2dmanager.onTap(x, y);\n    }\n    onTap(e) {\n        const lapplive2dmanager = this._subdelegates.at(0).getLive2DManager();\n        const { x, y } = this.transformOffset(e);\n        const model = lapplive2dmanager._models.at(0);\n        if (model.hitTest(LAppDefine.HitAreaNameBody, x, y)) {\n            window.dispatchEvent(new Event('live2d:tapbody'));\n        }\n    }\n    initializeEventListener() {\n        this.mouseMoveEventListener = this.onMouseMove.bind(this);\n        this.mouseEndedEventListener = this.onMouseEnd.bind(this);\n        this.tapEventListener = this.onTap.bind(this);\n        document.addEventListener('mousemove', this.mouseMoveEventListener, {\n            passive: true\n        });\n        document.addEventListener('mouseout', this.mouseEndedEventListener, {\n            passive: true\n        });\n        document.addEventListener('pointerdown', this.tapEventListener, {\n            passive: true\n        });\n    }\n    releaseEventListener() {\n        document.removeEventListener('mousemove', this.mouseMoveEventListener, {\n            passive: true\n        });\n        this.mouseMoveEventListener = null;\n        document.removeEventListener('mouseout', this.mouseEndedEventListener, {\n            passive: true\n        });\n        this.mouseEndedEventListener = null;\n        document.removeEventListener('pointerdown', this.tapEventListener, {\n            passive: true\n        });\n    }\n    initializeSubdelegates() {\n        this._canvases.prepareCapacity(LAppDefine.CanvasNum);\n        this._subdelegates.prepareCapacity(LAppDefine.CanvasNum);\n        const canvas = document.getElementById('live2d');\n        this._canvases.pushBack(canvas);\n        canvas.style.width = canvas.width;\n        canvas.style.height = canvas.height;\n        for (let i = 0; i < this._canvases.getSize(); i++) {\n            const subdelegate = new AppSubdelegate();\n            const result = subdelegate.initialize(this._canvases.at(i));\n            if (!result) {\n                logger.error('Failed to initialize AppSubdelegate');\n                return;\n            }\n            this._subdelegates.pushBack(subdelegate);\n        }\n        for (let i = 0; i < LAppDefine.CanvasNum; i++) {\n            if (this._subdelegates.at(i).isContextLost()) {\n                logger.error(`The context for Canvas at index ${i} was lost, possibly because the acquisition limit for WebGLRenderingContext was reached.`);\n            }\n        }\n    }\n    changeModel(modelSettingPath) {\n        const segments = modelSettingPath.split('/');\n        const modelJsonName = segments.pop();\n        const modelPath = segments.join('/') + '/';\n        const live2dManager = this._subdelegates.at(0).getLive2DManager();\n        live2dManager.releaseAllModel();\n        const instance = new LAppModel();\n        instance.setSubdelegate(live2dManager._subdelegate);\n        instance.loadAssets(modelPath, modelJsonName);\n        live2dManager._models.pushBack(instance);\n    }\n    get subdelegates() {\n        return this._subdelegates;\n    }\n}\n"
  },
  {
    "path": "build/drag.d.ts",
    "content": "declare function registerDrag(): void;\nexport default registerDrag;\n"
  },
  {
    "path": "build/drag.js",
    "content": "function registerDrag() {\n    const element = document.getElementById('waifu');\n    if (!element)\n        return;\n    let winWidth = window.innerWidth, winHeight = window.innerHeight;\n    const imgWidth = element.offsetWidth, imgHeight = element.offsetHeight;\n    element.addEventListener('mousedown', event => {\n        if (event.button === 2) {\n            return;\n        }\n        const canvas = document.getElementById('live2d');\n        if (event.target !== canvas)\n            return;\n        event.preventDefault();\n        const _offsetX = event.offsetX, _offsetY = event.offsetY;\n        document.onmousemove = event => {\n            const _x = event.clientX, _y = event.clientY;\n            let _left = _x - _offsetX, _top = _y - _offsetY;\n            if (_top < 0) {\n                _top = 0;\n            }\n            else if (_top >= winHeight - imgHeight) {\n                _top = winHeight - imgHeight;\n            }\n            if (_left < 0) {\n                _left = 0;\n            }\n            else if (_left >= winWidth - imgWidth) {\n                _left = winWidth - imgWidth;\n            }\n            element.style.top = _top + 'px';\n            element.style.left = _left + 'px';\n        };\n        document.onmouseup = () => {\n            document.onmousemove = null;\n        };\n    });\n    window.onresize = () => {\n        winWidth = window.innerWidth;\n        winHeight = window.innerHeight;\n    };\n}\nexport default registerDrag;\n"
  },
  {
    "path": "build/icons.d.ts",
    "content": "declare const fa_comment = \"<svg xmlns=\\\"http://www.w3.org/2000/svg\\\" viewBox=\\\"0 0 512 512\\\"><!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --><path d=\\\"M512 240c0 114.9-114.6 208-256 208c-37.1 0-72.3-6.4-104.1-17.9c-11.9 8.7-31.3 20.6-54.3 30.6C73.6 471.1 44.7 480 16 480c-6.5 0-12.3-3.9-14.8-9.9c-2.5-6-1.1-12.8 3.4-17.4c0 0 0 0 0 0s0 0 0 0s0 0 0 0c0 0 0 0 0 0l.3-.3c.3-.3 .7-.7 1.3-1.4c1.1-1.2 2.8-3.1 4.9-5.7c4.1-5 9.6-12.4 15.2-21.6c10-16.6 19.5-38.4 21.4-62.9C17.7 326.8 0 285.1 0 240C0 125.1 114.6 32 256 32s256 93.1 256 208z\\\"/></svg>\";\ndeclare const fa_paper_plane = \"<svg xmlns=\\\"http://www.w3.org/2000/svg\\\" viewBox=\\\"0 0 512 512\\\"><!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --><path d=\\\"M498.1 5.6c10.1 7 15.4 19.1 13.5 31.2l-64 416c-1.5 9.7-7.4 18.2-16 23s-18.9 5.4-28 1.6L284 427.7l-68.5 74.1c-8.9 9.7-22.9 12.9-35.2 8.1S160 493.2 160 480l0-83.6c0-4 1.5-7.8 4.2-10.8L331.8 202.8c5.8-6.3 5.6-16-.4-22s-15.7-6.4-22-.7L106 360.8 17.7 316.6C7.1 311.3 .3 300.7 0 288.9s5.9-22.8 16.1-28.7l448-256c10.7-6.1 23.9-5.5 34 1.4z\\\"/></svg>\";\ndeclare const fa_street_view = \"<svg xmlns=\\\"http://www.w3.org/2000/svg\\\" viewBox=\\\"0 0 512 512\\\"><!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --><path d=\\\"M320 64A64 64 0 1 0 192 64a64 64 0 1 0 128 0zm-96 96c-35.3 0-64 28.7-64 64l0 48c0 17.7 14.3 32 32 32l1.8 0 11.1 99.5c1.8 16.2 15.5 28.5 31.8 28.5l38.7 0c16.3 0 30-12.3 31.8-28.5L318.2 304l1.8 0c17.7 0 32-14.3 32-32l0-48c0-35.3-28.7-64-64-64l-64 0zM132.3 394.2c13-2.4 21.7-14.9 19.3-27.9s-14.9-21.7-27.9-19.3c-32.4 5.9-60.9 14.2-82 24.8c-10.5 5.3-20.3 11.7-27.8 19.6C6.4 399.5 0 410.5 0 424c0 21.4 15.5 36.1 29.1 45c14.7 9.6 34.3 17.3 56.4 23.4C130.2 504.7 190.4 512 256 512s125.8-7.3 170.4-19.6c22.1-6.1 41.8-13.8 56.4-23.4c13.7-8.9 29.1-23.6 29.1-45c0-13.5-6.4-24.5-14-32.6c-7.5-7.9-17.3-14.3-27.8-19.6c-21-10.6-49.5-18.9-82-24.8c-13-2.4-25.5 6.3-27.9 19.3s6.3 25.5 19.3 27.9c30.2 5.5 53.7 12.8 69 20.5c3.2 1.6 5.8 3.1 7.9 4.5c3.6 2.4 3.6 7.2 0 9.6c-8.8 5.7-23.1 11.8-43 17.3C374.3 457 318.5 464 256 464s-118.3-7-157.7-17.9c-19.9-5.5-34.2-11.6-43-17.3c-3.6-2.4-3.6-7.2 0-9.6c2.1-1.4 4.8-2.9 7.9-4.5c15.3-7.7 38.8-14.9 69-20.5z\\\"/></svg>\";\ndeclare const fa_shirt = \"<svg xmlns=\\\"http://www.w3.org/2000/svg\\\" viewBox=\\\"0 0 640 512\\\"><!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --><path d=\\\"M211.8 0c7.8 0 14.3 5.7 16.7 13.2C240.8 51.9 277.1 80 320 80s79.2-28.1 91.5-66.8C413.9 5.7 420.4 0 428.2 0l12.6 0c22.5 0 44.2 7.9 61.5 22.3L628.5 127.4c6.6 5.5 10.7 13.5 11.4 22.1s-2.1 17.1-7.8 23.6l-56 64c-11.4 13.1-31.2 14.6-44.6 3.5L480 197.7 480 448c0 35.3-28.7 64-64 64l-192 0c-35.3 0-64-28.7-64-64l0-250.3-51.5 42.9c-13.3 11.1-33.1 9.6-44.6-3.5l-56-64c-5.7-6.5-8.5-15-7.8-23.6s4.8-16.6 11.4-22.1L137.7 22.3C155 7.9 176.7 0 199.2 0l12.6 0z\\\"/></svg>\";\ndeclare const fa_camera_retro = \"<svg xmlns=\\\"http://www.w3.org/2000/svg\\\" viewBox=\\\"0 0 512 512\\\"><!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --><path d=\\\"M220.6 121.2L271.1 96 448 96l0 96-114.8 0c-21.9-15.1-48.5-24-77.2-24s-55.2 8.9-77.2 24L64 192l0-64 128 0c9.9 0 19.7-2.3 28.6-6.8zM0 128L0 416c0 35.3 28.7 64 64 64l384 0c35.3 0 64-28.7 64-64l0-320c0-35.3-28.7-64-64-64L271.1 32c-9.9 0-19.7 2.3-28.6 6.8L192 64l-32 0 0-16c0-8.8-7.2-16-16-16L80 32c-8.8 0-16 7.2-16 16l0 16C28.7 64 0 92.7 0 128zM168 304a88 88 0 1 1 176 0 88 88 0 1 1 -176 0z\\\"/></svg>\";\ndeclare const fa_info_circle = \"<svg xmlns=\\\"http://www.w3.org/2000/svg\\\" viewBox=\\\"0 0 512 512\\\"><!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --><path d=\\\"M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM216 336l24 0 0-64-24 0c-13.3 0-24-10.7-24-24s10.7-24 24-24l48 0c13.3 0 24 10.7 24 24l0 88 8 0c13.3 0 24 10.7 24 24s-10.7 24-24 24l-80 0c-13.3 0-24-10.7-24-24s10.7-24 24-24zm40-208a32 32 0 1 1 0 64 32 32 0 1 1 0-64z\\\"/></svg>\";\ndeclare const fa_xmark = \"<svg xmlns=\\\"http://www.w3.org/2000/svg\\\" viewBox=\\\"0 0 384 512\\\"><!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --><path d=\\\"M342.6 150.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L192 210.7 86.6 105.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L146.7 256 41.4 361.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0L192 301.3 297.4 406.6c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L237.3 256 342.6 150.6z\\\"/></svg>\";\ndeclare const fa_child = \"<svg xmlns=\\\"http://www.w3.org/2000/svg\\\" viewBox=\\\"0 0 320 512\\\"><!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --><path d=\\\"M96 64a64 64 0 1 1 128 0A64 64 0 1 1 96 64zm48 320l0 96c0 17.7-14.3 32-32 32s-32-14.3-32-32l0-192.2L59.1 321c-9.4 15-29.2 19.4-44.1 10S-4.5 301.9 4.9 287l39.9-63.3C69.7 184 113.2 160 160 160s90.3 24 115.2 63.6L315.1 287c9.4 15 4.9 34.7-10 44.1s-34.7 4.9-44.1-10L240 287.8 240 480c0 17.7-14.3 32-32 32s-32-14.3-32-32l0-96-32 0z\\\"/></svg>\";\nexport { fa_comment, fa_paper_plane, fa_street_view, fa_shirt, fa_camera_retro, fa_info_circle, fa_xmark, fa_child };\n"
  },
  {
    "path": "build/icons.js",
    "content": "const fa_comment = '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 512 512\"><!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --><path d=\"M512 240c0 114.9-114.6 208-256 208c-37.1 0-72.3-6.4-104.1-17.9c-11.9 8.7-31.3 20.6-54.3 30.6C73.6 471.1 44.7 480 16 480c-6.5 0-12.3-3.9-14.8-9.9c-2.5-6-1.1-12.8 3.4-17.4c0 0 0 0 0 0s0 0 0 0s0 0 0 0c0 0 0 0 0 0l.3-.3c.3-.3 .7-.7 1.3-1.4c1.1-1.2 2.8-3.1 4.9-5.7c4.1-5 9.6-12.4 15.2-21.6c10-16.6 19.5-38.4 21.4-62.9C17.7 326.8 0 285.1 0 240C0 125.1 114.6 32 256 32s256 93.1 256 208z\"/></svg>';\nconst fa_paper_plane = '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 512 512\"><!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --><path d=\"M498.1 5.6c10.1 7 15.4 19.1 13.5 31.2l-64 416c-1.5 9.7-7.4 18.2-16 23s-18.9 5.4-28 1.6L284 427.7l-68.5 74.1c-8.9 9.7-22.9 12.9-35.2 8.1S160 493.2 160 480l0-83.6c0-4 1.5-7.8 4.2-10.8L331.8 202.8c5.8-6.3 5.6-16-.4-22s-15.7-6.4-22-.7L106 360.8 17.7 316.6C7.1 311.3 .3 300.7 0 288.9s5.9-22.8 16.1-28.7l448-256c10.7-6.1 23.9-5.5 34 1.4z\"/></svg>';\nconst fa_street_view = '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 512 512\"><!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --><path d=\"M320 64A64 64 0 1 0 192 64a64 64 0 1 0 128 0zm-96 96c-35.3 0-64 28.7-64 64l0 48c0 17.7 14.3 32 32 32l1.8 0 11.1 99.5c1.8 16.2 15.5 28.5 31.8 28.5l38.7 0c16.3 0 30-12.3 31.8-28.5L318.2 304l1.8 0c17.7 0 32-14.3 32-32l0-48c0-35.3-28.7-64-64-64l-64 0zM132.3 394.2c13-2.4 21.7-14.9 19.3-27.9s-14.9-21.7-27.9-19.3c-32.4 5.9-60.9 14.2-82 24.8c-10.5 5.3-20.3 11.7-27.8 19.6C6.4 399.5 0 410.5 0 424c0 21.4 15.5 36.1 29.1 45c14.7 9.6 34.3 17.3 56.4 23.4C130.2 504.7 190.4 512 256 512s125.8-7.3 170.4-19.6c22.1-6.1 41.8-13.8 56.4-23.4c13.7-8.9 29.1-23.6 29.1-45c0-13.5-6.4-24.5-14-32.6c-7.5-7.9-17.3-14.3-27.8-19.6c-21-10.6-49.5-18.9-82-24.8c-13-2.4-25.5 6.3-27.9 19.3s6.3 25.5 19.3 27.9c30.2 5.5 53.7 12.8 69 20.5c3.2 1.6 5.8 3.1 7.9 4.5c3.6 2.4 3.6 7.2 0 9.6c-8.8 5.7-23.1 11.8-43 17.3C374.3 457 318.5 464 256 464s-118.3-7-157.7-17.9c-19.9-5.5-34.2-11.6-43-17.3c-3.6-2.4-3.6-7.2 0-9.6c2.1-1.4 4.8-2.9 7.9-4.5c15.3-7.7 38.8-14.9 69-20.5z\"/></svg>';\nconst fa_shirt = '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 640 512\"><!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --><path d=\"M211.8 0c7.8 0 14.3 5.7 16.7 13.2C240.8 51.9 277.1 80 320 80s79.2-28.1 91.5-66.8C413.9 5.7 420.4 0 428.2 0l12.6 0c22.5 0 44.2 7.9 61.5 22.3L628.5 127.4c6.6 5.5 10.7 13.5 11.4 22.1s-2.1 17.1-7.8 23.6l-56 64c-11.4 13.1-31.2 14.6-44.6 3.5L480 197.7 480 448c0 35.3-28.7 64-64 64l-192 0c-35.3 0-64-28.7-64-64l0-250.3-51.5 42.9c-13.3 11.1-33.1 9.6-44.6-3.5l-56-64c-5.7-6.5-8.5-15-7.8-23.6s4.8-16.6 11.4-22.1L137.7 22.3C155 7.9 176.7 0 199.2 0l12.6 0z\"/></svg>';\nconst fa_camera_retro = '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 512 512\"><!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --><path d=\"M220.6 121.2L271.1 96 448 96l0 96-114.8 0c-21.9-15.1-48.5-24-77.2-24s-55.2 8.9-77.2 24L64 192l0-64 128 0c9.9 0 19.7-2.3 28.6-6.8zM0 128L0 416c0 35.3 28.7 64 64 64l384 0c35.3 0 64-28.7 64-64l0-320c0-35.3-28.7-64-64-64L271.1 32c-9.9 0-19.7 2.3-28.6 6.8L192 64l-32 0 0-16c0-8.8-7.2-16-16-16L80 32c-8.8 0-16 7.2-16 16l0 16C28.7 64 0 92.7 0 128zM168 304a88 88 0 1 1 176 0 88 88 0 1 1 -176 0z\"/></svg>';\nconst fa_info_circle = '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 512 512\"><!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --><path d=\"M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM216 336l24 0 0-64-24 0c-13.3 0-24-10.7-24-24s10.7-24 24-24l48 0c13.3 0 24 10.7 24 24l0 88 8 0c13.3 0 24 10.7 24 24s-10.7 24-24 24l-80 0c-13.3 0-24-10.7-24-24s10.7-24 24-24zm40-208a32 32 0 1 1 0 64 32 32 0 1 1 0-64z\"/></svg>';\nconst fa_xmark = '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 384 512\"><!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --><path d=\"M342.6 150.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L192 210.7 86.6 105.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L146.7 256 41.4 361.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0L192 301.3 297.4 406.6c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L237.3 256 342.6 150.6z\"/></svg>';\nconst fa_child = '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 320 512\"><!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --><path d=\"M96 64a64 64 0 1 1 128 0A64 64 0 1 1 96 64zm48 320l0 96c0 17.7-14.3 32-32 32s-32-14.3-32-32l0-192.2L59.1 321c-9.4 15-29.2 19.4-44.1 10S-4.5 301.9 4.9 287l39.9-63.3C69.7 184 113.2 160 160 160s90.3 24 115.2 63.6L315.1 287c9.4 15 4.9 34.7-10 44.1s-34.7 4.9-44.1-10L240 287.8 240 480c0 17.7-14.3 32-32 32s-32-14.3-32-32l0-96-32 0z\"/></svg>';\nexport { fa_comment, fa_paper_plane, fa_street_view, fa_shirt, fa_camera_retro, fa_info_circle, fa_xmark, fa_child };\n"
  },
  {
    "path": "build/index.d.ts",
    "content": "export { default as registerDrag } from './drag.js';\nexport { default as logger, LogLevel } from './logger.js';\nexport { default as Cubism2Model } from './cubism2/index.js';\nexport * from './tools.js';\nexport * from './message.js';\nexport * from './model.js';\nexport * from './utils.js';\nexport * from './widget.js';\n"
  },
  {
    "path": "build/index.js",
    "content": "export { default as registerDrag } from './drag.js';\nexport { default as logger } from './logger.js';\nexport { default as Cubism2Model } from './cubism2/index.js';\nexport * from './tools.js';\nexport * from './message.js';\nexport * from './model.js';\nexport * from './utils.js';\nexport * from './widget.js';\n"
  },
  {
    "path": "build/logger.d.ts",
    "content": "type LogLevel = 'error' | 'warn' | 'info' | 'trace';\ndeclare class Logger {\n    private static levelOrder;\n    private level;\n    constructor(level?: LogLevel);\n    setLevel(level: LogLevel | undefined): void;\n    private shouldLog;\n    error(message: string, ...args: any[]): void;\n    warn(message: string, ...args: any[]): void;\n    info(message: string, ...args: any[]): void;\n    trace(message: string, ...args: any[]): void;\n}\ndeclare const logger: Logger;\nexport default logger;\nexport { LogLevel };\n"
  },
  {
    "path": "build/logger.js",
    "content": "class Logger {\n    constructor(level = 'info') {\n        this.level = level;\n    }\n    setLevel(level) {\n        if (!level)\n            return;\n        this.level = level;\n    }\n    shouldLog(level) {\n        return Logger.levelOrder[level] <= Logger.levelOrder[this.level];\n    }\n    error(message, ...args) {\n        if (this.shouldLog('error')) {\n            console.error('[Live2D Widget][ERROR]', message, ...args);\n        }\n    }\n    warn(message, ...args) {\n        if (this.shouldLog('warn')) {\n            console.warn('[Live2D Widget][WARN]', message, ...args);\n        }\n    }\n    info(message, ...args) {\n        if (this.shouldLog('info')) {\n            console.log('[Live2D Widget][INFO]', message, ...args);\n        }\n    }\n    trace(message, ...args) {\n        if (this.shouldLog('trace')) {\n            console.log('[Live2D Widget][TRACE]', message, ...args);\n        }\n    }\n}\nLogger.levelOrder = {\n    error: 0,\n    warn: 1,\n    info: 2,\n    trace: 3,\n};\nconst logger = new Logger();\nexport default logger;\n"
  },
  {
    "path": "build/message.d.ts",
    "content": "type Time = {\n    hour: string;\n    text: string;\n}[];\ndeclare function showMessage(text: string | string[], timeout: number, priority: number, override?: boolean): void;\ndeclare function welcomeMessage(time: Time, welcomeTemplate?: string, referrerTemplate?: string): string;\ndeclare function i18n(template: string, ...args: string[]): string;\nexport { showMessage, welcomeMessage, i18n, Time };\n"
  },
  {
    "path": "build/message.js",
    "content": "import { randomSelection } from './utils.js';\nlet messageTimer = null;\nfunction showMessage(text, timeout, priority, override = true) {\n    let currentPriority = parseInt(sessionStorage.getItem('waifu-message-priority'), 10);\n    if (isNaN(currentPriority)) {\n        currentPriority = 0;\n    }\n    if (!text ||\n        (override && currentPriority > priority) ||\n        (!override && currentPriority >= priority))\n        return;\n    if (messageTimer) {\n        clearTimeout(messageTimer);\n        messageTimer = null;\n    }\n    text = randomSelection(text);\n    sessionStorage.setItem('waifu-message-priority', String(priority));\n    const tips = document.getElementById('waifu-tips');\n    tips.innerHTML = text;\n    tips.classList.add('waifu-tips-active');\n    messageTimer = setTimeout(() => {\n        sessionStorage.removeItem('waifu-message-priority');\n        tips.classList.remove('waifu-tips-active');\n    }, timeout);\n}\nfunction welcomeMessage(time, welcomeTemplate, referrerTemplate) {\n    if (location.pathname === '/') {\n        for (const { hour, text } of time) {\n            const now = new Date(), after = hour.split('-')[0], before = hour.split('-')[1] || after;\n            if (Number(after) <= now.getHours() &&\n                now.getHours() <= Number(before)) {\n                return text;\n            }\n        }\n    }\n    if (!welcomeTemplate)\n        return '';\n    const text = i18n(welcomeTemplate, document.title);\n    if (document.referrer === '' || !referrerTemplate)\n        return text;\n    const referrer = new URL(document.referrer);\n    if (location.hostname === referrer.hostname)\n        return text;\n    return `${i18n(referrerTemplate, referrer.hostname)}<br>${text}`;\n}\nfunction i18n(template, ...args) {\n    return template.replace(/\\$(\\d+)/g, (_, idx) => {\n        var _b;\n        const i = parseInt(idx, 10) - 1;\n        return (_b = args[i]) !== null && _b !== void 0 ? _b : '';\n    });\n}\nexport { showMessage, welcomeMessage, i18n };\n"
  },
  {
    "path": "build/model.d.ts",
    "content": "import { LogLevel } from './logger.js';\ninterface ModelList {\n    name: string;\n    paths: string[];\n    message: string;\n}\ninterface Config {\n    waifuPath: string;\n    apiPath?: string;\n    cdnPath?: string;\n    cubism2Path?: string;\n    cubism5Path?: string;\n    modelId?: number;\n    tools?: string[];\n    drag?: boolean;\n    logLevel?: LogLevel;\n}\ndeclare class ModelManager {\n    readonly useCDN: boolean;\n    private readonly cdnPath;\n    private readonly cubism2Path;\n    private readonly cubism5Path;\n    private _modelId;\n    private _modelTexturesId;\n    private modelList;\n    private cubism2model;\n    private cubism5model;\n    private currentModelVersion;\n    private loading;\n    private modelJSONCache;\n    private models;\n    private constructor();\n    static initCheck(config: Config, models?: ModelList[]): Promise<ModelManager>;\n    set modelId(modelId: number);\n    get modelId(): number;\n    set modelTexturesId(modelTexturesId: number);\n    get modelTexturesId(): number;\n    resetCanvas(): void;\n    fetchWithCache(url: string): Promise<any>;\n    checkModelVersion(modelSetting: any): 2 | 3;\n    loadLive2D(modelSettingPath: string, modelSetting: object): Promise<void>;\n    loadTextureCache(modelName: string): Promise<any[]>;\n    loadModel(message: string | string[]): Promise<void>;\n    loadRandTexture(successMessage?: string | string[], failMessage?: string | string[]): Promise<void>;\n    loadNextModel(): Promise<void>;\n}\nexport { ModelManager, Config, ModelList };\n"
  },
  {
    "path": "build/model.js",
    "content": "import { showMessage } from './message.js';\nimport { loadExternalResource, randomOtherOption } from './utils.js';\nimport logger from './logger.js';\nclass ModelManager {\n    constructor(config, models = []) {\n        var _b;\n        this.modelList = null;\n        let { apiPath, cdnPath } = config;\n        const { cubism2Path, cubism5Path } = config;\n        let useCDN = false;\n        if (typeof cdnPath === 'string') {\n            if (!cdnPath.endsWith('/'))\n                cdnPath += '/';\n            useCDN = true;\n        }\n        else if (typeof apiPath === 'string') {\n            if (!apiPath.endsWith('/'))\n                apiPath += '/';\n            cdnPath = apiPath;\n            useCDN = true;\n            logger.warn('apiPath option is deprecated. Please use cdnPath instead.');\n        }\n        else if (!models.length) {\n            throw 'Invalid initWidget argument!';\n        }\n        let modelId = parseInt(localStorage.getItem('modelId'), 10);\n        let modelTexturesId = parseInt(localStorage.getItem('modelTexturesId'), 10);\n        if (isNaN(modelId) || isNaN(modelTexturesId)) {\n            modelTexturesId = 0;\n        }\n        if (isNaN(modelId)) {\n            modelId = (_b = config.modelId) !== null && _b !== void 0 ? _b : 0;\n        }\n        this.useCDN = useCDN;\n        this.cdnPath = cdnPath || '';\n        this.cubism2Path = cubism2Path || '';\n        this.cubism5Path = cubism5Path || '';\n        this._modelId = modelId;\n        this._modelTexturesId = modelTexturesId;\n        this.currentModelVersion = 0;\n        this.loading = false;\n        this.modelJSONCache = {};\n        this.models = models;\n    }\n    static async initCheck(config, models = []) {\n        const model = new ModelManager(config, models);\n        if (model.useCDN) {\n            const response = await fetch(`${model.cdnPath}model_list.json`);\n            model.modelList = await response.json();\n            if (model.modelId >= model.modelList.models.length) {\n                model.modelId = 0;\n            }\n            const modelName = model.modelList.models[model.modelId];\n            if (Array.isArray(modelName)) {\n                if (model.modelTexturesId >= modelName.length) {\n                    model.modelTexturesId = 0;\n                }\n            }\n            else {\n                const modelSettingPath = `${model.cdnPath}model/${modelName}/index.json`;\n                const modelSetting = await model.fetchWithCache(modelSettingPath);\n                const version = model.checkModelVersion(modelSetting);\n                if (version === 2) {\n                    const textureCache = await model.loadTextureCache(modelName);\n                    if (model.modelTexturesId >= textureCache.length) {\n                        model.modelTexturesId = 0;\n                    }\n                }\n            }\n        }\n        else {\n            if (model.modelId >= model.models.length) {\n                model.modelId = 0;\n            }\n            if (model.modelTexturesId >= model.models[model.modelId].paths.length) {\n                model.modelTexturesId = 0;\n            }\n        }\n        return model;\n    }\n    set modelId(modelId) {\n        this._modelId = modelId;\n        localStorage.setItem('modelId', modelId.toString());\n    }\n    get modelId() {\n        return this._modelId;\n    }\n    set modelTexturesId(modelTexturesId) {\n        this._modelTexturesId = modelTexturesId;\n        localStorage.setItem('modelTexturesId', modelTexturesId.toString());\n    }\n    get modelTexturesId() {\n        return this._modelTexturesId;\n    }\n    resetCanvas() {\n        document.getElementById('waifu-canvas').innerHTML = '<canvas id=\"live2d\" width=\"800\" height=\"800\"></canvas>';\n    }\n    async fetchWithCache(url) {\n        let result;\n        if (url in this.modelJSONCache) {\n            result = this.modelJSONCache[url];\n        }\n        else {\n            try {\n                const response = await fetch(url);\n                result = await response.json();\n            }\n            catch (_b) {\n                result = null;\n            }\n            this.modelJSONCache[url] = result;\n        }\n        return result;\n    }\n    checkModelVersion(modelSetting) {\n        if (modelSetting.Version === 3 || modelSetting.FileReferences) {\n            return 3;\n        }\n        return 2;\n    }\n    async loadLive2D(modelSettingPath, modelSetting) {\n        if (this.loading) {\n            logger.warn('Still loading. Abort.');\n            return;\n        }\n        this.loading = true;\n        try {\n            const version = this.checkModelVersion(modelSetting);\n            if (version === 2) {\n                if (!this.cubism2model) {\n                    if (!this.cubism2Path) {\n                        logger.error('No cubism2Path set, cannot load Cubism 2 Core.');\n                        return;\n                    }\n                    await loadExternalResource(this.cubism2Path, 'js');\n                    const { default: Cubism2Model } = await import('./cubism2/index.js');\n                    this.cubism2model = new Cubism2Model();\n                }\n                if (this.currentModelVersion === 3) {\n                    this.cubism5model.release();\n                    this.resetCanvas();\n                }\n                if (this.currentModelVersion === 3 || !this.cubism2model.gl) {\n                    await this.cubism2model.init('live2d', modelSettingPath, modelSetting);\n                }\n                else {\n                    await this.cubism2model.changeModelWithJSON(modelSettingPath, modelSetting);\n                }\n            }\n            else {\n                if (!this.cubism5Path) {\n                    logger.error('No cubism5Path set, cannot load Cubism 5 Core.');\n                    return;\n                }\n                await loadExternalResource(this.cubism5Path, 'js');\n                const { AppDelegate: Cubism5Model } = await import('./cubism5/index.js');\n                this.cubism5model = new Cubism5Model();\n                if (this.currentModelVersion === 2) {\n                    this.cubism2model.destroy();\n                    this.resetCanvas();\n                }\n                if (this.currentModelVersion === 2 || !this.cubism5model.subdelegates.at(0)) {\n                    this.cubism5model.initialize();\n                    this.cubism5model.changeModel(modelSettingPath);\n                    this.cubism5model.run();\n                }\n                else {\n                    this.cubism5model.changeModel(modelSettingPath);\n                }\n            }\n            logger.info(`Model ${modelSettingPath} (Cubism version ${version}) loaded`);\n            this.currentModelVersion = version;\n        }\n        catch (err) {\n            console.error('loadLive2D failed', err);\n        }\n        this.loading = false;\n    }\n    async loadTextureCache(modelName) {\n        const textureCache = await this.fetchWithCache(`${this.cdnPath}model/${modelName}/textures.cache`);\n        return textureCache || [];\n    }\n    async loadModel(message) {\n        let modelSettingPath, modelSetting;\n        if (this.useCDN) {\n            let modelName = this.modelList.models[this.modelId];\n            if (Array.isArray(modelName)) {\n                modelName = modelName[this.modelTexturesId];\n            }\n            modelSettingPath = `${this.cdnPath}model/${modelName}/index.json`;\n            modelSetting = await this.fetchWithCache(modelSettingPath);\n            const version = this.checkModelVersion(modelSetting);\n            if (version === 2) {\n                const textureCache = await this.loadTextureCache(modelName);\n                if (textureCache.length > 0) {\n                    let textures = textureCache[this.modelTexturesId];\n                    if (typeof textures === 'string')\n                        textures = [textures];\n                    modelSetting.textures = textures;\n                }\n            }\n        }\n        else {\n            modelSettingPath = this.models[this.modelId].paths[this.modelTexturesId];\n            modelSetting = await this.fetchWithCache(modelSettingPath);\n        }\n        await this.loadLive2D(modelSettingPath, modelSetting);\n        showMessage(message, 4000, 10);\n    }\n    async loadRandTexture(successMessage = '', failMessage = '') {\n        const { modelId } = this;\n        let noTextureAvailable = false;\n        if (this.useCDN) {\n            const modelName = this.modelList.models[modelId];\n            if (Array.isArray(modelName)) {\n                this.modelTexturesId = randomOtherOption(modelName.length, this.modelTexturesId);\n            }\n            else {\n                const modelSettingPath = `${this.cdnPath}model/${modelName}/index.json`;\n                const modelSetting = await this.fetchWithCache(modelSettingPath);\n                const version = this.checkModelVersion(modelSetting);\n                if (version === 2) {\n                    const textureCache = await this.loadTextureCache(modelName);\n                    if (textureCache.length <= 1) {\n                        noTextureAvailable = true;\n                    }\n                    else {\n                        this.modelTexturesId = randomOtherOption(textureCache.length, this.modelTexturesId);\n                    }\n                }\n                else {\n                    noTextureAvailable = true;\n                }\n            }\n        }\n        else {\n            if (this.models[modelId].paths.length === 1) {\n                noTextureAvailable = true;\n            }\n            else {\n                this.modelTexturesId = randomOtherOption(this.models[modelId].paths.length, this.modelTexturesId);\n            }\n        }\n        if (noTextureAvailable) {\n            showMessage(failMessage, 4000, 10);\n        }\n        else {\n            await this.loadModel(successMessage);\n        }\n    }\n    async loadNextModel() {\n        this.modelTexturesId = 0;\n        if (this.useCDN) {\n            this.modelId = (this.modelId + 1) % this.modelList.models.length;\n            await this.loadModel(this.modelList.messages[this.modelId]);\n        }\n        else {\n            this.modelId = (this.modelId + 1) % this.models.length;\n            await this.loadModel(this.models[this.modelId].message);\n        }\n    }\n}\nexport { ModelManager };\n"
  },
  {
    "path": "build/tools.d.ts",
    "content": "import type { Config, ModelManager } from './model.js';\nimport type { Tips } from './widget.js';\ninterface Tools {\n    [key: string]: {\n        icon: string;\n        callback: (message: any) => void;\n    };\n}\ndeclare class ToolsManager {\n    tools: Tools;\n    config: Config;\n    constructor(model: ModelManager, config: Config, tips: Tips);\n    registerTools(): void;\n}\nexport { ToolsManager, Tools };\n"
  },
  {
    "path": "build/tools.js",
    "content": "import { fa_comment, fa_paper_plane, fa_street_view, fa_shirt, fa_camera_retro, fa_info_circle, fa_xmark } from './icons.js';\nimport { showMessage, i18n } from './message.js';\nclass ToolsManager {\n    constructor(model, config, tips) {\n        this.config = config;\n        this.tools = {\n            hitokoto: {\n                icon: fa_comment,\n                callback: async () => {\n                    const response = await fetch('https://v1.hitokoto.cn');\n                    const result = await response.json();\n                    const template = tips.message.hitokoto;\n                    const text = i18n(template, result.from, result.creator);\n                    showMessage(result.hitokoto, 6000, 9);\n                    setTimeout(() => {\n                        showMessage(text, 4000, 9);\n                    }, 6000);\n                }\n            },\n            asteroids: {\n                icon: fa_paper_plane,\n                callback: () => {\n                    if (window.Asteroids) {\n                        if (!window.ASTEROIDSPLAYERS)\n                            window.ASTEROIDSPLAYERS = [];\n                        window.ASTEROIDSPLAYERS.push(new window.Asteroids());\n                    }\n                    else {\n                        const script = document.createElement('script');\n                        script.src =\n                            'https://fastly.jsdelivr.net/gh/stevenjoezhang/asteroids/asteroids.js';\n                        document.head.appendChild(script);\n                    }\n                }\n            },\n            'switch-model': {\n                icon: fa_street_view,\n                callback: () => model.loadNextModel()\n            },\n            'switch-texture': {\n                icon: fa_shirt,\n                callback: () => {\n                    let successMessage = '', failMessage = '';\n                    if (tips) {\n                        successMessage = tips.message.changeSuccess;\n                        failMessage = tips.message.changeFail;\n                    }\n                    model.loadRandTexture(successMessage, failMessage);\n                }\n            },\n            photo: {\n                icon: fa_camera_retro,\n                callback: () => {\n                    const message = tips.message.photo;\n                    showMessage(message, 6000, 9);\n                    const canvas = document.getElementById('live2d');\n                    if (!canvas)\n                        return;\n                    const imageUrl = canvas.toDataURL();\n                    const link = document.createElement('a');\n                    link.style.display = 'none';\n                    link.href = imageUrl;\n                    link.download = 'live2d-photo.png';\n                    document.body.appendChild(link);\n                    link.click();\n                    document.body.removeChild(link);\n                }\n            },\n            info: {\n                icon: fa_info_circle,\n                callback: () => {\n                    open('https://github.com/stevenjoezhang/live2d-widget');\n                }\n            },\n            quit: {\n                icon: fa_xmark,\n                callback: () => {\n                    localStorage.setItem('waifu-display', Date.now().toString());\n                    const message = tips.message.goodbye;\n                    showMessage(message, 2000, 11);\n                    const waifu = document.getElementById('waifu');\n                    if (!waifu)\n                        return;\n                    waifu.classList.remove('waifu-active');\n                    setTimeout(() => {\n                        waifu.classList.add('waifu-hidden');\n                        const waifuToggle = document.getElementById('waifu-toggle');\n                        waifuToggle === null || waifuToggle === void 0 ? void 0 : waifuToggle.classList.add('waifu-toggle-active');\n                    }, 3000);\n                }\n            }\n        };\n    }\n    registerTools() {\n        var _b;\n        if (!Array.isArray(this.config.tools)) {\n            this.config.tools = Object.keys(this.tools);\n        }\n        for (const toolName of this.config.tools) {\n            if (this.tools[toolName]) {\n                const { icon, callback } = this.tools[toolName];\n                const element = document.createElement('span');\n                element.id = `waifu-tool-${toolName}`;\n                element.innerHTML = icon;\n                (_b = document\n                    .getElementById('waifu-tool')) === null || _b === void 0 ? void 0 : _b.insertAdjacentElement('beforeend', element);\n                element.addEventListener('click', callback);\n            }\n        }\n    }\n}\nexport { ToolsManager };\n"
  },
  {
    "path": "build/utils.d.ts",
    "content": "declare function randomSelection(obj: string[] | string): string;\ndeclare function randomOtherOption(total: number, excludeIndex: number): number;\ndeclare function loadExternalResource(url: string, type: string): Promise<string>;\nexport { randomSelection, loadExternalResource, randomOtherOption };\n"
  },
  {
    "path": "build/utils.js",
    "content": "function randomSelection(obj) {\n    return Array.isArray(obj) ? obj[Math.floor(Math.random() * obj.length)] : obj;\n}\nfunction randomOtherOption(total, excludeIndex) {\n    const idx = Math.floor(Math.random() * (total - 1));\n    return idx >= excludeIndex ? idx + 1 : idx;\n}\nfunction loadExternalResource(url, type) {\n    return new Promise((resolve, reject) => {\n        let tag;\n        if (type === 'css') {\n            tag = document.createElement('link');\n            tag.rel = 'stylesheet';\n            tag.href = url;\n        }\n        else if (type === 'js') {\n            tag = document.createElement('script');\n            tag.src = url;\n        }\n        if (tag) {\n            tag.onload = () => resolve(url);\n            tag.onerror = () => reject(url);\n            document.head.appendChild(tag);\n        }\n    });\n}\nexport { randomSelection, loadExternalResource, randomOtherOption };\n"
  },
  {
    "path": "build/waifu-tips.d.ts",
    "content": "export {};\n"
  },
  {
    "path": "build/waifu-tips.js",
    "content": "import { initWidget } from './widget.js';\nwindow.initWidget = initWidget;\n"
  },
  {
    "path": "build/widget.d.ts",
    "content": "import { Config, ModelList } from './model.js';\nimport { Time } from './message.js';\ninterface Tips {\n    message: {\n        default: string[];\n        console: string;\n        copy: string;\n        visibilitychange: string;\n        changeSuccess: string;\n        changeFail: string;\n        photo: string;\n        goodbye: string;\n        hitokoto: string;\n        welcome: string;\n        referrer: string;\n        hoverBody: string | string[];\n        tapBody: string | string[];\n    };\n    time: Time;\n    mouseover: {\n        selector: string;\n        text: string | string[];\n    }[];\n    click: {\n        selector: string;\n        text: string | string[];\n    }[];\n    seasons: {\n        date: string;\n        text: string | string[];\n    }[];\n    models: ModelList[];\n}\ndeclare function initWidget(config: string | Config): void;\nexport { initWidget, Tips };\n"
  },
  {
    "path": "build/widget.js",
    "content": "import { ModelManager } from './model.js';\nimport { showMessage, welcomeMessage } from './message.js';\nimport { randomSelection } from './utils.js';\nimport { ToolsManager } from './tools.js';\nimport logger from './logger.js';\nimport registerDrag from './drag.js';\nimport { fa_child } from './icons.js';\nfunction registerEventListener(tips) {\n    let userAction = false;\n    let userActionTimer;\n    const messageArray = tips.message.default;\n    tips.seasons.forEach(({ date, text }) => {\n        const now = new Date(), after = date.split('-')[0], before = date.split('-')[1] || after;\n        if (Number(after.split('/')[0]) <= now.getMonth() + 1 &&\n            now.getMonth() + 1 <= Number(before.split('/')[0]) &&\n            Number(after.split('/')[1]) <= now.getDate() &&\n            now.getDate() <= Number(before.split('/')[1])) {\n            text = randomSelection(text);\n            text = text.replace('{year}', String(now.getFullYear()));\n            messageArray.push(text);\n        }\n    });\n    let lastHoverElement;\n    window.addEventListener('mousemove', () => (userAction = true));\n    window.addEventListener('keydown', () => (userAction = true));\n    setInterval(() => {\n        if (userAction) {\n            userAction = false;\n            clearInterval(userActionTimer);\n            userActionTimer = null;\n        }\n        else if (!userActionTimer) {\n            userActionTimer = setInterval(() => {\n                showMessage(messageArray, 6000, 9);\n            }, 20000);\n        }\n    }, 1000);\n    window.addEventListener('mouseover', (event) => {\n        var _b;\n        for (let { selector, text } of tips.mouseover) {\n            if (!((_b = event.target) === null || _b === void 0 ? void 0 : _b.closest(selector)))\n                continue;\n            if (lastHoverElement === selector)\n                return;\n            lastHoverElement = selector;\n            text = randomSelection(text);\n            text = text.replace('{text}', event.target.innerText);\n            showMessage(text, 4000, 8);\n            return;\n        }\n    });\n    window.addEventListener('click', (event) => {\n        var _b;\n        for (let { selector, text } of tips.click) {\n            if (!((_b = event.target) === null || _b === void 0 ? void 0 : _b.closest(selector)))\n                continue;\n            text = randomSelection(text);\n            text = text.replace('{text}', event.target.innerText);\n            showMessage(text, 4000, 8);\n            return;\n        }\n    });\n    window.addEventListener('live2d:hoverbody', () => {\n        const text = randomSelection(tips.message.hoverBody);\n        showMessage(text, 4000, 8, false);\n    });\n    window.addEventListener('live2d:tapbody', () => {\n        const text = randomSelection(tips.message.tapBody);\n        showMessage(text, 4000, 9);\n    });\n    const devtools = () => { };\n    console.log('%c', devtools);\n    devtools.toString = () => {\n        showMessage(tips.message.console, 6000, 9);\n    };\n    window.addEventListener('copy', () => {\n        showMessage(tips.message.copy, 6000, 9);\n    });\n    window.addEventListener('visibilitychange', () => {\n        if (!document.hidden)\n            showMessage(tips.message.visibilitychange, 6000, 9);\n    });\n}\nasync function loadWidget(config) {\n    var _b;\n    localStorage.removeItem('waifu-display');\n    sessionStorage.removeItem('waifu-message-priority');\n    document.body.insertAdjacentHTML('beforeend', `<div id=\"waifu\">\n       <div id=\"waifu-tips\"></div>\n       <div id=\"waifu-canvas\">\n         <canvas id=\"live2d\" width=\"800\" height=\"800\"></canvas>\n       </div>\n       <div id=\"waifu-tool\"></div>\n     </div>`);\n    let models = [];\n    let tips;\n    if (config.waifuPath) {\n        const response = await fetch(config.waifuPath);\n        tips = await response.json();\n        models = tips.models;\n        registerEventListener(tips);\n        showMessage(welcomeMessage(tips.time, tips.message.welcome, tips.message.referrer), 7000, 11);\n    }\n    const model = await ModelManager.initCheck(config, models);\n    await model.loadModel('');\n    new ToolsManager(model, config, tips).registerTools();\n    if (config.drag)\n        registerDrag();\n    (_b = document.getElementById('waifu')) === null || _b === void 0 ? void 0 : _b.classList.add('waifu-active');\n}\nfunction initWidget(config) {\n    if (typeof config === 'string') {\n        logger.error('Your config for Live2D initWidget is outdated. Please refer to https://github.com/stevenjoezhang/live2d-widget/blob/master/dist/autoload.js');\n        return;\n    }\n    logger.setLevel(config.logLevel);\n    document.body.insertAdjacentHTML('beforeend', `<div id=\"waifu-toggle\">\n       ${fa_child}\n     </div>`);\n    const toggle = document.getElementById('waifu-toggle');\n    toggle === null || toggle === void 0 ? void 0 : toggle.addEventListener('click', () => {\n        var _b;\n        toggle === null || toggle === void 0 ? void 0 : toggle.classList.remove('waifu-toggle-active');\n        if (toggle === null || toggle === void 0 ? void 0 : toggle.getAttribute('first-time')) {\n            loadWidget(config);\n            toggle === null || toggle === void 0 ? void 0 : toggle.removeAttribute('first-time');\n        }\n        else {\n            localStorage.removeItem('waifu-display');\n            (_b = document.getElementById('waifu')) === null || _b === void 0 ? void 0 : _b.classList.remove('waifu-hidden');\n            setTimeout(() => {\n                var _b;\n                (_b = document.getElementById('waifu')) === null || _b === void 0 ? void 0 : _b.classList.add('waifu-active');\n            }, 0);\n        }\n    });\n    if (localStorage.getItem('waifu-display') &&\n        Date.now() - Number(localStorage.getItem('waifu-display')) <= 86400000) {\n        toggle === null || toggle === void 0 ? void 0 : toggle.setAttribute('first-time', 'true');\n        setTimeout(() => {\n            toggle === null || toggle === void 0 ? void 0 : toggle.classList.add('waifu-toggle-active');\n        }, 0);\n    }\n    else {\n        loadWidget(config);\n    }\n}\nexport { initWidget };\n"
  },
  {
    "path": "demo/chat.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n<title>看板娘聊天平台</title>\n<link rel=\"stylesheet\" href=\"https://fastly.jsdelivr.net/npm/bootstrap@5/dist/css/bootstrap.min.css\">\n<link rel=\"stylesheet\" href=\"https://fastly.jsdelivr.net/npm/@fortawesome/fontawesome-free@6/css/all.min.css\">\n<script src=\"../dist/live2d.min.js\"></script>\n<style>\nhtml, body {\n\theight: 100%;\n}\nbody {\n\tdisplay: flex;\n\talign-items: center;\n\tjustify-content: center;\n\tpadding-top: 40px;\n\tpadding-bottom: 40px;\n\tbackground-color: #f5f5f5;\n}\n#waifu {\n\tbottom: 0;\n\tleft: 0;\n\tline-height: 0;\n\tmargin-bottom: -10px;\n\tposition: fixed;\n\ttransform: translateY(3px);\n\ttransition: transform .3s ease-in-out, bottom 3s ease-in-out;\n\tz-index: 1;\n}\n#waifu:hover {\n\ttransform: translateY(0);\n}\n#waifu-tips {\n\tanimation: shake 50s ease-in-out 5s infinite;\n\tbackground-color: rgba(236, 217, 188, .5);\n\tborder: 1px solid rgba(224, 186, 140, .62);\n\tborder-radius: 12px;\n\tbox-shadow: 0 3px 15px 2px rgba(191, 158, 118, .2);\n\tfont-size: 14px;\n\tline-height: 24px;\n\tmargin: -100px 20px;\n\tmin-height: 70px;\n\toverflow: hidden;\n\tpadding: 5px 10px;\n\tposition: absolute;\n\ttext-overflow: ellipsis;\n\ttransition: opacity 1s;\n\twidth: 250px;\n\tword-break: break-all;\n}\n#waifu-tips.waifu-tips-active {\n\topacity: 1;\n\ttransition: opacity .2s;\n}\n#waifu-tips span {\n\tcolor: #0099cc;\n}\n#live2d {\n\tcursor: grab;\n\theight: 300px;\n\tposition: relative;\n\twidth: 300px;\n}\n#live2d:active {\n\tcursor: grabbing;\n}\ntextarea {\n\tbackground-color: transparent;\n    border: none;\n\twidth: 100%;\n\tresize: none;\n\tmin-height: 100px;\n}\ntextarea:focus {\n  outline: none;\n}\n</style>\n</head>\n<body>\n\t<div id=\"waifu\">\n\t\t<div id=\"waifu-tips\"><textarea id=\"text\" disabled=\"true\"></textarea></div>\n\t\t<canvas id=\"live2d\" width=\"800\" height=\"800\"></canvas>\n\t</div>\n<script type=\"module\">\n/*\n * _(:з」∠)_\n * Created by Shuqiao Zhang in 2025.\n * https://zhangshuqiao.org\n */\n\n/*\n * This program is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n */\nimport { Cubism2Model } from \"../build/index.js\";\n\nclass ChatManager {\n\tconstructor() {\n\t\tthis.apiUrl = null;\n\t\tthis.apiKey = null;\n\t\tthis.conversationHistory = [];\n\t\tthis.systemPrompt = '请扮演Potion Maker中的Pio，在接下来的对话中，使用萌萌哒的语气回答问题。';\n\t}\n\n\tasync create() {\n\t\t// 提示用户输入API URL和Key\n\t\tthis.apiUrl = prompt(\"请输入大模型API URL (例如: https://api.openai.com/v1/chat/completions):\");\n\t\tif (!this.apiUrl) {\n\t\t\treturn \"呜呜~ 你没有输入API URL呢，Pio无法开始对话啦~\";\n\t\t}\n\n\t\tthis.apiKey = prompt(\"请输入API Key:\");\n\t\tif (!this.apiKey) {\n\t\t\treturn \"呜呜~ 你没有输入API Key呢，Pio无法开始对话啦~\";\n\t\t}\n\n\t\t// 初始化对话历史，添加系统提示词\n\t\tthis.conversationHistory = [\n\t\t\t{\n\t\t\t\trole: \"system\",\n\t\t\t\tcontent: this.systemPrompt\n\t\t\t}\n\t\t];\n\n\t\treturn \"嗨~ 我是Pio哦！有什么可以帮助你的吗？(按Enter发送消息)\";\n\t}\n\n\tasync message(content) {\n\t\tif (!this.apiUrl || !this.apiKey) {\n\t\t\treturn \"呜呜~ API配置不完整，请刷新页面重新配置~\";\n\t\t}\n\n\t\t// 添加用户消息到历史\n\t\tthis.conversationHistory.push({\n\t\t\trole: \"user\",\n\t\t\tcontent: content\n\t\t});\n\n\t\ttry {\n\t\t\tconst response = await fetch(this.apiUrl, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t\t'Authorization': `Bearer ${this.apiKey}`\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tmessages: this.conversationHistory,\n\t\t\t\t\ttemperature: 0.7,\n\t\t\t\t\tmax_tokens: 1000\n\t\t\t\t})\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\tthrow new Error(`API请求失败: ${response.status} ${response.statusText}`);\n\t\t\t}\n\n\t\t\tconst data = await response.json();\n\t\t\tconst assistantMessage = data.choices[0].message.content;\n\n\t\t\t// 添加助手回复到历史\n\t\t\tthis.conversationHistory.push({\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: assistantMessage\n\t\t\t});\n\n\t\t\treturn assistantMessage;\n\t\t} catch (error) {\n\t\t\tconsole.error(\"API调用出错:\", error);\n\t\t\treturn `呜呜~ 出错了呢: ${error.message}`;\n\t\t}\n\t}\n}\n\nwindow.addEventListener(\"load\", async () => {\n\t\"use strict\";\n\n\tconst apiPath = \"https://live2d.fghrsh.net/api\";\n\tconst text = document.getElementById(\"text\");\n\tconst manager = new ChatManager();\n\tlet state = 0, loading = false,\n\t\tmodelId = localStorage.getItem(\"modelId\"),\n\t\tmodelTexturesId = localStorage.getItem(\"modelTexturesId\");\n\tif (modelId === null) {\n\t\tmodelId = 1;\n\t\tmodelTexturesId = 53;\n\t}\n\tconst model = new Cubism2Model();\n\tawait loadModel(modelId, modelTexturesId);\n\n\tasync function loadModel(modelId, modelTexturesId) {\n\t\tlocalStorage.setItem(\"modelId\", modelId);\n\t\tif (modelTexturesId === undefined) modelTexturesId = 0;\n\t\tlocalStorage.setItem(\"modelTexturesId\", modelTexturesId);\n\t\tconst modelSettingPath = `${apiPath}/get/?id=${modelId}-${modelTexturesId}`;\n\t\tconst response = await fetch(modelSettingPath);\n\t\tconst modelSetting = await response.json();\n\t\tif (!model.gl) {\n\t\t\tawait model.init('live2d', modelSettingPath, modelSetting);\n\t\t} else {\n\t\t\tawait model.changeModelWithJSON(modelSettingPath, modelSetting);\n\t\t}\n\t\tconsole.log(\"live2d\", `模型 ${modelId}-${modelTexturesId} 加载完成`);\n\t\tsetTimeout(() => {\n\t\t\tstate = 2;\n\t\t}, 2000);\n\t}\n\n\ttext.addEventListener(\"keydown\", async (e) => {\n\t\tif (e.code === \"Enter\") {\n\t\t\te.preventDefault();\n\t\t\tlet content = text.value;\n\t\t\tif (content === \"\") return;\n\t\t\tconsole.log(content);\n\t\t\ttext.disabled = true;\n\t\t\ttext.value = await manager.message(content);\n\t\t\ttext.disabled = false;\n\t\t}\n\t});\n\n\tconst message = await manager.create();\n\ttext.value = message;\n\ttext.disabled = false;\n});\n</script>\n</body>\n</html>\n"
  },
  {
    "path": "demo/demo.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"UTF-8\">\n<title>Live2D 看板娘 / Demo</title>\n<style>\n#github svg {\n\ttransition: all 1s;\n\tfill: #222;\n\tcolor: #fff;\n\tposition: absolute;\n\ttop: 0;\n\tright: 0;\n\tborder: 0;\n\twidth: 80px;\n\theight: 80px;\n}\n#github:hover svg {\n\twidth: 160px;\n\theight: 160px;\n}\n</style>\n</head>\n<body>\n<a id=\"github\" href=\"https://github.com/stevenjoezhang/live2d-widget\" target=\"_blank\" title=\"Visit the open-source code on GitHub!\">\n\t<svg viewBox=\"0 0 250 250\" aria-hidden=\"true\">\n\t\t<path d=\"M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z\"></path>\n\t\t<path d=\"M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2\" fill=\"currentColor\" class=\"octo-arm\"></path>\n\t\t<path d=\"M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z\" fill=\"currentColor\" class=\"octo-body\"></path>\n\t</svg>\n</a>\n<script src=\"../dist/autoload.js\"></script>\n</body>\n</html>\n"
  },
  {
    "path": "demo/login.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n<title>看板娘登陆平台</title>\n<link rel=\"stylesheet\" href=\"https://fastly.jsdelivr.net/npm/bootstrap@5/dist/css/bootstrap.min.css\">\n<link rel=\"stylesheet\" href=\"https://fastly.jsdelivr.net/npm/@fortawesome/fontawesome-free@6/css/all.min.css\">\n<script src=\"../dist/live2d.min.js\"></script>\n<style>\nhtml, body {\n\theight: 100%;\n}\nbody {\n\tdisplay: flex;\n\talign-items: center;\n\tjustify-content: center;\n\tpadding-top: 40px;\n\tpadding-bottom: 40px;\n\tbackground-color: #f5f5f5;\n}\n.form-signin {\n\twidth: 100%;\n\tmax-width: 330px;\n\tpadding: 15px;\n\tmargin: 0 auto;\n}\n.form-signin .checkbox {\n\tfont-weight: 400;\n}\n.form-signin .form-control {\n\tposition: relative;\n\tbox-sizing: border-box;\n\theight: auto;\n\tpadding: 10px;\n\tfont-size: 16px;\n}\n.form-signin .form-control:focus {\n\tz-index: 2;\n}\n.form-signin input[type=text] {\n\tmargin-bottom: -1px;\n\tborder-bottom-right-radius: 0;\n\tborder-bottom-left-radius: 0;\n}\n.form-signin input[type=password] {\n\tmargin-bottom: 10px;\n\tborder-top-left-radius: 0;\n\tborder-top-right-radius: 0;\n}\n#stage {\n\tposition: relative;\n}\n#stage img {\n\twidth: 100%;\n\tmargin-bottom: 20px;\n\tborder-radius: 20px;\n}\n#stage button {\n\tposition: absolute;\n\tpadding: 0;\n}\n#inner {\n\tposition: relative;\n\tbackground-color: #999;\n\tclip-path: circle(120px at center);\n}\n#cover {\n\tposition: absolute;\n\tbackground-color: #CB3837;\n\twidth: 100%;\n\theight: 100%;\n\tbottom: 0;\n\ttransition: all 1s;\n\tbox-shadow: 0 0 0 5px rgba(0, 0, 0, .1);\n\toverflow: hidden;\n}\n#text {\n\tposition: absolute;\n\tfont-size: 2em;\n\topacity: 0.4;\n\tfont-weight: bold;\n\tword-wrap: break-word;\n\tmax-width: 100%;\n}\n#detail {\n\tposition: absolute;\n\tbackground: rgba(255, 255, 255, .1);\n\twidth: 100%;\n\theight: 10px;\n\tbottom: 0;\n}\n#handle {\n\tposition: absolute;\n\tbackground: #ccc;\n\tbottom: -2px;\n\tbox-shadow: 0 1px 0 1px rgba(0, 0, 0, .1);\n\theight: 8px;\n\tleft: 50%;\n\tmargin-left: -15px;\n\twidth: 30px;\n\tcursor: pointer;\n}\n#info {\n\tleft: 40px;\n\tbottom: 20px;\n}\n#refresh {\n\tright: 40px;\n\tbottom: 20px;\n}\n#live2d {\n\tcursor: grab;\n\theight: 300px;\n\twidth: 300px;\n}\n#live2d:active {\n\tcursor: grabbing;\n}\n</style>\n</head>\n<body class=\"text-center\">\n<form class=\"form-signin\" action=\"login.php\" method=\"post\">\n\t<div id=\"stage\">\n\t\t<div id=\"inner\">\n\t\t\t<div id=\"cover\">\n\t\t\t\t<div id=\"text\"></div>\n\t\t\t\t<div id=\"detail\"></div>\n\t\t\t\t<div id=\"handle\"></div>\n\t\t\t</div>\n\t\t\t<canvas class=\"mb-4\" id=\"live2d\" width=\"800\" height=\"800\"></canvas>\n\t\t</div>\n\t\t<button class=\"btn btn-link\" id=\"info\"><i class=\"fa fa-lg fa-info\"></i></button>\n\t\t<button class=\"btn btn-link\" id=\"refresh\"><i class=\"fa fa-lg fa-sync-alt\"></i></button>\n\t</div>\n\t<h1 class=\"h3 mb-3 fw-normal\">看板娘登陆平台</h1>\n\t<label for=\"room\" class=\"sr-only\">用户名</label>\n\t<input type=\"text\" name=\"room\" class=\"form-control\" placeholder=\"用户名\" required autofocus>\n\t<label for=\"pass\" class=\"sr-only\">密码</label>\n\t<input type=\"password\" name=\"pass\" class=\"form-control\" placeholder=\"密码\" required>\n\t<div class=\"checkbox mb-4\">\n\t\t<input class=\"form-check-input me-1\" type=\"checkbox\" value=\"remember-me\" id=\"remember-me\">\n\t\t<label class=\"form-check-label\" for=\"remember-me\">记住我</label>\n\t</div>\n\t<div class=\"d-grid\">\n\t\t<button class=\"btn btn-lg btn-primary\" type=\"submit\">登录</button>\n\t</div>\n\t<p class=\"mt-5 mb-3 text-muted\">Copyleft &copy; Mimi <span id=\"year\"></span></p>\n</form>\n<script type=\"module\">\n/*\n * _(:з」∠)_\n * Created by Shuqiao Zhang in 2019.\n * https://zhangshuqiao.org\n */\n\n/*\n * This program is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n */\nimport { Cubism2Model } from \"../build/index.js\";\ndocument.getElementById(\"text\").innerHTML = `<span style=\"color: cyan;\">MIMI</span><span style=\"color: white;\">POWERED</span>`.repeat(10);\ndocument.getElementById(\"year\").innerText = new Date().getFullYear();\nwindow.addEventListener(\"load\", () => {\n\tif (!CSS.supports(\"clip-path\", \"circle(120px at center)\")) {\n\t\tdocument.getElementById(\"stage\").innerHTML = '<img src=\"./screenshots/screenshot-1.png\">';\n\t\treturn;\n\t}\n\n\tconst coverPosition = pos => document.getElementById(\"cover\").style.bottom = pos;\n\n\tconst apiPath = \"https://live2d.fghrsh.net/api\";\n\tlet state = 0, loading = false;\n\tconst model = new Cubism2Model();\n\tconst modelId = 1;\n\tlet modelTexturesId = 0;\n\tloadModel();\n\n\tfunction setState(newState) {\n\t\tstate = newState;\n\t\tif (state === 0) coverPosition(\"10%\");\n\t\telse if (state === 1) coverPosition(\"20%\");\n\t\telse if (state === 2) coverPosition(\"80%\");\n\t}\n\n\tasync function loadModel() {\n\t\tconst modelSettingPath = `${apiPath}/get/?id=${modelId}-${modelTexturesId}`;\n\t\tconst response = await fetch(modelSettingPath);\n\t\tconst modelSetting = await response.json();\n\t\tif (!model.gl) {\n\t\t\tawait model.init('live2d', modelSettingPath, modelSetting);\n\t\t} else {\n\t\t\tawait model.changeModelWithJSON(modelSettingPath, modelSetting);\n\t\t}\n\t\tconsole.log(\"live2d\", `模型 ${modelId}-${modelTexturesId} 加载完成`);\n\t\tsetState(2);\n\t}\n\n\tasync function loadRandModel() {\n\t\tconst response = await fetch(`${apiPath}/rand_textures/?id=${modelId}-${modelTexturesId}`);\n\t\tconst result = await response.json();\n\t\tmodelTexturesId = result.textures.id;\n\t\tawait loadModel();\n\t\tsetState(2);\n\t}\n\n\tdocument.getElementById(\"info\").addEventListener(\"click\", () => {\n\t\tfetch(\"https://v1.hitokoto.cn\")\n\t\t\t.then(response => response.json())\n\t\t\t.then(result => {\n\t\t\t\talert(\"「\" + result.hitokoto + \"」——\" + result.from);\n\t\t\t});\n\t});\n\n\tdocument.getElementById(\"refresh\").addEventListener(\"click\", async () => {\n\t\tif (loading) return;\n\t\tloading = true;\n\t\tsetState(0);\n\t\tawait loadRandModel();\n\t\tloading = false;\n\t});\n\n\tdocument.getElementById(\"handle\").addEventListener(\"click\", () => {\n\t\tif (state === 1) {\n\t\t\tsetState(2);\n\t\t}\n\t\telse if (state === 2) {\n\t\t\tsetState(1);\n\t\t}\n\t});\n\n\tdocument.querySelector(\"input[type=password]\").addEventListener(\"focus\", () => {\n\t\tif (state === 2) {\n\t\t\tsetState(1);\n\t\t}\n\t});\n\n\tdocument.querySelector(\"input[type=password]\").addEventListener(\"blur\", () => {\n\t\tif (state === 1) {\n\t\t\tsetState(2);\n\t\t}\n\t});\n});\n</script>\n</body>\n</html>\n"
  },
  {
    "path": "dist/autoload.js",
    "content": "/*!\n * Live2D Widget\n * https://github.com/stevenjoezhang/live2d-widget\n */\n\n// Recommended to use absolute path for live2d_path parameter\n// live2d_path 参数建议使用绝对路径\nconst live2d_path = 'https://fastly.jsdelivr.net/npm/live2d-widgets@1.0.0-rc.6/dist/';\n// const live2d_path = '/dist/';\n\n// Method to encapsulate asynchronous resource loading\n// 封装异步加载资源的方法\nfunction loadExternalResource(url, type) {\n  return new Promise((resolve, reject) => {\n    let tag;\n\n    if (type === 'css') {\n      tag = document.createElement('link');\n      tag.rel = 'stylesheet';\n      tag.href = url;\n    }\n    else if (type === 'js') {\n      tag = document.createElement('script');\n      tag.type = 'module';\n      tag.src = url;\n    }\n    if (tag) {\n      tag.onload = () => resolve(url);\n      tag.onerror = () => reject(url);\n      document.head.appendChild(tag);\n    }\n  });\n}\n\n(async () => {\n  // If you are concerned about display issues on mobile devices, you can use screen.width to determine whether to load\n  // 如果担心手机上显示效果不佳，可以根据屏幕宽度来判断是否加载\n  // if (screen.width < 768) return;\n\n  // Avoid cross-origin issues with image resources\n  // 避免图片资源跨域问题\n  const OriginalImage = window.Image;\n  window.Image = function(...args) {\n    const img = new OriginalImage(...args);\n    img.crossOrigin = \"anonymous\";\n    return img;\n  };\n  window.Image.prototype = OriginalImage.prototype;\n  // Load waifu.css and waifu-tips.js\n  // 加载 waifu.css 和 waifu-tips.js\n  await Promise.all([\n    loadExternalResource(live2d_path + 'waifu.css', 'css'),\n    loadExternalResource(live2d_path + 'waifu-tips.js', 'js')\n  ]);\n  // For detailed usage of configuration options, see README.en.md\n  // 配置选项的具体用法见 README.md\n  initWidget({\n    waifuPath: live2d_path + 'waifu-tips.json',\n    // cdnPath: 'https://fastly.jsdelivr.net/gh/fghrsh/live2d_api/',\n    cubism2Path: live2d_path + 'live2d.min.js',\n    cubism5Path: 'https://cubism.live2d.com/sdk-web/cubismcore/live2dcubismcore.min.js',\n    tools: ['hitokoto', 'asteroids', 'switch-model', 'switch-texture', 'photo', 'info', 'quit'],\n    logLevel: 'warn',\n    drag: false,\n  });\n})();\n\nconsole.log(`\\n%cLive2D%cWidget%c\\n`, 'padding: 8px; background: #cd3e45; font-weight: bold; font-size: large; color: white;', 'padding: 8px; background: #ff5450; font-size: large; color: #eee;', '');\n\n/*\nく__,.ヘヽ.        /  ,ー､ 〉\n         ＼ ', !-─‐-i  /  /´\n         ／｀ｰ'       L/／｀ヽ､\n       /   ／,   /|   ,   ,       ',\n     ｲ   / /-‐/  ｉ  L_ ﾊ ヽ!   i\n      ﾚ ﾍ 7ｲ｀ﾄ   ﾚ'ｧ-ﾄ､!ハ|   |\n        !,/7 '0'     ´0iソ|    |\n        |.从\"    _     ,,,, / |./    |\n        ﾚ'| i＞.､,,__  _,.イ /   .i   |\n          ﾚ'| | / k_７_/ﾚ'ヽ,  ﾊ.  |\n            | |/i 〈|/   i  ,.ﾍ |  i  |\n           .|/ /  ｉ：    ﾍ!    ＼  |\n            kヽ>､ﾊ    _,.ﾍ､    /､!\n            !'〈//｀Ｔ´', ＼ ｀'7'ｰr'\n            ﾚ'ヽL__|___i,___,ンﾚ|ノ\n                ﾄ-,/  |___./\n                'ｰ'    !_,.:\n*/\n"
  },
  {
    "path": "dist/chunk/index.js",
    "content": "/*!\n * Live2D Widget\n * https://github.com/stevenjoezhang/live2d-widget\n */\nimport{l as t}from\"../waifu-tips.js\";class e{constructor(){this.live2DModel=null,this.modelMatrix=null,this.eyeBlink=null,this.physics=null,this.pose=null,this.initialized=!1,this.updating=!1,this.alpha=1,this.accAlpha=0,this.lipSync=!1,this.lipSyncValue=0,this.accelX=0,this.accelY=0,this.accelZ=0,this.dragX=0,this.dragY=0,this.startTimeMSec=null,this.mainMotionManager=new l,this.expressionManager=new l,this.motions={},this.expressions={},this.isTexLoaded=!1}getModelMatrix(){return this.modelMatrix}setAlpha(t){t>.999&&(t=1),t<.001&&(t=0),this.alpha=t}getAlpha(){return this.alpha}isInitialized(){return this.initialized}setInitialized(t){this.initialized=t}isUpdating(){return this.updating}setUpdating(t){this.updating=t}getLive2DModel(){return this.live2DModel}setLipSync(t){this.lipSync=t}setLipSyncValue(t){this.lipSyncValue=t}setAccel(t,e,i){this.accelX=t,this.accelY=e,this.accelZ=i}setDrag(t,e){this.dragX=t,this.dragY=e}getMainMotionManager(){return this.mainMotionManager}getExpressionManager(){return this.expressionManager}loadModelData(e,i){const s=M.getPlatformManager();t.info(\"Load model : \"+e),s.loadLive2DModel(e,(e=>{this.live2DModel=e,this.live2DModel.saveParam();0==Live2D.getError()?(this.modelMatrix=new h(this.live2DModel.getCanvasWidth(),this.live2DModel.getCanvasHeight()),this.modelMatrix.setWidth(2),this.modelMatrix.setCenterPosition(0,0),i(this.live2DModel)):t.error(\"Error : Failed to loadModelData().\")}))}loadTexture(e,s,n){i++;const a=M.getPlatformManager();t.info(\"Load Texture : \"+s),a.loadTexture(this.live2DModel,e,s,(()=>{i--,0==i&&(this.isTexLoaded=!0),\"function\"==typeof n&&n()}))}loadMotion(e,i,s){const n=M.getPlatformManager();t.trace(\"Load Motion : \"+i);let a=null;n.loadBytes(i,(t=>{a=Live2DMotion.loadMotion(t),null!=e&&(this.motions[e]=a),s(a)}))}loadExpression(e,i,n){const a=M.getPlatformManager();t.trace(\"Load Expression : \"+i),a.loadBytes(i,(t=>{null!=e&&(this.expressions[e]=s.loadJson(t)),\"function\"==typeof n&&n()}))}loadPose(e,i){const s=M.getPlatformManager();t.trace(\"Load Pose : \"+e);try{s.loadBytes(e,(t=>{this.pose=d.load(t),\"function\"==typeof i&&i()}))}catch(e){t.warn(e)}}loadPhysics(e){const i=M.getPlatformManager();t.trace(\"Load Physics : \"+e);try{i.loadBytes(e,(t=>{this.physics=c.load(t)}))}catch(e){t.warn(e)}}hitTestSimple(t,e,i){const s=this.live2DModel.getDrawDataIndex(t);if(s<0)return!1;const n=this.live2DModel.getTransformedPoints(s);let a=this.live2DModel.getCanvasWidth(),r=0,o=this.live2DModel.getCanvasHeight(),h=0;for(let t=0;t<n.length;t+=2){const e=n[t],i=n[t+1];e<a&&(a=e),e>r&&(r=e),i<o&&(o=i),i>h&&(h=i)}const l=this.modelMatrix.invertTransformX(e),c=this.modelMatrix.invertTransformY(i);return a<=l&&l<=r&&o<=c&&c<=h}}let i=0;class s extends AMotion{constructor(){super(),this.paramList=[]}static loadJson(t){const e=new s,i=M.getPlatformManager().jsonParseFromBytes(t);if(e.setFadeIn(parseInt(i.fade_in)>0?parseInt(i.fade_in):1e3),e.setFadeOut(parseInt(i.fade_out)>0?parseInt(i.fade_out):1e3),null==i.params)return e;const a=i.params,r=a.length;e.paramList=[];for(let t=0;t<r;t++){const i=a[t],r=i.id.toString();let o=parseFloat(i.val),h=s.TYPE_ADD;const l=null!=i.calc?i.calc.toString():\"add\";if(h=\"add\"===l?s.TYPE_ADD:\"mult\"===l?s.TYPE_MULT:\"set\"===l?s.TYPE_SET:s.TYPE_ADD,h==s.TYPE_ADD){o-=null==i.def?0:parseFloat(i.def)}else if(h==s.TYPE_MULT){let t=null==i.def?1:parseFloat(i.def);0==t&&(t=1),o/=t}const c=new n;c.id=r,c.type=h,c.value=o,e.paramList.push(c)}return e}updateParamExe(t,e,i,n){for(let e=this.paramList.length-1;e>=0;--e){const n=this.paramList[e];n.type==s.TYPE_ADD?t.addToParamFloat(n.id,n.value,i):n.type==s.TYPE_MULT?t.multParamFloat(n.id,n.value,i):n.type==s.TYPE_SET&&t.setParamFloat(n.id,n.value,i)}}}function n(){this.id=\"\",this.type=-1,this.value=null}s.EXPRESSION_DEFAULT=\"DEFAULT\",s.TYPE_SET=0,s.TYPE_ADD=1,s.TYPE_MULT=2;class a{constructor(){this.nextBlinkTime=null,this.stateStartTime=null,this.blinkIntervalMsec=null,this.eyeState=r.STATE_FIRST,this.blinkIntervalMsec=4e3,this.closingMotionMsec=100,this.closedMotionMsec=50,this.openingMotionMsec=150,this.closeIfZero=!0,this.eyeID_L=\"PARAM_EYE_L_OPEN\",this.eyeID_R=\"PARAM_EYE_R_OPEN\"}calcNextBlink(){return UtSystem.getUserTimeMSec()+Math.random()*(2*this.blinkIntervalMsec-1)}setInterval(t){this.blinkIntervalMsec=t}setEyeMotion(t,e,i){this.closingMotionMsec=t,this.closedMotionMsec=e,this.openingMotionMsec=i}updateParam(t){const e=UtSystem.getUserTimeMSec();let i,s=0;switch(this.eyeState){case r.STATE_CLOSING:s=(e-this.stateStartTime)/this.closingMotionMsec,s>=1&&(s=1,this.eyeState=r.STATE_CLOSED,this.stateStartTime=e),i=1-s;break;case r.STATE_CLOSED:s=(e-this.stateStartTime)/this.closedMotionMsec,s>=1&&(this.eyeState=r.STATE_OPENING,this.stateStartTime=e),i=0;break;case r.STATE_OPENING:s=(e-this.stateStartTime)/this.openingMotionMsec,s>=1&&(s=1,this.eyeState=r.STATE_INTERVAL,this.nextBlinkTime=this.calcNextBlink()),i=s;break;case r.STATE_INTERVAL:this.nextBlinkTime<e&&(this.eyeState=r.STATE_CLOSING,this.stateStartTime=e),i=1;break;case r.STATE_FIRST:default:this.eyeState=r.STATE_INTERVAL,this.nextBlinkTime=this.calcNextBlink(),i=1}this.closeIfZero||(i=-i),t.setParamFloat(this.eyeID_L,i),t.setParamFloat(this.eyeID_R,i)}}const r=()=>{};r.STATE_FIRST=\"STATE_FIRST\",r.STATE_INTERVAL=\"STATE_INTERVAL\",r.STATE_CLOSING=\"STATE_CLOSING\",r.STATE_CLOSED=\"STATE_CLOSED\",r.STATE_OPENING=\"STATE_OPENING\";class o{constructor(){this.tr=new Float32Array(16),this.identity()}static mul(t,e,i){const s=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];let n,a,r;for(n=0;n<4;n++)for(a=0;a<4;a++)for(r=0;r<4;r++)s[n+4*a]+=t[n+4*r]*e[r+4*a];for(n=0;n<16;n++)i[n]=s[n]}identity(){for(let t=0;t<16;t++)this.tr[t]=t%5==0?1:0}getArray(){return this.tr}getCopyMatrix(){return new Float32Array(this.tr)}setMatrix(t){if(null!=this.tr&&this.tr.length==this.tr.length)for(let e=0;e<16;e++)this.tr[e]=t[e]}getScaleX(){return this.tr[0]}getScaleY(){return this.tr[5]}transformX(t){return this.tr[0]*t+this.tr[12]}transformY(t){return this.tr[5]*t+this.tr[13]}invertTransformX(t){return(t-this.tr[12])/this.tr[0]}invertTransformY(t){return(t-this.tr[13])/this.tr[5]}multTranslate(t,e){const i=[1,0,0,0,0,1,0,0,0,0,1,0,t,e,0,1];o.mul(i,this.tr,this.tr)}translate(t,e){this.tr[12]=t,this.tr[13]=e}translateX(t){this.tr[12]=t}translateY(t){this.tr[13]=t}multScale(t,e){const i=[t,0,0,0,0,e,0,0,0,0,1,0,0,0,0,1];o.mul(i,this.tr,this.tr)}scale(t,e){this.tr[0]=t,this.tr[5]=e}}class h extends o{constructor(t,e){super(),this.width=t,this.height=e}setPosition(t,e){this.translate(t,e)}setCenterPosition(t,e){const i=this.width*this.getScaleX(),s=this.height*this.getScaleY();this.translate(t-i/2,e-s/2)}top(t){this.setY(t)}bottom(t){const e=this.height*this.getScaleY();this.translateY(t-e)}left(t){this.setX(t)}right(t){const e=this.width*this.getScaleX();this.translateX(t-e)}centerX(t){const e=this.width*this.getScaleX();this.translateX(t-e/2)}centerY(t){const e=this.height*this.getScaleY();this.translateY(t-e/2)}setX(t){this.translateX(t)}setY(t){this.translateY(t)}setHeight(t){const e=t/this.height,i=-e;this.scale(e,i)}setWidth(t){const e=t/this.width,i=-e;this.scale(e,i)}}class l extends MotionQueueManager{constructor(){super(),this.currentPriority=null,this.reservePriority=null,this.super=MotionQueueManager.prototype}getCurrentPriority(){return this.currentPriority}getReservePriority(){return this.reservePriority}reserveMotion(t){return!(this.reservePriority>=t)&&(!(this.currentPriority>=t)&&(this.reservePriority=t,!0))}setReservePriority(t){this.reservePriority=t}updateParam(t){const e=MotionQueueManager.prototype.updateParam.call(this,t);return this.isFinished()&&(this.currentPriority=0),e}startMotionPrio(t,e){return e==this.reservePriority&&(this.reservePriority=0),this.currentPriority=e,this.startMotion(t,!1)}}class c{constructor(){this.physicsList=[],this.startTimeMSec=UtSystem.getUserTimeMSec()}static load(t){const e=new c,i=M.getPlatformManager().jsonParseFromBytes(t).physics_hair,s=i.length;for(let t=0;t<s;t++){const s=i[t],n=new PhysicsHair,a=s.setup,r=parseFloat(a.length),o=parseFloat(a.regist),h=parseFloat(a.mass);n.setup(r,o,h);const l=s.src,c=l.length;for(let t=0;t<c;t++){const e=l[t];let i=e.id,s=PhysicsHair.Src.SRC_TO_X,a=e.ptype;\"x\"===a?s=PhysicsHair.Src.SRC_TO_X:\"y\"===a?s=PhysicsHair.Src.SRC_TO_Y:\"angle\"===a?s=PhysicsHair.Src.SRC_TO_G_ANGLE:UtDebug.error(\"live2d\",\"Invalid parameter:PhysicsHair.Src\");let r=parseFloat(e.scale),o=parseFloat(e.weight);n.addSrcParam(s,i,r,o)}const d=s.targets,u=d.length;for(let t=0;t<u;t++){const e=d[t];let i=e.id,s=PhysicsHair.Target.TARGET_FROM_ANGLE,a=e.ptype;\"angle\"===a?s=PhysicsHair.Target.TARGET_FROM_ANGLE:\"angle_v\"===a?s=PhysicsHair.Target.TARGET_FROM_ANGLE_V:UtDebug.error(\"live2d\",\"Invalid parameter:PhysicsHair.Target\");let r=parseFloat(e.scale),o=parseFloat(e.weight);n.addTargetParam(s,i,r,o)}e.physicsList.push(n)}return e}updateParam(t){const e=UtSystem.getUserTimeMSec()-this.startTimeMSec;for(let i=0;i<this.physicsList.length;i++)this.physicsList[i].update(t,e)}}class d{constructor(){this.lastTime=0,this.lastModel=null,this.partsGroups=[]}static load(t){const e=new d,i=M.getPlatformManager().jsonParseFromBytes(t).parts_visible,s=i.length;for(let t=0;t<s;t++){const s=i[t].group,n=s.length,a=[];for(let t=0;t<n;t++){const e=s[t],i=new u(e.id);if(a[t]=i,null==e.link)continue;const n=e.link,r=n.length;i.link=[];for(let t=0;t<r;t++){const e=new u(n[t]);i.link.push(e)}}e.partsGroups.push(a)}return e}updateParam(t){if(null==t)return;t!=this.lastModel&&this.initParam(t),this.lastModel=t;const e=UtSystem.getUserTimeMSec();let i=0==this.lastTime?0:(e-this.lastTime)/1e3;this.lastTime=e,i<0&&(i=0);for(let e=0;e<this.partsGroups.length;e++)this.normalizePartsOpacityGroup(t,this.partsGroups[e],i),this.copyOpacityOtherParts(t,this.partsGroups[e])}initParam(t){if(null!=t)for(let e=0;e<this.partsGroups.length;e++){const i=this.partsGroups[e];for(let e=0;e<i.length;e++){i[e].initIndex(t);const s=i[e].partsIndex,n=i[e].paramIndex;if(s<0)continue;const a=0!=t.getParamFloat(n);if(t.setPartsOpacity(s,a?1:0),t.setParamFloat(n,a?1:0),null!=i[e].link)for(let s=0;s<i[e].link.length;s++)i[e].link[s].initIndex(t)}}}normalizePartsOpacityGroup(t,e,i){let s=-1,n=1;const a=.5;for(let a=0;a<e.length;a++){let r=e[a].partsIndex;const o=e[a].paramIndex;if(!(r<0)&&0!=t.getParamFloat(o)){if(s>=0)break;s=a,n=t.getPartsOpacity(r),n+=i/.5,n>1&&(n=1)}}s<0&&(s=0,n=1);for(let i=0;i<e.length;i++){let r=e[i].partsIndex;if(!(r<0))if(s==i)t.setPartsOpacity(r,n);else{let e,i=t.getPartsOpacity(r);e=n<a?-.5*n/a+1:(1-n)*a/.5;(1-e)*(1-n)>.15&&(e=1-.15/(1-n)),i>e&&(i=e),t.setPartsOpacity(r,i)}}}copyOpacityOtherParts(t,e){for(let i=0;i<e.length;i++){const s=e[i];if(null==s.link)continue;if(s.partsIndex<0)continue;const n=t.getPartsOpacity(s.partsIndex);for(let e=0;e<s.link.length;e++){const i=s.link[e];i.partsIndex<0||t.setPartsOpacity(i.partsIndex,n)}}}}class u{constructor(t){this.paramIndex=-1,this.partsIndex=-1,this.link=null,this.id=t}initIndex(t){this.paramIndex=t.getParamIndex(\"VISIBLE:\"+this.id),this.partsIndex=t.getPartsDataIndex(PartsDataID.getID(this.id)),t.setParamFloat(this.paramIndex,1)}}class m{constructor(){this.EPSILON=.01,this.faceTargetX=0,this.faceTargetY=0,this.faceX=0,this.faceY=0,this.faceVX=0,this.faceVY=0,this.lastTimeSec=0}setPoint(t,e){this.faceTargetX=t,this.faceTargetY=e}getX(){return this.faceX}getY(){return this.faceY}update(){const t=40/7.5/m.FRAME_RATE;if(0==this.lastTimeSec)return void(this.lastTimeSec=UtSystem.getUserTimeMSec());const e=UtSystem.getUserTimeMSec(),i=(e-this.lastTimeSec)*m.FRAME_RATE/1e3;this.lastTimeSec=e;const s=i*t/(.15*m.FRAME_RATE),n=this.faceTargetX-this.faceX,a=this.faceTargetY-this.faceY;if(Math.abs(n)<=this.EPSILON&&Math.abs(a)<=this.EPSILON)return;const r=Math.sqrt(n*n+a*a),o=t*a/r;let h=t*n/r-this.faceVX,l=o-this.faceVY,c=Math.sqrt(h*h+l*l);(c<-s||c>s)&&(h*=s/c,l*=s/c,c=s),this.faceVX+=h,this.faceVY+=l;{const t=.5*(Math.sqrt(s*s+16*s*r-8*s*r)-s),e=Math.sqrt(this.faceVX*this.faceVX+this.faceVY*this.faceVY);e>t&&(this.faceVX*=t/e,this.faceVY*=t/e)}this.faceX+=this.faceVX,this.faceY+=this.faceVY}}m.FRAME_RATE=30;class g extends o{constructor(){super(),this.screenLeft=null,this.screenRight=null,this.screenTop=null,this.screenBottom=null,this.maxLeft=null,this.maxRight=null,this.maxTop=null,this.maxBottom=null,this.max=Number.MAX_VALUE,this.min=0}getMaxScale(){return this.max}getMinScale(){return this.min}setMaxScale(t){this.max=t}setMinScale(t){this.min=t}isMaxScale(){return this.getScaleX()==this.max}isMinScale(){return this.getScaleX()==this.min}adjustTranslate(t,e){this.tr[0]*this.maxLeft+(this.tr[12]+t)>this.screenLeft&&(t=this.screenLeft-this.tr[0]*this.maxLeft-this.tr[12]),this.tr[0]*this.maxRight+(this.tr[12]+t)<this.screenRight&&(t=this.screenRight-this.tr[0]*this.maxRight-this.tr[12]),this.tr[5]*this.maxTop+(this.tr[13]+e)<this.screenTop&&(e=this.screenTop-this.tr[5]*this.maxTop-this.tr[13]),this.tr[5]*this.maxBottom+(this.tr[13]+e)>this.screenBottom&&(e=this.screenBottom-this.tr[5]*this.maxBottom-this.tr[13]);const i=[1,0,0,0,0,1,0,0,0,0,1,0,t,e,0,1];o.mul(i,this.tr,this.tr)}adjustScale(t,e,i){const s=i*this.tr[0];s<this.min?this.tr[0]>0&&(i=this.min/this.tr[0]):s>this.max&&this.tr[0]>0&&(i=this.max/this.tr[0]);const n=[1,0,0,0,0,1,0,0,0,0,1,0,t,e,0,1],a=[i,0,0,0,0,i,0,0,0,0,1,0,0,0,0,1],r=[1,0,0,0,0,1,0,0,0,0,1,0,-t,-e,0,1];o.mul(r,this.tr,this.tr),o.mul(a,this.tr,this.tr),o.mul(n,this.tr,this.tr)}setScreenRect(t,e,i,s){this.screenLeft=t,this.screenRight=e,this.screenTop=s,this.screenBottom=i}setMaxScreenRect(t,e,i,s){this.maxLeft=t,this.maxRight=e,this.maxTop=s,this.maxBottom=i}getScreenLeft(){return this.screenLeft}getScreenRight(){return this.screenRight}getScreenBottom(){return this.screenBottom}getScreenTop(){return this.screenTop}getMaxLeft(){return this.maxLeft}getMaxRight(){return this.maxRight}getMaxBottom(){return this.maxBottom}getMaxTop(){return this.maxTop}}class M{static getPlatformManager(){return M.platformManager}static setPlatformManager(t){M.platformManager=t}}M.platformManager=null;const S=1.5,T=1,p=-1,E=1,v=-2,P=2,_=-2,I=2,x=1,f=2,A=3,y=\"idle\",R=\"tap_body\",O=\"pinch_in\",D=\"pinch_out\",L=\"head\",N=\"body\";class w{static reset(){this.depth=0}static loadIdentity(){for(let t=0;t<16;t++)this.currentMatrix[t]=t%5==0?1:0}static push(){this.depth;const t=16*(this.depth+1);this.matrixStack.length<t+16&&(this.matrixStack.length=t+16);for(let e=0;e<16;e++)this.matrixStack[t+e]=this.currentMatrix[e];this.depth++}static pop(){this.depth--,this.depth<0&&(this.depth=0);const t=16*this.depth;for(let e=0;e<16;e++)this.currentMatrix[e]=this.matrixStack[t+e]}static getMatrix(){return this.currentMatrix}static multMatrix(t){let e,i,s;for(e=0;e<16;e++)this.tmp[e]=0;for(e=0;e<4;e++)for(i=0;i<4;i++)for(s=0;s<4;s++)this.tmp[e+4*i]+=this.currentMatrix[e+4*s]*t[s+4*i];for(e=0;e<16;e++)this.currentMatrix[e]=this.tmp[e]}}w.matrixStack=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],w.depth=0,w.currentMatrix=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],w.tmp=new Array(16);class F{constructor(){this.NAME=\"name\",this.ID=\"id\",this.MODEL=\"model\",this.TEXTURES=\"textures\",this.HIT_AREAS=\"hit_areas\",this.HIT_AREAS_CUSTOM=\"hit_areas_custom\",this.PHYSICS=\"physics\",this.POSE=\"pose\",this.EXPRESSIONS=\"expressions\",this.MOTION_GROUPS=\"motions\",this.SOUND=\"sound\",this.FADE_IN=\"fade_in\",this.FADE_OUT=\"fade_out\",this.LAYOUT=\"layout\",this.INIT_PARAM=\"init_param\",this.INIT_PARTS_VISIBLE=\"init_parts_visible\",this.VALUE=\"val\",this.FILE=\"file\",this.json={}}loadModelSetting(t,e){M.getPlatformManager().loadBytes(t,(t=>{const i=String.fromCharCode.apply(null,new Uint8Array(t));this.json=JSON.parse(i),e()}))}getTextureFile(t){return null==this.json[this.TEXTURES]||null==this.json[this.TEXTURES][t]?null:this.json[this.TEXTURES][t]}getModelFile(){return this.json[this.MODEL]}getTextureNum(){return null==this.json[this.TEXTURES]?0:this.json[this.TEXTURES].length}getHitAreaNum(){return null==this.json[this.HIT_AREAS]?0:this.json[this.HIT_AREAS].length}getHitAreaCustom(){return this.json[this.HIT_AREAS_CUSTOM]}getHitAreaID(t){return null==this.json[this.HIT_AREAS]||null==this.json[this.HIT_AREAS][t]?null:this.json[this.HIT_AREAS][t][this.ID]}getHitAreaName(t){return null==this.json[this.HIT_AREAS]||null==this.json[this.HIT_AREAS][t]?null:this.json[this.HIT_AREAS][t][this.NAME]}getPhysicsFile(){return this.json[this.PHYSICS]}getPoseFile(){return this.json[this.POSE]}getExpressionNum(){return null==this.json[this.EXPRESSIONS]?0:this.json[this.EXPRESSIONS].length}getExpressionFile(t){return null==this.json[this.EXPRESSIONS]?null:this.json[this.EXPRESSIONS][t][this.FILE]}getExpressionName(t){return null==this.json[this.EXPRESSIONS]?null:this.json[this.EXPRESSIONS][t][this.NAME]}getLayout(){return this.json[this.LAYOUT]}getInitParamNum(){return null==this.json[this.INIT_PARAM]?0:this.json[this.INIT_PARAM].length}getMotionNum(t){return null==this.json[this.MOTION_GROUPS]||null==this.json[this.MOTION_GROUPS][t]?0:this.json[this.MOTION_GROUPS][t].length}getMotionFile(t,e){return null==this.json[this.MOTION_GROUPS]||null==this.json[this.MOTION_GROUPS][t]||null==this.json[this.MOTION_GROUPS][t][e]?null:this.json[this.MOTION_GROUPS][t][e][this.FILE]}getMotionSound(t,e){return null==this.json[this.MOTION_GROUPS]||null==this.json[this.MOTION_GROUPS][t]||null==this.json[this.MOTION_GROUPS][t][e]||null==this.json[this.MOTION_GROUPS][t][e][this.SOUND]?null:this.json[this.MOTION_GROUPS][t][e][this.SOUND]}getMotionFadeIn(t,e){return null==this.json[this.MOTION_GROUPS]||null==this.json[this.MOTION_GROUPS][t]||null==this.json[this.MOTION_GROUPS][t][e]||null==this.json[this.MOTION_GROUPS][t][e][this.FADE_IN]?1e3:this.json[this.MOTION_GROUPS][t][e][this.FADE_IN]}getMotionFadeOut(t,e){return null==this.json[this.MOTION_GROUPS]||null==this.json[this.MOTION_GROUPS][t]||null==this.json[this.MOTION_GROUPS][t][e]||null==this.json[this.MOTION_GROUPS][t][e][this.FADE_OUT]?1e3:this.json[this.MOTION_GROUPS][t][e][this.FADE_OUT]}getInitParamID(t){return null==this.json[this.INIT_PARAM]||null==this.json[this.INIT_PARAM][t]?null:this.json[this.INIT_PARAM][t][this.ID]}getInitParamValue(t){return null==this.json[this.INIT_PARAM]||null==this.json[this.INIT_PARAM][t]?NaN:this.json[this.INIT_PARAM][t][this.VALUE]}getInitPartsVisibleNum(){return null==this.json[this.INIT_PARTS_VISIBLE]?0:this.json[this.INIT_PARTS_VISIBLE].length}getInitPartsVisibleID(t){return null==this.json[this.INIT_PARTS_VISIBLE]||null==this.json[this.INIT_PARTS_VISIBLE][t]?null:this.json[this.INIT_PARTS_VISIBLE][t][this.ID]}getInitPartsVisibleValue(t){return null==this.json[this.INIT_PARTS_VISIBLE]||null==this.json[this.INIT_PARTS_VISIBLE][t]?NaN:this.json[this.INIT_PARTS_VISIBLE][t][this.VALUE]}}class U extends e{constructor(){super(),this.modelHomeDir=\"\",this.modelSetting=null,this.tmpMatrix=[]}loadJSON(t){const e=this.modelHomeDir+this.modelSetting.getModelFile();this.loadModelData(e,(e=>{for(let e=0;e<this.modelSetting.getTextureNum();e++){const i=this.modelHomeDir+this.modelSetting.getTextureFile(e);this.loadTexture(e,i,(()=>{if(this.isTexLoaded){if(this.modelSetting.getExpressionNum()>0){this.expressions={};for(let t=0;t<this.modelSetting.getExpressionNum();t++){const e=this.modelSetting.getExpressionName(t),i=this.modelHomeDir+this.modelSetting.getExpressionFile(t);this.loadExpression(e,i)}}else this.expressionManager=null,this.expressions={};if(null==this.eyeBlink&&(this.eyeBlink=new a),null!=this.modelSetting.getPhysicsFile()?this.loadPhysics(this.modelHomeDir+this.modelSetting.getPhysicsFile()):this.physics=null,null!=this.modelSetting.getPoseFile()?this.loadPose(this.modelHomeDir+this.modelSetting.getPoseFile(),(()=>{this.pose.updateParam(this.live2DModel)})):this.pose=null,null!=this.modelSetting.getLayout()){const t=this.modelSetting.getLayout();null!=t.width&&this.modelMatrix.setWidth(t.width),null!=t.height&&this.modelMatrix.setHeight(t.height),null!=t.x&&this.modelMatrix.setX(t.x),null!=t.y&&this.modelMatrix.setY(t.y),null!=t.center_x&&this.modelMatrix.centerX(t.center_x),null!=t.center_y&&this.modelMatrix.centerY(t.center_y),null!=t.top&&this.modelMatrix.top(t.top),null!=t.bottom&&this.modelMatrix.bottom(t.bottom),null!=t.left&&this.modelMatrix.left(t.left),null!=t.right&&this.modelMatrix.right(t.right)}for(let t=0;t<this.modelSetting.getInitParamNum();t++)this.live2DModel.setParamFloat(this.modelSetting.getInitParamID(t),this.modelSetting.getInitParamValue(t));for(let t=0;t<this.modelSetting.getInitPartsVisibleNum();t++)this.live2DModel.setPartsOpacity(this.modelSetting.getInitPartsVisibleID(t),this.modelSetting.getInitPartsVisibleValue(t));this.live2DModel.saveParam(),this.preloadMotionGroup(y),this.mainMotionManager.stopAllMotions(),this.setUpdating(!1),this.setInitialized(!0),\"function\"==typeof t&&t()}}))}}))}async loadModelSetting(t,e){this.setUpdating(!0),this.setInitialized(!1),this.modelHomeDir=t.substring(0,t.lastIndexOf(\"/\")+1),this.modelSetting=new F,this.modelSetting.json=e,await new Promise((t=>this.loadJSON(t)))}load(t,e,i){this.setUpdating(!0),this.setInitialized(!1),this.modelHomeDir=e.substring(0,e.lastIndexOf(\"/\")+1),this.modelSetting=new F,this.modelSetting.loadModelSetting(e,(()=>{this.loadJSON(i)}))}release(t){const e=M.getPlatformManager();t.deleteTexture(e.texture)}preloadMotionGroup(t){for(let e=0;e<this.modelSetting.getMotionNum(t);e++){const i=this.modelSetting.getMotionFile(t,e);this.loadMotion(i,this.modelHomeDir+i,(i=>{i.setFadeIn(this.modelSetting.getMotionFadeIn(t,e)),i.setFadeOut(this.modelSetting.getMotionFadeOut(t,e))}))}}update(){if(null==this.live2DModel)return void t.error(\"Failed to update.\");const e=2*((UtSystem.getUserTimeMSec()-this.startTimeMSec)/1e3)*Math.PI;this.mainMotionManager.isFinished()&&this.startRandomMotion(y,x),this.live2DModel.loadParam();this.mainMotionManager.updateParam(this.live2DModel)||null!=this.eyeBlink&&this.eyeBlink.updateParam(this.live2DModel),this.live2DModel.saveParam(),null==this.expressionManager||null==this.expressions||this.expressionManager.isFinished()||this.expressionManager.updateParam(this.live2DModel),this.live2DModel.addToParamFloat(\"PARAM_ANGLE_X\",30*this.dragX,1),this.live2DModel.addToParamFloat(\"PARAM_ANGLE_Y\",30*this.dragY,1),this.live2DModel.addToParamFloat(\"PARAM_ANGLE_Z\",this.dragX*this.dragY*-30,1),this.live2DModel.addToParamFloat(\"PARAM_BODY_ANGLE_X\",10*this.dragX,1),this.live2DModel.addToParamFloat(\"PARAM_EYE_BALL_X\",this.dragX,1),this.live2DModel.addToParamFloat(\"PARAM_EYE_BALL_Y\",this.dragY,1),this.live2DModel.addToParamFloat(\"PARAM_ANGLE_X\",Number(15*Math.sin(e/6.5345)),.5),this.live2DModel.addToParamFloat(\"PARAM_ANGLE_Y\",Number(8*Math.sin(e/3.5345)),.5),this.live2DModel.addToParamFloat(\"PARAM_ANGLE_Z\",Number(10*Math.sin(e/5.5345)),.5),this.live2DModel.addToParamFloat(\"PARAM_BODY_ANGLE_X\",Number(4*Math.sin(e/15.5345)),.5),this.live2DModel.setParamFloat(\"PARAM_BREATH\",Number(.5+.5*Math.sin(e/3.2345)),1),null!=this.physics&&this.physics.updateParam(this.live2DModel),null==this.lipSync&&this.live2DModel.setParamFloat(\"PARAM_MOUTH_OPEN_Y\",this.lipSyncValue),null!=this.pose&&this.pose.updateParam(this.live2DModel),this.live2DModel.update()}setRandomExpression(){const t=[];for(const e in this.expressions)t.push(e);const e=parseInt(Math.random()*t.length);this.setExpression(t[e])}startRandomMotion(t,e){const i=this.modelSetting.getMotionNum(t),s=parseInt(Math.random()*i);this.startMotion(t,s,e)}startMotion(e,i,s){const n=this.modelSetting.getMotionFile(e,i);if(null==n||\"\"==n)return;if(s==A)this.mainMotionManager.setReservePriority(s);else if(!this.mainMotionManager.reserveMotion(s))return void t.trace(\"Motion is running.\");let a;null==this.motions[e]?this.loadMotion(null,this.modelHomeDir+n,(t=>{a=t,this.setFadeInFadeOut(e,i,s,a)})):(a=this.motions[e],this.setFadeInFadeOut(e,i,s,a))}setFadeInFadeOut(e,i,s,n){const a=this.modelSetting.getMotionFile(e,i);if(n.setFadeIn(this.modelSetting.getMotionFadeIn(e,i)),n.setFadeOut(this.modelSetting.getMotionFadeOut(e,i)),t.trace(\"Start motion : \"+a),null==this.modelSetting.getMotionSound(e,i))this.mainMotionManager.startMotionPrio(n,s);else{const a=this.modelSetting.getMotionSound(e,i),r=document.createElement(\"audio\");r.src=this.modelHomeDir+a,t.trace(\"Start sound : \"+a),r.play(),this.mainMotionManager.startMotionPrio(n,s)}}setExpression(e){var i;const s=this.expressions[e];t.trace(\"Expression : \"+e),null===(i=this.expressionManager)||void 0===i||i.startMotion(s,!1)}draw(t){w.push(),w.multMatrix(this.modelMatrix.getArray()),this.tmpMatrix=w.getMatrix(),this.live2DModel.setMatrix(this.tmpMatrix),this.live2DModel.draw(),w.pop()}hitTest(t,e,i){const s=this.modelSetting.getHitAreaNum();if(0==s){const s=this.modelSetting.getHitAreaCustom();if(s){const n=s[t+\"_x\"],a=s[t+\"_y\"];if(e>Math.min(...n)&&e<Math.max(...n)&&i>Math.min(...a)&&i<Math.max(...a))return!0}}for(let n=0;n<s;n++)if(t==this.modelSetting.getHitAreaName(n)){const t=this.modelSetting.getHitAreaID(n);return this.hitTestSimple(t,e,i)}return!1}}class X{constructor(){this.cache={}}loadBytes(t,e){if(t in this.cache)return e(this.cache[t]);fetch(t).then((t=>t.arrayBuffer())).then((i=>{this.cache[t]=i,e(i)}))}loadLive2DModel(t,e){let i=null;this.loadBytes(t,(t=>{i=Live2DModelWebGL.loadModel(t),e(i)}))}loadTexture(e,i,s,n){const a=new Image;a.crossOrigin=\"anonymous\",a.src=s,a.onload=()=>{const s=document.getElementById(\"live2d\").getContext(\"webgl2\",{premultipliedAlpha:!0,preserveDrawingBuffer:!0});let r=s.createTexture();if(!r)return t.error(\"Failed to generate gl texture name.\"),-1;0==e.isPremultipliedAlpha()&&s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1),s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,1),s.activeTexture(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,r),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,s.RGBA,s.UNSIGNED_BYTE,a),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR_MIPMAP_NEAREST),s.generateMipmap(s.TEXTURE_2D),e.setTexture(i,r),r=null,\"function\"==typeof n&&n()},a.onerror=()=>{t.error(\"Failed to load image : \"+s)}}jsonParseFromBytes(t){let e;const i=new Uint8Array(t,0,3);e=239==i[0]&&187==i[1]&&191==i[2]?String.fromCharCode.apply(null,new Uint8Array(t,3)):String.fromCharCode.apply(null,new Uint8Array(t));return JSON.parse(e)}}class Y{constructor(){this.model=null,this.reloading=!1,Live2D.init(),M.setPlatformManager(new X)}getModel(){return this.model}releaseModel(t){this.model&&(this.model.release(t),this.model=null)}async changeModel(t,e){return new Promise(((i,s)=>{if(this.reloading)return;this.reloading=!0;const n=this.model,a=new U;a.load(t,e,(()=>{n&&n.release(t),this.model=a,this.reloading=!1,i()}))}))}async changeModelWithJSON(t,e,i){if(this.reloading)return;this.reloading=!0;const s=this.model,n=new U;await n.loadModelSetting(e,i),s&&s.release(t),this.model=n,this.reloading=!1}setDrag(t,e){this.model&&this.model.setDrag(t,e)}maxScaleEvent(){t.trace(\"Max scale event.\"),this.model&&this.model.startRandomMotion(O,f)}minScaleEvent(){t.trace(\"Min scale event.\"),this.model&&this.model.startRandomMotion(D,f)}tapEvent(e,i){return t.trace(\"tapEvent view x:\"+e+\" y:\"+i),!!this.model&&(this.model.hitTest(L,e,i)?(t.trace(\"Tap face.\"),this.model.setRandomExpression()):this.model.hitTest(N,e,i)&&(t.trace(\"Tap body.\"),this.model.startRandomMotion(R,f)),!0)}}function j(t,e,i,s,n,a){const r=t-i,o=e-s;let h=0,l=0;return h=r>=0?r/(n-i):r/i,l=o>=0?o/(a-s):o/s,{vx:h,vy:-l}}class G{constructor(){this.live2DMgr=new Y,this.isDrawStart=!1,this.gl=null,this.canvas=null,this.dragMgr=null,this.viewMatrix=null,this.projMatrix=null,this.deviceToScreen=null,this.oldLen=0,this._boundMouseEvent=this.mouseEvent.bind(this),this._boundTouchEvent=this.touchEvent.bind(this)}initL2dCanvas(t){this.canvas=document.getElementById(t),this.canvas.addEventListener&&(this.canvas.addEventListener(\"mousewheel\",this._boundMouseEvent,!1),this.canvas.addEventListener(\"click\",this._boundMouseEvent,!1),document.addEventListener(\"mousemove\",this._boundMouseEvent,!1),document.addEventListener(\"mouseout\",this._boundMouseEvent,!1),this.canvas.addEventListener(\"contextmenu\",this._boundMouseEvent,!1),this.canvas.addEventListener(\"touchstart\",this._boundTouchEvent,!1),this.canvas.addEventListener(\"touchend\",this._boundTouchEvent,!1),this.canvas.addEventListener(\"touchmove\",this._boundTouchEvent,!1))}async init(e,i,s){this.initL2dCanvas(e);const n=this.canvas.width,a=this.canvas.height;this.dragMgr=new m;const r=a/n,h=p,l=E,c=-r,d=r;this.viewMatrix=new g,this.viewMatrix.setScreenRect(h,l,c,d),this.viewMatrix.setMaxScreenRect(v,P,_,I),this.viewMatrix.setMaxScale(S),this.viewMatrix.setMinScale(T),this.projMatrix=new o,this.projMatrix.multScale(1,n/a),this.deviceToScreen=new o,this.deviceToScreen.multTranslate(-n/2,-a/2),this.deviceToScreen.multScale(2/n,-2/n),this.gl=this.canvas.getContext(\"webgl2\",{premultipliedAlpha:!0,preserveDrawingBuffer:!0}),this.gl?(Live2D.setGL(this.gl),this.gl.clearColor(0,0,0,0),await this.changeModelWithJSON(i,s),this.startDraw()):t.error(\"Failed to create WebGL context.\")}destroy(){this.canvas&&(this.canvas.removeEventListener(\"mousewheel\",this._boundMouseEvent,!1),this.canvas.removeEventListener(\"click\",this._boundMouseEvent,!1),document.removeEventListener(\"mousemove\",this._boundMouseEvent,!1),document.removeEventListener(\"mouseout\",this._boundMouseEvent,!1),this.canvas.removeEventListener(\"contextmenu\",this._boundMouseEvent,!1),this.canvas.removeEventListener(\"touchstart\",this._boundTouchEvent,!1),this.canvas.removeEventListener(\"touchend\",this._boundTouchEvent,!1),this.canvas.removeEventListener(\"touchmove\",this._boundTouchEvent,!1)),this._drawFrameId&&(window.cancelAnimationFrame(this._drawFrameId),this._drawFrameId=null),this.isDrawStart=!1,this.live2DMgr&&\"function\"==typeof this.live2DMgr.release&&this.live2DMgr.release(),this.gl,this.canvas=null,this.gl=null,this.dragMgr=null,this.viewMatrix=null,this.projMatrix=null,this.deviceToScreen=null}startDraw(){if(!this.isDrawStart){this.isDrawStart=!0;const t=()=>{this.draw(),this._drawFrameId=window.requestAnimationFrame(t,this.canvas)};t()}}draw(){w.reset(),w.loadIdentity(),this.dragMgr.update(),this.live2DMgr.setDrag(this.dragMgr.getX(),this.dragMgr.getY()),this.gl.clear(this.gl.COLOR_BUFFER_BIT),w.multMatrix(this.projMatrix.getArray()),w.multMatrix(this.viewMatrix.getArray()),w.push();const t=this.live2DMgr.getModel();null!=t&&(t.initialized&&!t.updating&&(t.update(),t.draw(this.gl)),w.pop())}async changeModel(t){await this.live2DMgr.changeModel(this.gl,t)}async changeModelWithJSON(t,e){await this.live2DMgr.changeModelWithJSON(this.gl,t,e)}modelScaling(t){const e=this.viewMatrix.isMaxScale(),i=this.viewMatrix.isMinScale();this.viewMatrix.adjustScale(0,0,t),e||this.viewMatrix.isMaxScale()&&this.live2DMgr.maxScaleEvent(),i||this.viewMatrix.isMinScale()&&this.live2DMgr.minScaleEvent()}modelTurnHead(e){var i;const s=this.canvas.getBoundingClientRect(),{vx:n,vy:a}=j(e.clientX,e.clientY,s.left+s.width/2,s.top+s.height/2,window.innerWidth,window.innerHeight);t.trace(\"onMouseDown device( x:\"+e.clientX+\" y:\"+e.clientY+\" ) view( x:\"+n+\" y:\"+a+\")\"),this.dragMgr.setPoint(n,a),this.live2DMgr.tapEvent(n,a),(null===(i=this.live2DMgr)||void 0===i?void 0:i.model.hitTest(N,n,a))&&window.dispatchEvent(new Event(\"live2d:tapbody\"))}followPointer(e){var i;const s=this.canvas.getBoundingClientRect(),{vx:n,vy:a}=j(e.clientX,e.clientY,s.left+s.width/2,s.top+s.height/2,window.innerWidth,window.innerHeight);t.trace(\"onMouseMove device( x:\"+e.clientX+\" y:\"+e.clientY+\" ) view( x:\"+n+\" y:\"+a+\")\"),this.dragMgr.setPoint(n,a),(null===(i=this.live2DMgr)||void 0===i?void 0:i.model.hitTest(N,n,a))&&window.dispatchEvent(new Event(\"live2d:hoverbody\"))}lookFront(){this.dragMgr.setPoint(0,0)}mouseEvent(t){t.preventDefault(),\"mousewheel\"==t.type?t.wheelDelta>0?this.modelScaling(1.1):this.modelScaling(.9):\"click\"==t.type||\"contextmenu\"==t.type?this.modelTurnHead(t):\"mousemove\"==t.type?this.followPointer(t):\"mouseout\"==t.type&&this.lookFront()}touchEvent(t){t.preventDefault();const e=t.touches[0];if(\"touchstart\"==t.type)1==t.touches.length&&this.modelTurnHead(e);else if(\"touchmove\"==t.type){if(this.followPointer(e),2==t.touches.length){const e=t.touches[0],i=t.touches[1],s=Math.pow(e.pageX-i.pageX,2)+Math.pow(e.pageY-i.pageY,2);this.oldLen-s<0?this.modelScaling(1.025):this.modelScaling(.975),this.oldLen=s}}else\"touchend\"==t.type&&this.lookFront()}transformViewX(t){const e=this.deviceToScreen.transformX(t);return this.viewMatrix.invertTransformX(e)}transformViewY(t){const e=this.deviceToScreen.transformY(t);return this.viewMatrix.invertTransformY(e)}transformScreenX(t){return this.deviceToScreen.transformX(t)}transformScreenY(t){return this.deviceToScreen.transformY(t)}}export{G as default};\n//# sourceMappingURL=index.js.map\n"
  },
  {
    "path": "dist/chunk/index2.js",
    "content": "/*!\n * Live2D Widget\n * https://github.com/stevenjoezhang/live2d-widget\n */\nimport{l as t}from\"../waifu-tips.js\";class e{constructor(t=0){t<1?(this._ptr=[],this._capacity=0,this._size=0):(this._ptr=new Array(t),this._capacity=t,this._size=0)}at(t){return this._ptr[t]}set(t,e){this._ptr[t]=e}get(t=0){const e=new Array;for(let i=t;i<this._size;i++)e.push(this._ptr[i]);return e}pushBack(t){this._size>=this._capacity&&this.prepareCapacity(0==this._capacity?e.DefaultSize:2*this._capacity),this._ptr[this._size++]=t}clear(){this._ptr.length=0,this._size=0}getSize(){return this._size}assign(t,e){this._size<t&&this.prepareCapacity(t);for(let i=0;i<t;i++)this._ptr[i]=e;this._size=t}resize(t,e=null){this.updateSize(t,e,!0)}updateSize(t,e=null,i=!0){if(this._size<t)if(this.prepareCapacity(t),i)for(let i=this._size;i<t;i++)this._ptr[i]=\"function\"==typeof e?JSON.parse(JSON.stringify(new e)):e;else for(let i=this._size;i<t;i++)this._ptr[i]=e;else{const e=this._size-t;this._ptr.splice(this._size-e,e)}this._size=t}insert(t,e,i){let s=t._index;const r=e._index,a=i._index,n=a-r;this.prepareCapacity(this._size+n);const o=this._size-s;if(o>0)for(let t=0;t<o;t++)this._ptr.splice(s+t,0,null);for(let t=r;t<a;t++,s++)this._ptr[s]=e._vector._ptr[t];this._size=this._size+n}remove(t){return!(t<0||this._size<=t)&&(this._ptr.splice(t,1),--this._size,!0)}erase(t){const e=t._index;if(e<0||this._size<=e)return t;this._ptr.splice(e,1),--this._size;return new i(this,e)}prepareCapacity(t){t>this._capacity&&(0==this._capacity?(this._ptr=new Array(t),this._capacity=t):(this._ptr.length=t,this._capacity=t))}begin(){return 0==this._size?this.end():new i(this,0)}end(){return new i(this,this._size)}getOffset(t){const i=new e;return i._ptr=this.get(t),i._size=this.get(t).length,i._capacity=this.get(t).length,i}}e.DefaultSize=10;let i=class t{constructor(t,e){this._vector=null!=t?t:null,this._index=null!=e?e:0}set(t){return this._index=t._index,this._vector=t._vector,this}preIncrement(){return++this._index,this}preDecrement(){return--this._index,this}increment(){return new t(this._vector,this._index++)}decrement(){return new t(this._vector,this._index--)}ptr(){return this._vector._ptr[this._index]}substitution(t){return this._index=t._index,this._vector=t._vector,this}notEqual(t){return this._index!=t._index||this._vector!=t._vector}};var s,r,a,n,o,l,h,u;!function(t){t.csmVector=e,t.iterator=i}(s||(s={}));class g{append(t,e){return this.s+=void 0!==e?t.substr(0,e):t,this}expansion(t,e){for(let i=0;i<t;i++)this.append(e);return this}getBytes(){return encodeURIComponent(this.s).replace(/%../g,\"x\").length}getLength(){return this.s.length}isLess(t){return this.s<t.s}isGreat(t){return this.s>t.s}isEqual(t){return this.s==t}isEmpty(){return 0==this.s.length}constructor(t){this.s=t}}(r||(r={})).csmString=g;class d{static createIdInternal(t){return new d(t)}getString(){return this._id}isEqual(t){return\"string\"==typeof t?this._id.isEqual(t):t instanceof g?this._id.isEqual(t.s):t instanceof d&&this._id.isEqual(t._id.s)}isNotEqual(t){return\"string\"==typeof t?!this._id.isEqual(t):t instanceof g?!this._id.isEqual(t.s):t instanceof d&&!this._id.isEqual(t._id.s)}constructor(t){this._id=\"string\"!=typeof t?t:new g(t)}}(a||(a={})).CubismId=d;class _{constructor(){this._ids=new e}release(){for(let t=0;t<this._ids.getSize();++t)this._ids.set(t,void 0);this._ids=null}registerIds(t){for(let e=0;e<t.length;e++)this.registerId(t[e])}registerId(t){let e=null;return\"string\"!=typeof t?this.registerId(t.s):(null!=(e=this.findId(t))||(e=d.createIdInternal(t),this._ids.pushBack(e)),e)}getId(t){return this.registerId(t)}isExist(t){return\"string\"==typeof t?null!=this.findId(t):this.isExist(t.s)}findId(t){for(let e=0;e<this._ids.getSize();++e)if(this._ids.at(e).getString().isEqual(t))return this._ids.at(e);return null}}(n||(n={})).CubismIdManager=_;class c{constructor(){this._tr=new Float32Array(16),this.loadIdentity()}static multiply(t,e,i){const s=new Float32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);for(let i=0;i<4;++i)for(let r=0;r<4;++r)for(let a=0;a<4;++a)s[r+4*i]+=t[a+4*i]*e[r+4*a];for(let t=0;t<16;++t)i[t]=s[t]}loadIdentity(){const t=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);this.setMatrix(t)}setMatrix(t){for(let e=0;e<16;++e)this._tr[e]=t[e]}getArray(){return this._tr}getScaleX(){return this._tr[0]}getScaleY(){return this._tr[5]}getTranslateX(){return this._tr[12]}getTranslateY(){return this._tr[13]}transformX(t){return this._tr[0]*t+this._tr[12]}transformY(t){return this._tr[5]*t+this._tr[13]}invertTransformX(t){return(t-this._tr[12])/this._tr[0]}invertTransformY(t){return(t-this._tr[13])/this._tr[5]}translateRelative(t,e){const i=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,t,e,0,1]);c.multiply(i,this._tr,this._tr)}translate(t,e){this._tr[12]=t,this._tr[13]=e}translateX(t){this._tr[12]=t}translateY(t){this._tr[13]=t}scaleRelative(t,e){const i=new Float32Array([t,0,0,0,0,e,0,0,0,0,1,0,0,0,0,1]);c.multiply(i,this._tr,this._tr)}scale(t,e){this._tr[0]=t,this._tr[5]=e}multiplyByMatrix(t){c.multiply(t.getArray(),this._tr,this._tr)}clone(){const t=new c;for(let e=0;e<this._tr.length;e++)t._tr[e]=this._tr[e];return t}}(o||(o={})).CubismMatrix44=c;class m{constructor(t,e,i,s){this.x=t,this.y=e,this.width=i,this.height=s}getCenterX(){return this.x+.5*this.width}getCenterY(){return this.y+.5*this.height}getRight(){return this.x+this.width}getBottom(){return this.y+this.height}setRect(t){this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height}expand(t,e){this.x-=t,this.y-=e,this.width+=2*t,this.height+=2*e}}(l||(l={})).csmRect=m;class p{static create(){return null}static delete(t){}initialize(t){this._model=t}drawModel(){null!=this.getModel()&&(this.saveProfile(),this.doDrawModel(),this.restoreProfile())}setMvpMatrix(t){this._mvpMatrix4x4.setMatrix(t.getArray())}getMvpMatrix(){return this._mvpMatrix4x4}setModelColor(t,e,i,s){t<0?t=0:t>1&&(t=1),e<0?e=0:e>1&&(e=1),i<0?i=0:i>1&&(i=1),s<0?s=0:s>1&&(s=1),this._modelColor.r=t,this._modelColor.g=e,this._modelColor.b=i,this._modelColor.a=s}getModelColor(){return JSON.parse(JSON.stringify(this._modelColor))}getModelColorWithOpacity(t){const e=this.getModelColor();return e.a*=t,this.isPremultipliedAlpha()&&(e.r*=e.a,e.g*=e.a,e.b*=e.a),e}setIsPremultipliedAlpha(t){this._isPremultipliedAlpha=t}isPremultipliedAlpha(){return this._isPremultipliedAlpha}setIsCulling(t){this._isCulling=t}isCulling(){return this._isCulling}setAnisotropy(t){this._anisotropy=t}getAnisotropy(){return this._anisotropy}getModel(){return this._model}useHighPrecisionMask(t){this._useHighPrecisionMask=t}isUsingHighPrecisionMask(){return this._useHighPrecisionMask}constructor(){this._isCulling=!1,this._isPremultipliedAlpha=!1,this._anisotropy=0,this._model=null,this._modelColor=new f,this._useHighPrecisionMask=!1,this._mvpMatrix4x4=new c,this._mvpMatrix4x4.loadIdentity()}}!function(t){t[t.CubismBlendMode_Normal=0]=\"CubismBlendMode_Normal\",t[t.CubismBlendMode_Additive=1]=\"CubismBlendMode_Additive\",t[t.CubismBlendMode_Multiplicative=2]=\"CubismBlendMode_Multiplicative\"}(h||(h={}));class f{constructor(t=1,e=1,i=1,s=1){this.r=t,this.g=e,this.b=i,this.a=s}}class y{constructor(t,e){this._clippingIdList=t,this._clippingIdCount=e,this._allClippedDrawRect=new m,this._layoutBounds=new m,this._clippedDrawableIndexList=[],this._matrixForMask=new c,this._matrixForDraw=new c,this._bufferIndex=0}release(){null!=this._layoutBounds&&(this._layoutBounds=null),null!=this._allClippedDrawRect&&(this._allClippedDrawRect=null),null!=this._clippedDrawableIndexList&&(this._clippedDrawableIndexList=null)}addClippedDrawable(t){this._clippedDrawableIndexList.push(t)}}!function(t){t.CubismBlendMode=h,t.CubismRenderer=p,t.CubismTextureColor=f}(u||(u={}));const S=(t,e,i)=>{((t,e,i)=>{P.print(t,\"[CSM]\"+e,i)})(t,e+\"\\n\",i)},C=t=>{console.assert(t)};let x,M,v,b;x=(t,...e)=>{S(K.LogLevel_Debug,\"[D]\"+t,e)},M=(t,...e)=>{S(K.LogLevel_Info,\"[I]\"+t,e)},v=(t,...e)=>{S(K.LogLevel_Warning,\"[W]\"+t,e)},b=(t,...e)=>{S(K.LogLevel_Error,\"[E]\"+t,e)};class P{static print(t,e,i){if(t<$.getLoggingLevel())return;const s=$.coreLogFunction;if(!s)return;s(e.replace(/\\{(\\d+)\\}/g,((t,e)=>i[e])))}static dumpBytes(t,e,i){for(let s=0;s<i;s++)s%16==0&&s>0?this.print(t,\"\\n\"):s%8==0&&s>0&&this.print(t,\"  \"),this.print(t,\"{0} \",[255&e[s]]);this.print(t,\"\\n\")}constructor(){}}var B,w;(B||(B={})).CubismDebug=P;class F{constructor(t,e){this.first=null==t?null:t,this.second=null==e?null:e}}class I{constructor(t){null!=t?t<1?(this._keyValues=[],this._dummyValue=null,this._size=0):(this._keyValues=new Array(t),this._size=t):(this._keyValues=[],this._dummyValue=null,this._size=0)}release(){this.clear()}appendKey(t){let e=-1;for(let i=0;i<this._size;i++)if(this._keyValues[i].first==t){e=i;break}-1==e?(this.prepareCapacity(this._size+1,!1),this._keyValues[this._size]=new F(t),this._size+=1):v(\"The key `{0}` is already append.\",t)}getValue(t){let e=-1;for(let i=0;i<this._size;i++)if(this._keyValues[i].first==t){e=i;break}return e>=0?this._keyValues[e].second:(this.appendKey(t),this._keyValues[this._size-1].second)}setValue(t,e){let i=-1;for(let e=0;e<this._size;e++)if(this._keyValues[e].first==t){i=e;break}i>=0?this._keyValues[i].second=e:(this.appendKey(t),this._keyValues[this._size-1].second=e)}isExist(t){for(let e=0;e<this._size;e++)if(this._keyValues[e].first==t)return!0;return!1}clear(){this._keyValues=void 0,this._keyValues=null,this._keyValues=[],this._size=0}getSize(){return this._size}prepareCapacity(t,e){t>this._keyValues.length&&(0==this._keyValues.length?(!e&&t<I.DefaultSize&&(t=I.DefaultSize),this._keyValues.length=t):(!e&&t<2*this._keyValues.length&&(t=2*this._keyValues.length),this._keyValues.length=t))}begin(){return new V(this,0)}end(){return new V(this,this._size)}erase(t){const e=t._index;if(e<0||this._size<=e)return t;this._keyValues.splice(e,1),--this._size;return new V(this,e)}dumpAsInt(){for(let t=0;t<this._size;t++)x(\"{0} ,\",this._keyValues[t]),x(\"\\n\")}}I.DefaultSize=10;class V{constructor(t,e){this._map=null!=t?t:new I,this._index=null!=e?e:0}set(t){return this._index=t._index,this._map=t._map,this}preIncrement(){return++this._index,this}preDecrement(){return--this._index,this}increment(){return new V(this._map,this._index++)}decrement(){const t=new V(this._map,this._index);return this._map=t._map,this._index=t._index,this}ptr(){return this._map._keyValues[this._index]}notEqual(t){return this._index!=t._index||this._map!=t._map}}!function(t){t.csmMap=I,t.csmPair=F,t.iterator=V}(w||(w={}));class E{static parseJsonObject(t,e){return Object.keys(t).forEach((i=>{if(\"boolean\"==typeof t[i]){const s=Boolean(t[i]);e.put(i,new A(s))}else if(\"string\"==typeof t[i]){const s=String(t[i]);e.put(i,new O(s))}else if(\"number\"==typeof t[i]){const s=Number(t[i]);e.put(i,new D(s))}else t[i]instanceof Array?e.put(i,E.parseJsonArray(t[i])):t[i]instanceof Object?e.put(i,E.parseJsonObject(t[i],new U)):null==t[i]?e.put(i,new N):e.put(i,t[i])})),e}static parseJsonArray(t){const e=new z;return Object.keys(t).forEach((i=>{if(\"number\"==typeof Number(i))if(\"boolean\"==typeof t[i]){const s=Boolean(t[i]);e.add(new A(s))}else if(\"string\"==typeof t[i]){const s=String(t[i]);e.add(new O(s))}else if(\"number\"==typeof t[i]){const s=Number(t[i]);e.add(new D(s))}else t[i]instanceof Array?e.add(this.parseJsonArray(t[i])):t[i]instanceof Object?e.add(this.parseJsonObject(t[i],new U)):null==t[i]?e.add(new N):e.add(t[i]);else if(t[i]instanceof Array)e.add(this.parseJsonArray(t[i]));else if(t[i]instanceof Object)e.add(this.parseJsonObject(t[i],new U));else if(null==t[i])e.add(new N);else{const s=Array(t[i]);for(let t=0;t<s.length;t++)e.add(s[t])}})),e}}const R=\"Error: type mismatch\";let T=class t{constructor(){}getRawString(t,e){return this.getString(t,e)}toInt(t=0){return t}toFloat(t=0){return t}toBoolean(t=!1){return t}getSize(){return 0}getArray(t=null){return t}getVector(t=new e){return t}getMap(t){return t}getValueByIndex(e){return t.errorValue.setErrorNotForClientCall(R)}getValueByString(e){return t.nullValue.setErrorNotForClientCall(R)}getKeys(){return t.dummyKeys}isError(){return!1}isNull(){return!1}isBool(){return!1}isFloat(){return!1}isString(){return!1}isArray(){return!1}isMap(){return!1}equals(t){return!1}isStatic(){return!1}setErrorNotForClientCall(t){return k.errorValue}static staticInitializeNotForClientCall(){A.trueValue=new A(!0),A.falseValue=new A(!1),t.errorValue=new k(\"ERROR\",!0),t.nullValue=new N,t.dummyKeys=new e}static staticReleaseNotForClientCall(){A.trueValue=null,A.falseValue=null,t.errorValue=null,t.nullValue=null,t.dummyKeys=null}};class L{constructor(t,e){this._parseCallback=E.parseJsonObject,this._error=null,this._lineCount=0,this._root=null,null!=t&&this.parseBytes(t,e,this._parseCallback)}static create(t,e){const i=new L;return i.parseBytes(t,e,i._parseCallback)?i:(L.delete(i),null)}static delete(t){}getRoot(){return this._root}static arrayBufferToString(t){const e=new Uint8Array(t);let i=\"\";for(let t=0,s=e.length;t<s;++t)i+=\"%\"+this.pad(e[t].toString(16));return i=decodeURIComponent(i),i}static pad(t){return t.length<2?\"0\"+t:t}parseBytes(t,e,i){const s=new Array(1),r=L.arrayBufferToString(t);if(this._root=null==i?this.parseValue(r,e,0,s):i(JSON.parse(r),new U),this._error){let t=\"\\0\";return t=\"Json parse error : @line \"+(this._lineCount+1)+\"\\n\",this._root=new O(t),M(\"{0}\",this._root.getRawString()),!1}return null!=this._root||(this._root=new k(new g(this._error),!1),!1)}getParseError(){return this._error}checkEndOfFile(){return this._root.getArray()[1].equals(\"EOF\")}parseValue(t,e,i,s){if(this._error)return null;let r,a=null,n=i;for(;n<e;n++){switch(t[n]){case\"-\":case\".\":case\"0\":case\"1\":case\"2\":case\"3\":case\"4\":case\"5\":case\"6\":case\"7\":case\"8\":case\"9\":{const e=new Array(1);return r=X(t.slice(n),e),s[0]=t.indexOf(e[0]),new D(r)}case'\"':return new O(this.parseString(t,e,n+1,s));case\"[\":return a=this.parseArray(t,e,n+1,s),a;case\"{\":return a=this.parseObject(t,e,n+1,s),a;case\"n\":return n+3<e?(a=new N,s[0]=n+4):this._error=\"parse null\",a;case\"t\":return n+3<e?(a=A.trueValue,s[0]=n+4):this._error=\"parse true\",a;case\"f\":return n+4<e?(a=A.falseValue,s[0]=n+5):this._error=\"illegal ',' position\",a;case\",\":return this._error=\"illegal ',' position\",null;case\"]\":return s[0]=n,null;case\"\\n\":this._lineCount++}}return this._error=\"illegal end of value\",null}parseString(t,e,i,s){if(this._error)return null;if(!t)return this._error=\"string is null\",null;let r,a,n=i;const o=new g(\"\");let l=i;for(;n<e;n++)switch(r=t[n],r){case'\"':return s[0]=n+1,o.append(t.slice(l),n-l),o.s;case\"//\":if(n++,n-1>l&&o.append(t.slice(l),n-l),l=n+1,n<e)switch(a=t[n],a){case\"\\\\\":o.expansion(1,\"\\\\\");break;case'\"':o.expansion(1,'\"');break;case\"/\":o.expansion(1,\"/\");break;case\"b\":o.expansion(1,\"\\b\");break;case\"f\":o.expansion(1,\"\\f\");break;case\"n\":o.expansion(1,\"\\n\");break;case\"r\":o.expansion(1,\"\\r\");break;case\"t\":o.expansion(1,\"\\t\");break;case\"u\":this._error=\"parse string/unicord escape not supported\"}else this._error=\"parse string/escape error\"}return this._error=\"parse string/illegal end\",null}parseObject(t,e,i,s){if(this._error)return null;if(!t)return this._error=\"buffer is null\",null;const r=new U;let a=\"\",n=i,o=\"\";const l=Array(1);let h=!1;for(;n<e;n++){t:for(;n<e;n++)switch(o=t[n],o){case'\"':if(a=this.parseString(t,e,n+1,l),this._error)return null;n=l[0],h=!0;break t;case\"}\":return s[0]=n+1,r;case\":\":this._error=\"illegal ':' position\";break;case\"\\n\":this._lineCount++}if(!h)return this._error=\"key not found\",null;h=!1;t:for(;n<e;n++)switch(o=t[n],o){case\":\":h=!0,n++;break t;case\"}\":this._error=\"illegal '}' position\";break;case\"\\n\":this._lineCount++}if(!h)return this._error=\"':' not found\",null;const i=this.parseValue(t,e,n,l);if(this._error)return null;n=l[0],r.put(a,i);t:for(;n<e;n++)switch(o=t[n],o){case\",\":break t;case\"}\":return s[0]=n+1,r;case\"\\n\":this._lineCount++}}return this._error=\"illegal end of perseObject\",null}parseArray(t,e,i,s){if(this._error)return null;if(!t)return this._error=\"buffer is null\",null;let r,a=new z,n=i;const o=new Array(1);for(;n<e;n++){const i=this.parseValue(t,e,n,o);if(this._error)return null;n=o[0],i&&a.add(i);t:for(;n<e;n++)switch(r=t[n],r){case\",\":break t;case\"]\":return s[0]=n+1,a;case\"\\n\":++this._lineCount}}return a=void 0,this._error=\"illegal end of parseObject\",null}}class D extends T{constructor(t){super(),this._value=t}isFloat(){return!0}getString(t,e){return this._value=parseFloat(\"\\0\"),this._stringBuffer=\"\\0\",this._stringBuffer}toInt(t=0){return parseInt(this._value.toString())}toFloat(t=0){return this._value}equals(t){return\"number\"==typeof t&&(!Math.round(t)&&t==this._value)}}class A extends T{isBool(){return!0}toBoolean(t=!1){return this._boolValue}getString(t,e){return this._stringBuffer=this._boolValue?\"true\":\"false\",this._stringBuffer}equals(t){return\"boolean\"==typeof t&&t==this._boolValue}isStatic(){return!0}constructor(t){super(),this._boolValue=t}}class O extends T{constructor(t){super(),\"string\"==typeof t&&(this._stringBuffer=t),t instanceof g&&(this._stringBuffer=t.s)}isString(){return!0}getString(t,e){return this._stringBuffer}equals(t){return\"string\"==typeof t?this._stringBuffer==t:t instanceof g&&this._stringBuffer==t.s}}class k extends O{isStatic(){return this._isStatic}setErrorNotForClientCall(t){return this._stringBuffer=t,this}constructor(t,e){super(t),this._isStatic=e}isError(){return!0}}class N extends T{isNull(){return!0}getString(t,e){return this._stringBuffer}isStatic(){return!0}setErrorNotForClientCall(t){return this._stringBuffer=t,k.nullValue}constructor(){super(),this._stringBuffer=\"NullValue\"}}class z extends T{constructor(){super(),this._array=new e}release(){for(let t=this._array.begin();t.notEqual(this._array.end());t.preIncrement()){let e=t.ptr();e&&!e.isStatic()&&(e=void 0,e=null)}}isArray(){return!0}getValueByIndex(t){if(t<0||this._array.getSize()<=t)return T.errorValue.setErrorNotForClientCall(\"Error: index out of bounds\");const e=this._array.at(t);return null==e?T.nullValue:e}getValueByString(t){return T.errorValue.setErrorNotForClientCall(R)}getString(t,e){const i=e+\"[\\n\";for(let t=this._array.begin();t.notEqual(this._array.end());t.increment()){const i=t.ptr();this._stringBuffer+=e+\"\"+i.getString(e+\" \")+\"\\n\"}return this._stringBuffer=i+e+\"]\\n\",this._stringBuffer}add(t){this._array.pushBack(t)}getVector(t=null){return this._array}getSize(){return this._array.getSize()}}class U extends T{constructor(){super(),this._map=new I}release(){const t=this._map.begin();for(;t.notEqual(this._map.end());){let e=t.ptr().second;e&&!e.isStatic()&&(e=void 0,e=null),t.preIncrement()}}isMap(){return!0}getValueByString(t){if(t instanceof g){const e=this._map.getValue(t.s);return null==e?T.nullValue:e}for(let e=this._map.begin();e.notEqual(this._map.end());e.preIncrement())if(e.ptr().first==t)return null==e.ptr().second?T.nullValue:e.ptr().second;return T.nullValue}getValueByIndex(t){return T.errorValue.setErrorNotForClientCall(R)}getString(t,e){this._stringBuffer=e+\"{\\n\";const i=this._map.begin();for(;i.notEqual(this._map.end());){const t=i.ptr().first,s=i.ptr().second;this._stringBuffer+=e+\" \"+t+\" : \"+s.getString(e+\"   \")+\" \\n\",i.preIncrement()}return this._stringBuffer+=e+\"}\\n\",this._stringBuffer}getMap(t){return this._map}put(t,e){this._map.setValue(t,e)}getKeys(){if(!this._keys){this._keys=new e;const t=this._map.begin();for(;t.notEqual(this._map.end());){const e=t.ptr().first;this._keys.pushBack(e),t.preIncrement()}}return this._keys}getSize(){return this._keys.getSize()}}var G;function X(t,e){let i=0;for(let e=1;;e++){const s=t.slice(e-1,e);if(\"e\"==s||\"-\"==s||\"E\"==s)continue;const r=t.substring(0,e),a=Number(r);if(isNaN(a))break;i=e}let s=parseFloat(t);return isNaN(s)&&(s=NaN),e[0]=t.slice(i),s}!function(t){t.CubismJson=L,t.JsonArray=z,t.JsonBoolean=A,t.JsonError=k,t.JsonFloat=D,t.JsonMap=U,t.JsonNullvalue=N,t.JsonString=O,t.Value=T}(G||(G={}));let Y=!1,j=!1,H=null,q=null;const W=Object.freeze({vertexOffset:0,vertexStep:2});function J(t){t&&(t=void 0)}class ${static startUp(t=null){if(Y)return M(\"CubismFramework.startUp() is already done.\"),Y;if(H=t,null!=H&&Live2DCubismCore.Logging.csmSetLogFunction(H.logFunction),Y=!0,Y){const t=Live2DCubismCore.Version.csmGetVersion(),e=(16711680&t)>>16,i=65535&t,s=t;M(\"Live2D Cubism Core version: {0}.{1}.{2} ({3})\",(\"00\"+((4278190080&t)>>24)).slice(-2),(\"00\"+e).slice(-2),(\"0000\"+i).slice(-4),s)}return M(\"CubismFramework.startUp() is complete.\"),Y}static cleanUp(){Y=!1,j=!1,H=null,q=null}static initialize(t=0){C(Y),Y?j?v(\"CubismFramework.initialize() skipped, already initialized.\"):(T.staticInitializeNotForClientCall(),q=new _,Live2DCubismCore.Memory.initializeAmountOfMemory(t),j=!0,M(\"CubismFramework.initialize() is complete.\")):v(\"CubismFramework is not started.\")}static dispose(){C(Y),Y?j?(T.staticReleaseNotForClientCall(),q.release(),q=null,p.staticRelease(),j=!1,M(\"CubismFramework.dispose() is complete.\")):v(\"CubismFramework.dispose() skipped, not initialized.\"):v(\"CubismFramework is not started.\")}static isStarted(){return Y}static isInitialized(){return j}static coreLogFunction(t){Live2DCubismCore.Logging.csmGetLogFunction()&&Live2DCubismCore.Logging.csmGetLogFunction()(t)}static getLoggingLevel(){return null!=H?H.loggingLevel:K.LogLevel_Off}static getIdManager(){return q}constructor(){}}class Z{}var K,Q;!function(t){t[t.LogLevel_Verbose=0]=\"LogLevel_Verbose\",t[t.LogLevel_Debug=1]=\"LogLevel_Debug\",t[t.LogLevel_Info=2]=\"LogLevel_Info\",t[t.LogLevel_Warning=3]=\"LogLevel_Warning\",t[t.LogLevel_Error=4]=\"LogLevel_Error\",t[t.LogLevel_Off=5]=\"LogLevel_Off\"}(K||(K={})),function(t){t.Constant=W,t.csmDelete=J,t.CubismFramework=$}(Q||(Q={}));const tt=\"../../Resources/\",et=[\"Haru\",\"Hiyori\",\"Mark\",\"Natori\",\"Rice\",\"Mao\",\"Wanko\"],it=et.length,st=\"Body\",rt=K.LogLevel_Verbose;class at{static loadFileAsBytes(t,e){fetch(t).then((t=>t.arrayBuffer())).then((t=>e(t,t.byteLength)))}static getDeltaTime(){return this.deltaTime}static updateTime(){this.currentFrame=Date.now(),this.deltaTime=(this.currentFrame-this.lastFrame)/1e3,this.lastFrame=this.currentFrame}static printMessage(t){console.trace(t)}}at.lastUpdate=Date.now(),at.currentFrame=0,at.lastFrame=0,at.deltaTime=0;class nt{constructor(){this._gl=null,this._gl=null}initialize(t){return this._gl=t.getContext(\"webgl2\"),!!this._gl||(alert(\"Cannot initialize WebGL. This browser does not support.\"),this._gl=null,!1)}release(){}getGl(){return this._gl}}const ot=Object.freeze({HitAreaPrefix:\"HitArea\",HitAreaHead:\"Head\",HitAreaBody:\"Body\",PartsIdCore:\"Parts01Core\",PartsArmPrefix:\"Parts01Arm_\",PartsArmLPrefix:\"Parts01ArmL_\",PartsArmRPrefix:\"Parts01ArmR_\",ParamAngleX:\"ParamAngleX\",ParamAngleY:\"ParamAngleY\",ParamAngleZ:\"ParamAngleZ\",ParamEyeLOpen:\"ParamEyeLOpen\",ParamEyeLSmile:\"ParamEyeLSmile\",ParamEyeROpen:\"ParamEyeROpen\",ParamEyeRSmile:\"ParamEyeRSmile\",ParamEyeBallX:\"ParamEyeBallX\",ParamEyeBallY:\"ParamEyeBallY\",ParamEyeBallForm:\"ParamEyeBallForm\",ParamBrowLY:\"ParamBrowLY\",ParamBrowRY:\"ParamBrowRY\",ParamBrowLX:\"ParamBrowLX\",ParamBrowRX:\"ParamBrowRX\",ParamBrowLAngle:\"ParamBrowLAngle\",ParamBrowRAngle:\"ParamBrowRAngle\",ParamBrowLForm:\"ParamBrowLForm\",ParamBrowRForm:\"ParamBrowRForm\",ParamMouthForm:\"ParamMouthForm\",ParamMouthOpenY:\"ParamMouthOpenY\",ParamCheek:\"ParamCheek\",ParamBodyAngleX:\"ParamBodyAngleX\",ParamBodyAngleY:\"ParamBodyAngleY\",ParamBodyAngleZ:\"ParamBodyAngleZ\",ParamBreath:\"ParamBreath\",ParamArmLA:\"ParamArmLA\",ParamArmRA:\"ParamArmRA\",ParamArmLB:\"ParamArmLB\",ParamArmRB:\"ParamArmRB\",ParamHandL:\"ParamHandL\",ParamHandR:\"ParamHandR\",ParamHairFront:\"ParamHairFront\",ParamHairSide:\"ParamHairSide\",ParamHairBack:\"ParamHairBack\",ParamHairFluffy:\"ParamHairFluffy\",ParamShoulderY:\"ParamShoulderY\",ParamBustX:\"ParamBustX\",ParamBustY:\"ParamBustY\",ParamBaseX:\"ParamBaseX\",ParamBaseY:\"ParamBaseY\",ParamNONE:\"NONE:\"});var lt,ht,ut,gt,dt,_t,ct;!function(t){t.HitAreaBody=ot.HitAreaBody,t.HitAreaHead=ot.HitAreaHead,t.HitAreaPrefix=ot.HitAreaPrefix,t.ParamAngleX=ot.ParamAngleX,t.ParamAngleY=ot.ParamAngleY,t.ParamAngleZ=ot.ParamAngleZ,t.ParamArmLA=ot.ParamArmLA,t.ParamArmLB=ot.ParamArmLB,t.ParamArmRA=ot.ParamArmRA,t.ParamArmRB=ot.ParamArmRB,t.ParamBaseX=ot.ParamBaseX,t.ParamBaseY=ot.ParamBaseY,t.ParamBodyAngleX=ot.ParamBodyAngleX,t.ParamBodyAngleY=ot.ParamBodyAngleY,t.ParamBodyAngleZ=ot.ParamBodyAngleZ,t.ParamBreath=ot.ParamBreath,t.ParamBrowLAngle=ot.ParamBrowLAngle,t.ParamBrowLForm=ot.ParamBrowLForm,t.ParamBrowLX=ot.ParamBrowLX,t.ParamBrowLY=ot.ParamBrowLY,t.ParamBrowRAngle=ot.ParamBrowRAngle,t.ParamBrowRForm=ot.ParamBrowRForm,t.ParamBrowRX=ot.ParamBrowRX,t.ParamBrowRY=ot.ParamBrowRY,t.ParamBustX=ot.ParamBustX,t.ParamBustY=ot.ParamBustY,t.ParamCheek=ot.ParamCheek,t.ParamEyeBallForm=ot.ParamEyeBallForm,t.ParamEyeBallX=ot.ParamEyeBallX,t.ParamEyeBallY=ot.ParamEyeBallY,t.ParamEyeLOpen=ot.ParamEyeLOpen,t.ParamEyeLSmile=ot.ParamEyeLSmile,t.ParamEyeROpen=ot.ParamEyeROpen,t.ParamEyeRSmile=ot.ParamEyeRSmile,t.ParamHairBack=ot.ParamHairBack,t.ParamHairFluffy=ot.ParamHairFluffy,t.ParamHairFront=ot.ParamHairFront,t.ParamHairSide=ot.ParamHairSide,t.ParamHandL=ot.ParamHandL,t.ParamHandR=ot.ParamHandR,t.ParamMouthForm=ot.ParamMouthForm,t.ParamMouthOpenY=ot.ParamMouthOpenY,t.ParamNONE=ot.ParamNONE,t.ParamShoulderY=ot.ParamShoulderY,t.PartsArmLPrefix=ot.PartsArmLPrefix,t.PartsArmPrefix=ot.PartsArmPrefix,t.PartsArmRPrefix=ot.PartsArmRPrefix,t.PartsIdCore=ot.PartsIdCore}(lt||(lt={}));class mt{}(ht||(ht={})).ICubismModelSetting=mt,function(t){t[t.FrequestNode_Groups=0]=\"FrequestNode_Groups\",t[t.FrequestNode_Moc=1]=\"FrequestNode_Moc\",t[t.FrequestNode_Motions=2]=\"FrequestNode_Motions\",t[t.FrequestNode_Expressions=3]=\"FrequestNode_Expressions\",t[t.FrequestNode_Textures=4]=\"FrequestNode_Textures\",t[t.FrequestNode_Physics=5]=\"FrequestNode_Physics\",t[t.FrequestNode_Pose=6]=\"FrequestNode_Pose\",t[t.FrequestNode_HitAreas=7]=\"FrequestNode_HitAreas\"}(ut||(ut={}));class pt extends mt{constructor(t,i){super(),this.version=\"Version\",this.fileReferences=\"FileReferences\",this.groups=\"Groups\",this.layout=\"Layout\",this.hitAreas=\"HitAreas\",this.moc=\"Moc\",this.textures=\"Textures\",this.physics=\"Physics\",this.pose=\"Pose\",this.expressions=\"Expressions\",this.motions=\"Motions\",this.userData=\"UserData\",this.name=\"Name\",this.filePath=\"File\",this.id=\"Id\",this.ids=\"Ids\",this.target=\"Target\",this.idle=\"Idle\",this.tapBody=\"TapBody\",this.pinchIn=\"PinchIn\",this.pinchOut=\"PinchOut\",this.shake=\"Shake\",this.flickHead=\"FlickHead\",this.parameter=\"Parameter\",this.soundPath=\"Sound\",this.fadeInTime=\"FadeInTime\",this.fadeOutTime=\"FadeOutTime\",this.centerX=\"CenterX\",this.centerY=\"CenterY\",this.x=\"X\",this.y=\"Y\",this.width=\"Width\",this.height=\"Height\",this.lipSync=\"LipSync\",this.eyeBlink=\"EyeBlink\",this.initParameter=\"init_param\",this.initPartsVisible=\"init_parts_visible\",this.val=\"val\",this._json=L.create(t,i),this.getJson()&&(this._jsonValue=new e,this._jsonValue.pushBack(this.getJson().getRoot().getValueByString(this.groups)),this._jsonValue.pushBack(this.getJson().getRoot().getValueByString(this.fileReferences).getValueByString(this.moc)),this._jsonValue.pushBack(this.getJson().getRoot().getValueByString(this.fileReferences).getValueByString(this.motions)),this._jsonValue.pushBack(this.getJson().getRoot().getValueByString(this.fileReferences).getValueByString(this.expressions)),this._jsonValue.pushBack(this.getJson().getRoot().getValueByString(this.fileReferences).getValueByString(this.textures)),this._jsonValue.pushBack(this.getJson().getRoot().getValueByString(this.fileReferences).getValueByString(this.physics)),this._jsonValue.pushBack(this.getJson().getRoot().getValueByString(this.fileReferences).getValueByString(this.pose)),this._jsonValue.pushBack(this.getJson().getRoot().getValueByString(this.hitAreas)))}release(){L.delete(this._json),this._jsonValue=null}getJson(){return this._json}getModelFileName(){return this.isExistModelFile()?this._jsonValue.at(ut.FrequestNode_Moc).getRawString():\"\"}getTextureCount(){return this.isExistTextureFiles()?this._jsonValue.at(ut.FrequestNode_Textures).getSize():0}getTextureDirectory(){const t=this._jsonValue.at(ut.FrequestNode_Textures).getValueByIndex(0).getRawString().split(\"/\"),e=t.length-1;let i=\"\";for(let s=0;s<e;s++)i+=t[s],s<e-1&&(i+=\"/\");return i}getTextureFileName(t){return this._jsonValue.at(ut.FrequestNode_Textures).getValueByIndex(t).getRawString()}getHitAreasCount(){return this.isExistHitAreas()?this._jsonValue.at(ut.FrequestNode_HitAreas).getSize():0}getHitAreaId(t){return $.getIdManager().getId(this._jsonValue.at(ut.FrequestNode_HitAreas).getValueByIndex(t).getValueByString(this.id).getRawString())}getHitAreaName(t){return this._jsonValue.at(ut.FrequestNode_HitAreas).getValueByIndex(t).getValueByString(this.name).getRawString()}getPhysicsFileName(){return this.isExistPhysicsFile()?this._jsonValue.at(ut.FrequestNode_Physics).getRawString():\"\"}getPoseFileName(){return this.isExistPoseFile()?this._jsonValue.at(ut.FrequestNode_Pose).getRawString():\"\"}getExpressionCount(){return this.isExistExpressionFile()?this._jsonValue.at(ut.FrequestNode_Expressions).getSize():0}getExpressionName(t){return this._jsonValue.at(ut.FrequestNode_Expressions).getValueByIndex(t).getValueByString(this.name).getRawString()}getExpressionFileName(t){return this._jsonValue.at(ut.FrequestNode_Expressions).getValueByIndex(t).getValueByString(this.filePath).getRawString()}getMotionGroupCount(){return this.isExistMotionGroups()?this._jsonValue.at(ut.FrequestNode_Motions).getKeys().getSize():0}getMotionGroupName(t){return this.isExistMotionGroups()?this._jsonValue.at(ut.FrequestNode_Motions).getKeys().at(t):null}getMotionCount(t){return this.isExistMotionGroupName(t)?this._jsonValue.at(ut.FrequestNode_Motions).getValueByString(t).getSize():0}getMotionFileName(t,e){return this.isExistMotionGroupName(t)?this._jsonValue.at(ut.FrequestNode_Motions).getValueByString(t).getValueByIndex(e).getValueByString(this.filePath).getRawString():\"\"}getMotionSoundFileName(t,e){return this.isExistMotionSoundFile(t,e)?this._jsonValue.at(ut.FrequestNode_Motions).getValueByString(t).getValueByIndex(e).getValueByString(this.soundPath).getRawString():\"\"}getMotionFadeInTimeValue(t,e){return this.isExistMotionFadeIn(t,e)?this._jsonValue.at(ut.FrequestNode_Motions).getValueByString(t).getValueByIndex(e).getValueByString(this.fadeInTime).toFloat():-1}getMotionFadeOutTimeValue(t,e){return this.isExistMotionFadeOut(t,e)?this._jsonValue.at(ut.FrequestNode_Motions).getValueByString(t).getValueByIndex(e).getValueByString(this.fadeOutTime).toFloat():-1}getUserDataFile(){return this.isExistUserDataFile()?this.getJson().getRoot().getValueByString(this.fileReferences).getValueByString(this.userData).getRawString():\"\"}getLayoutMap(t){const e=this.getJson().getRoot().getValueByString(this.layout).getMap();if(null==e)return!1;let i=!1;for(const s=e.begin();s.notEqual(e.end());s.preIncrement())t.setValue(s.ptr().first,s.ptr().second.toFloat()),i=!0;return i}getEyeBlinkParameterCount(){if(!this.isExistEyeBlinkParameters())return 0;let t=0;for(let e=0;e<this._jsonValue.at(ut.FrequestNode_Groups).getSize();e++){const i=this._jsonValue.at(ut.FrequestNode_Groups).getValueByIndex(e);if(!i.isNull()&&!i.isError()&&i.getValueByString(this.name).getRawString()==this.eyeBlink){t=i.getValueByString(this.ids).getVector().getSize();break}}return t}getEyeBlinkParameterId(t){if(!this.isExistEyeBlinkParameters())return null;for(let e=0;e<this._jsonValue.at(ut.FrequestNode_Groups).getSize();e++){const i=this._jsonValue.at(ut.FrequestNode_Groups).getValueByIndex(e);if(!i.isNull()&&!i.isError()&&i.getValueByString(this.name).getRawString()==this.eyeBlink)return $.getIdManager().getId(i.getValueByString(this.ids).getValueByIndex(t).getRawString())}return null}getLipSyncParameterCount(){if(!this.isExistLipSyncParameters())return 0;let t=0;for(let e=0;e<this._jsonValue.at(ut.FrequestNode_Groups).getSize();e++){const i=this._jsonValue.at(ut.FrequestNode_Groups).getValueByIndex(e);if(!i.isNull()&&!i.isError()&&i.getValueByString(this.name).getRawString()==this.lipSync){t=i.getValueByString(this.ids).getVector().getSize();break}}return t}getLipSyncParameterId(t){if(!this.isExistLipSyncParameters())return null;for(let e=0;e<this._jsonValue.at(ut.FrequestNode_Groups).getSize();e++){const i=this._jsonValue.at(ut.FrequestNode_Groups).getValueByIndex(e);if(!i.isNull()&&!i.isError()&&i.getValueByString(this.name).getRawString()==this.lipSync)return $.getIdManager().getId(i.getValueByString(this.ids).getValueByIndex(t).getRawString())}return null}isExistModelFile(){const t=this._jsonValue.at(ut.FrequestNode_Moc);return!t.isNull()&&!t.isError()}isExistTextureFiles(){const t=this._jsonValue.at(ut.FrequestNode_Textures);return!t.isNull()&&!t.isError()}isExistHitAreas(){const t=this._jsonValue.at(ut.FrequestNode_HitAreas);return!t.isNull()&&!t.isError()}isExistPhysicsFile(){const t=this._jsonValue.at(ut.FrequestNode_Physics);return!t.isNull()&&!t.isError()}isExistPoseFile(){const t=this._jsonValue.at(ut.FrequestNode_Pose);return!t.isNull()&&!t.isError()}isExistExpressionFile(){const t=this._jsonValue.at(ut.FrequestNode_Expressions);return!t.isNull()&&!t.isError()}isExistMotionGroups(){const t=this._jsonValue.at(ut.FrequestNode_Motions);return!t.isNull()&&!t.isError()}isExistMotionGroupName(t){const e=this._jsonValue.at(ut.FrequestNode_Motions).getValueByString(t);return!e.isNull()&&!e.isError()}isExistMotionSoundFile(t,e){const i=this._jsonValue.at(ut.FrequestNode_Motions).getValueByString(t).getValueByIndex(e).getValueByString(this.soundPath);return!i.isNull()&&!i.isError()}isExistMotionFadeIn(t,e){const i=this._jsonValue.at(ut.FrequestNode_Motions).getValueByString(t).getValueByIndex(e).getValueByString(this.fadeInTime);return!i.isNull()&&!i.isError()}isExistMotionFadeOut(t,e){const i=this._jsonValue.at(ut.FrequestNode_Motions).getValueByString(t).getValueByIndex(e).getValueByString(this.fadeOutTime);return!i.isNull()&&!i.isError()}isExistUserDataFile(){const t=this.getJson().getRoot().getValueByString(this.fileReferences).getValueByString(this.userData);return!t.isNull()&&!t.isError()}isExistEyeBlinkParameters(){if(this._jsonValue.at(ut.FrequestNode_Groups).isNull()||this._jsonValue.at(ut.FrequestNode_Groups).isError())return!1;for(let t=0;t<this._jsonValue.at(ut.FrequestNode_Groups).getSize();++t)if(this._jsonValue.at(ut.FrequestNode_Groups).getValueByIndex(t).getValueByString(this.name).getRawString()==this.eyeBlink)return!0;return!1}isExistLipSyncParameters(){if(this._jsonValue.at(ut.FrequestNode_Groups).isNull()||this._jsonValue.at(ut.FrequestNode_Groups).isError())return!1;for(let t=0;t<this._jsonValue.at(ut.FrequestNode_Groups).getSize();++t)if(this._jsonValue.at(ut.FrequestNode_Groups).getValueByIndex(t).getValueByString(this.name).getRawString()==this.lipSync)return!0;return!1}}!function(t){t.CubismModelSettingJson=pt,t.FrequestNode=ut}(gt||(gt={}));class ft{static create(){return new ft}static delete(t){}setParameters(t){this._breathParameters=t}getParameters(){return this._breathParameters}updateParameters(t,e){this._currentTime+=e;const i=2*this._currentTime*Math.PI;for(let e=0;e<this._breathParameters.getSize();++e){const s=this._breathParameters.at(e);t.addParameterValueById(s.parameterId,s.offset+s.peak*Math.sin(i/s.cycle),s.weight)}}constructor(){this._currentTime=0}}class yt{constructor(t,e,i,s,r){this.parameterId=null==t?null:t,this.offset=null==e?0:e,this.peak=null==i?0:i,this.cycle=null==s?0:s,this.weight=null==r?0:r}}!function(t){t.BreathParameterData=yt,t.CubismBreath=ft}(dt||(dt={}));class St{static create(t=null){return new St(t)}static delete(t){}setBlinkingInterval(t){this._blinkingIntervalSeconds=t}setBlinkingSetting(t,e,i){this._closingSeconds=t,this._closedSeconds=e,this._openingSeconds=i}setParameterIds(t){this._parameterIds=t}getParameterIds(){return this._parameterIds}updateParameters(t,e){let i;this._userTimeSeconds+=e;let s=0;switch(this._blinkingState){case _t.EyeState_Closing:s=(this._userTimeSeconds-this._stateStartTimeSeconds)/this._closingSeconds,s>=1&&(s=1,this._blinkingState=_t.EyeState_Closed,this._stateStartTimeSeconds=this._userTimeSeconds),i=1-s;break;case _t.EyeState_Closed:s=(this._userTimeSeconds-this._stateStartTimeSeconds)/this._closedSeconds,s>=1&&(this._blinkingState=_t.EyeState_Opening,this._stateStartTimeSeconds=this._userTimeSeconds),i=0;break;case _t.EyeState_Opening:s=(this._userTimeSeconds-this._stateStartTimeSeconds)/this._openingSeconds,s>=1&&(s=1,this._blinkingState=_t.EyeState_Interval,this._nextBlinkingTime=this.determinNextBlinkingTiming()),i=s;break;case _t.EyeState_Interval:this._nextBlinkingTime<this._userTimeSeconds&&(this._blinkingState=_t.EyeState_Closing,this._stateStartTimeSeconds=this._userTimeSeconds),i=1;break;case _t.EyeState_First:default:this._blinkingState=_t.EyeState_Interval,this._nextBlinkingTime=this.determinNextBlinkingTiming(),i=1}St.CloseIfZero||(i=-i);for(let e=0;e<this._parameterIds.getSize();++e)t.setParameterValueById(this._parameterIds.at(e),i)}constructor(t){if(this._blinkingState=_t.EyeState_First,this._nextBlinkingTime=0,this._stateStartTimeSeconds=0,this._blinkingIntervalSeconds=4,this._closingSeconds=.1,this._closedSeconds=.05,this._openingSeconds=.15,this._userTimeSeconds=0,this._parameterIds=new e,null!=t)for(let e=0;e<t.getEyeBlinkParameterCount();++e)this._parameterIds.pushBack(t.getEyeBlinkParameterId(e))}determinNextBlinkingTiming(){const t=Math.random();return this._userTimeSeconds+t*(2*this._blinkingIntervalSeconds-1)}}St.CloseIfZero=!0,function(t){t[t.EyeState_First=0]=\"EyeState_First\",t[t.EyeState_Interval=1]=\"EyeState_Interval\",t[t.EyeState_Closing=2]=\"EyeState_Closing\",t[t.EyeState_Closed=3]=\"EyeState_Closed\",t[t.EyeState_Opening=4]=\"EyeState_Opening\"}(_t||(_t={})),function(t){t.CubismEyeBlink=St,t.EyeState=_t}(ct||(ct={}));const Ct=\"FadeInTime\",xt=\"Link\";class Mt{static create(t,e){const i=L.create(t,e);if(!i)return null;const s=new Mt,r=i.getRoot();r.getValueByString(Ct).isNull()||(s._fadeTimeSeconds=r.getValueByString(Ct).toFloat(.5),s._fadeTimeSeconds<0&&(s._fadeTimeSeconds=.5));const a=r.getValueByString(\"Groups\"),n=a.getSize();for(let t=0;t<n;++t){const e=a.getValueByIndex(t),i=e.getSize();let r=0;for(let t=0;t<i;++t){const i=e.getValueByIndex(t),a=new vt,n=$.getIdManager().getId(i.getValueByString(\"Id\").getRawString());if(a.partId=n,!i.getValueByString(xt).isNull()){const t=i.getValueByString(xt),e=t.getSize();for(let i=0;i<e;++i){const e=new vt,s=$.getIdManager().getId(t.getValueByIndex(i).getString());e.partId=s,a.link.pushBack(e)}}s._partGroups.pushBack(a.clone()),++r}s._partGroupCounts.pushBack(r)}return L.delete(i),s}static delete(t){}updateParameters(t,e){t!=this._lastModel&&this.reset(t),this._lastModel=t,e<0&&(e=0);let i=0;for(let s=0;s<this._partGroupCounts.getSize();s++){const r=this._partGroupCounts.at(s);this.doFade(t,e,i,r),i+=r}this.copyPartOpacities(t)}reset(t){let e=0;for(let i=0;i<this._partGroupCounts.getSize();++i){const s=this._partGroupCounts.at(i);for(let i=e;i<e+s;++i){this._partGroups.at(i).initialize(t);const s=this._partGroups.at(i).partIndex,r=this._partGroups.at(i).parameterIndex;if(!(s<0)){t.setPartOpacityByIndex(s,i==e?1:0),t.setParameterValueByIndex(r,i==e?1:0);for(let e=0;e<this._partGroups.at(i).link.getSize();++e)this._partGroups.at(i).link.at(e).initialize(t)}}e+=s}}copyPartOpacities(t){for(let e=0;e<this._partGroups.getSize();++e){const i=this._partGroups.at(e);if(0==i.link.getSize())continue;const s=this._partGroups.at(e).partIndex,r=t.getPartOpacityByIndex(s);for(let e=0;e<i.link.getSize();++e){const s=i.link.at(e).partIndex;s<0||t.setPartOpacityByIndex(s,r)}}}doFade(t,e,i,s){let r=-1,a=1;const n=.5;for(let n=i;n<i+s;++n){const i=this._partGroups.at(n).partIndex,s=this._partGroups.at(n).parameterIndex;if(t.getParameterValueByIndex(s)>.001){if(r>=0)break;if(r=n,0==this._fadeTimeSeconds){a=1;continue}a=t.getPartOpacityByIndex(i),a+=e/this._fadeTimeSeconds,a>1&&(a=1)}}r<0&&(r=0,a=1);for(let e=i;e<i+s;++e){const i=this._partGroups.at(e).partIndex;if(r==e)t.setPartOpacityByIndex(i,a);else{let e,s=t.getPartOpacityByIndex(i);e=a<n?-.5*a/n+1:(1-a)*n/.5;(1-e)*(1-a)>.15&&(e=1-.15/(1-a)),s>e&&(s=e),t.setPartOpacityByIndex(i,s)}}}constructor(){this._fadeTimeSeconds=.5,this._lastModel=null,this._partGroups=new e,this._partGroupCounts=new e}}class vt{constructor(t){if(this.parameterIndex=0,this.partIndex=0,this.link=new e,null!=t){this.partId=t.partId;for(const e=t.link.begin();e.notEqual(t.link.end());e.preIncrement())this.link.pushBack(e.ptr().clone())}}assignment(t){this.partId=t.partId;for(const e=t.link.begin();e.notEqual(t.link.end());e.preIncrement())this.link.pushBack(e.ptr().clone());return this}initialize(t){this.parameterIndex=t.getParameterIndex(this.partId),this.partIndex=t.getPartIndex(this.partId),t.setParameterValueByIndex(this.parameterIndex,1)}clone(){const t=new vt;t.partId=this.partId,t.parameterIndex=this.parameterIndex,t.partIndex=this.partIndex,t.link=new e;for(let e=this.link.begin();e.notEqual(this.link.end());e.increment())t.link.pushBack(e.ptr().clone());return t}}var bt,Pt,Bt,wt;!function(t){t.CubismPose=Mt,t.PartData=vt}(bt||(bt={}));class Ft extends c{constructor(t,e){super(),this._width=void 0!==t?t:0,this._height=void 0!==e?e:0,this.setHeight(2)}setWidth(t){const e=t/this._width,i=e;this.scale(e,i)}setHeight(t){const e=t/this._height,i=e;this.scale(e,i)}setPosition(t,e){this.translate(t,e)}setCenterPosition(t,e){this.centerX(t),this.centerY(e)}top(t){this.setY(t)}bottom(t){const e=this._height*this.getScaleY();this.translateY(t-e)}left(t){this.setX(t)}right(t){const e=this._width*this.getScaleX();this.translateX(t-e)}centerX(t){const e=this._width*this.getScaleX();this.translateX(t-e/2)}setX(t){this.translateX(t)}centerY(t){const e=this._height*this.getScaleY();this.translateY(t-e/2)}setY(t){this.translateY(t)}setupFromLayout(t){for(const e=t.begin();e.notEqual(t.end());e.preIncrement()){const t=e.ptr().first,i=e.ptr().second;\"width\"==t?this.setWidth(i):\"height\"==t&&this.setHeight(i)}for(const e=t.begin();e.notEqual(t.end());e.preIncrement()){const t=e.ptr().first,i=e.ptr().second;\"x\"==t?this.setX(i):\"y\"==t?this.setY(i):\"center_x\"==t?this.centerX(i):\"center_y\"==t?this.centerY(i):\"top\"==t?this.top(i):\"bottom\"==t?this.bottom(i):\"left\"==t?this.left(i):\"right\"==t&&this.right(i)}}}(Pt||(Pt={})).CubismModelMatrix=Ft;class It{constructor(t,e){this.x=t,this.y=e,this.x=null==t?0:t,this.y=null==e?0:e}add(t){const e=new It(0,0);return e.x=this.x+t.x,e.y=this.y+t.y,e}substract(t){const e=new It(0,0);return e.x=this.x-t.x,e.y=this.y-t.y,e}multiply(t){const e=new It(0,0);return e.x=this.x*t.x,e.y=this.y*t.y,e}multiplyByScaler(t){return this.multiply(new It(t,t))}division(t){const e=new It(0,0);return e.x=this.x/t.x,e.y=this.y/t.y,e}divisionByScalar(t){return this.division(new It(t,t))}getLength(){return Math.sqrt(this.x*this.x+this.y*this.y)}getDistanceWith(t){return Math.sqrt((this.x-t.x)*(this.x-t.x)+(this.y-t.y)*(this.y-t.y))}dot(t){return this.x*t.x+this.y*t.y}normalize(){const t=Math.pow(this.x*this.x+this.y*this.y,.5);this.x=this.x/t,this.y=this.y/t}isEqual(t){return this.x==t.x&&this.y==t.y}isNotEqual(t){return!this.isEqual(t)}}(Bt||(Bt={})).CubismVector2=It;class Vt{static range(t,e,i){return t<e?t=e:t>i&&(t=i),t}static sin(t){return Math.sin(t)}static cos(t){return Math.cos(t)}static abs(t){return Math.abs(t)}static sqrt(t){return Math.sqrt(t)}static cbrt(t){if(0===t)return t;let e=t;const i=e<0;let s;return i&&(e=-e),e===1/0?s=1/0:(s=Math.exp(Math.log(e)/3),s=(e/(s*s)+2*s)/3),i?-s:s}static getEasingSine(t){return t<0?0:t>1?1:.5-.5*this.cos(t*Math.PI)}static max(t,e){return t>e?t:e}static min(t,e){return t>e?e:t}static clamp(t,e,i){return t<e?e:i<t?i:t}static degreesToRadian(t){return t/180*Math.PI}static radianToDegrees(t){return 180*t/Math.PI}static directionToRadian(t,e){let i=Math.atan2(e.y,e.x)-Math.atan2(t.y,t.x);for(;i<-Math.PI;)i+=2*Math.PI;for(;i>Math.PI;)i-=2*Math.PI;return i}static directionToDegrees(t,e){const i=this.directionToRadian(t,e);let s=this.radianToDegrees(i);return e.x-t.x>0&&(s=-s),s}static radianToDirection(t){const e=new It;return e.x=this.sin(t),e.y=this.cos(t),e}static quadraticEquation(t,e,i){return this.abs(t)<Vt.Epsilon?this.abs(e)<Vt.Epsilon?-i:-i/e:-(e+this.sqrt(e*e-4*t*i))/(2*t)}static cardanoAlgorithmForBezier(t,e,i,s){if(this.abs(t)<Vt.Epsilon)return this.range(this.quadraticEquation(e,i,s),0,1);const r=e/t,a=i/t,n=(3*a-r*r)/3,o=n/3,l=(2*r*r*r-9*r*a+27*(s/t))/27,h=l/2,u=h*h+o*o*o,g=.5,d=.51;if(u<0){const t=-n/3,e=t*t*t,i=this.sqrt(e),s=-l/(2*i),a=this.range(s,-1,1),o=Math.acos(a),h=2*this.cbrt(i),u=h*this.cos(o/3)-r/3;if(this.abs(u-g)<d)return this.range(u,0,1);const _=h*this.cos((o+2*Math.PI)/3)-r/3;if(this.abs(_-g)<d)return this.range(_,0,1);const c=h*this.cos((o+4*Math.PI)/3)-r/3;return this.range(c,0,1)}if(0==u){let t;t=h<0?this.cbrt(-h):-this.cbrt(h);const e=2*t-r/3;if(this.abs(e-g)<d)return this.range(e,0,1);const i=-t-r/3;return this.range(i,0,1)}const _=this.sqrt(u),c=this.cbrt(_-h)-this.cbrt(_+h)-r/3;return this.range(c,0,1)}static mod(t,e){if(!isFinite(t)||0===e||isNaN(t)||isNaN(e))return console.warn(`divided: ${t}, divisor: ${e} mod() returns 'NaN'.`),NaN;const i=Math.abs(t),s=Math.abs(e);let r=i-Math.floor(i/s)*s;return r*=Math.sign(t),r}constructor(){}}Vt.Epsilon=1e-5,(wt||(wt={})).CubismMath=Vt;class Et{constructor(){this._faceTargetX=0,this._faceTargetY=0,this._faceX=0,this._faceY=0,this._faceVX=0,this._faceVY=0,this._lastTimeSeconds=0,this._userTimeSeconds=0}update(t){this._userTimeSeconds+=t;const e=4/30;if(0==this._lastTimeSeconds)return void(this._lastTimeSeconds=this._userTimeSeconds);const i=30*(this._userTimeSeconds-this._lastTimeSeconds);this._lastTimeSeconds=this._userTimeSeconds;const s=i*e/4.5,r=this._faceTargetX-this._faceX,a=this._faceTargetY-this._faceY;if(Vt.abs(r)<=.01&&Vt.abs(a)<=.01)return;const n=Vt.sqrt(r*r+a*a),o=e*a/n;let l=e*r/n-this._faceVX,h=o-this._faceVY;const u=Vt.sqrt(l*l+h*h);(u<-s||u>s)&&(l*=s/u,h*=s/u),this._faceVX+=l,this._faceVY+=h;{const t=.5*(Vt.sqrt(s*s+16*s*n-8*s*n)-s),e=Vt.sqrt(this._faceVX*this._faceVX+this._faceVY*this._faceVY);e>t&&(this._faceVX*=t/e,this._faceVY*=t/e)}this._faceX+=this._faceVX,this._faceY+=this._faceVY}getX(){return this._faceX}getY(){return this._faceY}set(t,e){this._faceTargetX=t,this._faceTargetY=e}}var Rt,Tt;(Rt||(Rt={})).CubismTargetPoint=Et;class Lt{static delete(t){t.release(),t=null}constructor(){this.setBeganMotionHandler=t=>this._onBeganMotion=t,this.getBeganMotionHandler=()=>this._onBeganMotion,this.setFinishedMotionHandler=t=>this._onFinishedMotion=t,this.getFinishedMotionHandler=()=>this._onFinishedMotion,this._fadeInSeconds=-1,this._fadeOutSeconds=-1,this._weight=1,this._offsetSeconds=0,this._isLoop=!1,this._isLoopFadeIn=!0,this._previousLoopState=this._isLoop,this._firedEventValues=new e}release(){this._weight=0}updateParameters(t,e,i){if(!e.isAvailable()||e.isFinished())return;this.setupMotionQueueEntry(e,i);const s=this.updateFadeWeight(e,i);this.doUpdateParameters(t,i,s,e),e.getEndTime()>0&&e.getEndTime()<i&&e.setIsFinished(!0)}setupMotionQueueEntry(t,e){null==t||t.isStarted()||t.isAvailable()&&(t.setIsStarted(!0),t.setStartTime(e-this._offsetSeconds),t.setFadeInStartTime(e),t.getEndTime()<0&&this.adjustEndTime(t),t._motion._onBeganMotion&&t._motion._onBeganMotion(t._motion))}updateFadeWeight(t,e){null==t&&P.print(K.LogLevel_Error,\"motionQueueEntry is null.\");let i=this._weight;return i=i*(0==this._fadeInSeconds?1:Vt.getEasingSine((e-t.getFadeInStartTime())/this._fadeInSeconds))*(0==this._fadeOutSeconds||t.getEndTime()<0?1:Vt.getEasingSine((t.getEndTime()-e)/this._fadeOutSeconds)),t.setState(e,i),C(0<=i&&i<=1),i}setFadeInTime(t){this._fadeInSeconds=t}setFadeOutTime(t){this._fadeOutSeconds=t}getFadeOutTime(){return this._fadeOutSeconds}getFadeInTime(){return this._fadeInSeconds}setWeight(t){this._weight=t}getWeight(){return this._weight}getDuration(){return-1}getLoopDuration(){return-1}setOffsetTime(t){this._offsetSeconds=t}setLoop(t){this._isLoop=t}getLoop(){return this._isLoop}setLoopFadeIn(t){this._isLoopFadeIn=t}getLoopFadeIn(){return this._isLoopFadeIn}getFiredEvent(t,e){return this._firedEventValues}isExistModelOpacity(){return!1}getModelOpacityIndex(){return-1}getModelOpacityId(t){return null}getModelOpacityValue(){return 1}adjustEndTime(t){const e=this.getDuration(),i=e<=0?-1:t.getStartTime()+e;t.setEndTime(i)}}(Tt||(Tt={})).ACubismMotion=Lt;const Dt=\"Parameters\",At=\"Blend\";class Ot extends Lt{static create(t,e){const i=new Ot;return i.parse(t,e),i}doUpdateParameters(t,e,i,s){for(let e=0;e<this._parameters.getSize();++e){const s=this._parameters.at(e);switch(s.blendType){case kt.Additive:t.addParameterValueById(s.parameterId,s.value,i);break;case kt.Multiply:t.multiplyParameterValueById(s.parameterId,s.value,i);break;case kt.Overwrite:t.setParameterValueById(s.parameterId,s.value,i)}}}calculateExpressionParameters(t,e,i,s,r,a){if(null!=i&&null!=s&&i.isAvailable()){this._fadeWeight=this.updateFadeWeight(i,e);for(let e=0;e<s.getSize();++e){const i=s.at(e);if(null==i.parameterId)continue;const n=i.overwriteValue=t.getParameterValueById(i.parameterId),o=this.getExpressionParameters();let l=-1;for(let t=0;t<o.getSize();++t)if(i.parameterId==o.at(t).parameterId){l=t;break}if(l<0){0==r?(i.additiveValue=Ot.DefaultAdditiveValue,i.multiplyValue=Ot.DefaultMultiplyValue,i.overwriteValue=n):(i.additiveValue=this.calculateValue(i.additiveValue,Ot.DefaultAdditiveValue,a),i.multiplyValue=this.calculateValue(i.multiplyValue,Ot.DefaultMultiplyValue,a),i.overwriteValue=this.calculateValue(i.overwriteValue,n,a));continue}const h=o.at(l).value;let u,g,d;switch(o.at(l).blendType){case kt.Additive:u=h,g=Ot.DefaultMultiplyValue,d=n;break;case kt.Multiply:u=Ot.DefaultAdditiveValue,g=h,d=n;break;case kt.Overwrite:u=Ot.DefaultAdditiveValue,g=Ot.DefaultMultiplyValue,d=h;break;default:return}0==r?(i.additiveValue=u,i.multiplyValue=g,i.overwriteValue=d):(i.additiveValue=i.additiveValue*(1-a)+u*a,i.multiplyValue=i.multiplyValue*(1-a)+g*a,i.overwriteValue=i.overwriteValue*(1-a)+d*a)}}}getExpressionParameters(){return this._parameters}getFadeWeight(){return this._fadeWeight}parse(t,e){const i=L.create(t,e);if(!i)return;const s=i.getRoot();this.setFadeInTime(s.getValueByString(\"FadeInTime\").toFloat(1)),this.setFadeOutTime(s.getValueByString(\"FadeOutTime\").toFloat(1));const r=s.getValueByString(Dt).getSize();this._parameters.prepareCapacity(r);for(let t=0;t<r;++t){const e=s.getValueByString(Dt).getValueByIndex(t),i=$.getIdManager().getId(e.getValueByString(\"Id\").getRawString()),r=e.getValueByString(\"Value\").toFloat();let a;a=e.getValueByString(At).isNull()||\"Add\"==e.getValueByString(At).getString()?kt.Additive:\"Multiply\"==e.getValueByString(At).getString()?kt.Multiply:\"Overwrite\"==e.getValueByString(At).getString()?kt.Overwrite:kt.Additive;const n=new Ut;n.parameterId=i,n.blendType=a,n.value=r,this._parameters.pushBack(n)}L.delete(i)}calculateValue(t,e,i){return t*(1-i)+e*i}constructor(){super(),this._parameters=new e,this._fadeWeight=0}}var kt,Nt,zt;Ot.DefaultAdditiveValue=0,Ot.DefaultMultiplyValue=1,function(t){t[t.Additive=0]=\"Additive\",t[t.Multiply=1]=\"Multiply\",t[t.Overwrite=2]=\"Overwrite\"}(kt||(kt={}));class Ut{}!function(t){t.CubismExpressionMotion=Ot,t.ExpressionBlendType=kt,t.ExpressionParameter=Ut}(Nt||(Nt={}));class Gt{constructor(){this._autoDelete=!1,this._motion=null,this._available=!0,this._finished=!1,this._started=!1,this._startTimeSeconds=-1,this._fadeInStartTimeSeconds=0,this._endTimeSeconds=-1,this._stateTimeSeconds=0,this._stateWeight=0,this._lastEventCheckSeconds=0,this._motionQueueEntryHandle=this,this._fadeOutSeconds=0,this._isTriggeredFadeOut=!1}release(){this._autoDelete&&this._motion&&Lt.delete(this._motion)}setFadeOut(t){this._fadeOutSeconds=t,this._isTriggeredFadeOut=!0}startFadeOut(t,e){const i=e+t;this._isTriggeredFadeOut=!0,(this._endTimeSeconds<0||i<this._endTimeSeconds)&&(this._endTimeSeconds=i)}isFinished(){return this._finished}isStarted(){return this._started}getStartTime(){return this._startTimeSeconds}getFadeInStartTime(){return this._fadeInStartTimeSeconds}getEndTime(){return this._endTimeSeconds}setStartTime(t){this._startTimeSeconds=t}setFadeInStartTime(t){this._fadeInStartTimeSeconds=t}setEndTime(t){this._endTimeSeconds=t}setIsFinished(t){this._finished=t}setIsStarted(t){this._started=t}isAvailable(){return this._available}setIsAvailable(t){this._available=t}setState(t,e){this._stateTimeSeconds=t,this._stateWeight=e}getStateTime(){return this._stateTimeSeconds}getStateWeight(){return this._stateWeight}getLastCheckEventSeconds(){return this._lastEventCheckSeconds}setLastCheckEventSeconds(t){this._lastEventCheckSeconds=t}isTriggeredFadeOut(){return this._isTriggeredFadeOut}getFadeOutSeconds(){return this._fadeOutSeconds}getCubismMotion(){return this._motion}}(zt||(zt={})).CubismMotionQueueEntry=Gt;class Xt{constructor(){this._userTimeSeconds=0,this._eventCallBack=null,this._eventCustomData=null,this._motions=new e}release(){for(let t=0;t<this._motions.getSize();++t)this._motions.at(t)&&(this._motions.at(t).release(),this._motions.set(t,null));this._motions=null}startMotion(t,e,i){if(null==t)return Yt;let s=null;for(let t=0;t<this._motions.getSize();++t)s=this._motions.at(t),null!=s&&s.setFadeOut(s._motion.getFadeOutTime());return s=new Gt,s._autoDelete=e,s._motion=t,this._motions.pushBack(s),s._motionQueueEntryHandle}isFinished(){for(let t=this._motions.begin();t.notEqual(this._motions.end());){let e=t.ptr();if(null==e){t=this._motions.erase(t);continue}if(null!=e._motion){if(!e.isFinished())return!1;t.preIncrement()}else e.release(),e=null,t=this._motions.erase(t)}return!0}isFinishedByHandle(t){for(let e=this._motions.begin();e.notEqual(this._motions.end());e.increment()){const i=e.ptr();if(null!=i&&(i._motionQueueEntryHandle==t&&!i.isFinished()))return!1}return!0}stopAllMotions(){for(let t=this._motions.begin();t.notEqual(this._motions.end());){let e=t.ptr();null!=e?(e.release(),e=null,t=this._motions.erase(t)):t=this._motions.erase(t)}}getCubismMotionQueueEntries(){return this._motions}getCubismMotionQueueEntry(t){for(let e=this._motions.begin();e.notEqual(this._motions.end());e.preIncrement()){const i=e.ptr();if(null!=i&&i._motionQueueEntryHandle==t)return i}return null}setEventCallback(t,e=null){this._eventCallBack=t,this._eventCustomData=e}doUpdateMotion(t,e){let i=!1;for(let s=this._motions.begin();s.notEqual(this._motions.end());){let r=s.ptr();if(null==r){s=this._motions.erase(s);continue}const a=r._motion;if(null==a){r.release(),r=null,s=this._motions.erase(s);continue}a.updateParameters(t,r,e),i=!0;const n=a.getFiredEvent(r.getLastCheckEventSeconds()-r.getStartTime(),e-r.getStartTime());for(let t=0;t<n.getSize();++t)this._eventCallBack(this,n.at(t),this._eventCustomData);r.setLastCheckEventSeconds(e),r.isFinished()?(r.release(),r=null,s=this._motions.erase(s)):(r.isTriggeredFadeOut()&&r.startFadeOut(r.getFadeOutSeconds(),e),s.preIncrement())}return i}}const Yt=-1;var jt,Ht,qt,Wt,Jt;!function(t){t.CubismMotionQueueManager=Xt,t.InvalidMotionQueueEntryHandleValue=Yt}(jt||(jt={}));class $t{}class Zt extends Xt{constructor(){super(),this._currentPriority=0,this._reservePriority=0,this._expressionParameterValues=new e,this._fadeWeights=new e}release(){this._expressionParameterValues&&(J(this._expressionParameterValues),this._expressionParameterValues=null),this._fadeWeights&&(J(this._fadeWeights),this._fadeWeights=null)}getCurrentPriority(){return M(\"CubismExpressionMotionManager.getCurrentPriority() is deprecated because a priority value is not actually used during expression motion playback.\"),this._currentPriority}getReservePriority(){return M(\"CubismExpressionMotionManager.getReservePriority() is deprecated because a priority value is not actually used during expression motion playback.\"),this._reservePriority}getFadeWeight(t){return t<0||this._fadeWeights.getSize()<1||t>=this._fadeWeights.getSize()?(console.warn(\"Failed to get the fade weight value. The element at that index does not exist.\"),-1):this._fadeWeights.at(t)}setFadeWeight(t,e){t<0||this._fadeWeights.getSize()<1||this._fadeWeights.getSize()<=t?console.warn(\"Failed to set the fade weight value. The element at that index does not exist.\"):this._fadeWeights.set(t,e)}setReservePriority(t){M(\"CubismExpressionMotionManager.setReservePriority() is deprecated because a priority value is not actually used during expression motion playback.\"),this._reservePriority=t}startMotionPriority(t,e,i){return M(\"CubismExpressionMotionManager.startMotionPriority() is deprecated because a priority value is not actually used during expression motion playback.\"),i==this.getReservePriority()&&this.setReservePriority(0),this._currentPriority=i,this.startMotion(t,e)}updateMotion(t,e){this._userTimeSeconds+=e;let i=!1;const s=this.getCubismMotionQueueEntries();let r=0,a=0;if(this._fadeWeights.getSize()!==s.getSize()){const t=s.getSize()-this._fadeWeights.getSize();for(let e=0;e<t;e++)this._fadeWeights.pushBack(0)}for(let e=this._motions.begin();e.notEqual(this._motions.end());){const n=e.ptr();if(null==n){e=s.erase(e);continue}const o=n.getCubismMotion();if(null==o){J(n),e=s.erase(e);continue}const l=o.getExpressionParameters();if(n.isAvailable())for(let e=0;e<l.getSize();++e){if(null==l.at(e).parameterId)continue;let i=-1;for(let t=0;t<this._expressionParameterValues.getSize();++t)if(this._expressionParameterValues.at(t).parameterId==l.at(e).parameterId){i=t;break}if(i>=0)continue;const s=new $t;s.parameterId=l.at(e).parameterId,s.additiveValue=Ot.DefaultAdditiveValue,s.multiplyValue=Ot.DefaultMultiplyValue,s.overwriteValue=t.getParameterValueById(s.parameterId),this._expressionParameterValues.pushBack(s)}o.setupMotionQueueEntry(n,this._userTimeSeconds),this.setFadeWeight(a,o.updateFadeWeight(n,this._userTimeSeconds)),o.calculateExpressionParameters(t,this._userTimeSeconds,n,this._expressionParameterValues,a,this.getFadeWeight(a)),r+=0==o.getFadeInTime()?1:Vt.getEasingSine((this._userTimeSeconds-n.getFadeInStartTime())/o.getFadeInTime()),i=!0,n.isTriggeredFadeOut()&&n.startFadeOut(n.getFadeOutSeconds(),this._userTimeSeconds),e.preIncrement(),++a}if(s.getSize()>1){if(this.getFadeWeight(this._fadeWeights.getSize()-1)>=1)for(let t=s.getSize()-2;t>=0;--t){J(s.at(t)),s.remove(t),this._fadeWeights.remove(t)}}r>1&&(r=1);for(let e=0;e<this._expressionParameterValues.getSize();++e){const i=this._expressionParameterValues.at(e);t.setParameterValueById(i.parameterId,(i.overwriteValue+i.additiveValue)*i.multiplyValue,r),i.additiveValue=Ot.DefaultAdditiveValue,i.multiplyValue=Ot.DefaultMultiplyValue}return i}}(Ht||(Ht={})).CubismExpressionMotionManager=Zt,function(t){t[t.CubismMotionCurveTarget_Model=0]=\"CubismMotionCurveTarget_Model\",t[t.CubismMotionCurveTarget_Parameter=1]=\"CubismMotionCurveTarget_Parameter\",t[t.CubismMotionCurveTarget_PartOpacity=2]=\"CubismMotionCurveTarget_PartOpacity\"}(qt||(qt={})),function(t){t[t.CubismMotionSegmentType_Linear=0]=\"CubismMotionSegmentType_Linear\",t[t.CubismMotionSegmentType_Bezier=1]=\"CubismMotionSegmentType_Bezier\",t[t.CubismMotionSegmentType_Stepped=2]=\"CubismMotionSegmentType_Stepped\",t[t.CubismMotionSegmentType_InverseStepped=3]=\"CubismMotionSegmentType_InverseStepped\"}(Wt||(Wt={}));class Kt{constructor(){this.time=0,this.value=0}}class Qt{constructor(){this.evaluate=null,this.basePointIndex=0,this.segmentType=0}}class te{constructor(){this.type=qt.CubismMotionCurveTarget_Model,this.segmentCount=0,this.baseSegmentIndex=0,this.fadeInTime=0,this.fadeOutTime=0}}class ee{constructor(){this.fireTime=0}}class ie{constructor(){this.duration=0,this.loop=!1,this.curveCount=0,this.eventCount=0,this.fps=0,this.curves=new e,this.segments=new e,this.points=new e,this.events=new e}}!function(t){t.CubismMotionCurve=te,t.CubismMotionCurveTarget=qt,t.CubismMotionData=ie,t.CubismMotionEvent=ee,t.CubismMotionPoint=Kt,t.CubismMotionSegment=Qt,t.CubismMotionSegmentType=Wt}(Jt||(Jt={}));const se=\"Meta\",re=\"Curves\",ae=\"FadeInTime\",ne=\"FadeOutTime\",oe=\"Segments\",le=\"UserData\";class he{constructor(t,e){this._json=L.create(t,e)}release(){L.delete(this._json)}getMotionDuration(){return this._json.getRoot().getValueByString(se).getValueByString(\"Duration\").toFloat()}isMotionLoop(){return this._json.getRoot().getValueByString(se).getValueByString(\"Loop\").toBoolean()}hasConsistency(){let t=!0;if(!this._json||!this._json.getRoot())return!1;const e=this._json.getRoot().getValueByString(re).getVector().getSize();let i=0,s=0;for(let t=0;t<e;++t)for(let e=0;e<this.getMotionCurveSegmentCount(t);){0==e&&(s+=1,e+=2);switch(this.getMotionCurveSegment(t,e)){case Wt.CubismMotionSegmentType_Linear:s+=1,e+=3;break;case Wt.CubismMotionSegmentType_Bezier:s+=3,e+=7;break;case Wt.CubismMotionSegmentType_Stepped:case Wt.CubismMotionSegmentType_InverseStepped:s+=1,e+=3;break;default:C(0)}++i}return e!=this.getMotionCurveCount()&&(v(\"The number of curves does not match the metadata.\"),t=!1),i!=this.getMotionTotalSegmentCount()&&(v(\"The number of segment does not match the metadata.\"),t=!1),s!=this.getMotionTotalPointCount()&&(v(\"The number of point does not match the metadata.\"),t=!1),t}getEvaluationOptionFlag(t){return ue.EvaluationOptionFlag_AreBeziersRistricted==t&&this._json.getRoot().getValueByString(se).getValueByString(\"AreBeziersRestricted\").toBoolean()}getMotionCurveCount(){return this._json.getRoot().getValueByString(se).getValueByString(\"CurveCount\").toInt()}getMotionFps(){return this._json.getRoot().getValueByString(se).getValueByString(\"Fps\").toFloat()}getMotionTotalSegmentCount(){return this._json.getRoot().getValueByString(se).getValueByString(\"TotalSegmentCount\").toInt()}getMotionTotalPointCount(){return this._json.getRoot().getValueByString(se).getValueByString(\"TotalPointCount\").toInt()}isExistMotionFadeInTime(){return!this._json.getRoot().getValueByString(se).getValueByString(ae).isNull()}isExistMotionFadeOutTime(){return!this._json.getRoot().getValueByString(se).getValueByString(ne).isNull()}getMotionFadeInTime(){return this._json.getRoot().getValueByString(se).getValueByString(ae).toFloat()}getMotionFadeOutTime(){return this._json.getRoot().getValueByString(se).getValueByString(ne).toFloat()}getMotionCurveTarget(t){return this._json.getRoot().getValueByString(re).getValueByIndex(t).getValueByString(\"Target\").getRawString()}getMotionCurveId(t){return $.getIdManager().getId(this._json.getRoot().getValueByString(re).getValueByIndex(t).getValueByString(\"Id\").getRawString())}isExistMotionCurveFadeInTime(t){return!this._json.getRoot().getValueByString(re).getValueByIndex(t).getValueByString(ae).isNull()}isExistMotionCurveFadeOutTime(t){return!this._json.getRoot().getValueByString(re).getValueByIndex(t).getValueByString(ne).isNull()}getMotionCurveFadeInTime(t){return this._json.getRoot().getValueByString(re).getValueByIndex(t).getValueByString(ae).toFloat()}getMotionCurveFadeOutTime(t){return this._json.getRoot().getValueByString(re).getValueByIndex(t).getValueByString(ne).toFloat()}getMotionCurveSegmentCount(t){return this._json.getRoot().getValueByString(re).getValueByIndex(t).getValueByString(oe).getVector().getSize()}getMotionCurveSegment(t,e){return this._json.getRoot().getValueByString(re).getValueByIndex(t).getValueByString(oe).getValueByIndex(e).toFloat()}getEventCount(){return this._json.getRoot().getValueByString(se).getValueByString(\"UserDataCount\").toInt()}getTotalEventValueSize(){return this._json.getRoot().getValueByString(se).getValueByString(\"TotalUserDataSize\").toInt()}getEventTime(t){return this._json.getRoot().getValueByString(le).getValueByIndex(t).getValueByString(\"Time\").toFloat()}getEventValue(t){return new g(this._json.getRoot().getValueByString(le).getValueByIndex(t).getValueByString(\"Value\").getRawString())}}var ue,ge;!function(t){t[t.EvaluationOptionFlag_AreBeziersRistricted=0]=\"EvaluationOptionFlag_AreBeziersRistricted\"}(ue||(ue={})),(ge||(ge={})).CubismMotionJson=he;const de=\"Opacity\";function _e(t,e,i){const s=new Kt;return s.time=t.time+(e.time-t.time)*i,s.value=t.value+(e.value-t.value)*i,s}function ce(t,e){let i=(e-t[0].time)/(t[1].time-t[0].time);return i<0&&(i=0),t[0].value+(t[1].value-t[0].value)*i}function me(t,e){let i=(e-t[0].time)/(t[3].time-t[0].time);i<0&&(i=0);const s=_e(t[0],t[1],i),r=_e(t[1],t[2],i),a=_e(t[2],t[3],i),n=_e(s,r,i),o=_e(r,a,i);return _e(n,o,i).value}function pe(t,e){const i=e,s=t[0].time,r=t[3].time,a=t[1].time,n=t[2].time,o=r-3*n+3*a-s,l=3*n-6*a+3*s,h=3*a-3*s,u=s-i,g=Vt.cardanoAlgorithmForBezier(o,l,h,u),d=_e(t[0],t[1],g),_=_e(t[1],t[2],g),c=_e(t[2],t[3],g),m=_e(d,_,g),p=_e(_,c,g);return _e(m,p,g).value}function fe(t,e){return t[0].value}function ye(t,e){return t[1].value}function Se(t,e,i,s,r){const a=t.curves.at(e);let n=-1;const o=a.baseSegmentIndex+a.segmentCount;let l=0;for(let e=a.baseSegmentIndex;e<o;++e)if(l=t.segments.at(e).basePointIndex+(t.segments.at(e).segmentType==Wt.CubismMotionSegmentType_Bezier?3:1),t.points.at(l).time>i){n=e;break}if(-1==n)return s&&i<r?function(t,e,i,s,r,a){const n=[new Kt,new Kt];{const e=t.points.at(s);n[0].time=e.time,n[0].value=e.value}{const e=t.points.at(i);n[1].time=a,n[1].value=e.value}switch(t.segments.at(e).segmentType){case Wt.CubismMotionSegmentType_Linear:case Wt.CubismMotionSegmentType_Bezier:default:return ce(n,r);case Wt.CubismMotionSegmentType_Stepped:return fe(n);case Wt.CubismMotionSegmentType_InverseStepped:return ye(n)}}(t,o-1,t.segments.at(a.baseSegmentIndex).basePointIndex,l,i,r):t.points.at(l).value;const h=t.segments.at(n);return h.evaluate(t.points.get(h.basePointIndex),i)}var Ce,xe,Me,ve,be,Pe;!function(t){t[t.MotionBehavior_V1=0]=\"MotionBehavior_V1\",t[t.MotionBehavior_V2=1]=\"MotionBehavior_V2\"}(Ce||(Ce={}));class Be extends Lt{static create(t,e,i,s,r=!1){const a=new Be;return a.parse(t,e,r),a._motionData?(a._sourceFrameRate=a._motionData.fps,a._loopDurationSeconds=a._motionData.duration,a._onFinishedMotion=i,a._onBeganMotion=s,a):(J(a),null)}doUpdateParameters(t,e,i,s){null==this._modelCurveIdEyeBlink&&(this._modelCurveIdEyeBlink=$.getIdManager().getId(\"EyeBlink\")),null==this._modelCurveIdLipSync&&(this._modelCurveIdLipSync=$.getIdManager().getId(\"LipSync\")),null==this._modelCurveIdOpacity&&(this._modelCurveIdOpacity=$.getIdManager().getId(de)),this._motionBehavior===Ce.MotionBehavior_V2&&this._previousLoopState!==this._isLoop&&(this.adjustEndTime(s),this._previousLoopState=this._isLoop);let r=e-s.getStartTime();r<0&&(r=0);let a=Number.MAX_VALUE,n=Number.MAX_VALUE;const o=64;let l=0,h=0;this._eyeBlinkParameterIds.getSize()>o&&x(\"too many eye blink targets : {0}\",this._eyeBlinkParameterIds.getSize()),this._lipSyncParameterIds.getSize()>o&&x(\"too many lip sync targets : {0}\",this._lipSyncParameterIds.getSize());const u=this._fadeInSeconds<=0?1:Vt.getEasingSine((e-s.getFadeInStartTime())/this._fadeInSeconds),g=this._fadeOutSeconds<=0||s.getEndTime()<0?1:Vt.getEasingSine((s.getEndTime()-e)/this._fadeOutSeconds);let d,_,c,m=r,p=this._motionData.duration;const f=this._motionBehavior===Ce.MotionBehavior_V2&&this._isLoop;if(this._isLoop)for(this._motionBehavior===Ce.MotionBehavior_V2&&(p+=1/this._motionData.fps);m>p;)m-=p;const y=this._motionData.curves;for(_=0;_<this._motionData.curveCount&&y.at(_).type==qt.CubismMotionCurveTarget_Model;++_)d=Se(this._motionData,_,m,f,p),y.at(_).id==this._modelCurveIdEyeBlink?n=d:y.at(_).id==this._modelCurveIdLipSync?a=d:y.at(_).id==this._modelCurveIdOpacity&&(this._modelOpacity=d,t.setModelOapcity(this.getModelOpacityValue()));for(;_<this._motionData.curveCount&&y.at(_).type==qt.CubismMotionCurveTarget_Parameter;++_){if(c=t.getParameterIndex(y.at(_).id),-1==c)continue;const r=t.getParameterValueByIndex(c);if(d=Se(this._motionData,_,m,f,p),n!=Number.MAX_VALUE)for(let t=0;t<this._eyeBlinkParameterIds.getSize()&&t<o;++t)if(this._eyeBlinkParameterIds.at(t)==y.at(_).id){d*=n,h|=1<<t;break}if(a!=Number.MAX_VALUE)for(let t=0;t<this._lipSyncParameterIds.getSize()&&t<o;++t)if(this._lipSyncParameterIds.at(t)==y.at(_).id){d+=a,l|=1<<t;break}let S;if(t.isRepeat(c)&&(d=t.getParameterRepeatValue(c,d)),y.at(_).fadeInTime<0&&y.at(_).fadeOutTime<0)S=r+(d-r)*i;else{let t,i;t=y.at(_).fadeInTime<0?u:0==y.at(_).fadeInTime?1:Vt.getEasingSine((e-s.getFadeInStartTime())/y.at(_).fadeInTime),i=y.at(_).fadeOutTime<0?g:0==y.at(_).fadeOutTime||s.getEndTime()<0?1:Vt.getEasingSine((s.getEndTime()-e)/y.at(_).fadeOutTime);S=r+(d-r)*(this._weight*t*i)}t.setParameterValueByIndex(c,S,1)}if(n!=Number.MAX_VALUE)for(let e=0;e<this._eyeBlinkParameterIds.getSize()&&e<o;++e){const s=t.getParameterValueById(this._eyeBlinkParameterIds.at(e));if(h>>e&1)continue;const r=s+(n-s)*i;t.setParameterValueById(this._eyeBlinkParameterIds.at(e),r)}if(a!=Number.MAX_VALUE)for(let e=0;e<this._lipSyncParameterIds.getSize()&&e<o;++e){const s=t.getParameterValueById(this._lipSyncParameterIds.at(e));if(l>>e&1)continue;const r=s+(a-s)*i;t.setParameterValueById(this._lipSyncParameterIds.at(e),r)}for(;_<this._motionData.curveCount&&y.at(_).type==qt.CubismMotionCurveTarget_PartOpacity;++_)c=t.getParameterIndex(y.at(_).id),-1!=c&&(d=Se(this._motionData,_,m,f,p),t.setParameterValueByIndex(c,d));r>=p&&(this._isLoop?this.updateForNextLoop(s,e,m):(this._onFinishedMotion&&this._onFinishedMotion(this),s.setIsFinished(!0))),this._lastWeight=i}setIsLoop(t){v(\"setIsLoop() is a deprecated function. Please use setLoop().\"),this._isLoop=t}isLoop(){return v(\"isLoop() is a deprecated function. Please use getLoop().\"),this._isLoop}setIsLoopFadeIn(t){v(\"setIsLoopFadeIn() is a deprecated function. Please use setLoopFadeIn().\"),this._isLoopFadeIn=t}isLoopFadeIn(){return v(\"isLoopFadeIn() is a deprecated function. Please use getLoopFadeIn().\"),this._isLoopFadeIn}setMotionBehavior(t){this._motionBehavior=t}getMotionBehavior(){return this._motionBehavior}getDuration(){return this._isLoop?-1:this._loopDurationSeconds}getLoopDuration(){return this._loopDurationSeconds}setParameterFadeInTime(t,e){const i=this._motionData.curves;for(let s=0;s<this._motionData.curveCount;++s)if(t==i.at(s).id)return void(i.at(s).fadeInTime=e)}setParameterFadeOutTime(t,e){const i=this._motionData.curves;for(let s=0;s<this._motionData.curveCount;++s)if(t==i.at(s).id)return void(i.at(s).fadeOutTime=e)}getParameterFadeInTime(t){const e=this._motionData.curves;for(let i=0;i<this._motionData.curveCount;++i)if(t==e.at(i).id)return e.at(i).fadeInTime;return-1}getParameterFadeOutTime(t){const e=this._motionData.curves;for(let i=0;i<this._motionData.curveCount;++i)if(t==e.at(i).id)return e.at(i).fadeOutTime;return-1}setEffectIds(t,e){this._eyeBlinkParameterIds=t,this._lipSyncParameterIds=e}constructor(){super(),this._motionBehavior=Ce.MotionBehavior_V2,this._sourceFrameRate=30,this._loopDurationSeconds=-1,this._isLoop=!1,this._isLoopFadeIn=!0,this._lastWeight=0,this._motionData=null,this._modelCurveIdEyeBlink=null,this._modelCurveIdLipSync=null,this._modelCurveIdOpacity=null,this._eyeBlinkParameterIds=null,this._lipSyncParameterIds=null,this._modelOpacity=1,this._debugMode=!1}release(){this._motionData=void 0,this._motionData=null}updateForNextLoop(t,e,i){switch(this._motionBehavior){case Ce.MotionBehavior_V2:default:t.setStartTime(e-i),this._isLoopFadeIn&&t.setFadeInStartTime(e-i),null!=this._onFinishedMotion&&this._onFinishedMotion(this);break;case Ce.MotionBehavior_V1:t.setStartTime(e),this._isLoopFadeIn&&t.setFadeInStartTime(e)}}parse(t,e,i=!1){let s=new he(t,e);if(!s)return s.release(),void(s=void 0);if(i){if(!s.hasConsistency())return s.release(),void b(\"Inconsistent motion3.json.\")}this._motionData=new ie,this._motionData.duration=s.getMotionDuration(),this._motionData.loop=s.isMotionLoop(),this._motionData.curveCount=s.getMotionCurveCount(),this._motionData.fps=s.getMotionFps(),this._motionData.eventCount=s.getEventCount();const r=s.getEvaluationOptionFlag(ue.EvaluationOptionFlag_AreBeziersRistricted);s.isExistMotionFadeInTime()?this._fadeInSeconds=s.getMotionFadeInTime()<0?1:s.getMotionFadeInTime():this._fadeInSeconds=1,s.isExistMotionFadeOutTime()?this._fadeOutSeconds=s.getMotionFadeOutTime()<0?1:s.getMotionFadeOutTime():this._fadeOutSeconds=1,this._motionData.curves.updateSize(this._motionData.curveCount,te,!0),this._motionData.segments.updateSize(s.getMotionTotalSegmentCount(),Qt,!0),this._motionData.points.updateSize(s.getMotionTotalPointCount(),Kt,!0),this._motionData.events.updateSize(this._motionData.eventCount,ee,!0);let a=0,n=0;for(let t=0;t<this._motionData.curveCount;++t){\"Model\"==s.getMotionCurveTarget(t)?this._motionData.curves.at(t).type=qt.CubismMotionCurveTarget_Model:\"Parameter\"==s.getMotionCurveTarget(t)?this._motionData.curves.at(t).type=qt.CubismMotionCurveTarget_Parameter:\"PartOpacity\"==s.getMotionCurveTarget(t)?this._motionData.curves.at(t).type=qt.CubismMotionCurveTarget_PartOpacity:v('Warning : Unable to get segment type from Curve! The number of \"CurveCount\" may be incorrect!'),this._motionData.curves.at(t).id=s.getMotionCurveId(t),this._motionData.curves.at(t).baseSegmentIndex=n,this._motionData.curves.at(t).fadeInTime=s.isExistMotionCurveFadeInTime(t)?s.getMotionCurveFadeInTime(t):-1,this._motionData.curves.at(t).fadeOutTime=s.isExistMotionCurveFadeOutTime(t)?s.getMotionCurveFadeOutTime(t):-1;for(let e=0;e<s.getMotionCurveSegmentCount(t);){0==e?(this._motionData.segments.at(n).basePointIndex=a,this._motionData.points.at(a).time=s.getMotionCurveSegment(t,e),this._motionData.points.at(a).value=s.getMotionCurveSegment(t,e+1),a+=1,e+=2):this._motionData.segments.at(n).basePointIndex=a-1;switch(s.getMotionCurveSegment(t,e)){case Wt.CubismMotionSegmentType_Linear:this._motionData.segments.at(n).segmentType=Wt.CubismMotionSegmentType_Linear,this._motionData.segments.at(n).evaluate=ce,this._motionData.points.at(a).time=s.getMotionCurveSegment(t,e+1),this._motionData.points.at(a).value=s.getMotionCurveSegment(t,e+2),a+=1,e+=3;break;case Wt.CubismMotionSegmentType_Bezier:this._motionData.segments.at(n).segmentType=Wt.CubismMotionSegmentType_Bezier,this._motionData.segments.at(n).evaluate=r?me:pe,this._motionData.points.at(a).time=s.getMotionCurveSegment(t,e+1),this._motionData.points.at(a).value=s.getMotionCurveSegment(t,e+2),this._motionData.points.at(a+1).time=s.getMotionCurveSegment(t,e+3),this._motionData.points.at(a+1).value=s.getMotionCurveSegment(t,e+4),this._motionData.points.at(a+2).time=s.getMotionCurveSegment(t,e+5),this._motionData.points.at(a+2).value=s.getMotionCurveSegment(t,e+6),a+=3,e+=7;break;case Wt.CubismMotionSegmentType_Stepped:this._motionData.segments.at(n).segmentType=Wt.CubismMotionSegmentType_Stepped,this._motionData.segments.at(n).evaluate=fe,this._motionData.points.at(a).time=s.getMotionCurveSegment(t,e+1),this._motionData.points.at(a).value=s.getMotionCurveSegment(t,e+2),a+=1,e+=3;break;case Wt.CubismMotionSegmentType_InverseStepped:this._motionData.segments.at(n).segmentType=Wt.CubismMotionSegmentType_InverseStepped,this._motionData.segments.at(n).evaluate=ye,this._motionData.points.at(a).time=s.getMotionCurveSegment(t,e+1),this._motionData.points.at(a).value=s.getMotionCurveSegment(t,e+2),a+=1,e+=3;break;default:C(0)}++this._motionData.curves.at(t).segmentCount,++n}}for(let t=0;t<s.getEventCount();++t)this._motionData.events.at(t).fireTime=s.getEventTime(t),this._motionData.events.at(t).value=s.getEventValue(t);s.release(),s=void 0,s=null}getFiredEvent(t,e){this._firedEventValues.updateSize(0);for(let i=0;i<this._motionData.eventCount;++i)this._motionData.events.at(i).fireTime>t&&this._motionData.events.at(i).fireTime<=e&&this._firedEventValues.pushBack(new g(this._motionData.events.at(i).value.s));return this._firedEventValues}isExistModelOpacity(){for(let t=0;t<this._motionData.curveCount;t++){const e=this._motionData.curves.at(t);if(e.type==qt.CubismMotionCurveTarget_Model&&0==e.id.getString().s.localeCompare(de))return!0}return!1}getModelOpacityIndex(){if(this.isExistModelOpacity())for(let t=0;t<this._motionData.curveCount;t++){const e=this._motionData.curves.at(t);if(e.type==qt.CubismMotionCurveTarget_Model&&0==e.id.getString().s.localeCompare(de))return t}return-1}getModelOpacityId(t){if(-1!=t){const e=this._motionData.curves.at(t);if(e.type==qt.CubismMotionCurveTarget_Model&&0==e.id.getString().s.localeCompare(de))return $.getIdManager().getId(e.id.getString().s)}return null}getModelOpacityValue(){return this._modelOpacity}setDebugMode(t){this._debugMode=t}}(xe||(xe={})).CubismMotion=Be;class we extends Xt{constructor(){super(),this._currentPriority=0,this._reservePriority=0}getCurrentPriority(){return this._currentPriority}getReservePriority(){return this._reservePriority}setReservePriority(t){this._reservePriority=t}startMotionPriority(t,e,i){return i==this._reservePriority&&(this._reservePriority=0),this._currentPriority=i,super.startMotion(t,e)}updateMotion(t,e){this._userTimeSeconds+=e;const i=super.doUpdateMotion(t,this._userTimeSeconds);return this.isFinished()&&(this._currentPriority=0),i}reserveMotion(t){return!(t<=this._reservePriority||t<=this._currentPriority)&&(this._reservePriority=t,!0)}}(Me||(Me={})).CubismMotionManager=we,function(t){t[t.CubismPhysicsTargetType_Parameter=0]=\"CubismPhysicsTargetType_Parameter\"}(ve||(ve={})),function(t){t[t.CubismPhysicsSource_X=0]=\"CubismPhysicsSource_X\",t[t.CubismPhysicsSource_Y=1]=\"CubismPhysicsSource_Y\",t[t.CubismPhysicsSource_Angle=2]=\"CubismPhysicsSource_Angle\"}(be||(be={}));class Fe{constructor(){this.gravity=new It(0,0),this.wind=new It(0,0)}}class Ie{}class Ve{}class Ee{constructor(){this.initialPosition=new It(0,0),this.position=new It(0,0),this.lastPosition=new It(0,0),this.lastGravity=new It(0,0),this.force=new It(0,0),this.velocity=new It(0,0)}}class Re{constructor(){this.normalizationPosition=new Ve,this.normalizationAngle=new Ve}}class Te{constructor(){this.source=new Ie}}class Le{constructor(){this.destination=new Ie,this.translationScale=new It(0,0)}}class De{constructor(){this.settings=new e,this.inputs=new e,this.outputs=new e,this.particles=new e,this.gravity=new It(0,0),this.wind=new It(0,0),this.fps=0}}!function(t){t.CubismPhysicsInput=Te,t.CubismPhysicsNormalization=Ve,t.CubismPhysicsOutput=Le,t.CubismPhysicsParameter=Ie,t.CubismPhysicsParticle=Ee,t.CubismPhysicsRig=De,t.CubismPhysicsSource=be,t.CubismPhysicsSubRig=Re,t.CubismPhysicsTargetType=ve,t.PhysicsJsonEffectiveForces=Fe}(Pe||(Pe={}));const Ae=\"Position\",Oe=\"Angle\",ke=\"Type\",Ne=\"Meta\",ze=\"EffectiveForces\",Ue=\"Gravity\",Ge=\"Wind\",Xe=\"PhysicsSettings\",Ye=\"Normalization\",je=\"Minimum\",He=\"Maximum\",qe=\"Default\",We=\"Reflect\",Je=\"Weight\",$e=\"Input\",Ze=\"Output\",Ke=\"Vertices\";class Qe{constructor(t,e){this._json=L.create(t,e)}release(){L.delete(this._json)}getGravity(){const t=new It(0,0);return t.x=this._json.getRoot().getValueByString(Ne).getValueByString(ze).getValueByString(Ue).getValueByString(\"X\").toFloat(),t.y=this._json.getRoot().getValueByString(Ne).getValueByString(ze).getValueByString(Ue).getValueByString(\"Y\").toFloat(),t}getWind(){const t=new It(0,0);return t.x=this._json.getRoot().getValueByString(Ne).getValueByString(ze).getValueByString(Ge).getValueByString(\"X\").toFloat(),t.y=this._json.getRoot().getValueByString(Ne).getValueByString(ze).getValueByString(Ge).getValueByString(\"Y\").toFloat(),t}getFps(){return this._json.getRoot().getValueByString(Ne).getValueByString(\"Fps\").toFloat(0)}getSubRigCount(){return this._json.getRoot().getValueByString(Ne).getValueByString(\"PhysicsSettingCount\").toInt()}getTotalInputCount(){return this._json.getRoot().getValueByString(Ne).getValueByString(\"TotalInputCount\").toInt()}getTotalOutputCount(){return this._json.getRoot().getValueByString(Ne).getValueByString(\"TotalOutputCount\").toInt()}getVertexCount(){return this._json.getRoot().getValueByString(Ne).getValueByString(\"VertexCount\").toInt()}getNormalizationPositionMinimumValue(t){return this._json.getRoot().getValueByString(Xe).getValueByIndex(t).getValueByString(Ye).getValueByString(Ae).getValueByString(je).toFloat()}getNormalizationPositionMaximumValue(t){return this._json.getRoot().getValueByString(Xe).getValueByIndex(t).getValueByString(Ye).getValueByString(Ae).getValueByString(He).toFloat()}getNormalizationPositionDefaultValue(t){return this._json.getRoot().getValueByString(Xe).getValueByIndex(t).getValueByString(Ye).getValueByString(Ae).getValueByString(qe).toFloat()}getNormalizationAngleMinimumValue(t){return this._json.getRoot().getValueByString(Xe).getValueByIndex(t).getValueByString(Ye).getValueByString(Oe).getValueByString(je).toFloat()}getNormalizationAngleMaximumValue(t){return this._json.getRoot().getValueByString(Xe).getValueByIndex(t).getValueByString(Ye).getValueByString(Oe).getValueByString(He).toFloat()}getNormalizationAngleDefaultValue(t){return this._json.getRoot().getValueByString(Xe).getValueByIndex(t).getValueByString(Ye).getValueByString(Oe).getValueByString(qe).toFloat()}getInputCount(t){return this._json.getRoot().getValueByString(Xe).getValueByIndex(t).getValueByString($e).getVector().getSize()}getInputWeight(t,e){return this._json.getRoot().getValueByString(Xe).getValueByIndex(t).getValueByString($e).getValueByIndex(e).getValueByString(Je).toFloat()}getInputReflect(t,e){return this._json.getRoot().getValueByString(Xe).getValueByIndex(t).getValueByString($e).getValueByIndex(e).getValueByString(We).toBoolean()}getInputType(t,e){return this._json.getRoot().getValueByString(Xe).getValueByIndex(t).getValueByString($e).getValueByIndex(e).getValueByString(ke).getRawString()}getInputSourceId(t,e){return $.getIdManager().getId(this._json.getRoot().getValueByString(Xe).getValueByIndex(t).getValueByString($e).getValueByIndex(e).getValueByString(\"Source\").getValueByString(\"Id\").getRawString())}getOutputCount(t){return this._json.getRoot().getValueByString(Xe).getValueByIndex(t).getValueByString(Ze).getVector().getSize()}getOutputVertexIndex(t,e){return this._json.getRoot().getValueByString(Xe).getValueByIndex(t).getValueByString(Ze).getValueByIndex(e).getValueByString(\"VertexIndex\").toInt()}getOutputAngleScale(t,e){return this._json.getRoot().getValueByString(Xe).getValueByIndex(t).getValueByString(Ze).getValueByIndex(e).getValueByString(\"Scale\").toFloat()}getOutputWeight(t,e){return this._json.getRoot().getValueByString(Xe).getValueByIndex(t).getValueByString(Ze).getValueByIndex(e).getValueByString(Je).toFloat()}getOutputDestinationId(t,e){return $.getIdManager().getId(this._json.getRoot().getValueByString(Xe).getValueByIndex(t).getValueByString(Ze).getValueByIndex(e).getValueByString(\"Destination\").getValueByString(\"Id\").getRawString())}getOutputType(t,e){return this._json.getRoot().getValueByString(Xe).getValueByIndex(t).getValueByString(Ze).getValueByIndex(e).getValueByString(ke).getRawString()}getOutputReflect(t,e){return this._json.getRoot().getValueByString(Xe).getValueByIndex(t).getValueByString(Ze).getValueByIndex(e).getValueByString(We).toBoolean()}getParticleCount(t){return this._json.getRoot().getValueByString(Xe).getValueByIndex(t).getValueByString(Ke).getVector().getSize()}getParticleMobility(t,e){return this._json.getRoot().getValueByString(Xe).getValueByIndex(t).getValueByString(Ke).getValueByIndex(e).getValueByString(\"Mobility\").toFloat()}getParticleDelay(t,e){return this._json.getRoot().getValueByString(Xe).getValueByIndex(t).getValueByString(Ke).getValueByIndex(e).getValueByString(\"Delay\").toFloat()}getParticleAcceleration(t,e){return this._json.getRoot().getValueByString(Xe).getValueByIndex(t).getValueByString(Ke).getValueByIndex(e).getValueByString(\"Acceleration\").toFloat()}getParticleRadius(t,e){return this._json.getRoot().getValueByString(Xe).getValueByIndex(t).getValueByString(Ke).getValueByIndex(e).getValueByString(\"Radius\").toFloat()}getParticlePosition(t,e){const i=new It(0,0);return i.x=this._json.getRoot().getValueByString(Xe).getValueByIndex(t).getValueByString(Ke).getValueByIndex(e).getValueByString(Ae).getValueByString(\"X\").toFloat(),i.y=this._json.getRoot().getValueByString(Xe).getValueByIndex(t).getValueByString(Ke).getValueByIndex(e).getValueByString(Ae).getValueByString(\"Y\").toFloat(),i}}var ti;(ti||(ti={})).CubismPhysicsJson=Qe;const ei=\"Angle\";class ii{static create(t,e){const i=new ii;return i.parse(t,e),i._physicsRig.gravity.y=0,i}static delete(t){null!=t&&(t.release(),t=null)}parse(t,e){this._physicsRig=new De;let i=new Qe(t,e);this._physicsRig.gravity=i.getGravity(),this._physicsRig.wind=i.getWind(),this._physicsRig.subRigCount=i.getSubRigCount(),this._physicsRig.fps=i.getFps(),this._physicsRig.settings.updateSize(this._physicsRig.subRigCount,Re,!0),this._physicsRig.inputs.updateSize(i.getTotalInputCount(),Te,!0),this._physicsRig.outputs.updateSize(i.getTotalOutputCount(),Le,!0),this._physicsRig.particles.updateSize(i.getVertexCount(),Ee,!0),this._currentRigOutputs.clear(),this._previousRigOutputs.clear();let s=0,r=0,a=0;for(let t=0;t<this._physicsRig.settings.getSize();++t){this._physicsRig.settings.at(t).normalizationPosition.minimum=i.getNormalizationPositionMinimumValue(t),this._physicsRig.settings.at(t).normalizationPosition.maximum=i.getNormalizationPositionMaximumValue(t),this._physicsRig.settings.at(t).normalizationPosition.defalut=i.getNormalizationPositionDefaultValue(t),this._physicsRig.settings.at(t).normalizationAngle.minimum=i.getNormalizationAngleMinimumValue(t),this._physicsRig.settings.at(t).normalizationAngle.maximum=i.getNormalizationAngleMaximumValue(t),this._physicsRig.settings.at(t).normalizationAngle.defalut=i.getNormalizationAngleDefaultValue(t),this._physicsRig.settings.at(t).inputCount=i.getInputCount(t),this._physicsRig.settings.at(t).baseInputIndex=s;for(let e=0;e<this._physicsRig.settings.at(t).inputCount;++e)this._physicsRig.inputs.at(s+e).sourceParameterIndex=-1,this._physicsRig.inputs.at(s+e).weight=i.getInputWeight(t,e),this._physicsRig.inputs.at(s+e).reflect=i.getInputReflect(t,e),\"X\"==i.getInputType(t,e)?(this._physicsRig.inputs.at(s+e).type=be.CubismPhysicsSource_X,this._physicsRig.inputs.at(s+e).getNormalizedParameterValue=ai):\"Y\"==i.getInputType(t,e)?(this._physicsRig.inputs.at(s+e).type=be.CubismPhysicsSource_Y,this._physicsRig.inputs.at(s+e).getNormalizedParameterValue=ni):i.getInputType(t,e)==ei&&(this._physicsRig.inputs.at(s+e).type=be.CubismPhysicsSource_Angle,this._physicsRig.inputs.at(s+e).getNormalizedParameterValue=oi),this._physicsRig.inputs.at(s+e).source.targetType=ve.CubismPhysicsTargetType_Parameter,this._physicsRig.inputs.at(s+e).source.id=i.getInputSourceId(t,e);s+=this._physicsRig.settings.at(t).inputCount,this._physicsRig.settings.at(t).outputCount=i.getOutputCount(t),this._physicsRig.settings.at(t).baseOutputIndex=r;const e=new ri;e.outputs.resize(this._physicsRig.settings.at(t).outputCount);const n=new ri;n.outputs.resize(this._physicsRig.settings.at(t).outputCount);for(let s=0;s<this._physicsRig.settings.at(t).outputCount;++s)e.outputs.set(s,0),n.outputs.set(s,0),this._physicsRig.outputs.at(r+s).destinationParameterIndex=-1,this._physicsRig.outputs.at(r+s).vertexIndex=i.getOutputVertexIndex(t,s),this._physicsRig.outputs.at(r+s).angleScale=i.getOutputAngleScale(t,s),this._physicsRig.outputs.at(r+s).weight=i.getOutputWeight(t,s),this._physicsRig.outputs.at(r+s).destination.targetType=ve.CubismPhysicsTargetType_Parameter,this._physicsRig.outputs.at(r+s).destination.id=i.getOutputDestinationId(t,s),\"X\"==i.getOutputType(t,s)?(this._physicsRig.outputs.at(r+s).type=be.CubismPhysicsSource_X,this._physicsRig.outputs.at(r+s).getValue=li,this._physicsRig.outputs.at(r+s).getScale=di):\"Y\"==i.getOutputType(t,s)?(this._physicsRig.outputs.at(r+s).type=be.CubismPhysicsSource_Y,this._physicsRig.outputs.at(r+s).getValue=hi,this._physicsRig.outputs.at(r+s).getScale=_i):i.getOutputType(t,s)==ei&&(this._physicsRig.outputs.at(r+s).type=be.CubismPhysicsSource_Angle,this._physicsRig.outputs.at(r+s).getValue=ui,this._physicsRig.outputs.at(r+s).getScale=ci),this._physicsRig.outputs.at(r+s).reflect=i.getOutputReflect(t,s);this._currentRigOutputs.pushBack(e),this._previousRigOutputs.pushBack(n),r+=this._physicsRig.settings.at(t).outputCount,this._physicsRig.settings.at(t).particleCount=i.getParticleCount(t),this._physicsRig.settings.at(t).baseParticleIndex=a;for(let e=0;e<this._physicsRig.settings.at(t).particleCount;++e)this._physicsRig.particles.at(a+e).mobility=i.getParticleMobility(t,e),this._physicsRig.particles.at(a+e).delay=i.getParticleDelay(t,e),this._physicsRig.particles.at(a+e).acceleration=i.getParticleAcceleration(t,e),this._physicsRig.particles.at(a+e).radius=i.getParticleRadius(t,e),this._physicsRig.particles.at(a+e).position=i.getParticlePosition(t,e);a+=this._physicsRig.settings.at(t).particleCount}this.initialize(),i.release(),i=void 0,i=null}stabilization(t){var e,i,s,r;let a,n,o,l;const h=new It;let u,g,d,_;const c=t.getModel().parameters.values,m=t.getModel().parameters.maximumValues,p=t.getModel().parameters.minimumValues,f=t.getModel().parameters.defaultValues;(null!==(i=null===(e=this._parameterCaches)||void 0===e?void 0:e.length)&&void 0!==i?i:0)<t.getParameterCount()&&(this._parameterCaches=new Float32Array(t.getParameterCount())),(null!==(r=null===(s=this._parameterInputCaches)||void 0===s?void 0:s.length)&&void 0!==r?r:0)<t.getParameterCount()&&(this._parameterInputCaches=new Float32Array(t.getParameterCount()));for(let e=0;e<t.getParameterCount();++e)this._parameterCaches[e]=c[e],this._parameterInputCaches[e]=c[e];for(let e=0;e<this._physicsRig.subRigCount;++e){a={angle:0},h.x=0,h.y=0,u=this._physicsRig.settings.at(e),g=this._physicsRig.inputs.get(u.baseInputIndex),d=this._physicsRig.outputs.get(u.baseOutputIndex),_=this._physicsRig.particles.get(u.baseParticleIndex);for(let e=0;e<u.inputCount;++e)n=g[e].weight/100,-1==g[e].sourceParameterIndex&&(g[e].sourceParameterIndex=t.getParameterIndex(g[e].source.id)),g[e].getNormalizedParameterValue(h,a,c[g[e].sourceParameterIndex],p[g[e].sourceParameterIndex],m[g[e].sourceParameterIndex],f[g[e].sourceParameterIndex],u.normalizationPosition,u.normalizationAngle,g[e].reflect,n),this._parameterCaches[g[e].sourceParameterIndex]=c[g[e].sourceParameterIndex];o=Vt.degreesToRadian(-a.angle),h.x=h.x*Vt.cos(o)-h.y*Vt.sin(o),h.y=h.x*Vt.sin(o)+h.y*Vt.cos(o),pi(_,u.particleCount,h,a.angle,this._options.wind,.001*u.normalizationPosition.maximum);for(let i=0;i<u.outputCount;++i){const s=d[i].vertexIndex;if(-1==d[i].destinationParameterIndex&&(d[i].destinationParameterIndex=t.getParameterIndex(d[i].destination.id)),s<1||s>=u.particleCount)continue;let r=new It;r=_[s].position.substract(_[s-1].position),l=d[i].getValue(r,_,s,d[i].reflect,this._options.gravity),this._currentRigOutputs.at(e).outputs.set(i,l),this._previousRigOutputs.at(e).outputs.set(i,l);const a=d[i].destinationParameterIndex,n=!Float32Array.prototype.slice&&\"subarray\"in Float32Array.prototype?JSON.parse(JSON.stringify(c.subarray(a))):c.slice(a);fi(n,p[a],m[a],l,d[i]);for(let t=a,e=0;t<this._parameterCaches.length;t++,e++)c[t]=this._parameterCaches[t]=n[e]}}}evaluate(t,e){var i,s,r,a;let n,o,l,h;const u=new It;let g,d,_,c;if(0>=e)return;const m=t.getModel().parameters.values,p=t.getModel().parameters.maximumValues,f=t.getModel().parameters.minimumValues,y=t.getModel().parameters.defaultValues;let S;if(this._currentRemainTime+=e,this._currentRemainTime>5&&(this._currentRemainTime=0),(null!==(s=null===(i=this._parameterCaches)||void 0===i?void 0:i.length)&&void 0!==s?s:0)<t.getParameterCount()&&(this._parameterCaches=new Float32Array(t.getParameterCount())),(null!==(a=null===(r=this._parameterInputCaches)||void 0===r?void 0:r.length)&&void 0!==a?a:0)<t.getParameterCount()){this._parameterInputCaches=new Float32Array(t.getParameterCount());for(let e=0;e<t.getParameterCount();++e)this._parameterInputCaches[e]=m[e]}for(S=this._physicsRig.fps>0?1/this._physicsRig.fps:e;this._currentRemainTime>=S;){for(let t=0;t<this._physicsRig.subRigCount;++t){g=this._physicsRig.settings.at(t),_=this._physicsRig.outputs.get(g.baseOutputIndex);for(let e=0;e<g.outputCount;++e)this._previousRigOutputs.at(t).outputs.set(e,this._currentRigOutputs.at(t).outputs.at(e))}const e=S/this._currentRemainTime;for(let i=0;i<t.getParameterCount();++i)this._parameterCaches[i]=this._parameterInputCaches[i]*(1-e)+m[i]*e,this._parameterInputCaches[i]=this._parameterCaches[i];for(let e=0;e<this._physicsRig.subRigCount;++e){n={angle:0},u.x=0,u.y=0,g=this._physicsRig.settings.at(e),d=this._physicsRig.inputs.get(g.baseInputIndex),_=this._physicsRig.outputs.get(g.baseOutputIndex),c=this._physicsRig.particles.get(g.baseParticleIndex);for(let e=0;e<g.inputCount;++e)o=d[e].weight/100,-1==d[e].sourceParameterIndex&&(d[e].sourceParameterIndex=t.getParameterIndex(d[e].source.id)),d[e].getNormalizedParameterValue(u,n,this._parameterCaches[d[e].sourceParameterIndex],f[d[e].sourceParameterIndex],p[d[e].sourceParameterIndex],y[d[e].sourceParameterIndex],g.normalizationPosition,g.normalizationAngle,d[e].reflect,o);l=Vt.degreesToRadian(-n.angle),u.x=u.x*Vt.cos(l)-u.y*Vt.sin(l),u.y=u.x*Vt.sin(l)+u.y*Vt.cos(l),mi(c,g.particleCount,u,n.angle,this._options.wind,.001*g.normalizationPosition.maximum,S,5);for(let i=0;i<g.outputCount;++i){const s=_[i].vertexIndex;if(-1==_[i].destinationParameterIndex&&(_[i].destinationParameterIndex=t.getParameterIndex(_[i].destination.id)),s<1||s>=g.particleCount)continue;const r=new It;r.x=c[s].position.x-c[s-1].position.x,r.y=c[s].position.y-c[s-1].position.y,h=_[i].getValue(r,c,s,_[i].reflect,this._options.gravity),this._currentRigOutputs.at(e).outputs.set(i,h);const a=_[i].destinationParameterIndex,n=!Float32Array.prototype.slice&&\"subarray\"in Float32Array.prototype?JSON.parse(JSON.stringify(this._parameterCaches.subarray(a))):this._parameterCaches.slice(a);fi(n,f[a],p[a],h,_[i]);for(let t=a,e=0;t<this._parameterCaches.length;t++,e++)this._parameterCaches[t]=n[e]}}this._currentRemainTime-=S}const C=this._currentRemainTime/S;this.interpolate(t,C)}interpolate(t,e){let i,s;const r=t.getModel().parameters.values,a=t.getModel().parameters.maximumValues,n=t.getModel().parameters.minimumValues;for(let t=0;t<this._physicsRig.subRigCount;++t){s=this._physicsRig.settings.at(t),i=this._physicsRig.outputs.get(s.baseOutputIndex);for(let o=0;o<s.outputCount;++o){if(-1==i[o].destinationParameterIndex)continue;const s=i[o].destinationParameterIndex,l=!Float32Array.prototype.slice&&\"subarray\"in Float32Array.prototype?JSON.parse(JSON.stringify(r.subarray(s))):r.slice(s);fi(l,n[s],a[s],this._previousRigOutputs.at(t).outputs.at(o)*(1-e)+this._currentRigOutputs.at(t).outputs.at(o)*e,i[o]);for(let t=s,e=0;t<r.length;t++,e++)r[t]=l[e]}}}setOptions(t){this._options=t}getOption(){return this._options}constructor(){this._physicsRig=null,this._options=new si,this._options.gravity.y=-1,this._options.gravity.x=0,this._options.wind.x=0,this._options.wind.y=0,this._currentRigOutputs=new e,this._previousRigOutputs=new e,this._currentRemainTime=0,this._parameterCaches=null,this._parameterInputCaches=null}release(){this._physicsRig=void 0,this._physicsRig=null}initialize(){let t,e,i;for(let s=0;s<this._physicsRig.subRigCount;++s){e=this._physicsRig.settings.at(s),t=this._physicsRig.particles.get(e.baseParticleIndex),t[0].initialPosition=new It(0,0),t[0].lastPosition=new It(t[0].initialPosition.x,t[0].initialPosition.y),t[0].lastGravity=new It(0,-1),t[0].lastGravity.y*=-1,t[0].velocity=new It(0,0),t[0].force=new It(0,0);for(let s=1;s<e.particleCount;++s)i=new It(0,0),i.y=t[s].radius,t[s].initialPosition=new It(t[s-1].initialPosition.x+i.x,t[s-1].initialPosition.y+i.y),t[s].position=new It(t[s].initialPosition.x,t[s].initialPosition.y),t[s].lastPosition=new It(t[s].initialPosition.x,t[s].initialPosition.y),t[s].lastGravity=new It(0,-1),t[s].lastGravity.y*=-1,t[s].velocity=new It(0,0),t[s].force=new It(0,0)}}}class si{constructor(){this.gravity=new It(0,0),this.wind=new It(0,0)}}class ri{constructor(){this.outputs=new e(0)}}function ai(t,e,i,s,r,a,n,o,l,h){t.x+=yi(i,s,r,a,n.minimum,n.maximum,n.defalut,l)*h}function ni(t,e,i,s,r,a,n,o,l,h){t.y+=yi(i,s,r,a,n.minimum,n.maximum,n.defalut,l)*h}function oi(t,e,i,s,r,a,n,o,l,h){e.angle+=yi(i,s,r,a,o.minimum,o.maximum,o.defalut,l)*h}function li(t,e,i,s,r){let a=t.x;return s&&(a*=-1),a}function hi(t,e,i,s,r){let a=t.y;return s&&(a*=-1),a}function ui(t,e,i,s,r){let a;return r=i>=2?e[i-1].position.substract(e[i-2].position):r.multiplyByScaler(-1),a=Vt.directionToRadian(r,t),s&&(a*=-1),a}function gi(t,e){return Vt.min(t,e)+function(t,e){const i=Vt.max(t,e),s=Vt.min(t,e);return Vt.abs(i-s)}(t,e)/2}function di(t,e){return JSON.parse(JSON.stringify(t.x))}function _i(t,e){return JSON.parse(JSON.stringify(t.y))}function ci(t,e){return JSON.parse(JSON.stringify(e))}function mi(t,e,i,s,r,a,n,o){let l,h,u=new It(0,0),g=new It(0,0),d=new It(0,0),_=new It(0,0);t[0].position=new It(i.x,i.y);const c=Vt.degreesToRadian(s),m=Vt.radianToDirection(c);m.normalize();for(let i=1;i<e;++i)t[i].force=m.multiplyByScaler(t[i].acceleration).add(r),t[i].lastPosition=new It(t[i].position.x,t[i].position.y),l=t[i].delay*n*30,u=t[i].position.substract(t[i-1].position),h=Vt.directionToRadian(t[i].lastGravity,m)/o,u.x=Vt.cos(h)*u.x-u.y*Vt.sin(h),u.y=Vt.sin(h)*u.x+u.y*Vt.cos(h),t[i].position=t[i-1].position.add(u),g=t[i].velocity.multiplyByScaler(l),d=t[i].force.multiplyByScaler(l).multiplyByScaler(l),t[i].position=t[i].position.add(g).add(d),_=t[i].position.substract(t[i-1].position),_.normalize(),t[i].position=t[i-1].position.add(_.multiplyByScaler(t[i].radius)),Vt.abs(t[i].position.x)<a&&(t[i].position.x=0),0!=l&&(t[i].velocity=t[i].position.substract(t[i].lastPosition),t[i].velocity=t[i].velocity.divisionByScalar(l),t[i].velocity=t[i].velocity.multiplyByScaler(t[i].mobility)),t[i].force=new It(0,0),t[i].lastGravity=new It(m.x,m.y)}function pi(t,e,i,s,r,a){let n=new It(0,0);t[0].position=new It(i.x,i.y);const o=Vt.degreesToRadian(s),l=Vt.radianToDirection(o);l.normalize();for(let i=1;i<e;++i)t[i].force=l.multiplyByScaler(t[i].acceleration).add(r),t[i].lastPosition=new It(t[i].position.x,t[i].position.y),t[i].velocity=new It(0,0),n=t[i].force,n.normalize(),n=n.multiplyByScaler(t[i].radius),t[i].position=t[i-1].position.add(n),Vt.abs(t[i].position.x)<a&&(t[i].position.x=0),t[i].force=new It(0,0),t[i].lastGravity=new It(l.x,l.y)}function fi(t,e,i,s,r){let a;a=s*r.getScale(r.translationScale,r.angleScale),a<e?(a<r.valueBelowMinimum&&(r.valueBelowMinimum=a),a=e):a>i&&(a>r.valueExceededMaximum&&(r.valueExceededMaximum=a),a=i);const n=r.weight/100;n>=1||(a=t[0]*(1-n)+a*n),t[0]=a}function yi(t,e,i,s,r,a,n,o){let l=0;const h=Vt.max(i,e);h<t&&(t=h);const u=Vt.min(i,e);u>t&&(t=u);const g=Vt.min(r,a),d=Vt.max(r,a),_=n,c=gi(u,h),m=t-c;switch(function(t){let e=0;return t>0?e=1:t<0&&(e=-1),e}(m)){case 1:{const t=h-c;0!=t&&(l=m*((d-_)/t),l+=_);break}case-1:{const t=u-c;0!=t&&(l=m*((g-_)/t),l+=_);break}case 0:l=_}return o?l:-1*l}var Si;!function(t){t.CubismPhysics=ii,t.Options=si}(Si||(Si={}));class Ci{constructor(t){this._renderTextureCount=0,this._clippingMaskBufferSize=256,this._clippingContextListForMask=new e,this._clippingContextListForDraw=new e,this._channelColors=new e,this._tmpBoundsOnModel=new m,this._tmpMatrix=new c,this._tmpMatrixForMask=new c,this._tmpMatrixForDraw=new c,this._clippingContexttConstructor=t;let i=new f;i.r=1,i.g=0,i.b=0,i.a=0,this._channelColors.pushBack(i),i=new f,i.r=0,i.g=1,i.b=0,i.a=0,this._channelColors.pushBack(i),i=new f,i.r=0,i.g=0,i.b=1,i.a=0,this._channelColors.pushBack(i),i=new f,i.r=0,i.g=0,i.b=0,i.a=1,this._channelColors.pushBack(i)}release(){for(let t=0;t<this._clippingContextListForMask.getSize();t++)this._clippingContextListForMask.at(t)&&(this._clippingContextListForMask.at(t).release(),this._clippingContextListForMask.set(t,void 0)),this._clippingContextListForMask.set(t,null);this._clippingContextListForMask=null;for(let t=0;t<this._clippingContextListForDraw.getSize();t++)this._clippingContextListForDraw.set(t,null);this._clippingContextListForDraw=null;for(let t=0;t<this._channelColors.getSize();t++)this._channelColors.set(t,null);this._channelColors=null,null!=this._clearedFrameBufferFlags&&this._clearedFrameBufferFlags.clear(),this._clearedFrameBufferFlags=null}initialize(t,i){i%1!=0&&(v(\"The number of render textures must be specified as an integer. The decimal point is rounded down and corrected to an integer.\"),i=~~i),i<1&&v(\"The number of render textures must be an integer greater than or equal to 1. Set the number of render textures to 1.\"),this._renderTextureCount=i<1?1:i,this._clearedFrameBufferFlags=new e(this._renderTextureCount);for(let e=0;e<t.getDrawableCount();e++){if(t.getDrawableMaskCounts()[e]<=0){this._clippingContextListForDraw.pushBack(null);continue}let i=this.findSameClip(t.getDrawableMasks()[e],t.getDrawableMaskCounts()[e]);null==i&&(i=new this._clippingContexttConstructor(this,t.getDrawableMasks()[e],t.getDrawableMaskCounts()[e]),this._clippingContextListForMask.pushBack(i)),i.addClippedDrawable(e),this._clippingContextListForDraw.pushBack(i)}}findSameClip(t,e){for(let i=0;i<this._clippingContextListForMask.getSize();i++){const s=this._clippingContextListForMask.at(i),r=s._clippingIdCount;if(r!=e)continue;let a=0;for(let e=0;e<r;e++){const i=s._clippingIdList[e];for(let e=0;e<r;e++)if(t[e]==i){a++;break}}if(a==r)return s}return null}setupMatrixForHighPrecision(t,e){let i=0;for(let e=0;e<this._clippingContextListForMask.getSize();e++){const s=this._clippingContextListForMask.at(e);this.calcClippedDrawTotalBounds(t,s),s._isUsing&&i++}if(i>0){if(this.setupLayoutBounds(0),this._clearedFrameBufferFlags.getSize()!=this._renderTextureCount){this._clearedFrameBufferFlags.clear();for(let t=0;t<this._renderTextureCount;t++)this._clearedFrameBufferFlags.pushBack(!1)}else for(let t=0;t<this._renderTextureCount;t++)this._clearedFrameBufferFlags.set(t,!1);for(let i=0;i<this._clippingContextListForMask.getSize();i++){const s=this._clippingContextListForMask.at(i),r=s._allClippedDrawRect,a=s._layoutBounds,n=.05;let o=0,l=0;const h=t.getPixelsPerUnit(),u=s.getClippingManager().getClippingMaskBufferSize(),g=a.width*u,d=a.height*u;this._tmpBoundsOnModel.setRect(r),this._tmpBoundsOnModel.width*h>g?(this._tmpBoundsOnModel.expand(r.width*n,0),o=a.width/this._tmpBoundsOnModel.width):o=h/g,this._tmpBoundsOnModel.height*h>d?(this._tmpBoundsOnModel.expand(0,r.height*n),l=a.height/this._tmpBoundsOnModel.height):l=h/d,this.createMatrixForMask(e,a,o,l),s._matrixForMask.setMatrix(this._tmpMatrixForMask.getArray()),s._matrixForDraw.setMatrix(this._tmpMatrixForDraw.getArray())}}}createMatrixForMask(t,e,i,s){this._tmpMatrix.loadIdentity(),this._tmpMatrix.translateRelative(-1,-1),this._tmpMatrix.scaleRelative(2,2),this._tmpMatrix.translateRelative(e.x,e.y),this._tmpMatrix.scaleRelative(i,s),this._tmpMatrix.translateRelative(-this._tmpBoundsOnModel.x,-this._tmpBoundsOnModel.y),this._tmpMatrixForMask.setMatrix(this._tmpMatrix.getArray()),this._tmpMatrix.loadIdentity(),this._tmpMatrix.translateRelative(e.x,e.y*(t?-1:1)),this._tmpMatrix.scaleRelative(i,s*(t?-1:1)),this._tmpMatrix.translateRelative(-this._tmpBoundsOnModel.x,-this._tmpBoundsOnModel.y),this._tmpMatrixForDraw.setMatrix(this._tmpMatrix.getArray())}setupLayoutBounds(t){const e=this._renderTextureCount<=1?36:32*this._renderTextureCount;if(t<=0||t>e){t>e&&b(\"not supported mask count : {0}\\n[Details] render texture count : {1}, mask count : {2}\",t-e,this._renderTextureCount,t);for(let t=0;t<this._clippingContextListForMask.getSize();t++){const e=this._clippingContextListForMask.at(t);e._layoutChannelIndex=0,e._layoutBounds.x=0,e._layoutBounds.y=0,e._layoutBounds.width=1,e._layoutBounds.height=1,e._bufferIndex=0}return}const i=this._renderTextureCount<=1?9:8;let s=t/this._renderTextureCount;const r=t%this._renderTextureCount;s=Math.ceil(s);let a=s/4;const n=s%4;a=~~a;let o=0;for(let s=0;s<this._renderTextureCount;s++)for(let l=0;l<4;l++){let h=a+(l<n?1:0);if(l==n+(a<1?-1:0)&&r>0&&(h-=s<r?0:1),0==h);else if(1==h){const t=this._clippingContextListForMask.at(o++);t._layoutChannelIndex=l,t._layoutBounds.x=0,t._layoutBounds.y=0,t._layoutBounds.width=1,t._layoutBounds.height=1,t._bufferIndex=s}else if(2==h)for(let t=0;t<h;t++){let e=t%2;e=~~e;const i=this._clippingContextListForMask.at(o++);i._layoutChannelIndex=l,i._layoutBounds.x=.5*e,i._layoutBounds.y=0,i._layoutBounds.width=.5,i._layoutBounds.height=1,i._bufferIndex=s}else if(h<=4)for(let t=0;t<h;t++){let e=t%2,i=t/2;e=~~e,i=~~i;const r=this._clippingContextListForMask.at(o++);r._layoutChannelIndex=l,r._layoutBounds.x=.5*e,r._layoutBounds.y=.5*i,r._layoutBounds.width=.5,r._layoutBounds.height=.5,r._bufferIndex=s}else if(h<=i)for(let t=0;t<h;t++){let e=t%3,i=t/3;e=~~e,i=~~i;const r=this._clippingContextListForMask.at(o++);r._layoutChannelIndex=l,r._layoutBounds.x=e/3,r._layoutBounds.y=i/3,r._layoutBounds.width=1/3,r._layoutBounds.height=1/3,r._bufferIndex=s}else{b(\"not supported mask count : {0}\\n[Details] render texture count : {1}, mask count : {2}\",t-e,this._renderTextureCount,t);for(let t=0;t<h;t++){const t=this._clippingContextListForMask.at(o++);t._layoutChannelIndex=0,t._layoutBounds.x=0,t._layoutBounds.y=0,t._layoutBounds.width=1,t._layoutBounds.height=1,t._bufferIndex=0}}}}calcClippedDrawTotalBounds(t,e){let i=Number.MAX_VALUE,s=Number.MAX_VALUE,r=Number.MIN_VALUE,a=Number.MIN_VALUE;const n=e._clippedDrawableIndexList.length;for(let o=0;o<n;o++){const n=e._clippedDrawableIndexList[o],l=t.getDrawableVertexCount(n),h=t.getDrawableVertices(n);let u=Number.MAX_VALUE,g=Number.MAX_VALUE,d=-Number.MAX_VALUE,_=-Number.MAX_VALUE;const c=l*W.vertexStep;for(let t=W.vertexOffset;t<c;t+=W.vertexStep){const e=h[t],i=h[t+1];e<u&&(u=e),e>d&&(d=e),i<g&&(g=i),i>_&&(_=i)}if(u!=Number.MAX_VALUE)if(u<i&&(i=u),g<s&&(s=g),d>r&&(r=d),_>a&&(a=_),i==Number.MAX_VALUE)e._allClippedDrawRect.x=0,e._allClippedDrawRect.y=0,e._allClippedDrawRect.width=0,e._allClippedDrawRect.height=0,e._isUsing=!1;else{e._isUsing=!0;const t=r-i,n=a-s;e._allClippedDrawRect.x=i,e._allClippedDrawRect.y=s,e._allClippedDrawRect.width=t,e._allClippedDrawRect.height=n}}}getClippingContextListForDraw(){return this._clippingContextListForDraw}getClippingMaskBufferSize(){return this._clippingMaskBufferSize}getRenderTextureCount(){return this._renderTextureCount}getChannelFlagAsColor(t){return this._channelColors.at(t)}setClippingMaskBufferSize(t){this._clippingMaskBufferSize=t}}let xi;class Mi{constructor(){this._shaderSets=new e}release(){this.releaseShaderProgram()}setupShaderProgramForDraw(t,e,i){let s,r,a,n;t.isPremultipliedAlpha()||b(\"NoPremultipliedAlpha is not allowed\"),0==this._shaderSets.getSize()&&this.generateShaders();const o=null!=t.getClippingContextBufferForDraw(),l=e.getDrawableInvertedMaskBit(i),u=o?l?2:1:0;let g;switch(e.getDrawableBlendMode(i)){case h.CubismBlendMode_Normal:default:g=this._shaderSets.at(Pi.ShaderNames_NormalPremultipliedAlpha+u),s=this.gl.ONE,r=this.gl.ONE_MINUS_SRC_ALPHA,a=this.gl.ONE,n=this.gl.ONE_MINUS_SRC_ALPHA;break;case h.CubismBlendMode_Additive:g=this._shaderSets.at(Pi.ShaderNames_AddPremultipliedAlpha+u),s=this.gl.ONE,r=this.gl.ONE,a=this.gl.ZERO,n=this.gl.ONE;break;case h.CubismBlendMode_Multiplicative:g=this._shaderSets.at(Pi.ShaderNames_MultPremultipliedAlpha+u),s=this.gl.DST_COLOR,r=this.gl.ONE_MINUS_SRC_ALPHA,a=this.gl.ZERO,n=this.gl.ONE}this.gl.useProgram(g.shaderProgram),null==t._bufferData.vertex&&(t._bufferData.vertex=this.gl.createBuffer()),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,t._bufferData.vertex);const d=e.getDrawableVertices(i);this.gl.bufferData(this.gl.ARRAY_BUFFER,d,this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(g.attributePositionLocation),this.gl.vertexAttribPointer(g.attributePositionLocation,2,this.gl.FLOAT,!1,0,0),null==t._bufferData.uv&&(t._bufferData.uv=this.gl.createBuffer()),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,t._bufferData.uv);const _=e.getDrawableVertexUvs(i);if(this.gl.bufferData(this.gl.ARRAY_BUFFER,_,this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(g.attributeTexCoordLocation),this.gl.vertexAttribPointer(g.attributeTexCoordLocation,2,this.gl.FLOAT,!1,0,0),o){this.gl.activeTexture(this.gl.TEXTURE1);const e=t.getClippingContextBufferForDraw().getClippingManager().getColorBuffer().at(t.getClippingContextBufferForDraw()._bufferIndex);this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.uniform1i(g.samplerTexture1Location,1),this.gl.uniformMatrix4fv(g.uniformClipMatrixLocation,!1,t.getClippingContextBufferForDraw()._matrixForDraw.getArray());const i=t.getClippingContextBufferForDraw()._layoutChannelIndex,s=t.getClippingContextBufferForDraw().getClippingManager().getChannelFlagAsColor(i);this.gl.uniform4f(g.uniformChannelFlagLocation,s.r,s.g,s.b,s.a)}const c=e.getDrawableTextureIndex(i),m=t.getBindedTextures().getValue(c);this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,m),this.gl.uniform1i(g.samplerTexture0Location,0);const p=t.getMvpMatrix();this.gl.uniformMatrix4fv(g.uniformMatrixLocation,!1,p.getArray());const f=t.getModelColorWithOpacity(e.getDrawableOpacity(i)),y=e.getMultiplyColor(i),S=e.getScreenColor(i);this.gl.uniform4f(g.uniformBaseColorLocation,f.r,f.g,f.b,f.a),this.gl.uniform4f(g.uniformMultiplyColorLocation,y.r,y.g,y.b,y.a),this.gl.uniform4f(g.uniformScreenColorLocation,S.r,S.g,S.b,S.a),null==t._bufferData.index&&(t._bufferData.index=this.gl.createBuffer());const C=e.getDrawableVertexIndices(i);this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER,t._bufferData.index),this.gl.bufferData(this.gl.ELEMENT_ARRAY_BUFFER,C,this.gl.DYNAMIC_DRAW),this.gl.blendFuncSeparate(s,r,a,n)}setupShaderProgramForMask(t,e,i){t.isPremultipliedAlpha()||b(\"NoPremultipliedAlpha is not allowed\"),0==this._shaderSets.getSize()&&this.generateShaders();const s=this._shaderSets.at(Pi.ShaderNames_SetupMask);this.gl.useProgram(s.shaderProgram),null==t._bufferData.vertex&&(t._bufferData.vertex=this.gl.createBuffer()),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,t._bufferData.vertex);const r=e.getDrawableVertices(i);this.gl.bufferData(this.gl.ARRAY_BUFFER,r,this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(s.attributePositionLocation),this.gl.vertexAttribPointer(s.attributePositionLocation,2,this.gl.FLOAT,!1,0,0),null==t._bufferData.uv&&(t._bufferData.uv=this.gl.createBuffer()),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,t._bufferData.uv);const a=e.getDrawableTextureIndex(i),n=t.getBindedTextures().getValue(a);this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,n),this.gl.uniform1i(s.samplerTexture0Location,0),null==t._bufferData.uv&&(t._bufferData.uv=this.gl.createBuffer()),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,t._bufferData.uv);const o=e.getDrawableVertexUvs(i);this.gl.bufferData(this.gl.ARRAY_BUFFER,o,this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(s.attributeTexCoordLocation),this.gl.vertexAttribPointer(s.attributeTexCoordLocation,2,this.gl.FLOAT,!1,0,0),t.getClippingContextBufferForMask();const l=t.getClippingContextBufferForMask()._layoutChannelIndex,h=t.getClippingContextBufferForMask().getClippingManager().getChannelFlagAsColor(l);this.gl.uniform4f(s.uniformChannelFlagLocation,h.r,h.g,h.b,h.a),this.gl.uniformMatrix4fv(s.uniformClipMatrixLocation,!1,t.getClippingContextBufferForMask()._matrixForMask.getArray());const u=t.getClippingContextBufferForMask()._layoutBounds;this.gl.uniform4f(s.uniformBaseColorLocation,2*u.x-1,2*u.y-1,2*u.getRight()-1,2*u.getBottom()-1);const g=e.getMultiplyColor(i),d=e.getScreenColor(i);this.gl.uniform4f(s.uniformMultiplyColorLocation,g.r,g.g,g.b,g.a),this.gl.uniform4f(s.uniformScreenColorLocation,d.r,d.g,d.b,d.a);const _=this.gl.ZERO,c=this.gl.ONE_MINUS_SRC_COLOR,m=this.gl.ZERO,p=this.gl.ONE_MINUS_SRC_ALPHA;null==t._bufferData.index&&(t._bufferData.index=this.gl.createBuffer());const f=e.getDrawableVertexIndices(i);this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER,t._bufferData.index),this.gl.bufferData(this.gl.ELEMENT_ARRAY_BUFFER,f,this.gl.DYNAMIC_DRAW),this.gl.blendFuncSeparate(_,c,m,p)}releaseShaderProgram(){for(let t=0;t<this._shaderSets.getSize();t++)this.gl.deleteProgram(this._shaderSets.at(t).shaderProgram),this._shaderSets.at(t).shaderProgram=0,this._shaderSets.set(t,void 0),this._shaderSets.set(t,null)}generateShaders(){for(let t=0;t<10;t++)this._shaderSets.pushBack(new bi);this._shaderSets.at(0).shaderProgram=this.loadShaderProgram(Bi,wi),this._shaderSets.at(1).shaderProgram=this.loadShaderProgram(Fi,Vi),this._shaderSets.at(2).shaderProgram=this.loadShaderProgram(Ii,Ei),this._shaderSets.at(3).shaderProgram=this.loadShaderProgram(Ii,Ri),this._shaderSets.at(4).shaderProgram=this._shaderSets.at(1).shaderProgram,this._shaderSets.at(5).shaderProgram=this._shaderSets.at(2).shaderProgram,this._shaderSets.at(6).shaderProgram=this._shaderSets.at(3).shaderProgram,this._shaderSets.at(7).shaderProgram=this._shaderSets.at(1).shaderProgram,this._shaderSets.at(8).shaderProgram=this._shaderSets.at(2).shaderProgram,this._shaderSets.at(9).shaderProgram=this._shaderSets.at(3).shaderProgram,this._shaderSets.at(0).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(0).shaderProgram,\"a_position\"),this._shaderSets.at(0).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(0).shaderProgram,\"a_texCoord\"),this._shaderSets.at(0).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(0).shaderProgram,\"s_texture0\"),this._shaderSets.at(0).uniformClipMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(0).shaderProgram,\"u_clipMatrix\"),this._shaderSets.at(0).uniformChannelFlagLocation=this.gl.getUniformLocation(this._shaderSets.at(0).shaderProgram,\"u_channelFlag\"),this._shaderSets.at(0).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(0).shaderProgram,\"u_baseColor\"),this._shaderSets.at(0).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(0).shaderProgram,\"u_multiplyColor\"),this._shaderSets.at(0).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(0).shaderProgram,\"u_screenColor\"),this._shaderSets.at(1).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(1).shaderProgram,\"a_position\"),this._shaderSets.at(1).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(1).shaderProgram,\"a_texCoord\"),this._shaderSets.at(1).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(1).shaderProgram,\"s_texture0\"),this._shaderSets.at(1).uniformMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(1).shaderProgram,\"u_matrix\"),this._shaderSets.at(1).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(1).shaderProgram,\"u_baseColor\"),this._shaderSets.at(1).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(1).shaderProgram,\"u_multiplyColor\"),this._shaderSets.at(1).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(1).shaderProgram,\"u_screenColor\"),this._shaderSets.at(2).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(2).shaderProgram,\"a_position\"),this._shaderSets.at(2).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(2).shaderProgram,\"a_texCoord\"),this._shaderSets.at(2).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(2).shaderProgram,\"s_texture0\"),this._shaderSets.at(2).samplerTexture1Location=this.gl.getUniformLocation(this._shaderSets.at(2).shaderProgram,\"s_texture1\"),this._shaderSets.at(2).uniformMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(2).shaderProgram,\"u_matrix\"),this._shaderSets.at(2).uniformClipMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(2).shaderProgram,\"u_clipMatrix\"),this._shaderSets.at(2).uniformChannelFlagLocation=this.gl.getUniformLocation(this._shaderSets.at(2).shaderProgram,\"u_channelFlag\"),this._shaderSets.at(2).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(2).shaderProgram,\"u_baseColor\"),this._shaderSets.at(2).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(2).shaderProgram,\"u_multiplyColor\"),this._shaderSets.at(2).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(2).shaderProgram,\"u_screenColor\"),this._shaderSets.at(3).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(3).shaderProgram,\"a_position\"),this._shaderSets.at(3).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(3).shaderProgram,\"a_texCoord\"),this._shaderSets.at(3).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(3).shaderProgram,\"s_texture0\"),this._shaderSets.at(3).samplerTexture1Location=this.gl.getUniformLocation(this._shaderSets.at(3).shaderProgram,\"s_texture1\"),this._shaderSets.at(3).uniformMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(3).shaderProgram,\"u_matrix\"),this._shaderSets.at(3).uniformClipMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(3).shaderProgram,\"u_clipMatrix\"),this._shaderSets.at(3).uniformChannelFlagLocation=this.gl.getUniformLocation(this._shaderSets.at(3).shaderProgram,\"u_channelFlag\"),this._shaderSets.at(3).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(3).shaderProgram,\"u_baseColor\"),this._shaderSets.at(3).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(3).shaderProgram,\"u_multiplyColor\"),this._shaderSets.at(3).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(3).shaderProgram,\"u_screenColor\"),this._shaderSets.at(4).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(4).shaderProgram,\"a_position\"),this._shaderSets.at(4).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(4).shaderProgram,\"a_texCoord\"),this._shaderSets.at(4).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(4).shaderProgram,\"s_texture0\"),this._shaderSets.at(4).uniformMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(4).shaderProgram,\"u_matrix\"),this._shaderSets.at(4).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(4).shaderProgram,\"u_baseColor\"),this._shaderSets.at(4).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(4).shaderProgram,\"u_multiplyColor\"),this._shaderSets.at(4).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(4).shaderProgram,\"u_screenColor\"),this._shaderSets.at(5).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(5).shaderProgram,\"a_position\"),this._shaderSets.at(5).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(5).shaderProgram,\"a_texCoord\"),this._shaderSets.at(5).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(5).shaderProgram,\"s_texture0\"),this._shaderSets.at(5).samplerTexture1Location=this.gl.getUniformLocation(this._shaderSets.at(5).shaderProgram,\"s_texture1\"),this._shaderSets.at(5).uniformMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(5).shaderProgram,\"u_matrix\"),this._shaderSets.at(5).uniformClipMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(5).shaderProgram,\"u_clipMatrix\"),this._shaderSets.at(5).uniformChannelFlagLocation=this.gl.getUniformLocation(this._shaderSets.at(5).shaderProgram,\"u_channelFlag\"),this._shaderSets.at(5).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(5).shaderProgram,\"u_baseColor\"),this._shaderSets.at(5).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(5).shaderProgram,\"u_multiplyColor\"),this._shaderSets.at(5).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(5).shaderProgram,\"u_screenColor\"),this._shaderSets.at(6).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(6).shaderProgram,\"a_position\"),this._shaderSets.at(6).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(6).shaderProgram,\"a_texCoord\"),this._shaderSets.at(6).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(6).shaderProgram,\"s_texture0\"),this._shaderSets.at(6).samplerTexture1Location=this.gl.getUniformLocation(this._shaderSets.at(6).shaderProgram,\"s_texture1\"),this._shaderSets.at(6).uniformMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(6).shaderProgram,\"u_matrix\"),this._shaderSets.at(6).uniformClipMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(6).shaderProgram,\"u_clipMatrix\"),this._shaderSets.at(6).uniformChannelFlagLocation=this.gl.getUniformLocation(this._shaderSets.at(6).shaderProgram,\"u_channelFlag\"),this._shaderSets.at(6).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(6).shaderProgram,\"u_baseColor\"),this._shaderSets.at(6).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(6).shaderProgram,\"u_multiplyColor\"),this._shaderSets.at(6).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(6).shaderProgram,\"u_screenColor\"),this._shaderSets.at(7).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(7).shaderProgram,\"a_position\"),this._shaderSets.at(7).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(7).shaderProgram,\"a_texCoord\"),this._shaderSets.at(7).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(7).shaderProgram,\"s_texture0\"),this._shaderSets.at(7).uniformMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(7).shaderProgram,\"u_matrix\"),this._shaderSets.at(7).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(7).shaderProgram,\"u_baseColor\"),this._shaderSets.at(7).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(7).shaderProgram,\"u_multiplyColor\"),this._shaderSets.at(7).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(7).shaderProgram,\"u_screenColor\"),this._shaderSets.at(8).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(8).shaderProgram,\"a_position\"),this._shaderSets.at(8).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(8).shaderProgram,\"a_texCoord\"),this._shaderSets.at(8).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(8).shaderProgram,\"s_texture0\"),this._shaderSets.at(8).samplerTexture1Location=this.gl.getUniformLocation(this._shaderSets.at(8).shaderProgram,\"s_texture1\"),this._shaderSets.at(8).uniformMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(8).shaderProgram,\"u_matrix\"),this._shaderSets.at(8).uniformClipMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(8).shaderProgram,\"u_clipMatrix\"),this._shaderSets.at(8).uniformChannelFlagLocation=this.gl.getUniformLocation(this._shaderSets.at(8).shaderProgram,\"u_channelFlag\"),this._shaderSets.at(8).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(8).shaderProgram,\"u_baseColor\"),this._shaderSets.at(8).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(8).shaderProgram,\"u_multiplyColor\"),this._shaderSets.at(8).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(8).shaderProgram,\"u_screenColor\"),this._shaderSets.at(9).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(9).shaderProgram,\"a_position\"),this._shaderSets.at(9).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(9).shaderProgram,\"a_texCoord\"),this._shaderSets.at(9).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(9).shaderProgram,\"s_texture0\"),this._shaderSets.at(9).samplerTexture1Location=this.gl.getUniformLocation(this._shaderSets.at(9).shaderProgram,\"s_texture1\"),this._shaderSets.at(9).uniformMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(9).shaderProgram,\"u_matrix\"),this._shaderSets.at(9).uniformClipMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(9).shaderProgram,\"u_clipMatrix\"),this._shaderSets.at(9).uniformChannelFlagLocation=this.gl.getUniformLocation(this._shaderSets.at(9).shaderProgram,\"u_channelFlag\"),this._shaderSets.at(9).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(9).shaderProgram,\"u_baseColor\"),this._shaderSets.at(9).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(9).shaderProgram,\"u_multiplyColor\"),this._shaderSets.at(9).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(9).shaderProgram,\"u_screenColor\")}loadShaderProgram(t,e){let i=this.gl.createProgram(),s=this.compileShaderSource(this.gl.VERTEX_SHADER,t);if(!s)return b(\"Vertex shader compile error!\"),0;let r=this.compileShaderSource(this.gl.FRAGMENT_SHADER,e);if(!r)return b(\"Vertex shader compile error!\"),0;this.gl.attachShader(i,s),this.gl.attachShader(i,r),this.gl.linkProgram(i);return this.gl.getProgramParameter(i,this.gl.LINK_STATUS)?(this.gl.deleteShader(s),this.gl.deleteShader(r),i):(b(\"Failed to link program: {0}\",i),this.gl.deleteShader(s),s=0,this.gl.deleteShader(r),r=0,i&&(this.gl.deleteProgram(i),i=0),0)}compileShaderSource(t,e){const i=e,s=this.gl.createShader(t);if(this.gl.shaderSource(s,i),this.gl.compileShader(s),!s){const t=this.gl.getShaderInfoLog(s);b(\"Shader compile log: {0} \",t)}return this.gl.getShaderParameter(s,this.gl.COMPILE_STATUS)?s:(this.gl.deleteShader(s),null)}setGl(t){this.gl=t}}class vi{static getInstance(){return null==xi&&(xi=new vi),xi}static deleteInstance(){xi&&(xi.release(),xi=null)}constructor(){this._shaderMap=new I}release(){for(const t=this._shaderMap.begin();t.notEqual(this._shaderMap.end());t.preIncrement())t.ptr().second.release();this._shaderMap.clear()}getShader(t){return this._shaderMap.getValue(t)}setGlContext(t){if(!this._shaderMap.isExist(t)){const e=new Mi;e.setGl(t),this._shaderMap.setValue(t,e)}}}class bi{}var Pi;!function(t){t[t.ShaderNames_SetupMask=0]=\"ShaderNames_SetupMask\",t[t.ShaderNames_NormalPremultipliedAlpha=1]=\"ShaderNames_NormalPremultipliedAlpha\",t[t.ShaderNames_NormalMaskedPremultipliedAlpha=2]=\"ShaderNames_NormalMaskedPremultipliedAlpha\",t[t.ShaderNames_NomralMaskedInvertedPremultipliedAlpha=3]=\"ShaderNames_NomralMaskedInvertedPremultipliedAlpha\",t[t.ShaderNames_AddPremultipliedAlpha=4]=\"ShaderNames_AddPremultipliedAlpha\",t[t.ShaderNames_AddMaskedPremultipliedAlpha=5]=\"ShaderNames_AddMaskedPremultipliedAlpha\",t[t.ShaderNames_AddMaskedPremultipliedAlphaInverted=6]=\"ShaderNames_AddMaskedPremultipliedAlphaInverted\",t[t.ShaderNames_MultPremultipliedAlpha=7]=\"ShaderNames_MultPremultipliedAlpha\",t[t.ShaderNames_MultMaskedPremultipliedAlpha=8]=\"ShaderNames_MultMaskedPremultipliedAlpha\",t[t.ShaderNames_MultMaskedPremultipliedAlphaInverted=9]=\"ShaderNames_MultMaskedPremultipliedAlphaInverted\"}(Pi||(Pi={}));const Bi=\"attribute vec4     a_position;attribute vec2     a_texCoord;varying vec2       v_texCoord;varying vec4       v_myPos;uniform mat4       u_clipMatrix;void main(){   gl_Position = u_clipMatrix * a_position;   v_myPos = u_clipMatrix * a_position;   v_texCoord = a_texCoord;   v_texCoord.y = 1.0 - v_texCoord.y;}\",wi=\"precision mediump float;varying vec2       v_texCoord;varying vec4       v_myPos;uniform vec4       u_baseColor;uniform vec4       u_channelFlag;uniform sampler2D  s_texture0;void main(){   float isInside =        step(u_baseColor.x, v_myPos.x/v_myPos.w)       * step(u_baseColor.y, v_myPos.y/v_myPos.w)       * step(v_myPos.x/v_myPos.w, u_baseColor.z)       * step(v_myPos.y/v_myPos.w, u_baseColor.w);   gl_FragColor = u_channelFlag * texture2D(s_texture0, v_texCoord).a * isInside;}\",Fi=\"attribute vec4     a_position;attribute vec2     a_texCoord;varying vec2       v_texCoord;uniform mat4       u_matrix;void main(){   gl_Position = u_matrix * a_position;   v_texCoord = a_texCoord;   v_texCoord.y = 1.0 - v_texCoord.y;}\",Ii=\"attribute vec4     a_position;attribute vec2     a_texCoord;varying vec2       v_texCoord;varying vec4       v_clipPos;uniform mat4       u_matrix;uniform mat4       u_clipMatrix;void main(){   gl_Position = u_matrix * a_position;   v_clipPos = u_clipMatrix * a_position;   v_texCoord = a_texCoord;   v_texCoord.y = 1.0 - v_texCoord.y;}\",Vi=\"precision mediump float;varying vec2       v_texCoord;uniform vec4       u_baseColor;uniform sampler2D  s_texture0;uniform vec4       u_multiplyColor;uniform vec4       u_screenColor;void main(){   vec4 texColor = texture2D(s_texture0, v_texCoord);   texColor.rgb = texColor.rgb * u_multiplyColor.rgb;   texColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb);   vec4 color = texColor * u_baseColor;   gl_FragColor = vec4(color.rgb, color.a);}\",Ei=\"precision mediump float;varying vec2       v_texCoord;varying vec4       v_clipPos;uniform vec4       u_baseColor;uniform vec4       u_channelFlag;uniform sampler2D  s_texture0;uniform sampler2D  s_texture1;uniform vec4       u_multiplyColor;uniform vec4       u_screenColor;void main(){   vec4 texColor = texture2D(s_texture0, v_texCoord);   texColor.rgb = texColor.rgb * u_multiplyColor.rgb;   texColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb);   vec4 col_formask = texColor * u_baseColor;   vec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag;   float maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a;   col_formask = col_formask * maskVal;   gl_FragColor = col_formask;}\",Ri=\"precision mediump float;varying vec2      v_texCoord;varying vec4      v_clipPos;uniform sampler2D s_texture0;uniform sampler2D s_texture1;uniform vec4      u_channelFlag;uniform vec4      u_baseColor;uniform vec4      u_multiplyColor;uniform vec4      u_screenColor;void main(){   vec4 texColor = texture2D(s_texture0, v_texCoord);   texColor.rgb = texColor.rgb * u_multiplyColor.rgb;   texColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb);   vec4 col_formask = texColor * u_baseColor;   vec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag;   float maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a;   col_formask = col_formask * (1.0 - maskVal);   gl_FragColor = col_formask;}\";var Ti;let Li,Di;!function(t){t.CubismShaderSet=bi,t.CubismShader_WebGL=Mi,t.CubismShaderManager_WebGL=vi,t.ShaderNames=Pi}(Ti||(Ti={}));class Ai extends Ci{getMaskRenderTexture(){if(this._maskTexture&&null!=this._maskTexture.textures)this._maskTexture.frameNo=this._currentFrameNo;else{null!=this._maskRenderTextures&&this._maskRenderTextures.clear(),this._maskRenderTextures=new e,null!=this._maskColorBuffers&&this._maskColorBuffers.clear(),this._maskColorBuffers=new e;const t=this._clippingMaskBufferSize;for(let e=0;e<this._renderTextureCount;e++)this._maskColorBuffers.pushBack(this.gl.createTexture()),this.gl.bindTexture(this.gl.TEXTURE_2D,this._maskColorBuffers.at(e)),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,t,t,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,null),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this._maskRenderTextures.pushBack(this.gl.createFramebuffer()),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this._maskRenderTextures.at(e)),this.gl.framebufferTexture2D(this.gl.FRAMEBUFFER,this.gl.COLOR_ATTACHMENT0,this.gl.TEXTURE_2D,this._maskColorBuffers.at(e),0);this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,Di),this._maskTexture=new Oi(this._currentFrameNo,this._maskRenderTextures)}return this._maskTexture.textures}setGL(t){this.gl=t}constructor(){super(ki)}setupClippingContext(t,i){this._currentFrameNo++;let s=0;for(let e=0;e<this._clippingContextListForMask.getSize();e++){const i=this._clippingContextListForMask.at(e);this.calcClippedDrawTotalBounds(t,i),i._isUsing&&s++}if(s>0){this.gl.viewport(0,0,this._clippingMaskBufferSize,this._clippingMaskBufferSize),this._currentMaskRenderTexture=this.getMaskRenderTexture().at(0),i.preDraw(),this.setupLayoutBounds(s),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this._currentMaskRenderTexture),this._clearedFrameBufferFlags.getSize()!=this._renderTextureCount&&(this._clearedFrameBufferFlags.clear(),this._clearedFrameBufferFlags=new e(this._renderTextureCount));for(let t=0;t<this._clearedFrameBufferFlags.getSize();t++)this._clearedFrameBufferFlags.set(t,!1);for(let e=0;e<this._clippingContextListForMask.getSize();e++){const s=this._clippingContextListForMask.at(e),r=s._allClippedDrawRect,a=s._layoutBounds,n=.05;let o=0,l=0;const h=this.getMaskRenderTexture().at(s._bufferIndex);this._currentMaskRenderTexture!=h&&(this._currentMaskRenderTexture=h,i.preDraw(),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this._currentMaskRenderTexture)),this._tmpBoundsOnModel.setRect(r),this._tmpBoundsOnModel.expand(r.width*n,r.height*n),o=a.width/this._tmpBoundsOnModel.width,l=a.height/this._tmpBoundsOnModel.height,this._tmpMatrix.loadIdentity(),this._tmpMatrix.translateRelative(-1,-1),this._tmpMatrix.scaleRelative(2,2),this._tmpMatrix.translateRelative(a.x,a.y),this._tmpMatrix.scaleRelative(o,l),this._tmpMatrix.translateRelative(-this._tmpBoundsOnModel.x,-this._tmpBoundsOnModel.y),this._tmpMatrixForMask.setMatrix(this._tmpMatrix.getArray()),this._tmpMatrix.loadIdentity(),this._tmpMatrix.translateRelative(a.x,a.y),this._tmpMatrix.scaleRelative(o,l),this._tmpMatrix.translateRelative(-this._tmpBoundsOnModel.x,-this._tmpBoundsOnModel.y),this._tmpMatrixForDraw.setMatrix(this._tmpMatrix.getArray()),s._matrixForMask.setMatrix(this._tmpMatrixForMask.getArray()),s._matrixForDraw.setMatrix(this._tmpMatrixForDraw.getArray());const u=s._clippingIdCount;for(let e=0;e<u;e++){const r=s._clippingIdList[e];t.getDrawableDynamicFlagVertexPositionsDidChange(r)&&(i.setIsCulling(0!=t.getDrawableCulling(r)),this._clearedFrameBufferFlags.at(s._bufferIndex)||(this.gl.clearColor(1,1,1,1),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this._clearedFrameBufferFlags.set(s._bufferIndex,!0)),i.setClippingContextBufferForMask(s),i.drawMeshWebGL(t,r))}}this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,Di),i.setClippingContextBufferForMask(null),this.gl.viewport(Li[0],Li[1],Li[2],Li[3])}}getColorBuffer(){return this._maskColorBuffers}getClippingMaskCount(){return this._clippingContextListForMask.getSize()}}class Oi{constructor(t,e){this.frameNo=t,this.textures=e}}class ki extends y{constructor(t,e,i){super(e,i),this._owner=t}getClippingManager(){return this._owner}setGl(t){this._owner.setGL(t)}}class Ni{setGlEnable(t,e){e?this.gl.enable(t):this.gl.disable(t)}setGlEnableVertexAttribArray(t,e){e?this.gl.enableVertexAttribArray(t):this.gl.disableVertexAttribArray(t)}save(){null!=this.gl?(this._lastArrayBufferBinding=this.gl.getParameter(this.gl.ARRAY_BUFFER_BINDING),this._lastElementArrayBufferBinding=this.gl.getParameter(this.gl.ELEMENT_ARRAY_BUFFER_BINDING),this._lastProgram=this.gl.getParameter(this.gl.CURRENT_PROGRAM),this._lastActiveTexture=this.gl.getParameter(this.gl.ACTIVE_TEXTURE),this.gl.activeTexture(this.gl.TEXTURE1),this._lastTexture1Binding2D=this.gl.getParameter(this.gl.TEXTURE_BINDING_2D),this.gl.activeTexture(this.gl.TEXTURE0),this._lastTexture0Binding2D=this.gl.getParameter(this.gl.TEXTURE_BINDING_2D),this._lastVertexAttribArrayEnabled[0]=this.gl.getVertexAttrib(0,this.gl.VERTEX_ATTRIB_ARRAY_ENABLED),this._lastVertexAttribArrayEnabled[1]=this.gl.getVertexAttrib(1,this.gl.VERTEX_ATTRIB_ARRAY_ENABLED),this._lastVertexAttribArrayEnabled[2]=this.gl.getVertexAttrib(2,this.gl.VERTEX_ATTRIB_ARRAY_ENABLED),this._lastVertexAttribArrayEnabled[3]=this.gl.getVertexAttrib(3,this.gl.VERTEX_ATTRIB_ARRAY_ENABLED),this._lastScissorTest=this.gl.isEnabled(this.gl.SCISSOR_TEST),this._lastStencilTest=this.gl.isEnabled(this.gl.STENCIL_TEST),this._lastDepthTest=this.gl.isEnabled(this.gl.DEPTH_TEST),this._lastCullFace=this.gl.isEnabled(this.gl.CULL_FACE),this._lastBlend=this.gl.isEnabled(this.gl.BLEND),this._lastFrontFace=this.gl.getParameter(this.gl.FRONT_FACE),this._lastColorMask=this.gl.getParameter(this.gl.COLOR_WRITEMASK),this._lastBlending[0]=this.gl.getParameter(this.gl.BLEND_SRC_RGB),this._lastBlending[1]=this.gl.getParameter(this.gl.BLEND_DST_RGB),this._lastBlending[2]=this.gl.getParameter(this.gl.BLEND_SRC_ALPHA),this._lastBlending[3]=this.gl.getParameter(this.gl.BLEND_DST_ALPHA),this._lastFBO=this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING),this._lastViewport=this.gl.getParameter(this.gl.VIEWPORT)):b(\"'gl' is null. WebGLRenderingContext is required.\\nPlease call 'CubimRenderer_WebGL.startUp' function.\")}restore(){null!=this.gl?(this.gl.useProgram(this._lastProgram),this.setGlEnableVertexAttribArray(0,this._lastVertexAttribArrayEnabled[0]),this.setGlEnableVertexAttribArray(1,this._lastVertexAttribArrayEnabled[1]),this.setGlEnableVertexAttribArray(2,this._lastVertexAttribArrayEnabled[2]),this.setGlEnableVertexAttribArray(3,this._lastVertexAttribArrayEnabled[3]),this.setGlEnable(this.gl.SCISSOR_TEST,this._lastScissorTest),this.setGlEnable(this.gl.STENCIL_TEST,this._lastStencilTest),this.setGlEnable(this.gl.DEPTH_TEST,this._lastDepthTest),this.setGlEnable(this.gl.CULL_FACE,this._lastCullFace),this.setGlEnable(this.gl.BLEND,this._lastBlend),this.gl.frontFace(this._lastFrontFace),this.gl.colorMask(this._lastColorMask[0],this._lastColorMask[1],this._lastColorMask[2],this._lastColorMask[3]),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this._lastArrayBufferBinding),this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER,this._lastElementArrayBufferBinding),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this._lastTexture1Binding2D),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this._lastTexture0Binding2D),this.gl.activeTexture(this._lastActiveTexture),this.gl.blendFuncSeparate(this._lastBlending[0],this._lastBlending[1],this._lastBlending[2],this._lastBlending[3])):b(\"'gl' is null. WebGLRenderingContext is required.\\nPlease call 'CubimRenderer_WebGL.startUp' function.\")}setGl(t){this.gl=t}constructor(){this._lastVertexAttribArrayEnabled=new Array(4),this._lastColorMask=new Array(4),this._lastBlending=new Array(4),this._lastViewport=new Array(4)}}class zi extends p{initialize(t,e=1){t.isUsingMasking()&&(this._clippingManager=new Ai,this._clippingManager.initialize(t,e)),this._sortedDrawableIndexList.resize(t.getDrawableCount(),0),super.initialize(t)}bindTexture(t,e){this._textures.setValue(t,e)}getBindedTextures(){return this._textures}setClippingMaskBufferSize(t){if(!this._model.isUsingMasking())return;const e=this._clippingManager.getRenderTextureCount();this._clippingManager.release(),this._clippingManager=void 0,this._clippingManager=null,this._clippingManager=new Ai,this._clippingManager.setClippingMaskBufferSize(t),this._clippingManager.initialize(this.getModel(),e)}getClippingMaskBufferSize(){return this._model.isUsingMasking()?this._clippingManager.getClippingMaskBufferSize():-1}getRenderTextureCount(){return this._model.isUsingMasking()?this._clippingManager.getRenderTextureCount():-1}constructor(){super(),this._clippingContextBufferForMask=null,this._clippingContextBufferForDraw=null,this._rendererProfile=new Ni,this.firstDraw=!0,this._textures=new I,this._sortedDrawableIndexList=new e,this._bufferData={vertex:WebGLBuffer=null,uv:WebGLBuffer=null,index:WebGLBuffer=null},this._textures.prepareCapacity(32,!0)}release(){this._clippingManager&&(this._clippingManager.release(),this._clippingManager=void 0,this._clippingManager=null),null!=this.gl&&(this.gl.deleteBuffer(this._bufferData.vertex),this._bufferData.vertex=null,this.gl.deleteBuffer(this._bufferData.uv),this._bufferData.uv=null,this.gl.deleteBuffer(this._bufferData.index),this._bufferData.index=null,this._bufferData=null,this._textures=null)}doDrawModel(){if(null==this.gl)return void b(\"'gl' is null. WebGLRenderingContext is required.\\nPlease call 'CubimRenderer_WebGL.startUp' function.\");null!=this._clippingManager&&(this.preDraw(),this.isUsingHighPrecisionMask()?this._clippingManager.setupMatrixForHighPrecision(this.getModel(),!1):this._clippingManager.setupClippingContext(this.getModel(),this)),this.preDraw();const t=this.getModel().getDrawableCount(),e=this.getModel().getDrawableRenderOrders();for(let i=0;i<t;++i){const t=e[i];this._sortedDrawableIndexList.set(t,i)}for(let e=0;e<t;++e){const t=this._sortedDrawableIndexList.at(e);if(!this.getModel().getDrawableDynamicFlagIsVisible(t))continue;const i=null!=this._clippingManager?this._clippingManager.getClippingContextListForDraw().at(t):null;if(null!=i&&this.isUsingHighPrecisionMask()){i._isUsing&&(this.gl.viewport(0,0,this._clippingManager.getClippingMaskBufferSize(),this._clippingManager.getClippingMaskBufferSize()),this.preDraw(),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,i.getClippingManager().getMaskRenderTexture().at(i._bufferIndex)),this.gl.clearColor(1,1,1,1),this.gl.clear(this.gl.COLOR_BUFFER_BIT));{const t=i._clippingIdCount;for(let e=0;e<t;e++){const t=i._clippingIdList[e];this._model.getDrawableDynamicFlagVertexPositionsDidChange(t)&&(this.setIsCulling(0!=this._model.getDrawableCulling(t)),this.setClippingContextBufferForMask(i),this.drawMeshWebGL(this._model,t))}}this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,Di),this.setClippingContextBufferForMask(null),this.gl.viewport(Li[0],Li[1],Li[2],Li[3]),this.preDraw()}this.setClippingContextBufferForDraw(i),this.setIsCulling(this.getModel().getDrawableCulling(t)),this.drawMeshWebGL(this._model,t)}}drawMeshWebGL(t,e){this.isCulling()?this.gl.enable(this.gl.CULL_FACE):this.gl.disable(this.gl.CULL_FACE),this.gl.frontFace(this.gl.CCW),this.isGeneratingMask()?vi.getInstance().getShader(this.gl).setupShaderProgramForMask(this,t,e):vi.getInstance().getShader(this.gl).setupShaderProgramForDraw(this,t,e);{const i=t.getDrawableVertexIndexCount(e);this.gl.drawElements(this.gl.TRIANGLES,i,this.gl.UNSIGNED_SHORT,0)}this.gl.useProgram(null),this.setClippingContextBufferForDraw(null),this.setClippingContextBufferForMask(null)}saveProfile(){this._rendererProfile.save()}restoreProfile(){this._rendererProfile.restore()}static doStaticRelease(){vi.deleteInstance()}setRenderState(t,e){Di=t,Li=e}preDraw(){if(this.firstDraw&&(this.firstDraw=!1),this.gl.disable(this.gl.SCISSOR_TEST),this.gl.disable(this.gl.STENCIL_TEST),this.gl.disable(this.gl.DEPTH_TEST),this.gl.frontFace(this.gl.CW),this.gl.enable(this.gl.BLEND),this.gl.colorMask(!0,!0,!0,!0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER,null),this.getAnisotropy()>0&&this._extension)for(let t=0;t<this._textures.getSize();++t)this.gl.bindTexture(this.gl.TEXTURE_2D,this._textures.getValue(t)),this.gl.texParameterf(this.gl.TEXTURE_2D,this._extension.TEXTURE_MAX_ANISOTROPY_EXT,this.getAnisotropy())}setClippingContextBufferForMask(t){this._clippingContextBufferForMask=t}getClippingContextBufferForMask(){return this._clippingContextBufferForMask}setClippingContextBufferForDraw(t){this._clippingContextBufferForDraw=t}getClippingContextBufferForDraw(){return this._clippingContextBufferForDraw}isGeneratingMask(){return null!=this.getClippingContextBufferForMask()}startUp(t){this.gl=t,this._clippingManager&&this._clippingManager.setGL(t),vi.getInstance().setGlContext(t),this._rendererProfile.setGl(t),this._extension=this.gl.getExtension(\"EXT_texture_filter_anisotropic\")||this.gl.getExtension(\"WEBKIT_EXT_texture_filter_anisotropic\")||this.gl.getExtension(\"MOZ_EXT_texture_filter_anisotropic\")}}var Ui,Gi,Xi;p.staticRelease=()=>{zi.doStaticRelease()},function(t){t.CubismClippingContext=ki,t.CubismClippingManager_WebGL=Ai,t.CubismRenderTextureResource=Oi,t.CubismRenderer_WebGL=zi}(Ui||(Ui={}));class Yi{constructor(t=!1,e=!1){this.isOverridden=t,this.isParameterRepeated=e}}class ji{constructor(t=!1,e=new f){this.isOverridden=t,this.color=e}get isOverwritten(){return this.isOverridden}}class Hi{constructor(t=!1,e=new f){this.isOverridden=t,this.color=e}get isOverwritten(){return this.isOverridden}}class qi{constructor(t=!1,e=!1){this.isOverridden=t,this.isCulling=e}get isOverwritten(){return this.isOverridden}}class Wi{update(){this._model.update(),this._model.drawables.resetDynamicFlags()}getPixelsPerUnit(){return null==this._model?0:this._model.canvasinfo.PixelsPerUnit}getCanvasWidth(){return null==this._model?0:this._model.canvasinfo.CanvasWidth/this._model.canvasinfo.PixelsPerUnit}getCanvasHeight(){return null==this._model?0:this._model.canvasinfo.CanvasHeight/this._model.canvasinfo.PixelsPerUnit}saveParameters(){const t=this._model.parameters.count,e=this._savedParameters.getSize();for(let i=0;i<t;++i)i<e?this._savedParameters.set(i,this._parameterValues[i]):this._savedParameters.pushBack(this._parameterValues[i])}getMultiplyColor(t){if(this.getOverrideFlagForModelMultiplyColors()||this.getOverrideFlagForDrawableMultiplyColors(t))return this._userMultiplyColors.at(t).color;return this.getDrawableMultiplyColor(t)}getScreenColor(t){if(this.getOverrideFlagForModelScreenColors()||this.getOverrideFlagForDrawableScreenColors(t))return this._userScreenColors.at(t).color;return this.getDrawableScreenColor(t)}setMultiplyColorByTextureColor(t,e){this.setMultiplyColorByRGBA(t,e.r,e.g,e.b,e.a)}setMultiplyColorByRGBA(t,e,i,s,r=1){this._userMultiplyColors.at(t).color.r=e,this._userMultiplyColors.at(t).color.g=i,this._userMultiplyColors.at(t).color.b=s,this._userMultiplyColors.at(t).color.a=r}setScreenColorByTextureColor(t,e){this.setScreenColorByRGBA(t,e.r,e.g,e.b,e.a)}setScreenColorByRGBA(t,e,i,s,r=1){this._userScreenColors.at(t).color.r=e,this._userScreenColors.at(t).color.g=i,this._userScreenColors.at(t).color.b=s,this._userScreenColors.at(t).color.a=r}getPartMultiplyColor(t){return this._userPartMultiplyColors.at(t).color}getPartScreenColor(t){return this._userPartScreenColors.at(t).color}setPartColor(t,e,i,s,r,a,n){if(a.at(t).color.r=e,a.at(t).color.g=i,a.at(t).color.b=s,a.at(t).color.a=r,a.at(t).isOverridden)for(let a=0;a<this._partChildDrawables.at(t).getSize();++a){const o=this._partChildDrawables.at(t).at(a);n.at(o).color.r=e,n.at(o).color.g=i,n.at(o).color.b=s,n.at(o).color.a=r}}setPartMultiplyColorByTextureColor(t,e){this.setPartMultiplyColorByRGBA(t,e.r,e.g,e.b,e.a)}setPartMultiplyColorByRGBA(t,e,i,s,r){this.setPartColor(t,e,i,s,r,this._userPartMultiplyColors,this._userMultiplyColors)}setPartScreenColorByTextureColor(t,e){this.setPartScreenColorByRGBA(t,e.r,e.g,e.b,e.a)}setPartScreenColorByRGBA(t,e,i,s,r){this.setPartColor(t,e,i,s,r,this._userPartScreenColors,this._userScreenColors)}getOverrideFlagForModelParameterRepeat(){return this._isOverriddenParameterRepeat}setOverrideFlagForModelParameterRepeat(t){this._isOverriddenParameterRepeat=t}getOverrideFlagForParameterRepeat(t){return this._userParameterRepeatDataList.at(t).isOverridden}setOverrideFlagForParameterRepeat(t,e){this._userParameterRepeatDataList.at(t).isOverridden=e}getRepeatFlagForParameterRepeat(t){return this._userParameterRepeatDataList.at(t).isParameterRepeated}setRepeatFlagForParameterRepeat(t,e){this._userParameterRepeatDataList.at(t).isParameterRepeated=e}getOverwriteFlagForModelMultiplyColors(){return v(\"getOverwriteFlagForModelMultiplyColors() is a deprecated function. Please use getOverrideFlagForModelMultiplyColors().\"),this.getOverrideFlagForModelMultiplyColors()}getOverrideFlagForModelMultiplyColors(){return this._isOverriddenModelMultiplyColors}getOverwriteFlagForModelScreenColors(){return v(\"getOverwriteFlagForModelScreenColors() is a deprecated function. Please use getOverrideFlagForModelScreenColors().\"),this.getOverrideFlagForModelScreenColors()}getOverrideFlagForModelScreenColors(){return this._isOverriddenModelScreenColors}setOverwriteFlagForModelMultiplyColors(t){v(\"setOverwriteFlagForModelMultiplyColors(value: boolean) is a deprecated function. Please use setOverrideFlagForModelMultiplyColors(value: boolean).\"),this.setOverrideFlagForModelMultiplyColors(t)}setOverrideFlagForModelMultiplyColors(t){this._isOverriddenModelMultiplyColors=t}setOverwriteFlagForModelScreenColors(t){v(\"setOverwriteFlagForModelScreenColors(value: boolean) is a deprecated function. Please use setOverrideFlagForModelScreenColors(value: boolean).\"),this.setOverrideFlagForModelScreenColors(t)}setOverrideFlagForModelScreenColors(t){this._isOverriddenModelScreenColors=t}getOverwriteFlagForDrawableMultiplyColors(t){return v(\"getOverwriteFlagForDrawableMultiplyColors(drawableindex: number) is a deprecated function. Please use getOverrideFlagForDrawableMultiplyColors(drawableindex: number).\"),this.getOverrideFlagForDrawableMultiplyColors(t)}getOverrideFlagForDrawableMultiplyColors(t){return this._userMultiplyColors.at(t).isOverridden}getOverwriteFlagForDrawableScreenColors(t){return v(\"getOverwriteFlagForDrawableScreenColors(drawableindex: number) is a deprecated function. Please use getOverrideFlagForDrawableScreenColors(drawableindex: number).\"),this.getOverrideFlagForDrawableScreenColors(t)}getOverrideFlagForDrawableScreenColors(t){return this._userScreenColors.at(t).isOverridden}setOverwriteFlagForDrawableMultiplyColors(t,e){v(\"setOverwriteFlagForDrawableMultiplyColors(drawableindex: number, value: boolean) is a deprecated function. Please use setOverrideFlagForDrawableMultiplyColors(drawableindex: number, value: boolean).\"),this.setOverrideFlagForDrawableMultiplyColors(t,e)}setOverrideFlagForDrawableMultiplyColors(t,e){this._userMultiplyColors.at(t).isOverridden=e}setOverwriteFlagForDrawableScreenColors(t,e){v(\"setOverwriteFlagForDrawableScreenColors(drawableindex: number, value: boolean) is a deprecated function. Please use setOverrideFlagForDrawableScreenColors(drawableindex: number, value: boolean).\"),this.setOverrideFlagForDrawableScreenColors(t,e)}setOverrideFlagForDrawableScreenColors(t,e){this._userScreenColors.at(t).isOverridden=e}getOverwriteColorForPartMultiplyColors(t){return v(\"getOverwriteColorForPartMultiplyColors(partIndex: number) is a deprecated function. Please use getOverrideColorForPartMultiplyColors(partIndex: number).\"),this.getOverrideColorForPartMultiplyColors(t)}getOverrideColorForPartMultiplyColors(t){return this._userPartMultiplyColors.at(t).isOverridden}getOverwriteColorForPartScreenColors(t){return v(\"getOverwriteColorForPartScreenColors(partIndex: number) is a deprecated function. Please use getOverrideColorForPartScreenColors(partIndex: number).\"),this.getOverrideColorForPartScreenColors(t)}getOverrideColorForPartScreenColors(t){return this._userPartScreenColors.at(t).isOverridden}setOverwriteColorForPartColors(t,e,i,s){v(\"setOverwriteColorForPartColors(partIndex: number, value: boolean, partColors: csmVector<PartColorData>, drawableColors: csmVector<DrawableColorData>) is a deprecated function. Please use setOverrideColorForPartColors(partIndex: number, value: boolean, partColors: csmVector<PartColorData>, drawableColors: csmVector<DrawableColorData>).\"),this.setOverrideColorForPartColors(t,e,i,s)}setOverrideColorForPartColors(t,e,i,s){i.at(t).isOverridden=e;for(let r=0;r<this._partChildDrawables.at(t).getSize();++r){const a=this._partChildDrawables.at(t).at(r);s.at(a).isOverridden=e,e&&(s.at(a).color.r=i.at(t).color.r,s.at(a).color.g=i.at(t).color.g,s.at(a).color.b=i.at(t).color.b,s.at(a).color.a=i.at(t).color.a)}}setOverwriteColorForPartMultiplyColors(t,e){v(\"setOverwriteColorForPartMultiplyColors(partIndex: number, value: boolean) is a deprecated function. Please use setOverrideColorForPartMultiplyColors(partIndex: number, value: boolean).\"),this.setOverrideColorForPartMultiplyColors(t,e)}setOverrideColorForPartMultiplyColors(t,e){this._userPartMultiplyColors.at(t).isOverridden=e,this.setOverrideColorForPartColors(t,e,this._userPartMultiplyColors,this._userMultiplyColors)}setOverwriteColorForPartScreenColors(t,e){v(\"setOverwriteColorForPartScreenColors(partIndex: number, value: boolean) is a deprecated function. Please use setOverrideColorForPartScreenColors(partIndex: number, value: boolean).\"),this.setOverrideColorForPartScreenColors(t,e)}setOverrideColorForPartScreenColors(t,e){this._userPartScreenColors.at(t).isOverridden=e,this.setOverrideColorForPartColors(t,e,this._userPartScreenColors,this._userScreenColors)}getDrawableCulling(t){if(this.getOverrideFlagForModelCullings()||this.getOverrideFlagForDrawableCullings(t))return this._userCullings.at(t).isCulling;const e=this._model.drawables.constantFlags;return!Live2DCubismCore.Utils.hasIsDoubleSidedBit(e[t])}setDrawableCulling(t,e){this._userCullings.at(t).isCulling=e}getOverwriteFlagForModelCullings(){return v(\"getOverwriteFlagForModelCullings() is a deprecated function. Please use getOverrideFlagForModelCullings().\"),this.getOverrideFlagForModelCullings()}getOverrideFlagForModelCullings(){return this._isOverriddenCullings}setOverwriteFlagForModelCullings(t){v(\"setOverwriteFlagForModelCullings(isOverriddenCullings: boolean) is a deprecated function. Please use setOverrideFlagForModelCullings(isOverriddenCullings: boolean).\"),this.setOverrideFlagForModelCullings(t)}setOverrideFlagForModelCullings(t){this._isOverriddenCullings=t}getOverwriteFlagForDrawableCullings(t){return v(\"getOverwriteFlagForDrawableCullings(drawableIndex: number) is a deprecated function. Please use getOverrideFlagForDrawableCullings(drawableIndex: number).\"),this.getOverrideFlagForDrawableCullings(t)}getOverrideFlagForDrawableCullings(t){return this._userCullings.at(t).isOverridden}setOverwriteFlagForDrawableCullings(t,e){v(\"setOverwriteFlagForDrawableCullings(drawableIndex: number, isOverriddenCullings: boolean) is a deprecated function. Please use setOverrideFlagForDrawableCullings(drawableIndex: number, isOverriddenCullings: boolean).\"),this.setOverrideFlagForDrawableCullings(t,e)}setOverrideFlagForDrawableCullings(t,e){this._userCullings.at(t).isOverridden=e}getModelOapcity(){return this._modelOpacity}setModelOapcity(t){this._modelOpacity=t}getModel(){return this._model}getPartIndex(t){let e;const i=this._model.parts.count;for(e=0;e<i;++e)if(t==this._partIds.at(e))return e;return this._notExistPartId.isExist(t)?this._notExistPartId.getValue(t):(e=i+this._notExistPartId.getSize(),this._notExistPartId.setValue(t,e),this._notExistPartOpacities.appendKey(e),e)}getPartId(t){const e=this._model.parts.ids[t];return $.getIdManager().getId(e)}getPartCount(){return this._model.parts.count}getPartParentPartIndices(){return this._model.parts.parentIndices}setPartOpacityByIndex(t,e){this._notExistPartOpacities.isExist(t)?this._notExistPartOpacities.setValue(t,e):(C(0<=t&&t<this.getPartCount()),this._partOpacities[t]=e)}setPartOpacityById(t,e){const i=this.getPartIndex(t);i<0||this.setPartOpacityByIndex(i,e)}getPartOpacityByIndex(t){return this._notExistPartOpacities.isExist(t)?this._notExistPartOpacities.getValue(t):(C(0<=t&&t<this.getPartCount()),this._partOpacities[t])}getPartOpacityById(t){const e=this.getPartIndex(t);return e<0?0:this.getPartOpacityByIndex(e)}getParameterIndex(t){let e;const i=this._model.parameters.count;for(e=0;e<i;++e)if(t==this._parameterIds.at(e))return e;return this._notExistParameterId.isExist(t)?this._notExistParameterId.getValue(t):(e=this._model.parameters.count+this._notExistParameterId.getSize(),this._notExistParameterId.setValue(t,e),this._notExistParameterValues.appendKey(e),e)}getParameterCount(){return this._model.parameters.count}getParameterType(t){return this._model.parameters.types[t]}getParameterMaximumValue(t){return this._model.parameters.maximumValues[t]}getParameterMinimumValue(t){return this._model.parameters.minimumValues[t]}getParameterDefaultValue(t){return this._model.parameters.defaultValues[t]}getParameterId(t){return $.getIdManager().getId(this._model.parameters.ids[t])}getParameterValueByIndex(t){return this._notExistParameterValues.isExist(t)?this._notExistParameterValues.getValue(t):(C(0<=t&&t<this.getParameterCount()),this._parameterValues[t])}getParameterValueById(t){const e=this.getParameterIndex(t);return this.getParameterValueByIndex(e)}setParameterValueByIndex(t,e,i=1){this._notExistParameterValues.isExist(t)?this._notExistParameterValues.setValue(t,1==i?e:this._notExistParameterValues.getValue(t)*(1-i)+e*i):(C(0<=t&&t<this.getParameterCount()),e=this.isRepeat(t)?this.getParameterRepeatValue(t,e):this.getParameterClampValue(t,e),this._parameterValues[t]=1==i?e:this._parameterValues[t]=this._parameterValues[t]*(1-i)+e*i)}setParameterValueById(t,e,i=1){const s=this.getParameterIndex(t);this.setParameterValueByIndex(s,e,i)}addParameterValueByIndex(t,e,i=1){this.setParameterValueByIndex(t,this.getParameterValueByIndex(t)+e*i)}addParameterValueById(t,e,i=1){const s=this.getParameterIndex(t);this.addParameterValueByIndex(s,e,i)}isRepeat(t){if(this._notExistParameterValues.isExist(t))return!1;let e;return C(0<=t&&t<this.getParameterCount()),e=this._isOverriddenParameterRepeat||this._userParameterRepeatDataList.at(t).isOverridden?this._userParameterRepeatDataList.at(t).isParameterRepeated:0!=this._model.parameters.repeats[t],e}getParameterRepeatValue(t,e){if(this._notExistParameterValues.isExist(t))return e;C(0<=t&&t<this.getParameterCount());const i=this._model.parameters.maximumValues[t],s=this._model.parameters.minimumValues[t],r=i-s;if(i<e){const t=Vt.mod(e-i,r);e=Number.isNaN(t)?i:s+t}if(e<s){const t=Vt.mod(s-e,r);e=Number.isNaN(t)?s:i-t}return e}getParameterClampValue(t,e){if(this._notExistParameterValues.isExist(t))return e;C(0<=t&&t<this.getParameterCount());const i=this._model.parameters.maximumValues[t],s=this._model.parameters.minimumValues[t];return Vt.clamp(e,s,i)}getParameterRepeats(t){return 0!=this._model.parameters.repeats[t]}multiplyParameterValueById(t,e,i=1){const s=this.getParameterIndex(t);this.multiplyParameterValueByIndex(s,e,i)}multiplyParameterValueByIndex(t,e,i=1){this.setParameterValueByIndex(t,this.getParameterValueByIndex(t)*(1+(e-1)*i))}getDrawableIndex(t){const e=this._model.drawables.count;for(let i=0;i<e;++i)if(this._drawableIds.at(i)==t)return i;return-1}getDrawableCount(){return this._model.drawables.count}getDrawableId(t){const e=this._model.drawables.ids;return $.getIdManager().getId(e[t])}getDrawableRenderOrders(){return this._model.drawables.renderOrders}getDrawableTextureIndices(t){return this.getDrawableTextureIndex(t)}getDrawableTextureIndex(t){return this._model.drawables.textureIndices[t]}getDrawableDynamicFlagVertexPositionsDidChange(t){const e=this._model.drawables.dynamicFlags;return Live2DCubismCore.Utils.hasVertexPositionsDidChangeBit(e[t])}getDrawableVertexIndexCount(t){return this._model.drawables.indexCounts[t]}getDrawableVertexCount(t){return this._model.drawables.vertexCounts[t]}getDrawableVertices(t){return this.getDrawableVertexPositions(t)}getDrawableVertexIndices(t){return this._model.drawables.indices[t]}getDrawableVertexPositions(t){return this._model.drawables.vertexPositions[t]}getDrawableVertexUvs(t){return this._model.drawables.vertexUvs[t]}getDrawableOpacity(t){return this._model.drawables.opacities[t]}getDrawableMultiplyColor(t){const e=this._model.drawables.multiplyColors,i=4*t,s=new f;return s.r=e[i],s.g=e[i+1],s.b=e[i+2],s.a=e[i+3],s}getDrawableScreenColor(t){const e=this._model.drawables.screenColors,i=4*t,s=new f;return s.r=e[i],s.g=e[i+1],s.b=e[i+2],s.a=e[i+3],s}getDrawableParentPartIndex(t){return this._model.drawables.parentPartIndices[t]}getDrawableBlendMode(t){const e=this._model.drawables.constantFlags;return Live2DCubismCore.Utils.hasBlendAdditiveBit(e[t])?h.CubismBlendMode_Additive:Live2DCubismCore.Utils.hasBlendMultiplicativeBit(e[t])?h.CubismBlendMode_Multiplicative:h.CubismBlendMode_Normal}getDrawableInvertedMaskBit(t){const e=this._model.drawables.constantFlags;return Live2DCubismCore.Utils.hasIsInvertedMaskBit(e[t])}getDrawableMasks(){return this._model.drawables.masks}getDrawableMaskCounts(){return this._model.drawables.maskCounts}isUsingMasking(){for(let t=0;t<this._model.drawables.count;++t)if(!(this._model.drawables.maskCounts[t]<=0))return!0;return!1}getDrawableDynamicFlagIsVisible(t){const e=this._model.drawables.dynamicFlags;return Live2DCubismCore.Utils.hasIsVisibleBit(e[t])}getDrawableDynamicFlagVisibilityDidChange(t){const e=this._model.drawables.dynamicFlags;return Live2DCubismCore.Utils.hasVisibilityDidChangeBit(e[t])}getDrawableDynamicFlagOpacityDidChange(t){const e=this._model.drawables.dynamicFlags;return Live2DCubismCore.Utils.hasOpacityDidChangeBit(e[t])}getDrawableDynamicFlagRenderOrderDidChange(t){const e=this._model.drawables.dynamicFlags;return Live2DCubismCore.Utils.hasRenderOrderDidChangeBit(e[t])}getDrawableDynamicFlagBlendColorDidChange(t){const e=this._model.drawables.dynamicFlags;return Live2DCubismCore.Utils.hasBlendColorDidChangeBit(e[t])}loadParameters(){let t=this._model.parameters.count;const e=this._savedParameters.getSize();t>e&&(t=e);for(let e=0;e<t;++e)this._parameterValues[e]=this._savedParameters.at(e)}initialize(){C(this._model),this._parameterValues=this._model.parameters.values,this._partOpacities=this._model.parts.opacities,this._parameterMaximumValues=this._model.parameters.maximumValues,this._parameterMinimumValues=this._model.parameters.minimumValues;{const t=this._model.parameters.ids,e=this._model.parameters.count;this._parameterIds.prepareCapacity(e),this._userParameterRepeatDataList.prepareCapacity(e);for(let i=0;i<e;++i)this._parameterIds.pushBack($.getIdManager().getId(t[i])),this._userParameterRepeatDataList.pushBack(new Yi(!1,!1))}const t=this._model.parts.count;{const e=this._model.parts.ids;this._partIds.prepareCapacity(t);for(let i=0;i<t;++i)this._partIds.pushBack($.getIdManager().getId(e[i]));this._userPartMultiplyColors.prepareCapacity(t),this._userPartScreenColors.prepareCapacity(t),this._partChildDrawables.prepareCapacity(t)}{const i=this._model.drawables.ids,s=this._model.drawables.count;this._userMultiplyColors.prepareCapacity(s),this._userScreenColors.prepareCapacity(s),this._userCullings.prepareCapacity(s);const r=new qi(!1,!1);for(let i=0;i<t;++i){const t=new f(1,1,1,1),r=new f(0,0,0,1),a=new Hi(!1,t),n=new Hi(!1,r);this._userPartMultiplyColors.pushBack(a),this._userPartScreenColors.pushBack(n),this._partChildDrawables.pushBack(new e),this._partChildDrawables.at(i).prepareCapacity(s)}for(let t=0;t<s;++t){const e=new f(1,1,1,1),s=new f(0,0,0,1),a=new ji(!1,e),n=new ji(!1,s);this._drawableIds.pushBack($.getIdManager().getId(i[t])),this._userMultiplyColors.pushBack(a),this._userScreenColors.pushBack(n),this._userCullings.pushBack(r);const o=this.getDrawableParentPartIndex(t);o>=0&&this._partChildDrawables.at(o).pushBack(t)}}}constructor(t){this._model=t,this._parameterValues=null,this._parameterMaximumValues=null,this._parameterMinimumValues=null,this._partOpacities=null,this._savedParameters=new e,this._parameterIds=new e,this._drawableIds=new e,this._partIds=new e,this._isOverriddenParameterRepeat=!0,this._isOverriddenModelMultiplyColors=!1,this._isOverriddenModelScreenColors=!1,this._isOverriddenCullings=!1,this._modelOpacity=1,this._userParameterRepeatDataList=new e,this._userMultiplyColors=new e,this._userScreenColors=new e,this._userCullings=new e,this._userPartMultiplyColors=new e,this._userPartScreenColors=new e,this._partChildDrawables=new e,this._notExistPartId=new I,this._notExistParameterId=new I,this._notExistParameterValues=new I,this._notExistPartOpacities=new I}release(){this._model.release(),this._model=null}}(Gi||(Gi={})).CubismModel=Wi;class Ji{static create(t,e){let i=null;if(e){if(!this.hasMocConsistency(t))return b(\"Inconsistent MOC3.\"),i}const s=Live2DCubismCore.Moc.fromArrayBuffer(t);return s&&(i=new Ji(s),i._mocVersion=Live2DCubismCore.Version.csmGetMocVersion(s,t)),i}static delete(t){t._moc._release(),t._moc=null,t=null}createModel(){let t=null;const e=Live2DCubismCore.Model.fromMoc(this._moc);return e&&(t=new Wi(e),t.initialize(),++this._modelCount),t}deleteModel(t){null!=t&&(t.release(),t=null,--this._modelCount)}constructor(t){this._moc=t,this._modelCount=0,this._mocVersion=0}release(){C(0==this._modelCount),this._moc._release(),this._moc=null}getLatestMocVersion(){return Live2DCubismCore.Version.csmGetLatestMocVersion()}getMocVersion(){return this._mocVersion}static hasMocConsistency(t){return 1===Live2DCubismCore.Moc.prototype.hasMocConsistency(t)}}(Xi||(Xi={})).CubismMoc=Ji;const $i=\"Meta\",Zi=\"UserData\";class Ki{constructor(t,e){this._json=L.create(t,e)}release(){L.delete(this._json)}getUserDataCount(){return this._json.getRoot().getValueByString($i).getValueByString(\"UserDataCount\").toInt()}getTotalUserDataSize(){return this._json.getRoot().getValueByString($i).getValueByString(\"TotalUserDataSize\").toInt()}getUserDataTargetType(t){return this._json.getRoot().getValueByString(Zi).getValueByIndex(t).getValueByString(\"Target\").getRawString()}getUserDataId(t){return $.getIdManager().getId(this._json.getRoot().getValueByString(Zi).getValueByIndex(t).getValueByString(\"Id\").getRawString())}getUserDataValue(t){return this._json.getRoot().getValueByString(Zi).getValueByIndex(t).getValueByString(\"Value\").getRawString()}}var Qi;(Qi||(Qi={})).CubismModelUserDataJson=Ki;class ts{}class es{static create(t,e){const i=new es;return i.parseUserData(t,e),i}static delete(t){null!=t&&(t.release(),t=null)}getArtMeshUserDatas(){return this._artMeshUserDataNode}parseUserData(t,e){let i=new Ki(t,e);if(!i)return i.release(),void(i=void 0);const s=$.getIdManager().getId(\"ArtMesh\"),r=i.getUserDataCount();for(let t=0;t<r;t++){const e=new ts;e.targetId=i.getUserDataId(t),e.targetType=$.getIdManager().getId(i.getUserDataTargetType(t)),e.value=new g(i.getUserDataValue(t)),this._userDataNodes.pushBack(e),e.targetType==s&&this._artMeshUserDataNode.pushBack(e)}i.release(),i=void 0}constructor(){this._userDataNodes=new e,this._artMeshUserDataNode=new e}release(){for(let t=0;t<this._userDataNodes.getSize();++t)this._userDataNodes.set(t,null);this._userDataNodes=null}}var is,ss;!function(t){t.CubismModelUserData=es,t.CubismModelUserDataNode=ts}(is||(is={}));class rs{isInitialized(){return this._initialized}setInitialized(t){this._initialized=t}isUpdating(){return this._updating}setUpdating(t){this._updating=t}setDragging(t,e){this._dragManager.set(t,e)}setAcceleration(t,e,i){this._accelerationX=t,this._accelerationY=e,this._accelerationZ=i}getModelMatrix(){return this._modelMatrix}setOpacity(t){this._opacity=t}getOpacity(){return this._opacity}loadModel(t,e=!1){this._moc=Ji.create(t,e),null!=this._moc?(this._model=this._moc.createModel(),null!=this._model?(this._model.saveParameters(),this._modelMatrix=new Ft(this._model.getCanvasWidth(),this._model.getCanvasHeight())):b(\"Failed to CreateModel().\")):b(\"Failed to CubismMoc.create().\")}loadMotion(t,e,i,s,r,a,n,o,l=!1){if(null==t||0==e)return b(\"Failed to loadMotion().\"),null;const h=Be.create(t,e,s,r,l);if(null==h)return b(\"Failed to create motion from buffer in LoadMotion()\"),null;if(a){const t=a.getMotionFadeInTimeValue(n,o);t>=0&&h.setFadeInTime(t);const e=a.getMotionFadeOutTimeValue(n,o);e>=0&&h.setFadeOutTime(e)}return h}loadExpression(t,e,i){return null==t||0==e?(b(\"Failed to loadExpression().\"),null):Ot.create(t,e)}loadPose(t,e){null!=t&&0!=e?this._pose=Mt.create(t,e):b(\"Failed to loadPose().\")}loadUserData(t,e){null!=t&&0!=e?this._modelUserData=es.create(t,e):b(\"Failed to loadUserData().\")}loadPhysics(t,e){null!=t&&0!=e?this._physics=ii.create(t,e):b(\"Failed to loadPhysics().\")}isHit(t,e,i){const s=this._model.getDrawableIndex(t);if(s<0)return!1;const r=this._model.getDrawableVertexCount(s),a=this._model.getDrawableVertices(s);let n=a[0],o=a[0],l=a[1],h=a[1];for(let t=1;t<r;++t){const e=a[W.vertexOffset+t*W.vertexStep],i=a[W.vertexOffset+t*W.vertexStep+1];e<n&&(n=e),e>o&&(o=e),i<l&&(l=i),i>h&&(h=i)}const u=this._modelMatrix.invertTransformX(e),g=this._modelMatrix.invertTransformY(i);return n<=u&&u<=o&&l<=g&&g<=h}getModel(){return this._model}getRenderer(){return this._renderer}createRenderer(t=1){this._renderer&&this.deleteRenderer(),this._renderer=new zi,this._renderer.initialize(this._model,t)}deleteRenderer(){null!=this._renderer&&(this._renderer.release(),this._renderer=null)}motionEventFired(t){M(\"{0}\",t.s)}static cubismDefaultMotionEventCallback(t,e,i){null!=i&&i.motionEventFired(e)}constructor(){this._moc=null,this._model=null,this._motionManager=null,this._expressionManager=null,this._eyeBlink=null,this._breath=null,this._modelMatrix=null,this._pose=null,this._dragManager=null,this._physics=null,this._modelUserData=null,this._initialized=!1,this._updating=!1,this._opacity=1,this._lipsync=!0,this._lastLipSyncValue=0,this._dragX=0,this._dragY=0,this._accelerationX=0,this._accelerationY=0,this._accelerationZ=0,this._mocConsistency=!1,this._debugMode=!1,this._renderer=null,this._motionManager=new we,this._motionManager.setEventCallback(rs.cubismDefaultMotionEventCallback,this),this._expressionManager=new Zt,this._dragManager=new Et}release(){null!=this._motionManager&&(this._motionManager.release(),this._motionManager=null),null!=this._expressionManager&&(this._expressionManager.release(),this._expressionManager=null),null!=this._moc&&(this._moc.deleteModel(this._model),this._moc.release(),this._moc=null),this._modelMatrix=null,Mt.delete(this._pose),St.delete(this._eyeBlink),ft.delete(this._breath),this._dragManager=null,ii.delete(this._physics),es.delete(this._modelUserData),this.deleteRenderer()}}(ss||(ss={})).CubismUserModel=rs;let as=null;class ns{static getInstance(){return null==as&&(as=new ns),as}static releaseInstance(){null!=as&&(as=void 0),as=null}update(t){let e,i;if(null==this._pcmData||this._sampleOffset>=this._wavFileInfo._samplesPerChannel)return this._lastRms=0,!1;this._userTimeSeconds+=t,e=Math.floor(this._userTimeSeconds*this._wavFileInfo._samplingRate),e>this._wavFileInfo._samplesPerChannel&&(e=this._wavFileInfo._samplesPerChannel),i=0;for(let t=0;t<this._wavFileInfo._numberOfChannels;t++)for(let s=this._sampleOffset;s<e;s++){const e=this._pcmData[t][s];i+=e*e}return i=Math.sqrt(i/(this._wavFileInfo._numberOfChannels*(e-this._sampleOffset))),this._lastRms=i,this._sampleOffset=e,!0}start(t){this._sampleOffset=0,this._userTimeSeconds=0,this._lastRms=0,this.loadWavFile(t)}getRms(){return this._lastRms}loadWavFile(t){return new Promise((e=>{let i=!1;null!=this._pcmData&&this.releasePcmData();(async()=>{if(this._byteReader._fileByte=await(async()=>fetch(t).then((t=>t.arrayBuffer())))(),this._byteReader._fileDataView=new DataView(this._byteReader._fileByte),this._byteReader._fileSize=this._byteReader._fileByte.byteLength,this._byteReader._readOffset=0,null==this._byteReader._fileByte||this._byteReader._fileSize<4)e(!1);else{this._wavFileInfo._fileName=t;try{if(!this._byteReader.getCheckSignature(\"RIFF\"))throw i=!1,new Error('Cannot find Signeture \"RIFF\".');if(this._byteReader.get32LittleEndian(),!this._byteReader.getCheckSignature(\"WAVE\"))throw i=!1,new Error('Cannot find Signeture \"WAVE\".');if(!this._byteReader.getCheckSignature(\"fmt \"))throw i=!1,new Error('Cannot find Signeture \"fmt\".');const t=this._byteReader.get32LittleEndian();if(1!=this._byteReader.get16LittleEndian())throw i=!1,new Error(\"File is not linear PCM.\");for(this._wavFileInfo._numberOfChannels=this._byteReader.get16LittleEndian(),this._wavFileInfo._samplingRate=this._byteReader.get32LittleEndian(),this._byteReader.get32LittleEndian(),this._byteReader.get16LittleEndian(),this._wavFileInfo._bitsPerSample=this._byteReader.get16LittleEndian(),t>16&&(this._byteReader._readOffset+=t-16);!this._byteReader.getCheckSignature(\"data\")&&this._byteReader._readOffset<this._byteReader._fileSize;)this._byteReader._readOffset+=this._byteReader.get32LittleEndian()+4;if(this._byteReader._readOffset>=this._byteReader._fileSize)throw i=!1,new Error('Cannot find \"data\" Chunk.');{const t=this._byteReader.get32LittleEndian();this._wavFileInfo._samplesPerChannel=8*t/(this._wavFileInfo._bitsPerSample*this._wavFileInfo._numberOfChannels)}this._pcmData=new Array(this._wavFileInfo._numberOfChannels);for(let t=0;t<this._wavFileInfo._numberOfChannels;t++)this._pcmData[t]=new Float32Array(this._wavFileInfo._samplesPerChannel);for(let t=0;t<this._wavFileInfo._samplesPerChannel;t++)for(let e=0;e<this._wavFileInfo._numberOfChannels;e++)this._pcmData[e][t]=this.getPcmSample();i=!0,e(i)}catch(t){console.log(t)}}})().then((()=>{e(i)}))}))}getPcmSample(){let t;switch(this._wavFileInfo._bitsPerSample){case 8:t=this._byteReader.get8()-128,t<<=24;break;case 16:t=this._byteReader.get16LittleEndian()<<16;break;case 24:t=this._byteReader.get24LittleEndian()<<8;break;default:t=0}return t/2147483647}getPcmDataChannel(t){return this._pcmData&&t<this._pcmData.length?Float32Array.from(this._pcmData[t]):null}getWavSamplingRate(){return!this._wavFileInfo||this._wavFileInfo._samplingRate<1?null:this._wavFileInfo._samplingRate}releasePcmData(){for(let t=0;t<this._wavFileInfo._numberOfChannels;t++)this._pcmData[t]=null;delete this._pcmData,this._pcmData=null}constructor(){this.loadFiletoBytes=(t,e)=>{this._byteReader._fileByte=t,this._byteReader._fileDataView=new DataView(this._byteReader._fileByte),this._byteReader._fileSize=e},this._pcmData=null,this._userTimeSeconds=0,this._lastRms=0,this._sampleOffset=0,this._wavFileInfo=new os,this._byteReader=new ls}}class os{constructor(){this._fileName=\"\",this._numberOfChannels=0,this._bitsPerSample=0,this._samplingRate=0,this._samplesPerChannel=0}}class ls{constructor(){this._fileByte=null,this._fileDataView=null,this._fileSize=0,this._readOffset=0}get8(){const t=this._fileDataView.getUint8(this._readOffset);return this._readOffset++,t}get16LittleEndian(){const t=this._fileDataView.getUint8(this._readOffset+1)<<8|this._fileDataView.getUint8(this._readOffset);return this._readOffset+=2,t}get24LittleEndian(){const t=this._fileDataView.getUint8(this._readOffset+2)<<16|this._fileDataView.getUint8(this._readOffset+1)<<8|this._fileDataView.getUint8(this._readOffset);return this._readOffset+=3,t}get32LittleEndian(){const t=this._fileDataView.getUint8(this._readOffset+3)<<24|this._fileDataView.getUint8(this._readOffset+2)<<16|this._fileDataView.getUint8(this._readOffset+1)<<8|this._fileDataView.getUint8(this._readOffset);return this._readOffset+=4,t}getCheckSignature(t){const e=new Uint8Array(4),i=(new TextEncoder).encode(t);if(4!=t.length)return!1;for(let t=0;t<4;t++)e[t]=this.get8();return e[0]==i[0]&&e[1]==i[1]&&e[2]==i[2]&&e[3]==i[3]}}var hs,us;!function(t){t[t.LoadAssets=0]=\"LoadAssets\",t[t.LoadModel=1]=\"LoadModel\",t[t.WaitLoadModel=2]=\"WaitLoadModel\",t[t.LoadExpression=3]=\"LoadExpression\",t[t.WaitLoadExpression=4]=\"WaitLoadExpression\",t[t.LoadPhysics=5]=\"LoadPhysics\",t[t.WaitLoadPhysics=6]=\"WaitLoadPhysics\",t[t.LoadPose=7]=\"LoadPose\",t[t.WaitLoadPose=8]=\"WaitLoadPose\",t[t.SetupEyeBlink=9]=\"SetupEyeBlink\",t[t.SetupBreath=10]=\"SetupBreath\",t[t.LoadUserData=11]=\"LoadUserData\",t[t.WaitLoadUserData=12]=\"WaitLoadUserData\",t[t.SetupEyeBlinkIds=13]=\"SetupEyeBlinkIds\",t[t.SetupLipSyncIds=14]=\"SetupLipSyncIds\",t[t.SetupLayout=15]=\"SetupLayout\",t[t.LoadMotion=16]=\"LoadMotion\",t[t.WaitLoadMotion=17]=\"WaitLoadMotion\",t[t.CompleteInitialize=18]=\"CompleteInitialize\",t[t.CompleteSetupModel=19]=\"CompleteSetupModel\",t[t.LoadTexture=20]=\"LoadTexture\",t[t.WaitLoadTexture=21]=\"WaitLoadTexture\",t[t.CompleteSetup=22]=\"CompleteSetup\"}(hs||(hs={}));class gs extends rs{loadAssets(t,e){this._modelHomeDir=t,fetch(`${this._modelHomeDir}${e}`).then((t=>t.arrayBuffer())).then((t=>{const e=new pt(t,t.byteLength);this._state=hs.LoadModel,this.setupModel(e)})).catch((t=>{b(`Failed to load file ${this._modelHomeDir}${e}`)}))}setupModel(t){if(this._updating=!0,this._initialized=!1,this._modelSetting=t,\"\"!=this._modelSetting.getModelFileName()){const t=this._modelSetting.getModelFileName();fetch(`${this._modelHomeDir}${t}`).then((e=>e.ok?e.arrayBuffer():e.status>=400?(b(`Failed to load file ${this._modelHomeDir}${t}`),new ArrayBuffer(0)):void 0)).then((t=>{this.loadModel(t,this._mocConsistency),this._state=hs.LoadExpression,i()})),this._state=hs.WaitLoadModel}else at.printMessage(\"Model data does not exist.\");const i=()=>{if(this._modelSetting.getExpressionCount()>0){const t=this._modelSetting.getExpressionCount();for(let e=0;e<t;e++){const i=this._modelSetting.getExpressionName(e),r=this._modelSetting.getExpressionFileName(e);fetch(`${this._modelHomeDir}${r}`).then((t=>t.ok?t.arrayBuffer():t.status>=400?(b(`Failed to load file ${this._modelHomeDir}${r}`),new ArrayBuffer(0)):void 0)).then((e=>{const r=this.loadExpression(e,e.byteLength,i);null!=this._expressions.getValue(i)&&(Lt.delete(this._expressions.getValue(i)),this._expressions.setValue(i,null)),this._expressions.setValue(i,r),this._expressionCount++,this._expressionCount>=t&&(this._state=hs.LoadPhysics,s())}))}this._state=hs.WaitLoadExpression}else this._state=hs.LoadPhysics,s()},s=()=>{if(\"\"!=this._modelSetting.getPhysicsFileName()){const t=this._modelSetting.getPhysicsFileName();fetch(`${this._modelHomeDir}${t}`).then((e=>e.ok?e.arrayBuffer():e.status>=400?(b(`Failed to load file ${this._modelHomeDir}${t}`),new ArrayBuffer(0)):void 0)).then((t=>{this.loadPhysics(t,t.byteLength),this._state=hs.LoadPose,r()})),this._state=hs.WaitLoadPhysics}else this._state=hs.LoadPose,r()},r=()=>{if(\"\"!=this._modelSetting.getPoseFileName()){const t=this._modelSetting.getPoseFileName();fetch(`${this._modelHomeDir}${t}`).then((e=>e.ok?e.arrayBuffer():e.status>=400?(b(`Failed to load file ${this._modelHomeDir}${t}`),new ArrayBuffer(0)):void 0)).then((t=>{this.loadPose(t,t.byteLength),this._state=hs.SetupEyeBlink,a()})),this._state=hs.WaitLoadPose}else this._state=hs.SetupEyeBlink,a()},a=()=>{this._modelSetting.getEyeBlinkParameterCount()>0&&(this._eyeBlink=St.create(this._modelSetting),this._state=hs.SetupBreath),n()},n=()=>{this._breath=ft.create();const t=new e;t.pushBack(new yt(this._idParamAngleX,0,15,6.5345,.5)),t.pushBack(new yt(this._idParamAngleY,0,8,3.5345,.5)),t.pushBack(new yt(this._idParamAngleZ,0,10,5.5345,.5)),t.pushBack(new yt(this._idParamBodyAngleX,0,4,15.5345,.5)),t.pushBack(new yt($.getIdManager().getId(ot.ParamBreath),.5,.5,3.2345,1)),this._breath.setParameters(t),this._state=hs.LoadUserData,o()},o=()=>{if(\"\"!=this._modelSetting.getUserDataFile()){const t=this._modelSetting.getUserDataFile();fetch(`${this._modelHomeDir}${t}`).then((e=>e.ok?e.arrayBuffer():e.status>=400?(b(`Failed to load file ${this._modelHomeDir}${t}`),new ArrayBuffer(0)):void 0)).then((t=>{this.loadUserData(t,t.byteLength),this._state=hs.SetupEyeBlinkIds,l()})),this._state=hs.WaitLoadUserData}else this._state=hs.SetupEyeBlinkIds,l()},l=()=>{const t=this._modelSetting.getEyeBlinkParameterCount();for(let e=0;e<t;++e)this._eyeBlinkIds.pushBack(this._modelSetting.getEyeBlinkParameterId(e));this._state=hs.SetupLipSyncIds,h()},h=()=>{const t=this._modelSetting.getLipSyncParameterCount();for(let e=0;e<t;++e)this._lipSyncIds.pushBack(this._modelSetting.getLipSyncParameterId(e));this._state=hs.SetupLayout,u()},u=()=>{const t=new I;null!=this._modelSetting&&null!=this._modelMatrix?(this._modelSetting.getLayoutMap(t),this._modelMatrix.setupFromLayout(t),this._state=hs.LoadMotion,g()):b(\"Failed to setupLayout().\")},g=()=>{this._state=hs.WaitLoadMotion,this._model.saveParameters(),this._allMotionCount=0,this._motionCount=0;const t=[],e=this._modelSetting.getMotionGroupCount();for(let i=0;i<e;i++)t[i]=this._modelSetting.getMotionGroupName(i),this._allMotionCount+=this._modelSetting.getMotionCount(t[i]);for(let i=0;i<e;i++)this.preLoadMotionGroup(t[i]);0==e&&(this._state=hs.LoadTexture,this._motionManager.stopAllMotions(),this._updating=!1,this._initialized=!0,this.createRenderer(),this.setupTextures(),this.getRenderer().startUp(this._subdelegate.getGlManager().getGl()))}}setupTextures(){const t=!0;if(this._state==hs.LoadTexture){const e=this._modelSetting.getTextureCount();for(let i=0;i<e;i++){if(\"\"==this._modelSetting.getTextureFileName(i)){console.log(\"getTextureFileName null\");continue}let s=this._modelSetting.getTextureFileName(i);s=this._modelHomeDir+s;const r=t=>{this.getRenderer().bindTexture(i,t.id),this._textureCount++,this._textureCount>=e&&(this._state=hs.CompleteSetup)};this._subdelegate.getTextureManager().createTextureFromPngFile(s,t,r),this.getRenderer().setIsPremultipliedAlpha(t)}this._state=hs.WaitLoadTexture}}reloadRenderer(){this.deleteRenderer(),this.createRenderer(),this.setupTextures()}update(){if(this._state!=hs.CompleteSetup)return;const t=at.getDeltaTime();this._userTimeSeconds+=t,this._dragManager.update(t),this._dragX=this._dragManager.getX(),this._dragY=this._dragManager.getY();let e=!1;if(this._model.loadParameters(),this._motionManager.isFinished()?this.startRandomMotion(\"Idle\",1):e=this._motionManager.updateMotion(this._model,t),this._model.saveParameters(),e||null!=this._eyeBlink&&this._eyeBlink.updateParameters(this._model,t),null!=this._expressionManager&&this._expressionManager.updateMotion(this._model,t),this._model.addParameterValueById(this._idParamAngleX,30*this._dragX),this._model.addParameterValueById(this._idParamAngleY,30*this._dragY),this._model.addParameterValueById(this._idParamAngleZ,this._dragX*this._dragY*-30),this._model.addParameterValueById(this._idParamBodyAngleX,10*this._dragX),this._model.addParameterValueById(this._idParamEyeBallX,this._dragX),this._model.addParameterValueById(this._idParamEyeBallY,this._dragY),null!=this._breath&&this._breath.updateParameters(this._model,t),null!=this._physics&&this._physics.evaluate(this._model,t),this._lipsync){let e=0;this._wavFileHandler.update(t),e=this._wavFileHandler.getRms();for(let t=0;t<this._lipSyncIds.getSize();++t)this._model.addParameterValueById(this._lipSyncIds.at(t),e,.8)}null!=this._pose&&this._pose.updateParameters(this._model,t),this._model.update()}startMotion(t,e,i,s,r){if(3==i)this._motionManager.setReservePriority(i);else if(!this._motionManager.reserveMotion(i))return this._debugMode&&at.printMessage(\"[APP]can't start motion.\"),Yt;const a=this._modelSetting.getMotionFileName(t,e),n=`${t}_${e}`;let o=this._motions.getValue(n),l=!1;if(null==o){if(fetch(`${this._modelHomeDir}${a}`).then((t=>t.ok?t.arrayBuffer():t.status>=400?(b(`Failed to load file ${this._modelHomeDir}${a}`),new ArrayBuffer(0)):void 0)).then((i=>{o=this.loadMotion(i,i.byteLength,null,s,r,this._modelSetting,t,e,this._motionConsistency)})),!o)return b(\"Can't start motion {0} .\",a),this._motionManager.setReservePriority(0),Yt;o.setEffectIds(this._eyeBlinkIds,this._lipSyncIds),l=!0}else o.setBeganMotionHandler(r),o.setFinishedMotionHandler(s);const h=this._modelSetting.getMotionSoundFileName(t,e);if(0!=h.localeCompare(\"\")){let t=h;t=this._modelHomeDir+t,this._wavFileHandler.start(t)}return this._debugMode&&at.printMessage(`[APP]start motion: [${t}_${e}]`),this._motionManager.startMotionPriority(o,l,i)}startRandomMotion(t,e,i,s){if(0==this._modelSetting.getMotionCount(t))return Yt;const r=Math.floor(Math.random()*this._modelSetting.getMotionCount(t));return this.startMotion(t,r,e,i,s)}setExpression(t){const e=this._expressions.getValue(t);this._debugMode&&at.printMessage(`[APP]expression: [${t}]`),null!=e?this._expressionManager.startMotion(e,!1):this._debugMode&&at.printMessage(`[APP]expression[${t}] is null`)}setRandomExpression(){if(0==this._expressions.getSize())return;const t=Math.floor(Math.random()*this._expressions.getSize());for(let e=0;e<this._expressions.getSize();e++)if(e==t){const t=this._expressions._keyValues[e].first;return void this.setExpression(t)}}motionEventFired(t){M(\"{0} is fired on LAppModel!!\",t.s)}hitTest(t,e,i){if(this._opacity<1)return!1;const s=this._modelSetting.getHitAreasCount();for(let r=0;r<s;r++)if(this._modelSetting.getHitAreaName(r)==t){const t=this._modelSetting.getHitAreaId(r);return this.isHit(t,e,i)}return!1}preLoadMotionGroup(t){for(let e=0;e<this._modelSetting.getMotionCount(t);e++){const i=this._modelSetting.getMotionFileName(t,e),s=`${t}_${e}`;this._debugMode&&at.printMessage(`[APP]load motion: ${i} => [${s}]`),fetch(`${this._modelHomeDir}${i}`).then((t=>t.ok?t.arrayBuffer():t.status>=400?(b(`Failed to load file ${this._modelHomeDir}${i}`),new ArrayBuffer(0)):void 0)).then((i=>{const r=this.loadMotion(i,i.byteLength,s,null,null,this._modelSetting,t,e,this._motionConsistency);null!=r?(r.setEffectIds(this._eyeBlinkIds,this._lipSyncIds),null!=this._motions.getValue(s)&&Lt.delete(this._motions.getValue(s)),this._motions.setValue(s,r),this._motionCount++):this._allMotionCount--,this._motionCount>=this._allMotionCount&&(this._state=hs.LoadTexture,this._motionManager.stopAllMotions(),this._updating=!1,this._initialized=!0,this.createRenderer(),this.setupTextures(),this.getRenderer().startUp(this._subdelegate.getGlManager().getGl()))}))}}releaseMotions(){this._motions.clear()}releaseExpressions(){this._expressions.clear()}doDraw(){if(null==this._model)return;const t=this._subdelegate.getCanvas(),e=[0,0,t.width,t.height];this.getRenderer().setRenderState(this._subdelegate.getFrameBuffer(),e),this.getRenderer().drawModel()}draw(t){null!=this._model&&this._state==hs.CompleteSetup&&(t.multiplyByMatrix(this._modelMatrix),this.getRenderer().setMvpMatrix(t),this.doDraw())}async hasMocConsistencyFromFile(){if(C(this._modelSetting.getModelFileName().localeCompare(\"\")),\"\"!=this._modelSetting.getModelFileName()){const t=this._modelSetting.getModelFileName(),e=await fetch(`${this._modelHomeDir}${t}`),i=await e.arrayBuffer();return this._consistency=Ji.hasMocConsistency(i),this._consistency?M(\"Consistent MOC3.\"):M(\"Inconsistent MOC3.\"),this._consistency}at.printMessage(\"Model data does not exist.\")}setSubdelegate(t){this._subdelegate=t}constructor(){super(),this._modelSetting=null,this._modelHomeDir=null,this._userTimeSeconds=0,this._eyeBlinkIds=new e,this._lipSyncIds=new e,this._motions=new I,this._expressions=new I,this._hitArea=new e,this._userArea=new e,this._idParamAngleX=$.getIdManager().getId(ot.ParamAngleX),this._idParamAngleY=$.getIdManager().getId(ot.ParamAngleY),this._idParamAngleZ=$.getIdManager().getId(ot.ParamAngleZ),this._idParamEyeBallX=$.getIdManager().getId(ot.ParamEyeBallX),this._idParamEyeBallY=$.getIdManager().getId(ot.ParamEyeBallY),this._idParamBodyAngleX=$.getIdManager().getId(ot.ParamBodyAngleX),this._mocConsistency=!0,this._motionConsistency=!0,this._state=hs.LoadAssets,this._expressionCount=0,this._textureCount=0,this._motionCount=0,this._allMotionCount=0,this._wavFileHandler=new ns,this._consistency=!1}}class ds{releaseAllModel(){this._models.clear()}onDrag(t,e){const i=this._models.at(0);i&&i.setDragging(t,e)}onTap(t,e){const i=this._models.at(0);i.hitTest(\"Head\",t,e)?i.setRandomExpression():i.hitTest(st,t,e)&&i.startRandomMotion(\"TapBody\",2,this.finishedMotion,this.beganMotion)}onUpdate(){const{width:t,height:e}=this._subdelegate.getCanvas(),i=new c,s=this._models.at(0);s.getModel()&&(s.getModel().getCanvasWidth()>1&&t<e?(s.getModelMatrix().setWidth(2),i.scale(1,t/e)):i.scale(e/t,1),null!=this._viewMatrix&&i.multiplyByMatrix(this._viewMatrix)),s.update(),s.draw(i)}nextScene(){const t=(this._sceneIndex+1)%it;this.changeScene(t)}changeScene(t){this._sceneIndex=t;const e=tt+et[t]+\"/\";let i=et[t];i+=\".model3.json\",this.releaseAllModel();const s=new gs;s.setSubdelegate(this._subdelegate),s.loadAssets(e,i),this._models.pushBack(s)}setViewMatrix(t){for(let e=0;e<16;e++)this._viewMatrix.getArray()[e]=t.getArray()[e]}addModel(t=0){this._sceneIndex=t,this.changeScene(this._sceneIndex)}constructor(){this.beganMotion=t=>{at.printMessage(\"Motion Began:\"),console.log(t)},this.finishedMotion=t=>{at.printMessage(\"Motion Finished:\"),console.log(t)},this._subdelegate=null,this._viewMatrix=new c,this._models=new e,this._sceneIndex=0}release(){}initialize(t){this._subdelegate=t,this.changeScene(this._sceneIndex)}}class _s{constructor(){this._textures=new e}release(){for(let t=this._textures.begin();t.notEqual(this._textures.end());t.preIncrement())this._glManager.getGl().deleteTexture(t.ptr().id);this._textures=null}createTextureFromPngFile(t,e,i){for(let s=this._textures.begin();s.notEqual(this._textures.end());s.preIncrement())if(s.ptr().fileName==t&&s.ptr().usePremultply==e)return s.ptr().img=new Image,s.ptr().img.addEventListener(\"load\",(()=>i(s.ptr())),{passive:!0}),void(s.ptr().img.src=t);const s=new Image;s.addEventListener(\"load\",(()=>{const r=this._glManager.getGl().createTexture();this._glManager.getGl().bindTexture(this._glManager.getGl().TEXTURE_2D,r),this._glManager.getGl().texParameteri(this._glManager.getGl().TEXTURE_2D,this._glManager.getGl().TEXTURE_MIN_FILTER,this._glManager.getGl().LINEAR_MIPMAP_LINEAR),this._glManager.getGl().texParameteri(this._glManager.getGl().TEXTURE_2D,this._glManager.getGl().TEXTURE_MAG_FILTER,this._glManager.getGl().LINEAR),e&&this._glManager.getGl().pixelStorei(this._glManager.getGl().UNPACK_PREMULTIPLY_ALPHA_WEBGL,1),this._glManager.getGl().texImage2D(this._glManager.getGl().TEXTURE_2D,0,this._glManager.getGl().RGBA,this._glManager.getGl().RGBA,this._glManager.getGl().UNSIGNED_BYTE,s),this._glManager.getGl().generateMipmap(this._glManager.getGl().TEXTURE_2D),this._glManager.getGl().bindTexture(this._glManager.getGl().TEXTURE_2D,null);const a=new cs;null!=a&&(a.fileName=t,a.width=s.width,a.height=s.height,a.id=r,a.img=s,a.usePremultply=e,null!=this._textures&&this._textures.pushBack(a)),i(a)}),{passive:!0}),s.src=t}releaseTextures(){for(let t=0;t<this._textures.getSize();t++)this._glManager.getGl().deleteTexture(this._textures.at(t).id),this._textures.set(t,null);this._textures.clear()}releaseTextureByTexture(t){for(let e=0;e<this._textures.getSize();e++)if(this._textures.at(e).id==t){this._glManager.getGl().deleteTexture(this._textures.at(e).id),this._textures.set(e,null),this._textures.remove(e);break}}releaseTextureByFilePath(t){for(let e=0;e<this._textures.getSize();e++)if(this._textures.at(e).fileName==t){this._glManager.getGl().deleteTexture(this._textures.at(e).id),this._textures.set(e,null),this._textures.remove(e);break}}setGlManager(t){this._glManager=t}}class cs{constructor(){this.id=null,this.width=0,this.height=0}}class ms extends c{constructor(){super(),this._screenLeft=0,this._screenRight=0,this._screenTop=0,this._screenBottom=0,this._maxLeft=0,this._maxRight=0,this._maxTop=0,this._maxBottom=0,this._maxScale=0,this._minScale=0}adjustTranslate(t,e){this._tr[0]*this._maxLeft+(this._tr[12]+t)>this._screenLeft&&(t=this._screenLeft-this._tr[0]*this._maxLeft-this._tr[12]),this._tr[0]*this._maxRight+(this._tr[12]+t)<this._screenRight&&(t=this._screenRight-this._tr[0]*this._maxRight-this._tr[12]),this._tr[5]*this._maxTop+(this._tr[13]+e)<this._screenTop&&(e=this._screenTop-this._tr[5]*this._maxTop-this._tr[13]),this._tr[5]*this._maxBottom+(this._tr[13]+e)>this._screenBottom&&(e=this._screenBottom-this._tr[5]*this._maxBottom-this._tr[13]);const i=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,t,e,0,1]);c.multiply(i,this._tr,this._tr)}adjustScale(t,e,i){const s=this.getMaxScale(),r=this.getMinScale(),a=i*this._tr[0];a<r?this._tr[0]>0&&(i=r/this._tr[0]):a>s&&this._tr[0]>0&&(i=s/this._tr[0]);const n=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,t,e,0,1]),o=new Float32Array([i,0,0,0,0,i,0,0,0,0,1,0,0,0,0,1]),l=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,-t,-e,0,1]);c.multiply(l,this._tr,this._tr),c.multiply(o,this._tr,this._tr),c.multiply(n,this._tr,this._tr)}setScreenRect(t,e,i,s){this._screenLeft=t,this._screenRight=e,this._screenBottom=i,this._screenTop=s}setMaxScreenRect(t,e,i,s){this._maxLeft=t,this._maxRight=e,this._maxTop=s,this._maxBottom=i}setMaxScale(t){this._maxScale=t}setMinScale(t){this._minScale=t}getMaxScale(){return this._maxScale}getMinScale(){return this._minScale}isMaxScale(){return this.getScaleX()>=this._maxScale}isMinScale(){return this.getScaleX()<=this._minScale}getScreenLeft(){return this._screenLeft}getScreenRight(){return this._screenRight}getScreenBottom(){return this._screenBottom}getScreenTop(){return this._screenTop}getMaxLeft(){return this._maxLeft}getMaxRight(){return this._maxRight}getMaxBottom(){return this._maxBottom}getMaxTop(){return this._maxTop}}!function(t){t.CubismViewMatrix=ms}(us||(us={}));class ps{constructor(t,e,i,s,r){this._rect=new fs,this._rect.left=t-.5*i,this._rect.right=t+.5*i,this._rect.up=e+.5*s,this._rect.down=e-.5*s,this._texture=r,this._vertexBuffer=null,this._uvBuffer=null,this._indexBuffer=null,this._positionLocation=null,this._uvLocation=null,this._textureLocation=null,this._positionArray=null,this._uvArray=null,this._indexArray=null,this._firstDraw=!0}release(){this._rect=null;const t=this._subdelegate.getGlManager().getGl();t.deleteTexture(this._texture),this._texture=null,t.deleteBuffer(this._uvBuffer),this._uvBuffer=null,t.deleteBuffer(this._vertexBuffer),this._vertexBuffer=null,t.deleteBuffer(this._indexBuffer),this._indexBuffer=null}getTexture(){return this._texture}render(t){if(null==this._texture)return;const e=this._subdelegate.getGlManager().getGl();if(this._firstDraw){this._positionLocation=e.getAttribLocation(t,\"position\"),e.enableVertexAttribArray(this._positionLocation),this._uvLocation=e.getAttribLocation(t,\"uv\"),e.enableVertexAttribArray(this._uvLocation),this._textureLocation=e.getUniformLocation(t,\"texture\"),e.uniform1i(this._textureLocation,0),this._uvArray=new Float32Array([1,0,0,0,0,1,1,1]),this._uvBuffer=e.createBuffer();{const t=this._subdelegate.getCanvas().width,i=this._subdelegate.getCanvas().height;this._positionArray=new Float32Array([(this._rect.right-.5*t)/(.5*t),(this._rect.up-.5*i)/(.5*i),(this._rect.left-.5*t)/(.5*t),(this._rect.up-.5*i)/(.5*i),(this._rect.left-.5*t)/(.5*t),(this._rect.down-.5*i)/(.5*i),(this._rect.right-.5*t)/(.5*t),(this._rect.down-.5*i)/(.5*i)]),this._vertexBuffer=e.createBuffer()}this._indexArray=new Uint16Array([0,1,2,3,2,0]),this._indexBuffer=e.createBuffer(),this._firstDraw=!1}e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.bufferData(e.ARRAY_BUFFER,this._uvArray,e.STATIC_DRAW),e.vertexAttribPointer(this._uvLocation,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this._positionArray,e.STATIC_DRAW),e.vertexAttribPointer(this._positionLocation,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this._indexArray,e.DYNAMIC_DRAW),e.bindTexture(e.TEXTURE_2D,this._texture),e.drawElements(e.TRIANGLES,this._indexArray.length,e.UNSIGNED_SHORT,0)}isHit(t,e){const{height:i}=this._subdelegate.getCanvas(),s=i-e;return t>=this._rect.left&&t<=this._rect.right&&s<=this._rect.up&&s>=this._rect.down}setSubdelegate(t){this._subdelegate=t}}class fs{}class ys{constructor(){this._startX=0,this._startY=0,this._lastX=0,this._lastY=0,this._lastX1=0,this._lastY1=0,this._lastX2=0,this._lastY2=0,this._lastTouchDistance=0,this._deltaX=0,this._deltaY=0,this._scale=1,this._touchSingle=!1,this._flipAvailable=!1}getCenterX(){return this._lastX}getCenterY(){return this._lastY}getDeltaX(){return this._deltaX}getDeltaY(){return this._deltaY}getStartX(){return this._startX}getStartY(){return this._startY}getScale(){return this._scale}getX(){return this._lastX}getY(){return this._lastY}getX1(){return this._lastX1}getY1(){return this._lastY1}getX2(){return this._lastX2}getY2(){return this._lastY2}isSingleTouch(){return this._touchSingle}isFlickAvailable(){return this._flipAvailable}disableFlick(){this._flipAvailable=!1}touchesBegan(t,e){this._lastX=t,this._lastY=e,this._startX=t,this._startY=e,this._lastTouchDistance=-1,this._flipAvailable=!0,this._touchSingle=!0}touchesMoved(t,e){this._lastX=t,this._lastY=e,this._lastTouchDistance=-1,this._touchSingle=!0}getFlickDistance(){return this.calculateDistance(this._startX,this._startY,this._lastX,this._lastY)}calculateDistance(t,e,i,s){return Math.sqrt((t-i)*(t-i)+(e-s)*(e-s))}calculateMovingAmount(t,e){if(t>0!=e>0)return 0;const i=t>0?1:-1,s=Math.abs(t),r=Math.abs(e);return i*(s<r?s:r)}}class Ss{constructor(){this._programId=null,this._back=null,this._gear=null,this._touchManager=new ys,this._deviceToScreen=new c,this._viewMatrix=new ms}initialize(t){this._subdelegate=t;const{width:e,height:i}=t.getCanvas(),s=e/i,r=-s,a=s;if(this._viewMatrix.setScreenRect(r,a,-1,1),this._viewMatrix.scale(1,1),this._deviceToScreen.loadIdentity(),e>i){const t=Math.abs(a-r);this._deviceToScreen.scaleRelative(t/e,-t/e)}else{const t=Math.abs(2);this._deviceToScreen.scaleRelative(t/i,-t/i)}this._deviceToScreen.translateRelative(.5*-e,.5*-i),this._viewMatrix.setMaxScale(2),this._viewMatrix.setMinScale(.8),this._viewMatrix.setMaxScreenRect(-2,2,-2,2)}release(){this._viewMatrix=null,this._touchManager=null,this._deviceToScreen=null,this._gear.release(),this._gear=null,this._back.release(),this._back=null,this._subdelegate.getGlManager().getGl().deleteProgram(this._programId),this._programId=null}render(){this._subdelegate.getGlManager().getGl().useProgram(this._programId),this._back&&this._back.render(this._programId),this._gear&&this._gear.render(this._programId),this._subdelegate.getGlManager().getGl().flush();const t=this._subdelegate.getLive2DManager();null!=t&&(t.setViewMatrix(this._viewMatrix),t.onUpdate())}initializeSprite(){const t=this._subdelegate.getCanvas().width,e=this._subdelegate.getCanvas().height,i=this._subdelegate.getTextureManager(),s=tt;let r=\"\";r=\"back_class_normal.png\";i.createTextureFromPngFile(s+r,!1,(i=>{const s=.5*t,r=.5*e,a=2*i.width,n=.95*e;this._back=new ps(s,r,a,n,i.id),this._back.setSubdelegate(this._subdelegate)})),r=\"icon_gear.png\";i.createTextureFromPngFile(s+r,!1,(i=>{const s=t-.5*i.width,r=e-.5*i.height,a=i.width,n=i.height;this._gear=new ps(s,r,a,n,i.id),this._gear.setSubdelegate(this._subdelegate)})),null==this._programId&&(this._programId=this._subdelegate.createShader())}onTouchesBegan(t,e){this._touchManager.touchesBegan(t*window.devicePixelRatio,e*window.devicePixelRatio)}onTouchesMoved(t,e){const i=t*window.devicePixelRatio,s=e*window.devicePixelRatio,r=this._subdelegate.getLive2DManager(),a=this.transformViewX(this._touchManager.getX()),n=this.transformViewY(this._touchManager.getY());this._touchManager.touchesMoved(i,s),r.onDrag(a,n)}onTouchesEnded(t,e){const i=t*window.devicePixelRatio,s=e*window.devicePixelRatio,r=this._subdelegate.getLive2DManager();r.onDrag(0,0);const a=this.transformViewX(i),n=this.transformViewY(s);r.onTap(a,n),this._gear.isHit(i,s)&&r.nextScene()}transformViewX(t){const e=this._deviceToScreen.transformX(t);return this._viewMatrix.invertTransformX(e)}transformViewY(t){const e=this._deviceToScreen.transformY(t);return this._viewMatrix.invertTransformY(e)}transformScreenX(t){return this._deviceToScreen.transformX(t)}transformScreenY(t){return this._deviceToScreen.transformY(t)}}class Cs{constructor(){this._canvas=null,this._glManager=new nt,this._textureManager=new _s,this._live2dManager=new ds,this._view=new Ss,this._frameBuffer=null,this._captured=!1}release(){this._resizeObserver.unobserve(this._canvas),this._resizeObserver.disconnect(),this._resizeObserver=null,this._live2dManager.release(),this._live2dManager=null,this._view.release(),this._view=null,this._textureManager.release(),this._textureManager=null,this._glManager.release(),this._glManager=null}initialize(t){if(!this._glManager.initialize(t))return!1;this._canvas=t,this.resizeCanvas(),this._textureManager.setGlManager(this._glManager);const e=this._glManager.getGl();return this._frameBuffer||(this._frameBuffer=e.getParameter(e.FRAMEBUFFER_BINDING)),e.enable(e.BLEND),e.blendFunc(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA),this._view.initialize(this),this._view.initializeSprite(),this._live2dManager.initialize(this),this._resizeObserver=new ResizeObserver(((t,e)=>this.resizeObserverCallback.call(this,t,e))),this._resizeObserver.observe(this._canvas),!0}onResize(){this.resizeCanvas(),this._view.initialize(this),this._view.initializeSprite()}resizeObserverCallback(t,e){this._needResize=!0}update(){if(this._glManager.getGl().isContextLost())return;this._needResize&&(this.onResize(),this._needResize=!1);const t=this._glManager.getGl();t.clearColor(0,0,0,1),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),t.clearDepth(1),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this._view.render()}createShader(){const t=this._glManager.getGl(),e=t.createShader(t.VERTEX_SHADER);if(null==e)return at.printMessage(\"failed to create vertexShader\"),null;t.shaderSource(e,\"precision mediump float;attribute vec3 position;attribute vec2 uv;varying vec2 vuv;void main(void){   gl_Position = vec4(position, 1.0);   vuv = uv;}\"),t.compileShader(e);const i=t.createShader(t.FRAGMENT_SHADER);if(null==i)return at.printMessage(\"failed to create fragmentShader\"),null;t.shaderSource(i,\"precision mediump float;varying vec2 vuv;uniform sampler2D texture;void main(void){   gl_FragColor = texture2D(texture, vuv);}\"),t.compileShader(i);const s=t.createProgram();return t.attachShader(s,e),t.attachShader(s,i),t.deleteShader(e),t.deleteShader(i),t.linkProgram(s),t.useProgram(s),s}getTextureManager(){return this._textureManager}getFrameBuffer(){return this._frameBuffer}getCanvas(){return this._canvas}getGlManager(){return this._glManager}getLive2DManager(){return this._live2dManager}resizeCanvas(){this._canvas.width=this._canvas.clientWidth*window.devicePixelRatio,this._canvas.height=this._canvas.clientHeight*window.devicePixelRatio;const t=this._glManager.getGl();t.viewport(0,0,t.drawingBufferWidth,t.drawingBufferHeight)}onPointBegan(t,e){if(!this._view)return void at.printMessage(\"view notfound\");this._captured=!0;const i=t-this._canvas.offsetLeft,s=e-this._canvas.offsetTop;this._view.onTouchesBegan(i,s)}onPointMoved(t,e){if(!this._captured)return;const i=t-this._canvas.offsetLeft,s=e-this._canvas.offsetTop;this._view.onTouchesMoved(i,s)}onPointEnded(t,e){if(this._captured=!1,!this._view)return void at.printMessage(\"view notfound\");const i=t-this._canvas.offsetLeft,s=e-this._canvas.offsetTop;this._view.onTouchesEnded(i,s)}onTouchCancel(t,e){if(this._captured=!1,!this._view)return void at.printMessage(\"view notfound\");const i=t-this._canvas.offsetLeft,s=e-this._canvas.offsetTop;this._view.onTouchesEnded(i,s)}isContextLost(){return this._glManager.getGl().isContextLost()}}let xs=null;class Ms{static getInstance(){return null==xs&&(xs=new Ms),xs}static releaseInstance(){null!=xs&&xs.release(),xs=null}onPointerBegan(t){for(let e=this._subdelegates.begin();e.notEqual(this._subdelegates.end());e.preIncrement())e.ptr().onPointBegan(t.pageX,t.pageY)}onPointerMoved(t){for(let e=this._subdelegates.begin();e.notEqual(this._subdelegates.end());e.preIncrement())e.ptr().onPointMoved(t.pageX,t.pageY)}onPointerEnded(t){for(let e=this._subdelegates.begin();e.notEqual(this._subdelegates.end());e.preIncrement())e.ptr().onPointEnded(t.pageX,t.pageY)}onPointerCancel(t){for(let e=this._subdelegates.begin();e.notEqual(this._subdelegates.end());e.preIncrement())e.ptr().onTouchCancel(t.pageX,t.pageY)}onResize(){for(let t=0;t<this._subdelegates.getSize();t++)this._subdelegates.at(t).onResize()}run(){const t=()=>{if(null!=xs){at.updateTime();for(let t=0;t<this._subdelegates.getSize();t++)this._subdelegates.at(t).update();requestAnimationFrame(t)}};t()}release(){this.releaseEventListener(),this.releaseSubdelegates(),$.dispose(),this._cubismOption=null}releaseEventListener(){document.removeEventListener(\"pointerup\",this.pointBeganEventListener),this.pointBeganEventListener=null,document.removeEventListener(\"pointermove\",this.pointMovedEventListener),this.pointMovedEventListener=null,document.removeEventListener(\"pointerdown\",this.pointEndedEventListener),this.pointEndedEventListener=null,document.removeEventListener(\"pointerdown\",this.pointCancelEventListener),this.pointCancelEventListener=null}releaseSubdelegates(){for(let t=this._subdelegates.begin();t.notEqual(this._subdelegates.end());t.preIncrement())t.ptr().release();this._subdelegates.clear(),this._subdelegates=null}initialize(){return this.initializeCubism(),this.initializeSubdelegates(),this.initializeEventListener(),!0}initializeEventListener(){this.pointBeganEventListener=this.onPointerBegan.bind(this),this.pointMovedEventListener=this.onPointerMoved.bind(this),this.pointEndedEventListener=this.onPointerEnded.bind(this),this.pointCancelEventListener=this.onPointerCancel.bind(this),document.addEventListener(\"pointerdown\",this.pointBeganEventListener,{passive:!0}),document.addEventListener(\"pointermove\",this.pointMovedEventListener,{passive:!0}),document.addEventListener(\"pointerup\",this.pointEndedEventListener,{passive:!0}),document.addEventListener(\"pointercancel\",this.pointCancelEventListener,{passive:!0})}initializeCubism(){at.updateTime(),this._cubismOption.logFunction=at.printMessage,this._cubismOption.loggingLevel=rt,$.startUp(this._cubismOption),$.initialize()}initializeSubdelegates(){let t=100;t=100,this._canvases.prepareCapacity(1),this._subdelegates.prepareCapacity(1);for(let t=0;t<1;t++){const t=document.createElement(\"canvas\");this._canvases.pushBack(t),t.style.width=\"100vw\",t.style.height=\"100vh\",document.body.appendChild(t)}for(let t=0;t<this._canvases.getSize();t++){const e=new Cs;e.initialize(this._canvases.at(t)),this._subdelegates.pushBack(e)}for(let t=0;t<1;t++)this._subdelegates.at(t).isContextLost()&&b(`The context for Canvas at index ${t} was lost, possibly because the acquisition limit for WebGLRenderingContext was reached.`)}constructor(){this._cubismOption=new Z,this._subdelegates=new e,this._canvases=new e}}at.printMessage=()=>{};class vs extends Cs{initialize(t){if(!this._glManager.initialize(t))return!1;this._canvas=t,this.resizeCanvas(),this._textureManager.setGlManager(this._glManager);const e=this._glManager.getGl();return this._frameBuffer||(this._frameBuffer=e.getParameter(e.FRAMEBUFFER_BINDING)),e.enable(e.BLEND),e.blendFunc(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA),this._view.initialize(this),this._view._gear={render:()=>{},isHit:()=>{},release:()=>{}},this._view._back={render:()=>{},release:()=>{}},this._live2dManager._subdelegate=this,this._resizeObserver=new window.ResizeObserver(((t,e)=>this.resizeObserverCallback.call(this,t,e))),this._resizeObserver.observe(this._canvas),!0}onResize(){this.resizeCanvas(),this._view.initialize(this)}update(){if(this._glManager.getGl().isContextLost())return;this._needResize&&(this.onResize(),this._needResize=!1);const t=this._glManager.getGl();t.clearColor(0,0,0,0),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),t.clearDepth(1),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this._view.render()}}class bs extends Ms{run(){const t=()=>{at.updateTime();for(let t=0;t<this._subdelegates.getSize();t++)this._subdelegates.at(t).update();this._drawFrameId=window.requestAnimationFrame(t)};t()}stop(){this._drawFrameId&&(window.cancelAnimationFrame(this._drawFrameId),this._drawFrameId=null)}release(){this.stop(),this.releaseEventListener(),this._subdelegates.clear(),this._cubismOption=null}transformOffset(t){const e=this._subdelegates.at(0),i=e.getCanvas().getBoundingClientRect(),s=t.pageX-i.left,r=t.pageY-i.top,a=s*window.devicePixelRatio,n=r*window.devicePixelRatio;return{x:e._view.transformViewX(a),y:e._view.transformViewY(n)}}onMouseMove(t){const e=this._subdelegates.at(0).getLive2DManager(),{x:i,y:s}=this.transformOffset(t),r=e._models.at(0);e.onDrag(i,s),e.onTap(i,s),r.hitTest(st,i,s)&&window.dispatchEvent(new Event(\"live2d:hoverbody\"))}onMouseEnd(t){const e=this._subdelegates.at(0).getLive2DManager(),{x:i,y:s}=this.transformOffset(t);e.onDrag(0,0),e.onTap(i,s)}onTap(t){const e=this._subdelegates.at(0).getLive2DManager(),{x:i,y:s}=this.transformOffset(t);e._models.at(0).hitTest(st,i,s)&&window.dispatchEvent(new Event(\"live2d:tapbody\"))}initializeEventListener(){this.mouseMoveEventListener=this.onMouseMove.bind(this),this.mouseEndedEventListener=this.onMouseEnd.bind(this),this.tapEventListener=this.onTap.bind(this),document.addEventListener(\"mousemove\",this.mouseMoveEventListener,{passive:!0}),document.addEventListener(\"mouseout\",this.mouseEndedEventListener,{passive:!0}),document.addEventListener(\"pointerdown\",this.tapEventListener,{passive:!0})}releaseEventListener(){document.removeEventListener(\"mousemove\",this.mouseMoveEventListener,{passive:!0}),this.mouseMoveEventListener=null,document.removeEventListener(\"mouseout\",this.mouseEndedEventListener,{passive:!0}),this.mouseEndedEventListener=null,document.removeEventListener(\"pointerdown\",this.tapEventListener,{passive:!0})}initializeSubdelegates(){this._canvases.prepareCapacity(1),this._subdelegates.prepareCapacity(1);const e=document.getElementById(\"live2d\");this._canvases.pushBack(e),e.style.width=e.width,e.style.height=e.height;for(let e=0;e<this._canvases.getSize();e++){const i=new vs;if(!i.initialize(this._canvases.at(e)))return void t.error(\"Failed to initialize AppSubdelegate\");this._subdelegates.pushBack(i)}for(let e=0;e<1;e++)this._subdelegates.at(e).isContextLost()&&t.error(`The context for Canvas at index ${e} was lost, possibly because the acquisition limit for WebGLRenderingContext was reached.`)}changeModel(t){const e=t.split(\"/\"),i=e.pop(),s=e.join(\"/\")+\"/\",r=this._subdelegates.at(0).getLive2DManager();r.releaseAllModel();const a=new gs;a.setSubdelegate(r._subdelegate),a.loadAssets(s,i),r._models.pushBack(a)}get subdelegates(){return this._subdelegates}}export{bs as AppDelegate};\n//# sourceMappingURL=index2.js.map\n"
  },
  {
    "path": "dist/waifu-tips.js",
    "content": "/*!\n * Live2D Widget\n * https://github.com/stevenjoezhang/live2d-widget\n */\nfunction e(e){return Array.isArray(e)?e[Math.floor(Math.random()*e.length)]:e}function t(e,t){const s=Math.floor(Math.random()*(e-1));return s>=t?s+1:s}function s(e,t){return new Promise(((t,s)=>{let o;o=document.createElement(\"script\"),o.src=e,o&&(o.onload=()=>t(e),o.onerror=()=>s(e),document.head.appendChild(o))}))}let o=null;function i(t,s,i,n=!0){let l=parseInt(sessionStorage.getItem(\"waifu-message-priority\"),10);if(isNaN(l)&&(l=0),!t||n&&l>i||!n&&l>=i)return;o&&(clearTimeout(o),o=null),t=e(t),sessionStorage.setItem(\"waifu-message-priority\",String(i));const a=document.getElementById(\"waifu-tips\");a.innerHTML=t,a.classList.add(\"waifu-tips-active\"),o=setTimeout((()=>{sessionStorage.removeItem(\"waifu-message-priority\"),a.classList.remove(\"waifu-tips-active\")}),s)}function n(e,...t){return e.replace(/\\$(\\d+)/g,((e,s)=>{var o;const i=parseInt(s,10)-1;return null!==(o=t[i])&&void 0!==o?o:\"\"}))}class l{constructor(e=\"info\"){this.level=e}setLevel(e){e&&(this.level=e)}shouldLog(e){return l.levelOrder[e]<=l.levelOrder[this.level]}error(e,...t){this.shouldLog(\"error\")&&console.error(\"[Live2D Widget][ERROR]\",e,...t)}warn(e,...t){this.shouldLog(\"warn\")&&console.warn(\"[Live2D Widget][WARN]\",e,...t)}info(e,...t){this.shouldLog(\"info\")&&console.log(\"[Live2D Widget][INFO]\",e,...t)}trace(e,...t){this.shouldLog(\"trace\")&&console.log(\"[Live2D Widget][TRACE]\",e,...t)}}l.levelOrder={error:0,warn:1,info:2,trace:3};const a=new l;class c{constructor(e,t=[]){var s;this.modelList=null;let{apiPath:o,cdnPath:i}=e;const{cubism2Path:n,cubism5Path:l}=e;let c=!1;if(\"string\"==typeof i)i.endsWith(\"/\")||(i+=\"/\"),c=!0;else if(\"string\"==typeof o)o.endsWith(\"/\")||(o+=\"/\"),i=o,c=!0,a.warn(\"apiPath option is deprecated. Please use cdnPath instead.\");else if(!t.length)throw\"Invalid initWidget argument!\";let d=parseInt(localStorage.getItem(\"modelId\"),10),r=parseInt(localStorage.getItem(\"modelTexturesId\"),10);(isNaN(d)||isNaN(r))&&(r=0),isNaN(d)&&(d=null!==(s=e.modelId)&&void 0!==s?s:0),this.useCDN=c,this.cdnPath=i||\"\",this.cubism2Path=n||\"\",this.cubism5Path=l||\"\",this._modelId=d,this._modelTexturesId=r,this.currentModelVersion=0,this.loading=!1,this.modelJSONCache={},this.models=t}static async initCheck(e,t=[]){const s=new c(e,t);if(s.useCDN){const e=await fetch(`${s.cdnPath}model_list.json`);s.modelList=await e.json(),s.modelId>=s.modelList.models.length&&(s.modelId=0);const t=s.modelList.models[s.modelId];if(Array.isArray(t))s.modelTexturesId>=t.length&&(s.modelTexturesId=0);else{const e=`${s.cdnPath}model/${t}/index.json`,o=await s.fetchWithCache(e);if(2===s.checkModelVersion(o)){const e=await s.loadTextureCache(t);s.modelTexturesId>=e.length&&(s.modelTexturesId=0)}}}else s.modelId>=s.models.length&&(s.modelId=0),s.modelTexturesId>=s.models[s.modelId].paths.length&&(s.modelTexturesId=0);return s}set modelId(e){this._modelId=e,localStorage.setItem(\"modelId\",e.toString())}get modelId(){return this._modelId}set modelTexturesId(e){this._modelTexturesId=e,localStorage.setItem(\"modelTexturesId\",e.toString())}get modelTexturesId(){return this._modelTexturesId}resetCanvas(){document.getElementById(\"waifu-canvas\").innerHTML='<canvas id=\"live2d\" width=\"800\" height=\"800\"></canvas>'}async fetchWithCache(e){let t;if(e in this.modelJSONCache)t=this.modelJSONCache[e];else{try{const s=await fetch(e);t=await s.json()}catch(e){t=null}this.modelJSONCache[e]=t}return t}checkModelVersion(e){return 3===e.Version||e.FileReferences?3:2}async loadLive2D(e,t){if(this.loading)a.warn(\"Still loading. Abort.\");else{this.loading=!0;try{const o=this.checkModelVersion(t);if(2===o){if(!this.cubism2model){if(!this.cubism2Path)return void a.error(\"No cubism2Path set, cannot load Cubism 2 Core.\");await s(this.cubism2Path);const{default:e}=await import(\"./chunk/index.js\");this.cubism2model=new e}3===this.currentModelVersion&&(this.cubism5model.release(),this.resetCanvas()),3!==this.currentModelVersion&&this.cubism2model.gl?await this.cubism2model.changeModelWithJSON(e,t):await this.cubism2model.init(\"live2d\",e,t)}else{if(!this.cubism5Path)return void a.error(\"No cubism5Path set, cannot load Cubism 5 Core.\");await s(this.cubism5Path);const{AppDelegate:t}=await import(\"./chunk/index2.js\");this.cubism5model=new t,2===this.currentModelVersion&&(this.cubism2model.destroy(),this.resetCanvas()),2!==this.currentModelVersion&&this.cubism5model.subdelegates.at(0)?this.cubism5model.changeModel(e):(this.cubism5model.initialize(),this.cubism5model.changeModel(e),this.cubism5model.run())}a.info(`Model ${e} (Cubism version ${o}) loaded`),this.currentModelVersion=o}catch(e){console.error(\"loadLive2D failed\",e)}this.loading=!1}}async loadTextureCache(e){return await this.fetchWithCache(`${this.cdnPath}model/${e}/textures.cache`)||[]}async loadModel(e){let t,s;if(this.useCDN){let e=this.modelList.models[this.modelId];Array.isArray(e)&&(e=e[this.modelTexturesId]),t=`${this.cdnPath}model/${e}/index.json`,s=await this.fetchWithCache(t);if(2===this.checkModelVersion(s)){const t=await this.loadTextureCache(e);if(t.length>0){let e=t[this.modelTexturesId];\"string\"==typeof e&&(e=[e]),s.textures=e}}}else t=this.models[this.modelId].paths[this.modelTexturesId],s=await this.fetchWithCache(t);await this.loadLive2D(t,s),i(e,4e3,10)}async loadRandTexture(e=\"\",s=\"\"){const{modelId:o}=this;let n=!1;if(this.useCDN){const e=this.modelList.models[o];if(Array.isArray(e))this.modelTexturesId=t(e.length,this.modelTexturesId);else{const s=`${this.cdnPath}model/${e}/index.json`,o=await this.fetchWithCache(s);if(2===this.checkModelVersion(o)){const s=await this.loadTextureCache(e);s.length<=1?n=!0:this.modelTexturesId=t(s.length,this.modelTexturesId)}else n=!0}}else 1===this.models[o].paths.length?n=!0:this.modelTexturesId=t(this.models[o].paths.length,this.modelTexturesId);n?i(s,4e3,10):await this.loadModel(e)}async loadNextModel(){this.modelTexturesId=0,this.useCDN?(this.modelId=(this.modelId+1)%this.modelList.models.length,await this.loadModel(this.modelList.messages[this.modelId])):(this.modelId=(this.modelId+1)%this.models.length,await this.loadModel(this.models[this.modelId].message))}}class d{constructor(e,t,s){this.config=t,this.tools={hitokoto:{icon:'<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 512 512\">\\x3c!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --\\x3e<path d=\"M512 240c0 114.9-114.6 208-256 208c-37.1 0-72.3-6.4-104.1-17.9c-11.9 8.7-31.3 20.6-54.3 30.6C73.6 471.1 44.7 480 16 480c-6.5 0-12.3-3.9-14.8-9.9c-2.5-6-1.1-12.8 3.4-17.4c0 0 0 0 0 0s0 0 0 0s0 0 0 0c0 0 0 0 0 0l.3-.3c.3-.3 .7-.7 1.3-1.4c1.1-1.2 2.8-3.1 4.9-5.7c4.1-5 9.6-12.4 15.2-21.6c10-16.6 19.5-38.4 21.4-62.9C17.7 326.8 0 285.1 0 240C0 125.1 114.6 32 256 32s256 93.1 256 208z\"/></svg>',callback:async()=>{const e=await fetch(\"https://v1.hitokoto.cn\"),t=await e.json(),o=n(s.message.hitokoto,t.from,t.creator);i(t.hitokoto,6e3,9),setTimeout((()=>{i(o,4e3,9)}),6e3)}},asteroids:{icon:'<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 512 512\">\\x3c!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --\\x3e<path d=\"M498.1 5.6c10.1 7 15.4 19.1 13.5 31.2l-64 416c-1.5 9.7-7.4 18.2-16 23s-18.9 5.4-28 1.6L284 427.7l-68.5 74.1c-8.9 9.7-22.9 12.9-35.2 8.1S160 493.2 160 480l0-83.6c0-4 1.5-7.8 4.2-10.8L331.8 202.8c5.8-6.3 5.6-16-.4-22s-15.7-6.4-22-.7L106 360.8 17.7 316.6C7.1 311.3 .3 300.7 0 288.9s5.9-22.8 16.1-28.7l448-256c10.7-6.1 23.9-5.5 34 1.4z\"/></svg>',callback:()=>{if(window.Asteroids)window.ASTEROIDSPLAYERS||(window.ASTEROIDSPLAYERS=[]),window.ASTEROIDSPLAYERS.push(new window.Asteroids);else{const e=document.createElement(\"script\");e.src=\"https://fastly.jsdelivr.net/gh/stevenjoezhang/asteroids/asteroids.js\",document.head.appendChild(e)}}},\"switch-model\":{icon:'<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 512 512\">\\x3c!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --\\x3e<path d=\"M320 64A64 64 0 1 0 192 64a64 64 0 1 0 128 0zm-96 96c-35.3 0-64 28.7-64 64l0 48c0 17.7 14.3 32 32 32l1.8 0 11.1 99.5c1.8 16.2 15.5 28.5 31.8 28.5l38.7 0c16.3 0 30-12.3 31.8-28.5L318.2 304l1.8 0c17.7 0 32-14.3 32-32l0-48c0-35.3-28.7-64-64-64l-64 0zM132.3 394.2c13-2.4 21.7-14.9 19.3-27.9s-14.9-21.7-27.9-19.3c-32.4 5.9-60.9 14.2-82 24.8c-10.5 5.3-20.3 11.7-27.8 19.6C6.4 399.5 0 410.5 0 424c0 21.4 15.5 36.1 29.1 45c14.7 9.6 34.3 17.3 56.4 23.4C130.2 504.7 190.4 512 256 512s125.8-7.3 170.4-19.6c22.1-6.1 41.8-13.8 56.4-23.4c13.7-8.9 29.1-23.6 29.1-45c0-13.5-6.4-24.5-14-32.6c-7.5-7.9-17.3-14.3-27.8-19.6c-21-10.6-49.5-18.9-82-24.8c-13-2.4-25.5 6.3-27.9 19.3s6.3 25.5 19.3 27.9c30.2 5.5 53.7 12.8 69 20.5c3.2 1.6 5.8 3.1 7.9 4.5c3.6 2.4 3.6 7.2 0 9.6c-8.8 5.7-23.1 11.8-43 17.3C374.3 457 318.5 464 256 464s-118.3-7-157.7-17.9c-19.9-5.5-34.2-11.6-43-17.3c-3.6-2.4-3.6-7.2 0-9.6c2.1-1.4 4.8-2.9 7.9-4.5c15.3-7.7 38.8-14.9 69-20.5z\"/></svg>',callback:()=>e.loadNextModel()},\"switch-texture\":{icon:'<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 640 512\">\\x3c!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --\\x3e<path d=\"M211.8 0c7.8 0 14.3 5.7 16.7 13.2C240.8 51.9 277.1 80 320 80s79.2-28.1 91.5-66.8C413.9 5.7 420.4 0 428.2 0l12.6 0c22.5 0 44.2 7.9 61.5 22.3L628.5 127.4c6.6 5.5 10.7 13.5 11.4 22.1s-2.1 17.1-7.8 23.6l-56 64c-11.4 13.1-31.2 14.6-44.6 3.5L480 197.7 480 448c0 35.3-28.7 64-64 64l-192 0c-35.3 0-64-28.7-64-64l0-250.3-51.5 42.9c-13.3 11.1-33.1 9.6-44.6-3.5l-56-64c-5.7-6.5-8.5-15-7.8-23.6s4.8-16.6 11.4-22.1L137.7 22.3C155 7.9 176.7 0 199.2 0l12.6 0z\"/></svg>',callback:()=>{let t=\"\",o=\"\";s&&(t=s.message.changeSuccess,o=s.message.changeFail),e.loadRandTexture(t,o)}},photo:{icon:'<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 512 512\">\\x3c!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --\\x3e<path d=\"M220.6 121.2L271.1 96 448 96l0 96-114.8 0c-21.9-15.1-48.5-24-77.2-24s-55.2 8.9-77.2 24L64 192l0-64 128 0c9.9 0 19.7-2.3 28.6-6.8zM0 128L0 416c0 35.3 28.7 64 64 64l384 0c35.3 0 64-28.7 64-64l0-320c0-35.3-28.7-64-64-64L271.1 32c-9.9 0-19.7 2.3-28.6 6.8L192 64l-32 0 0-16c0-8.8-7.2-16-16-16L80 32c-8.8 0-16 7.2-16 16l0 16C28.7 64 0 92.7 0 128zM168 304a88 88 0 1 1 176 0 88 88 0 1 1 -176 0z\"/></svg>',callback:()=>{i(s.message.photo,6e3,9);const e=document.getElementById(\"live2d\");if(!e)return;const t=e.toDataURL(),o=document.createElement(\"a\");o.style.display=\"none\",o.href=t,o.download=\"live2d-photo.png\",document.body.appendChild(o),o.click(),document.body.removeChild(o)}},info:{icon:'<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 512 512\">\\x3c!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --\\x3e<path d=\"M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM216 336l24 0 0-64-24 0c-13.3 0-24-10.7-24-24s10.7-24 24-24l48 0c13.3 0 24 10.7 24 24l0 88 8 0c13.3 0 24 10.7 24 24s-10.7 24-24 24l-80 0c-13.3 0-24-10.7-24-24s10.7-24 24-24zm40-208a32 32 0 1 1 0 64 32 32 0 1 1 0-64z\"/></svg>',callback:()=>{open(\"https://github.com/stevenjoezhang/live2d-widget\")}},quit:{icon:'<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 384 512\">\\x3c!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --\\x3e<path d=\"M342.6 150.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L192 210.7 86.6 105.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L146.7 256 41.4 361.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0L192 301.3 297.4 406.6c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L237.3 256 342.6 150.6z\"/></svg>',callback:()=>{localStorage.setItem(\"waifu-display\",Date.now().toString());i(s.message.goodbye,2e3,11);const e=document.getElementById(\"waifu\");e&&(e.classList.remove(\"waifu-active\"),setTimeout((()=>{e.classList.add(\"waifu-hidden\");const t=document.getElementById(\"waifu-toggle\");null==t||t.classList.add(\"waifu-toggle-active\")}),3e3))}}}}registerTools(){var e;Array.isArray(this.config.tools)||(this.config.tools=Object.keys(this.tools));for(const t of this.config.tools)if(this.tools[t]){const{icon:s,callback:o}=this.tools[t],i=document.createElement(\"span\");i.id=`waifu-tool-${t}`,i.innerHTML=s,null===(e=document.getElementById(\"waifu-tool\"))||void 0===e||e.insertAdjacentElement(\"beforeend\",i),i.addEventListener(\"click\",o)}}}async function r(t){var s;localStorage.removeItem(\"waifu-display\"),sessionStorage.removeItem(\"waifu-message-priority\"),document.body.insertAdjacentHTML(\"beforeend\",'<div id=\"waifu\">\\n       <div id=\"waifu-tips\"></div>\\n       <div id=\"waifu-canvas\">\\n         <canvas id=\"live2d\" width=\"800\" height=\"800\"></canvas>\\n       </div>\\n       <div id=\"waifu-tool\"></div>\\n     </div>');let o,l=[];if(t.waifuPath){const s=await fetch(t.waifuPath);o=await s.json(),l=o.models,function(t){let s,o=!1;const n=t.message.default;let l;t.seasons.forEach((({date:t,text:s})=>{const o=new Date,i=t.split(\"-\")[0],l=t.split(\"-\")[1]||i;Number(i.split(\"/\")[0])<=o.getMonth()+1&&o.getMonth()+1<=Number(l.split(\"/\")[0])&&Number(i.split(\"/\")[1])<=o.getDate()&&o.getDate()<=Number(l.split(\"/\")[1])&&(s=(s=e(s)).replace(\"{year}\",String(o.getFullYear())),n.push(s))})),window.addEventListener(\"mousemove\",(()=>o=!0)),window.addEventListener(\"keydown\",(()=>o=!0)),setInterval((()=>{o?(o=!1,clearInterval(s),s=null):s||(s=setInterval((()=>{i(n,6e3,9)}),2e4))}),1e3),window.addEventListener(\"mouseover\",(s=>{var o;for(let{selector:n,text:a}of t.mouseover)if(null===(o=s.target)||void 0===o?void 0:o.closest(n)){if(l===n)return;return l=n,a=e(a),a=a.replace(\"{text}\",s.target.innerText),void i(a,4e3,8)}})),window.addEventListener(\"click\",(s=>{var o;for(let{selector:n,text:l}of t.click)if(null===(o=s.target)||void 0===o?void 0:o.closest(n))return l=e(l),l=l.replace(\"{text}\",s.target.innerText),void i(l,4e3,8)})),window.addEventListener(\"live2d:hoverbody\",(()=>{i(e(t.message.hoverBody),4e3,8,!1)})),window.addEventListener(\"live2d:tapbody\",(()=>{i(e(t.message.tapBody),4e3,9)}));const a=()=>{};console.log(\"%c\",a),a.toString=()=>{i(t.message.console,6e3,9)},window.addEventListener(\"copy\",(()=>{i(t.message.copy,6e3,9)})),window.addEventListener(\"visibilitychange\",(()=>{document.hidden||i(t.message.visibilitychange,6e3,9)}))}(o),i(function(e,t,s){if(\"/\"===location.pathname)for(const{hour:t,text:s}of e){const e=new Date,o=t.split(\"-\")[0],i=t.split(\"-\")[1]||o;if(Number(o)<=e.getHours()&&e.getHours()<=Number(i))return s}if(!t)return\"\";const o=n(t,document.title);if(\"\"===document.referrer||!s)return o;const i=new URL(document.referrer);return location.hostname===i.hostname?o:`${n(s,i.hostname)}<br>${o}`}(o.time,o.message.welcome,o.message.referrer),7e3,11)}const a=await c.initCheck(t,l);await a.loadModel(\"\"),new d(a,t,o).registerTools(),t.drag&&function(){const e=document.getElementById(\"waifu\");if(!e)return;let t=window.innerWidth,s=window.innerHeight;const o=e.offsetWidth,i=e.offsetHeight;e.addEventListener(\"mousedown\",(n=>{if(2===n.button)return;const l=document.getElementById(\"live2d\");if(n.target!==l)return;n.preventDefault();const a=n.offsetX,c=n.offsetY;document.onmousemove=n=>{const l=n.clientX,d=n.clientY;let r=l-a,m=d-c;m<0?m=0:m>=s-i&&(m=s-i),r<0?r=0:r>=t-o&&(r=t-o),e.style.top=m+\"px\",e.style.left=r+\"px\"},document.onmouseup=()=>{document.onmousemove=null}})),window.onresize=()=>{t=window.innerWidth,s=window.innerHeight}}(),null===(s=document.getElementById(\"waifu\"))||void 0===s||s.classList.add(\"waifu-active\")}window.initWidget=function(e){if(\"string\"==typeof e)return void a.error(\"Your config for Live2D initWidget is outdated. Please refer to https://github.com/stevenjoezhang/live2d-widget/blob/master/dist/autoload.js\");a.setLevel(e.logLevel),document.body.insertAdjacentHTML(\"beforeend\",'<div id=\"waifu-toggle\">\\n       <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 320 512\">\\x3c!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --\\x3e<path d=\"M96 64a64 64 0 1 1 128 0A64 64 0 1 1 96 64zm48 320l0 96c0 17.7-14.3 32-32 32s-32-14.3-32-32l0-192.2L59.1 321c-9.4 15-29.2 19.4-44.1 10S-4.5 301.9 4.9 287l39.9-63.3C69.7 184 113.2 160 160 160s90.3 24 115.2 63.6L315.1 287c9.4 15 4.9 34.7-10 44.1s-34.7 4.9-44.1-10L240 287.8 240 480c0 17.7-14.3 32-32 32s-32-14.3-32-32l0-96-32 0z\"/></svg>\\n     </div>');const t=document.getElementById(\"waifu-toggle\");null==t||t.addEventListener(\"click\",(()=>{var s;null==t||t.classList.remove(\"waifu-toggle-active\"),(null==t?void 0:t.getAttribute(\"first-time\"))?(r(e),null==t||t.removeAttribute(\"first-time\")):(localStorage.removeItem(\"waifu-display\"),null===(s=document.getElementById(\"waifu\"))||void 0===s||s.classList.remove(\"waifu-hidden\"),setTimeout((()=>{var e;null===(e=document.getElementById(\"waifu\"))||void 0===e||e.classList.add(\"waifu-active\")}),0))})),localStorage.getItem(\"waifu-display\")&&Date.now()-Number(localStorage.getItem(\"waifu-display\"))<=864e5?(null==t||t.setAttribute(\"first-time\",\"true\"),setTimeout((()=>{null==t||t.classList.add(\"waifu-toggle-active\")}),0)):r(e)};export{a as l};\n//# sourceMappingURL=waifu-tips.js.map\n"
  },
  {
    "path": "dist/waifu-tips.json",
    "content": "{\n  \"mouseover\": [{\n    \"selector\": \"#waifu-tool-hitokoto\",\n    \"text\": [\"猜猜我要说些什么？\", \"我从青蛙王子那里听到了不少人生经验。\"]\n  }, {\n    \"selector\": \"#waifu-tool-asteroids\",\n    \"text\": [\"要不要来玩飞机大战？\", \"这个按钮上写着「不要点击」。\", \"怎么，你想来和我玩个游戏？\", \"听说这样可以蹦迪！\"]\n  }, {\n    \"selector\": \"#waifu-tool-switch-model\",\n    \"text\": [\"你是不是不爱人家了呀，呜呜呜～\", \"要见见我的姐姐嘛？\", \"想要看我妹妹嘛？\", \"要切换看板娘吗？\"]\n  }, {\n    \"selector\": \"#waifu-tool-switch-texture\",\n    \"text\": [\"喜欢换装 PLAY 吗？\", \"这次要扮演什么呢？\", \"变装！\", \"让我们看看接下来会发生什么！\"]\n  }, {\n    \"selector\": \"#waifu-tool-photo\",\n    \"text\": [\"你要给我拍照呀？一二三～茄子～\", \"要不，我们来合影吧！\", \"保持微笑就好了～\"]\n  }, {\n    \"selector\": \"#waifu-tool-info\",\n    \"text\": [\"想要知道更多关于我的事么？\", \"这里记录着我搬家的历史呢。\", \"你想深入了解我什么呢？\"]\n  }, {\n    \"selector\": \"#waifu-tool-quit\",\n    \"text\": [\"到了要说再见的时候了吗？\", \"呜呜 QAQ 后会有期……\", \"不要抛弃我呀……\", \"我们，还能再见面吗……\", \"哼，你会后悔的！\"]\n  }, {\n    \"selector\": \".menu-item-home a\",\n    \"text\": [\"点击前往首页，想回到上一页可以使用浏览器的后退功能哦。\", \"点它就可以回到首页啦！\", \"回首页看看吧。\"]\n  }, {\n    \"selector\": \".menu-item-about a\",\n    \"text\": [\"你想知道我家主人是谁吗？\", \"这里有一些关于我家主人的秘密哦，要不要看看呢？\", \"发现主人出没地点！\"]\n  }, {\n    \"selector\": \".menu-item-tags a\",\n    \"text\": [\"点击就可以看文章的标签啦！\", \"点击来查看所有标签哦。\"]\n  }, {\n    \"selector\": \".menu-item-categories a\",\n    \"text\": [\"文章都分类好啦～\", \"点击来查看文章分类哦。\"]\n  }, {\n    \"selector\": \".menu-item-archives a\",\n    \"text\": [\"翻页比较麻烦吗，那就来看看文章归档吧。\", \"文章目录都整理在这里啦！\"]\n  }, {\n    \"selector\": \".menu-item-friends a\",\n    \"text\": [\"这是我的朋友们哦ヾ(◍°∇°◍)ﾉﾞ\", \"要去大佬们的家看看吗？\", \"要去拜访一下我的朋友们吗？\"]\n  }, {\n    \"selector\": \".menu-item-search a\",\n    \"text\": [\"找不到想看的内容？搜索看看吧！\", \"在找什么东西呢，需要帮忙吗？\"]\n  }, {\n    \"selector\": \".menu-item a\",\n    \"text\": [\"快看看这里都有什么呢？\"]\n  }, {\n    \"selector\": \".site-author\",\n    \"text\": [\"我家主人好看吗？\", \"这是我家主人(*´∇｀*)\"]\n  }, {\n    \"selector\": \".site-state\",\n    \"text\": [\"这是文章的统计信息～\", \"要不要点进去看看？\"]\n  }, {\n    \"selector\": \".feed-link a\",\n    \"text\": [\"这里可以使用 RSS 订阅呢！\", \"利用 feed 订阅器，就能快速知道博客有没有更新了呢。\"]\n  }, {\n    \"selector\": \".cc-opacity, .post-copyright-author\",\n    \"text\": [\"要记得规范转载哦。\", \"所有文章均采用 CC BY-NC-SA 4.0 许可协议～\", \"转载前要先注意下文章的版权协议呢。\"]\n  }, {\n    \"selector\": \".links-of-author\",\n    \"text\": [\"这里是主人的常驻地址哦。\", \"这里有主人的联系方式！\"]\n  }, {\n    \"selector\": \".followme\",\n    \"text\": [\"手机扫一下就能继续看，很方便呢～\", \"扫一扫，打开新世界的大门！\"]\n  }, {\n    \"selector\": \".fancybox img, img.medium-zoom-image\",\n    \"text\": [\"点击图片可以放大呢！\"]\n  }, {\n    \"selector\": \".copy-btn\",\n    \"text\": [\"代码可以直接点击复制哟。\"]\n  }, {\n    \"selector\": \".highlight .table-container, .gist\",\n    \"text\": [\"GitHub！我是新手！\", \"PHP 是最好的语言！\"]\n  }, {\n    \"selector\": \"a[href^='mailto']\",\n    \"text\": [\"邮件我会及时回复的！\", \"点击就可以发送邮件啦～\"]\n  }, {\n    \"selector\": \"a[href^='/tags/']\",\n    \"text\": [\"要去看看 <span>{text}</span> 标签么？\", \"点它可以查看此标签下的所有文章哟！\"]\n  }, {\n    \"selector\": \"a[href^='/categories/']\",\n    \"text\": [\"要去看看 <span>{text}</span> 分类么？\", \"点它可以查看此分类下的所有文章哟！\"]\n  }, {\n    \"selector\": \".post-title-link\",\n    \"text\": [\"要看看 <span>{text}</span> 这篇文章吗？\"]\n  }, {\n    \"selector\": \"a[rel='contents']\",\n    \"text\": [\"点击来阅读全文哦。\"]\n  }, {\n    \"selector\": \"a[itemprop='discussionUrl']\",\n    \"text\": [\"要去看看评论吗？\"]\n  }, {\n    \"selector\": \".beian a\",\n    \"text\": [\"我也是有户口的人哦。\", \"我的主人可是遵纪守法的好主人。\"]\n  }, {\n    \"selector\": \".container a[href^='http'], .nav-link .nav-text\",\n    \"text\": [\"要去看看 <span>{text}</span> 么？\", \"去 <span>{text}</span> 逛逛吧。\", \"到 <span>{text}</span> 看看吧。\"]\n  }, {\n    \"selector\": \".back-to-top\",\n    \"text\": [\"点它就可以回到顶部啦！\", \"又回到最初的起点～\", \"要回到开始的地方么？\"]\n  }, {\n    \"selector\": \".reward-container\",\n    \"text\": [\"我是不是棒棒哒～快给我点赞吧！\", \"要打赏我嘛？好期待啊～\", \"主人最近在吃土呢，很辛苦的样子，给他一些钱钱吧～\"]\n  }, {\n    \"selector\": \"#wechat\",\n    \"text\": [\"这是我的微信二维码～\"]\n  }, {\n    \"selector\": \"#alipay\",\n    \"text\": [\"这是我的支付宝哦！\"]\n  }, {\n    \"selector\": \"#bitcoin\",\n    \"text\": [\"这是我的比特币账号！\"]\n  }, {\n    \"selector\": \"#needsharebutton-postbottom .btn\",\n    \"text\": [\"好东西要让更多人知道才行哦。\", \"觉得文章有帮助的话，可以分享给更多需要的朋友呢。\"]\n  }, {\n    \"selector\": \".need-share-button_weibo\",\n    \"text\": [\"微博？来分享一波喵！\"]\n  }, {\n    \"selector\": \".need-share-button_wechat\",\n    \"text\": [\"分享到微信吧！\"]\n  }, {\n    \"selector\": \".need-share-button_douban\",\n    \"text\": [\"分享到豆瓣好像也不错！\"]\n  }, {\n    \"selector\": \".need-share-button_qqzone\",\n    \"text\": [\"QQ 空间，一键转发，耶～\"]\n  }, {\n    \"selector\": \".need-share-button_twitter\",\n    \"text\": [\"Twitter？好像是不存在的东西？\"]\n  }, {\n    \"selector\": \".need-share-button_facebook\",\n    \"text\": [\"emmm…FB 好像也是不存在的东西？\"]\n  }, {\n    \"selector\": \".post-nav-item a[rel='next']\",\n    \"text\": [\"来看看下一篇文章吧。\", \"点它可以看下一篇文章哦！\", \"要翻到下一篇文章吗？\"]\n  }, {\n    \"selector\": \".post-nav-item a[rel='prev']\",\n    \"text\": [\"来看看上一篇文章吧。\", \"点它可以看上一篇文章哦！\", \"要翻到上一篇文章吗？\"]\n  }, {\n    \"selector\": \".extend.next\",\n    \"text\": [\"去下一页看看吧。\", \"点它可以前进哦！\", \"要翻到下一页吗？\"]\n  }, {\n    \"selector\": \".extend.prev\",\n    \"text\": [\"去上一页看看吧。\", \"点它可以后退哦！\", \"要翻到上一页吗？\"]\n  }, {\n    \"selector\": \"input.vnick\",\n    \"text\": [\"该怎么称呼你呢？\", \"留下你的尊姓大名！\"]\n  }, {\n    \"selector\": \".vmail\",\n    \"text\": [\"留下你的邮箱，不然就是无头像人士了！\", \"记得设置好 Gravatar 头像哦！\", \"为了方便通知你最新消息，一定要留下邮箱！\"]\n  }, {\n    \"selector\": \".vlink\",\n    \"text\": [\"快快告诉我你的家在哪里，好让我去参观参观！\"]\n  }, {\n    \"selector\": \".veditor\",\n    \"text\": [\"想要去评论些什么吗？\", \"要说点什么吗？\", \"觉得博客不错？快来留言和主人交流吧！\"]\n  }, {\n    \"selector\": \".vcontrol a\",\n    \"text\": [\"你会不会熟练使用 Markdown 呀？\", \"使用 Markdown 让评论更美观吧～\"]\n  }, {\n    \"selector\": \".vemoji-btn\",\n    \"text\": [\"要插入一个萌萌哒的表情吗？\", \"要来一发表情吗？\"]\n  }, {\n    \"selector\": \".vpreview-btn\",\n    \"text\": [\"要预览一下你的发言吗？\", \"快看看你的评论有多少负熵！\"]\n  }, {\n    \"selector\": \".vsubmit\",\n    \"text\": [\"评论没有审核，要对自己的发言负责哦～\", \"要提交了吗，请耐心等待回复哦～\"]\n  }, {\n    \"selector\": \".vcontent\",\n    \"text\": [\"哇，快看看这个精彩评论！\", \"如果有疑问，请尽快留言哦～\"]\n  }],\n  \"click\": [{\n    \"selector\": \".veditor\",\n    \"text\": [\"要吐槽些什么呢？\", \"一定要认真填写喵～\", \"有什么想说的吗？\"]\n  }, {\n    \"selector\": \".vsubmit\",\n    \"text\": [\"输入验证码就可以提交评论啦～\"]\n  }],\n  \"seasons\": [{\n    \"date\": \"01/01\",\n    \"text\": \"<span>元旦</span>了呢，新的一年又开始了，今年是{year}年～\"\n  }, {\n    \"date\": \"02/14\",\n    \"text\": \"又是一年<span>情人节</span>，{year}年找到对象了嘛～\"\n  }, {\n    \"date\": \"03/08\",\n    \"text\": \"今天是<span>国际妇女节</span>！\"\n  }, {\n    \"date\": \"03/12\",\n    \"text\": \"今天是<span>植树节</span>，要保护环境呀！\"\n  }, {\n    \"date\": \"04/01\",\n    \"text\": \"悄悄告诉你一个秘密～<span>今天是愚人节，不要被骗了哦～</span>\"\n  }, {\n    \"date\": \"05/01\",\n    \"text\": \"今天是<span>五一劳动节</span>，计划好假期去哪里了吗～\"\n  }, {\n    \"date\": \"06/01\",\n    \"text\": \"<span>儿童节</span>了呢，快活的时光总是短暂，要是永远长不大该多好啊…\"\n  }, {\n    \"date\": \"09/03\",\n    \"text\": \"<span>中国人民抗日战争胜利纪念日</span>，铭记历史、缅怀先烈、珍爱和平、开创未来。\"\n  }, {\n    \"date\": \"09/10\",\n    \"text\": \"<span>教师节</span>，在学校要给老师问声好呀～\"\n  }, {\n    \"date\": \"10/01\",\n    \"text\": \"<span>国庆节</span>到了，为祖国母亲庆生！\"\n  }, {\n    \"date\": \"11/05-11/12\",\n    \"text\": \"今年的<span>双十一</span>是和谁一起过的呢～\"\n  }, {\n    \"date\": \"12/20-12/31\",\n    \"text\": \"这几天是<span>圣诞节</span>，主人肯定又去剁手买买买了～\"\n  }],\n  \"time\": [{\n    \"hour\": \"6-7\",\n    \"text\": \"早上好！一日之计在于晨，美好的一天就要开始了～\"\n  }, {\n    \"hour\": \"8-11\",\n    \"text\": \"上午好！工作顺利嘛，不要久坐，多起来走动走动哦！\"\n  }, {\n    \"hour\": \"12-13\",\n    \"text\": \"中午了，工作了一个上午，现在是午餐时间！\"\n  }, {\n    \"hour\": \"14-17\",\n    \"text\": \"午后很容易犯困呢，今天的运动目标完成了吗？\"\n  }, {\n    \"hour\": \"18-19\",\n    \"text\": \"傍晚了！窗外夕阳的景色很美丽呢，最美不过夕阳红～\"\n  }, {\n    \"hour\": \"20-21\",\n    \"text\": \"晚上好，今天过得怎么样？\"\n  }, {\n    \"hour\": \"22-23\",\n    \"text\": [\"已经这么晚了呀，早点休息吧，晚安～\", \"深夜时要爱护眼睛呀！\"]\n  }, {\n    \"hour\": \"0-5\",\n    \"text\": \"你是夜猫子呀？这么晚还不睡觉，明天起的来嘛？\"\n  }],\n  \"message\": {\n    \"default\": [\"好久不见，日子过得好快呢……\", \"大坏蛋！你都多久没理人家了呀，嘤嘤嘤～\", \"嗨～快来逗我玩吧！\", \"拿小拳拳锤你胸口！\", \"记得把小家加入收藏夹哦！\"],\n    \"console\": \"哈哈，你打开了控制台，是想要看看我的小秘密吗？\",\n    \"copy\": \"你都复制了些什么呀，转载要记得加上出处哦！\",\n    \"visibilitychange\": \"哇，你终于回来了～\",\n    \"changeSuccess\": \"我的新衣服好看嘛？\",\n    \"changeFail\": \"我还没有其他衣服呢！\",\n    \"photo\": \"照好了嘛，是不是很可爱呢？\",\n    \"goodbye\": \"愿你有一天能与重要的人重逢。\",\n    \"hitokoto\": \"这句一言来自 <span>「$1」</span>，是 <span>$2</span> 在 hitokoto.cn 投稿的。\",\n    \"welcome\": \"欢迎阅读<span>「$1」</span>\",\n    \"referrer\": \"Hello！来自 <span>$1</span> 的朋友\",\n    \"hoverBody\": [\"干嘛呢你，快把手拿开～～\", \"鼠…鼠标放错地方了！\", \"你要干嘛呀？\", \"喵喵喵？\", \"怕怕(ノ≧∇≦)ノ\", \"非礼呀！救命！\", \"这样的话，只能使用武力了！\", \"我要生气了哦\", \"不要动手动脚的！\", \"真…真的是不知羞耻！\", \"Hentai！\"],\n    \"tapBody\": [\"是…是不小心碰到了吧…\", \"萝莉控是什么呀？\", \"你看到我的小熊了吗？\", \"再摸的话我可要报警了！⌇●﹏●⌇\", \"110 吗，这里有个变态一直在摸我(ó﹏ò｡)\", \"不要摸我了，我会告诉老婆来打你的！\", \"干嘛动我呀！小心我咬你！\", \"别摸我，有什么好摸的！\"]\n  },\n  \"models\": [{\n    \"name\": \"Potion-Maker/Pio\",\n    \"paths\": [\"https://fastly.jsdelivr.net/gh/fghrsh/live2d_api/model/Potion-Maker/Pio/index.json\"],\n    \"message\": \"来自 Potion Maker 的 Pio 酱 ~\"\n  }, {\n    \"name\": \"Potion-Maker/Tia\",\n    \"paths\": [\"https://fastly.jsdelivr.net/gh/fghrsh/live2d_api/model/Potion-Maker/Tia/index.json\"],\n    \"message\": \"来自 Potion Maker 的 Tia 酱 ~\"\n  }, {\n    \"name\": \"HyperdimensionNeptunia\",\n    \"paths\": [\n      \"https://fastly.jsdelivr.net/gh/fghrsh/live2d_api/model/HyperdimensionNeptunia/neptune_classic/index.json\",\n      \"https://fastly.jsdelivr.net/gh/fghrsh/live2d_api/model/HyperdimensionNeptunia/nepnep/index.json\",\n      \"https://fastly.jsdelivr.net/gh/fghrsh/live2d_api/model/HyperdimensionNeptunia/neptune_santa/index.json\",\n      \"https://fastly.jsdelivr.net/gh/fghrsh/live2d_api/model/HyperdimensionNeptunia/nepmaid/index.json\",\n      \"https://fastly.jsdelivr.net/gh/fghrsh/live2d_api/model/HyperdimensionNeptunia/nepswim/index.json\",\n      \"https://fastly.jsdelivr.net/gh/fghrsh/live2d_api/model/HyperdimensionNeptunia/noir_classic/index.json\",\n      \"https://fastly.jsdelivr.net/gh/fghrsh/live2d_api/model/HyperdimensionNeptunia/noir/index.json\",\n      \"https://fastly.jsdelivr.net/gh/fghrsh/live2d_api/model/HyperdimensionNeptunia/noir_santa/index.json\",\n      \"https://fastly.jsdelivr.net/gh/fghrsh/live2d_api/model/HyperdimensionNeptunia/noireswim/index.json\",\n      \"https://fastly.jsdelivr.net/gh/fghrsh/live2d_api/model/HyperdimensionNeptunia/blanc_classic/index.json\",\n      \"https://fastly.jsdelivr.net/gh/fghrsh/live2d_api/model/HyperdimensionNeptunia/blanc_normal/index.json\",\n      \"https://fastly.jsdelivr.net/gh/fghrsh/live2d_api/model/HyperdimensionNeptunia/blanc_swimwear/index.json\",\n      \"https://fastly.jsdelivr.net/gh/fghrsh/live2d_api/model/HyperdimensionNeptunia/vert_classic/index.json\",\n      \"https://fastly.jsdelivr.net/gh/fghrsh/live2d_api/model/HyperdimensionNeptunia/vert_normal/index.json\",\n      \"https://fastly.jsdelivr.net/gh/fghrsh/live2d_api/model/HyperdimensionNeptunia/vert_swimwear/index.json\",\n      \"https://fastly.jsdelivr.net/gh/fghrsh/live2d_api/model/HyperdimensionNeptunia/nepgear/index.json\",\n      \"https://fastly.jsdelivr.net/gh/fghrsh/live2d_api/model/HyperdimensionNeptunia/nepgear_extra/index.json\",\n      \"https://fastly.jsdelivr.net/gh/fghrsh/live2d_api/model/HyperdimensionNeptunia/nepgearswim/index.json\",\n      \"https://fastly.jsdelivr.net/gh/fghrsh/live2d_api/model/HyperdimensionNeptunia/histoire/index.json\",\n      \"https://fastly.jsdelivr.net/gh/fghrsh/live2d_api/model/HyperdimensionNeptunia/histoirenohover\"\n    ],\n    \"message\": \"Nep! Nep! 超次元游戏：海王星 系列\"\n  }, {\n    \"name\": \"Hiyori\",\n    \"paths\": [\"https://fastly.jsdelivr.net/gh/Live2D/CubismWebSamples/Samples/Resources/Hiyori/Hiyori.model3.json\"],\n    \"message\": \"是 Hiyori 哦 ~\"\n  }]\n}\n"
  },
  {
    "path": "dist/waifu.css",
    "content": "#waifu-toggle {\n\tbackground-color: #fa0;\n\tborder-radius: 5px;\n\tbottom: 66px;\n\tcursor: pointer;\n\tdisplay: flex;\n\tjustify-content: flex-end;\n\tleft: 0;\n\tmargin-left: -100px;\n\tpadding: 5px;\n\tposition: fixed;\n\ttransition: margin-left 1s;\n\twidth: 60px;\n}\n\n#waifu-toggle.waifu-toggle-active {\n\tmargin-left: -50px;\n}\n\n#waifu-toggle.waifu-toggle-active:hover {\n\tmargin-left: -30px;\n}\n\n#waifu-toggle svg {\n\tfill: #fff;\n\theight: 25px;\n}\n\n#waifu {\n\tbottom: -500px;\n\tleft: 0;\n\tposition: fixed;\n\ttransform: translateY(25px);\n\ttransition: transform .3s ease-in-out, bottom 3s ease-in-out;\n\tz-index: 1;\n}\n\n#waifu.waifu-active {\n\tbottom: 0;\n}\n\n#waifu.waifu-hidden {\n\tdisplay: none;\n}\n\n#waifu:hover {\n\ttransform: translateY(20px);\n}\n\n#waifu-tips {\n\tanimation: waifu-shake 50s ease-in-out 5s infinite;\n\tbackground-color: rgba(236, 217, 188, .5);\n\tborder: 1px solid rgba(224, 186, 140, .62);\n\tborder-radius: 12px;\n\tbox-shadow: 0 3px 15px 2px rgba(191, 158, 118, .2);\n\tfont-size: 14px;\n\tline-height: 24px;\n\tmargin: -30px 20px;\n\tmin-height: 70px;\n\topacity: 0;\n\toverflow: hidden;\n\tpadding: 5px 10px;\n\tposition: absolute;\n\ttext-overflow: ellipsis;\n\ttransition: opacity 1s;\n\twidth: 250px;\n\tword-break: break-all;\n}\n\n#waifu-tips.waifu-tips-active {\n\topacity: 1;\n\ttransition: opacity .2s;\n}\n\n#waifu-tips span {\n\tcolor: #0099cc;\n}\n\n#live2d {\n\tcursor: grab;\n\theight: 300px;\n\tposition: relative;\n\twidth: 300px;\n}\n\n#live2d:active {\n\tcursor: grabbing;\n}\n\n#waifu-tool {\n\talign-items: center;\n\tdisplay: flex;\n\tflex-direction: column;\n\tgap: 5px;\n\topacity: 0;\n\tposition: absolute;\n\tright: -10px;\n\ttop: 70px;\n\ttransition: opacity 1s;\n}\n\n#waifu:hover #waifu-tool {\n\topacity: 1;\n}\n\n#waifu-tool svg {\n\tcursor: pointer;\n\tdisplay: block;\n\tfill: #7b8c9d;\n\theight: 25px;\n\ttransition: fill .3s;\n}\n\n#waifu-tool svg:hover {\n\tfill: #0684bd; /* #34495e */\n}\n\n@keyframes waifu-shake {\n\t2% {\n\t\ttransform: translate(.5px, -1.5px) rotate(-.5deg);\n\t}\n\t4% {\n\t\ttransform: translate(.5px, 1.5px) rotate(1.5deg);\n\t}\n\t6% {\n\t\ttransform: translate(1.5px, 1.5px) rotate(1.5deg);\n\t}\n\t8% {\n\t\ttransform: translate(2.5px, 1.5px) rotate(.5deg);\n\t}\n\t10% {\n\t\ttransform: translate(.5px, 2.5px) rotate(.5deg);\n\t}\n\t12% {\n\t\ttransform: translate(1.5px, 1.5px) rotate(.5deg);\n\t}\n\t14% {\n\t\ttransform: translate(.5px, .5px) rotate(.5deg);\n\t}\n\t16% {\n\t\ttransform: translate(-1.5px, -.5px) rotate(1.5deg);\n\t}\n\t18% {\n\t\ttransform: translate(.5px, .5px) rotate(1.5deg);\n\t}\n\t20% {\n\t\ttransform: translate(2.5px, 2.5px) rotate(1.5deg);\n\t}\n\t22% {\n\t\ttransform: translate(.5px, -1.5px) rotate(1.5deg);\n\t}\n\t24% {\n\t\ttransform: translate(-1.5px, 1.5px) rotate(-.5deg);\n\t}\n\t26% {\n\t\ttransform: translate(1.5px, .5px) rotate(1.5deg);\n\t}\n\t28% {\n\t\ttransform: translate(-.5px, -.5px) rotate(-.5deg);\n\t}\n\t30% {\n\t\ttransform: translate(1.5px, -.5px) rotate(-.5deg);\n\t}\n\t32% {\n\t\ttransform: translate(2.5px, -1.5px) rotate(1.5deg);\n\t}\n\t34% {\n\t\ttransform: translate(2.5px, 2.5px) rotate(-.5deg);\n\t}\n\t36% {\n\t\ttransform: translate(.5px, -1.5px) rotate(.5deg);\n\t}\n\t38% {\n\t\ttransform: translate(2.5px, -.5px) rotate(-.5deg);\n\t}\n\t40% {\n\t\ttransform: translate(-.5px, 2.5px) rotate(.5deg);\n\t}\n\t42% {\n\t\ttransform: translate(-1.5px, 2.5px) rotate(.5deg);\n\t}\n\t44% {\n\t\ttransform: translate(-1.5px, 1.5px) rotate(.5deg);\n\t}\n\t46% {\n\t\ttransform: translate(1.5px, -.5px) rotate(-.5deg);\n\t}\n\t48% {\n\t\ttransform: translate(2.5px, -.5px) rotate(.5deg);\n\t}\n\t50% {\n\t\ttransform: translate(-1.5px, 1.5px) rotate(.5deg);\n\t}\n\t52% {\n\t\ttransform: translate(-.5px, 1.5px) rotate(.5deg);\n\t}\n\t54% {\n\t\ttransform: translate(-1.5px, 1.5px) rotate(.5deg);\n\t}\n\t56% {\n\t\ttransform: translate(.5px, 2.5px) rotate(1.5deg);\n\t}\n\t58% {\n\t\ttransform: translate(2.5px, 2.5px) rotate(.5deg);\n\t}\n\t60% {\n\t\ttransform: translate(2.5px, -1.5px) rotate(1.5deg);\n\t}\n\t62% {\n\t\ttransform: translate(-1.5px, .5px) rotate(1.5deg);\n\t}\n\t64% {\n\t\ttransform: translate(-1.5px, 1.5px) rotate(1.5deg);\n\t}\n\t66% {\n\t\ttransform: translate(.5px, 2.5px) rotate(1.5deg);\n\t}\n\t68% {\n\t\ttransform: translate(2.5px, -1.5px) rotate(1.5deg);\n\t}\n\t70% {\n\t\ttransform: translate(2.5px, 2.5px) rotate(.5deg);\n\t}\n\t72% {\n\t\ttransform: translate(-.5px, -1.5px) rotate(1.5deg);\n\t}\n\t74% {\n\t\ttransform: translate(-1.5px, 2.5px) rotate(1.5deg);\n\t}\n\t76% {\n\t\ttransform: translate(-1.5px, 2.5px) rotate(1.5deg);\n\t}\n\t78% {\n\t\ttransform: translate(-1.5px, 2.5px) rotate(.5deg);\n\t}\n\t80% {\n\t\ttransform: translate(-1.5px, .5px) rotate(-.5deg);\n\t}\n\t82% {\n\t\ttransform: translate(-1.5px, .5px) rotate(-.5deg);\n\t}\n\t84% {\n\t\ttransform: translate(-.5px, .5px) rotate(1.5deg);\n\t}\n\t86% {\n\t\ttransform: translate(2.5px, 1.5px) rotate(.5deg);\n\t}\n\t88% {\n\t\ttransform: translate(-1.5px, .5px) rotate(1.5deg);\n\t}\n\t90% {\n\t\ttransform: translate(-1.5px, -.5px) rotate(-.5deg);\n\t}\n\t92% {\n\t\ttransform: translate(-1.5px, -1.5px) rotate(1.5deg);\n\t}\n\t94% {\n\t\ttransform: translate(.5px, .5px) rotate(-.5deg);\n\t}\n\t96% {\n\t\ttransform: translate(2.5px, -.5px) rotate(-.5deg);\n\t}\n\t98% {\n\t\ttransform: translate(-1.5px, -1.5px) rotate(-.5deg);\n\t}\n\t0%, 100% {\n\t\ttransform: translate(0, 0) rotate(0);\n\t}\n}\n"
  },
  {
    "path": "eslint.config.js",
    "content": "// @ts-check\n\nimport eslint from '@eslint/js';\nimport tseslint from 'typescript-eslint';\n\nexport default tseslint.config(\n  eslint.configs.recommended,\n  tseslint.configs.recommended,\n  {\n    rules: {\n      '@typescript-eslint/no-explicit-any': 'off',\n      quotes: ['error', 'single'],\n      indent: ['error', 2],\n    }\n  },\n  {\n    ignores: [\n      'src/CubismSdkForWeb-*/**',\n      'dist/**',\n      'build/**',\n      'node_modules/**'\n    ]\n  }\n);\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"live2d-widgets\",\n  \"version\": \"1.0.0\",\n  \"description\": \"Live2D widget for web pages\",\n  \"main\": \"build/index.js\",\n  \"files\": [\n    \"build\",\n    \"!build/CubismSdkForWeb*\",\n    \"demo\",\n    \"dist\",\n    \"src\",\n    \"!src/CubismSdkForWeb*\",\n    \"README.en.md\"\n  ],\n  \"types\": \"build/index.d.ts\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"build\": \"tsc && rollup -c rollup.config.js\",\n    \"build-dev\": \"rollup -c rollup.config.js -w\",\n    \"eslint\": \"eslint src/\",\n    \"prepublishOnly\": \"npm run build\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/stevenjoezhang/live2d-widget.git\"\n  },\n  \"keywords\": [\n    \"Live2D\",\n    \"WebGL\"\n  ],\n  \"author\": \"stevenjoezhang <stevenjoezhang@gmail.com>\",\n  \"license\": \"GPL-3.0-or-later\",\n  \"bugs\": {\n    \"url\": \"https://github.com/stevenjoezhang/live2d-widget/issues\"\n  },\n  \"homepage\": \"https://github.com/stevenjoezhang/live2d-widget#readme\",\n  \"dependencies\": {\n    \"@fortawesome/fontawesome-free\": \"6.7.2\"\n  },\n  \"devDependencies\": {\n    \"@eslint/js\": \"9.38.0\",\n    \"@rollup/plugin-alias\": \"5.1.1\",\n    \"@rollup/plugin-terser\": \"0.4.4\",\n    \"@types/node\": \"22.18.11\",\n    \"eslint\": \"9.38.0\",\n    \"rollup\": \"4.52.5\",\n    \"typescript\": \"5.9.3\",\n    \"typescript-eslint\": \"8.46.1\"\n  }\n}\n"
  },
  {
    "path": "renovate.json",
    "content": "{\n  \"$schema\": \"https://docs.renovatebot.com/renovate-schema.json\",\n  \"extends\": [\n    \"config:recommended\"\n  ]\n}\n"
  },
  {
    "path": "rollup.config.js",
    "content": "import terser from '@rollup/plugin-terser';\nimport alias from '@rollup/plugin-alias';\nimport fs from 'fs';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\nfunction findCubismDir() {\n  const buildDir = path.join(__dirname, 'build');\n  let candidates = fs.readdirSync(buildDir)\n    .filter(f => f.startsWith('CubismSdkForWeb-') && fs.statSync(path.join(buildDir, f)).isDirectory());\n  if (candidates.length === 0) {\n    candidates = ['CubismSdkForWeb-5-r.4'];\n  }\n  return path.join(buildDir, candidates[0]);\n}\n\nconst cubismDir = findCubismDir();\n\nexport default {\n  input: 'build/waifu-tips.js',\n  output: {\n    dir: 'dist/',\n    format: 'esm',\n    chunkFileNames: 'chunk/[name].js',\n    sourcemap: true,\n    banner: `/*!\n * Live2D Widget\n * https://github.com/stevenjoezhang/live2d-widget\n */\n`\n  },\n  plugins: [\n    alias({\n      entries: [\n        {\n          find: '@demo',\n          replacement: path.resolve(cubismDir, 'Samples/TypeScript/Demo/src/')\n        },\n        {\n          find: '@framework',\n          replacement: path.resolve(cubismDir, 'Framework/src/')\n        }\n      ]\n    }),\n    terser(),\n  ],\n  context: 'this',\n};\n"
  },
  {
    "path": "src/cubism2/LAppDefine.js",
    "content": "const LAppDefine = {\n  VIEW_MAX_SCALE: 1.5,\n  VIEW_MIN_SCALE: 1,\n\n  VIEW_LOGICAL_LEFT: -1,\n  VIEW_LOGICAL_RIGHT: 1,\n\n  VIEW_LOGICAL_MAX_LEFT: -2,\n  VIEW_LOGICAL_MAX_RIGHT: 2,\n  VIEW_LOGICAL_MAX_BOTTOM: -2,\n  VIEW_LOGICAL_MAX_TOP: 2,\n\n  PRIORITY_NONE: 0,\n  PRIORITY_IDLE: 1,\n  PRIORITY_NORMAL: 2,\n  PRIORITY_FORCE: 3,\n\n  MOTION_GROUP_IDLE: 'idle',\n  MOTION_GROUP_TAP_BODY: 'tap_body',\n  MOTION_GROUP_FLICK_HEAD: 'flick_head',\n  MOTION_GROUP_PINCH_IN: 'pinch_in',\n  MOTION_GROUP_PINCH_OUT: 'pinch_out',\n  MOTION_GROUP_SHAKE: 'shake',\n\n  HIT_AREA_HEAD: 'head',\n  HIT_AREA_BODY: 'body',\n};\n\nexport default LAppDefine;\n"
  },
  {
    "path": "src/cubism2/LAppLive2DManager.js",
    "content": "/* global Live2D */\nimport { Live2DFramework } from './Live2DFramework.js';\nimport LAppModel from './LAppModel.js';\nimport PlatformManager from './PlatformManager.js';\nimport LAppDefine from './LAppDefine.js';\nimport logger from '../logger.js';\n\nclass LAppLive2DManager {\n  constructor() {\n    this.model = null;\n    this.reloading = false;\n\n    Live2D.init();\n    Live2DFramework.setPlatformManager(new PlatformManager());\n  }\n\n  getModel() {\n    return this.model;\n  }\n\n  releaseModel(gl) {\n    if (this.model) {\n      this.model.release(gl);\n      this.model = null;\n    }\n  }\n\n  async changeModel(gl, modelSettingPath) {\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    return new Promise((resolve, reject) => {\n      if (this.reloading) return;\n      this.reloading = true;\n\n      const oldModel = this.model;\n      const newModel = new LAppModel();\n\n      newModel.load(gl, modelSettingPath, () => {\n        if (oldModel) {\n          oldModel.release(gl);\n        }\n        this.model = newModel;\n        this.reloading = false;\n        resolve();\n      });\n    });\n  }\n\n  async changeModelWithJSON(gl, modelSettingPath, modelSetting) {\n    if (this.reloading) return;\n    this.reloading = true;\n\n    const oldModel = this.model;\n    const newModel = new LAppModel();\n\n    await newModel.loadModelSetting(modelSettingPath, modelSetting);\n    if (oldModel) {\n      oldModel.release(gl);\n    }\n    this.model = newModel;\n    this.reloading = false;\n  }\n\n  setDrag(x, y) {\n    if (this.model) {\n      this.model.setDrag(x, y);\n    }\n  }\n\n  maxScaleEvent() {\n    logger.trace('Max scale event.');\n    if (this.model) {\n      this.model.startRandomMotion(\n        LAppDefine.MOTION_GROUP_PINCH_IN,\n        LAppDefine.PRIORITY_NORMAL,\n      );\n    }\n  }\n\n  minScaleEvent() {\n    logger.trace('Min scale event.');\n    if (this.model) {\n      this.model.startRandomMotion(\n        LAppDefine.MOTION_GROUP_PINCH_OUT,\n        LAppDefine.PRIORITY_NORMAL,\n      );\n    }\n  }\n\n  tapEvent(x, y) {\n    logger.trace('tapEvent view x:' + x + ' y:' + y);\n\n    if (!this.model) return false;\n\n    if (this.model.hitTest(LAppDefine.HIT_AREA_HEAD, x, y)) {\n      logger.trace('Tap face.');\n      this.model.setRandomExpression();\n    } else if (this.model.hitTest(LAppDefine.HIT_AREA_BODY, x, y)) {\n      logger.trace('Tap body.');\n      this.model.startRandomMotion(\n        LAppDefine.MOTION_GROUP_TAP_BODY,\n        LAppDefine.PRIORITY_NORMAL,\n      );\n    }\n    return true;\n  }\n}\n\nexport default LAppLive2DManager;\n"
  },
  {
    "path": "src/cubism2/LAppModel.js",
    "content": "/* global UtSystem, document */\nimport { L2DBaseModel, Live2DFramework, L2DEyeBlink } from './Live2DFramework.js';\nimport ModelSettingJson from './utils/ModelSettingJson.js';\nimport LAppDefine from './LAppDefine.js';\nimport MatrixStack from './utils/MatrixStack.js';\nimport logger from '../logger.js';\n\n//============================================================\n//============================================================\n//  class LAppModel     extends L2DBaseModel\n//============================================================\n//============================================================\nclass LAppModel extends L2DBaseModel {\n  constructor() {\n    //L2DBaseModel.apply(this, arguments);\n    super();\n\n    this.modelHomeDir = '';\n    this.modelSetting = null;\n    this.tmpMatrix = [];\n  }\n\n  loadJSON(callback) {\n    const path = this.modelHomeDir + this.modelSetting.getModelFile();\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    this.loadModelData(path, model => {\n      for (let i = 0; i < this.modelSetting.getTextureNum(); i++) {\n        const texPaths =\n          this.modelHomeDir + this.modelSetting.getTextureFile(i);\n\n        this.loadTexture(i, texPaths, () => {\n          if (this.isTexLoaded) {\n            if (this.modelSetting.getExpressionNum() > 0) {\n              this.expressions = {};\n\n              for (\n                let j = 0;\n                j < this.modelSetting.getExpressionNum();\n                j++\n              ) {\n                const expName = this.modelSetting.getExpressionName(j);\n                const expFilePath =\n                  this.modelHomeDir +\n                  this.modelSetting.getExpressionFile(j);\n\n                this.loadExpression(expName, expFilePath);\n              }\n            } else {\n              this.expressionManager = null;\n              this.expressions = {};\n            }\n\n            if (this.eyeBlink == null) {\n              this.eyeBlink = new L2DEyeBlink();\n            }\n\n            if (this.modelSetting.getPhysicsFile() != null) {\n              this.loadPhysics(\n                this.modelHomeDir + this.modelSetting.getPhysicsFile(),\n              );\n            } else {\n              this.physics = null;\n            }\n\n            if (this.modelSetting.getPoseFile() != null) {\n              this.loadPose(\n                this.modelHomeDir + this.modelSetting.getPoseFile(),\n                () => {\n                  this.pose.updateParam(this.live2DModel);\n                },\n              );\n            } else {\n              this.pose = null;\n            }\n\n            if (this.modelSetting.getLayout() != null) {\n              const layout = this.modelSetting.getLayout();\n              if (layout['width'] != null)\n                this.modelMatrix.setWidth(layout['width']);\n              if (layout['height'] != null)\n                this.modelMatrix.setHeight(layout['height']);\n\n              if (layout['x'] != null) this.modelMatrix.setX(layout['x']);\n              if (layout['y'] != null) this.modelMatrix.setY(layout['y']);\n              if (layout['center_x'] != null)\n                this.modelMatrix.centerX(layout['center_x']);\n              if (layout['center_y'] != null)\n                this.modelMatrix.centerY(layout['center_y']);\n              if (layout['top'] != null)\n                this.modelMatrix.top(layout['top']);\n              if (layout['bottom'] != null)\n                this.modelMatrix.bottom(layout['bottom']);\n              if (layout['left'] != null)\n                this.modelMatrix.left(layout['left']);\n              if (layout['right'] != null)\n                this.modelMatrix.right(layout['right']);\n            }\n\n            for (let j = 0; j < this.modelSetting.getInitParamNum(); j++) {\n              this.live2DModel.setParamFloat(\n                this.modelSetting.getInitParamID(j),\n                this.modelSetting.getInitParamValue(j),\n              );\n            }\n\n            for (\n              let j = 0;\n              j < this.modelSetting.getInitPartsVisibleNum();\n              j++\n            ) {\n              this.live2DModel.setPartsOpacity(\n                this.modelSetting.getInitPartsVisibleID(j),\n                this.modelSetting.getInitPartsVisibleValue(j),\n              );\n            }\n\n            this.live2DModel.saveParam();\n            // this.live2DModel.setGL(gl);\n\n            this.preloadMotionGroup(LAppDefine.MOTION_GROUP_IDLE);\n            this.mainMotionManager.stopAllMotions();\n\n            this.setUpdating(false);\n            this.setInitialized(true);\n\n            if (typeof callback == 'function') callback();\n          }\n        });\n      }\n    });\n  }\n\n  async loadModelSetting(modelSettingPath, modelSetting) {\n    this.setUpdating(true);\n    this.setInitialized(false);\n\n    this.modelHomeDir = modelSettingPath.substring(\n      0,\n      modelSettingPath.lastIndexOf('/') + 1,\n    );\n\n    this.modelSetting = new ModelSettingJson();\n    this.modelSetting.json = modelSetting;\n    await new Promise(resolve => this.loadJSON(resolve));\n  }\n\n  load(gl, modelSettingPath, callback) {\n    this.setUpdating(true);\n    this.setInitialized(false);\n\n    this.modelHomeDir = modelSettingPath.substring(\n      0,\n      modelSettingPath.lastIndexOf('/') + 1,\n    );\n\n    this.modelSetting = new ModelSettingJson();\n\n    this.modelSetting.loadModelSetting(modelSettingPath, () => {\n      this.loadJSON(callback);\n    });\n  }\n\n  release(gl) {\n    // this.live2DModel.deleteTextures();\n    const pm = Live2DFramework.getPlatformManager();\n\n    gl.deleteTexture(pm.texture);\n  }\n\n  preloadMotionGroup(name) {\n    for (let i = 0; i < this.modelSetting.getMotionNum(name); i++) {\n      const file = this.modelSetting.getMotionFile(name, i);\n      this.loadMotion(file, this.modelHomeDir + file, motion => {\n        motion.setFadeIn(this.modelSetting.getMotionFadeIn(name, i));\n        motion.setFadeOut(this.modelSetting.getMotionFadeOut(name, i));\n      });\n    }\n  }\n\n  update() {\n    // logger.trace(\"--> LAppModel.update()\");\n\n    if (this.live2DModel == null) {\n      logger.error('Failed to update.');\n\n      return;\n    }\n\n    const timeMSec = UtSystem.getUserTimeMSec() - this.startTimeMSec;\n    const timeSec = timeMSec / 1000.0;\n    const t = timeSec * 2 * Math.PI;\n\n    if (this.mainMotionManager.isFinished()) {\n      this.startRandomMotion(\n        LAppDefine.MOTION_GROUP_IDLE,\n        LAppDefine.PRIORITY_IDLE,\n      );\n    }\n\n    //-----------------------------------------------------------------\n\n    this.live2DModel.loadParam();\n\n    const update = this.mainMotionManager.updateParam(this.live2DModel);\n    if (!update) {\n      if (this.eyeBlink != null) {\n        this.eyeBlink.updateParam(this.live2DModel);\n      }\n    }\n\n    this.live2DModel.saveParam();\n\n    //-----------------------------------------------------------------\n\n    if (\n      this.expressionManager != null &&\n      this.expressions != null &&\n      !this.expressionManager.isFinished()\n    ) {\n      this.expressionManager.updateParam(this.live2DModel);\n    }\n\n    this.live2DModel.addToParamFloat('PARAM_ANGLE_X', this.dragX * 30, 1);\n    this.live2DModel.addToParamFloat('PARAM_ANGLE_Y', this.dragY * 30, 1);\n    this.live2DModel.addToParamFloat(\n      'PARAM_ANGLE_Z',\n      this.dragX * this.dragY * -30,\n      1,\n    );\n\n    this.live2DModel.addToParamFloat('PARAM_BODY_ANGLE_X', this.dragX * 10, 1);\n\n    this.live2DModel.addToParamFloat('PARAM_EYE_BALL_X', this.dragX, 1);\n    this.live2DModel.addToParamFloat('PARAM_EYE_BALL_Y', this.dragY, 1);\n\n    this.live2DModel.addToParamFloat(\n      'PARAM_ANGLE_X',\n      Number(15 * Math.sin(t / 6.5345)),\n      0.5,\n    );\n    this.live2DModel.addToParamFloat(\n      'PARAM_ANGLE_Y',\n      Number(8 * Math.sin(t / 3.5345)),\n      0.5,\n    );\n    this.live2DModel.addToParamFloat(\n      'PARAM_ANGLE_Z',\n      Number(10 * Math.sin(t / 5.5345)),\n      0.5,\n    );\n    this.live2DModel.addToParamFloat(\n      'PARAM_BODY_ANGLE_X',\n      Number(4 * Math.sin(t / 15.5345)),\n      0.5,\n    );\n    this.live2DModel.setParamFloat(\n      'PARAM_BREATH',\n      Number(0.5 + 0.5 * Math.sin(t / 3.2345)),\n      1,\n    );\n\n    if (this.physics != null) {\n      this.physics.updateParam(this.live2DModel);\n    }\n\n    if (this.lipSync == null) {\n      this.live2DModel.setParamFloat('PARAM_MOUTH_OPEN_Y', this.lipSyncValue);\n    }\n\n    if (this.pose != null) {\n      this.pose.updateParam(this.live2DModel);\n    }\n\n    this.live2DModel.update();\n  }\n\n  setRandomExpression() {\n    const tmp = [];\n    for (const name in this.expressions) {\n      tmp.push(name);\n    }\n\n    const no = parseInt(Math.random() * tmp.length);\n\n    this.setExpression(tmp[no]);\n  }\n\n  startRandomMotion(name, priority) {\n    const max = this.modelSetting.getMotionNum(name);\n    const no = parseInt(Math.random() * max);\n    this.startMotion(name, no, priority);\n  }\n\n  startMotion(name, no, priority) {\n    // logger.trace(\"startMotion : \" + name + \" \" + no + \" \" + priority);\n\n    const motionName = this.modelSetting.getMotionFile(name, no);\n\n    if (motionName == null || motionName == '') {\n      return;\n    }\n\n    if (priority == LAppDefine.PRIORITY_FORCE) {\n      this.mainMotionManager.setReservePriority(priority);\n    } else if (!this.mainMotionManager.reserveMotion(priority)) {\n      logger.trace('Motion is running.');\n      return;\n    }\n\n    let motion;\n\n    if (this.motions[name] == null) {\n      this.loadMotion(null, this.modelHomeDir + motionName, mtn => {\n        motion = mtn;\n\n        this.setFadeInFadeOut(name, no, priority, motion);\n      });\n    } else {\n      motion = this.motions[name];\n\n      this.setFadeInFadeOut(name, no, priority, motion);\n    }\n  }\n\n  setFadeInFadeOut(name, no, priority, motion) {\n    const motionName = this.modelSetting.getMotionFile(name, no);\n\n    motion.setFadeIn(this.modelSetting.getMotionFadeIn(name, no));\n    motion.setFadeOut(this.modelSetting.getMotionFadeOut(name, no));\n\n    logger.trace('Start motion : ' + motionName);\n\n    if (this.modelSetting.getMotionSound(name, no) == null) {\n      this.mainMotionManager.startMotionPrio(motion, priority);\n    } else {\n      const soundName = this.modelSetting.getMotionSound(name, no);\n      // var player = new Sound(this.modelHomeDir + soundName);\n\n      const snd = document.createElement('audio');\n      snd.src = this.modelHomeDir + soundName;\n\n      logger.trace('Start sound : ' + soundName);\n\n      snd.play();\n      this.mainMotionManager.startMotionPrio(motion, priority);\n    }\n  }\n\n  setExpression(name) {\n    const motion = this.expressions[name];\n\n    logger.trace('Expression : ' + name);\n\n    this.expressionManager?.startMotion(motion, false);\n  }\n\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  draw(gl) {\n    //logger.trace(\"--> LAppModel.draw()\");\n\n    // if(this.live2DModel == null) return;\n\n    MatrixStack.push();\n\n    MatrixStack.multMatrix(this.modelMatrix.getArray());\n\n    this.tmpMatrix = MatrixStack.getMatrix();\n    this.live2DModel.setMatrix(this.tmpMatrix);\n    this.live2DModel.draw();\n\n    MatrixStack.pop();\n  }\n\n  hitTest(id, testX, testY) {\n    const len = this.modelSetting.getHitAreaNum();\n    if (len == 0) {\n      const hitAreasCustom = this.modelSetting.getHitAreaCustom();\n      if (hitAreasCustom) {\n        const x = hitAreasCustom[id + '_x'];\n        const y = hitAreasCustom[id + '_y'];\n\n        if (testX > Math.min(...x) && testX < Math.max(...x) &&\n            testY > Math.min(...y) && testY < Math.max(...y)) {\n          return true;\n        }\n      }\n    }\n    for (let i = 0; i < len; i++) {\n      if (id == this.modelSetting.getHitAreaName(i)) {\n        const drawID = this.modelSetting.getHitAreaID(i);\n\n        return this.hitTestSimple(drawID, testX, testY);\n      }\n    }\n\n    return false;\n  }\n}\n\nexport default LAppModel;\n"
  },
  {
    "path": "src/cubism2/Live2DFramework.js",
    "content": "/* global Live2D, Live2DMotion, AMotion, UtSystem, MotionQueueManager, PhysicsHair, UtDebug, PartsDataID */\n/**\n *\n *  You can modify and use this source freely\n *  only for the development of application related Live2D.\n *\n *  (c) Live2D Inc. All rights reserved.\n */\nimport logger from '../logger.js';\n//============================================================\n//============================================================\n//  class L2DBaseModel\n//============================================================\n//============================================================\nclass L2DBaseModel {\n  constructor() {\n    this.live2DModel = null; // ALive2DModel\n    this.modelMatrix = null; // L2DModelMatrix\n    this.eyeBlink = null; // L2DEyeBlink\n    this.physics = null; // L2DPhysics\n    this.pose = null; // L2DPose\n    this.initialized = false;\n    this.updating = false;\n    this.alpha = 1;\n    this.accAlpha = 0;\n    this.lipSync = false;\n    this.lipSyncValue = 0;\n    this.accelX = 0;\n    this.accelY = 0;\n    this.accelZ = 0;\n    this.dragX = 0;\n    this.dragY = 0;\n    this.startTimeMSec = null;\n    this.mainMotionManager = new L2DMotionManager(); //L2DMotionManager\n    this.expressionManager = new L2DMotionManager(); //L2DMotionManager\n    this.motions = {};\n    this.expressions = {};\n\n    this.isTexLoaded = false;\n  }\n\n  //============================================================\n  //    L2DBaseModel # getModelMatrix()\n  //============================================================\n  getModelMatrix() {\n    return this.modelMatrix;\n  }\n\n  //============================================================\n  //    L2DBaseModel # setAlpha()\n  //============================================================\n  setAlpha(a /*float*/) {\n    if (a > 0.999) a = 1;\n    if (a < 0.001) a = 0;\n    this.alpha = a;\n  }\n\n  //============================================================\n  //    L2DBaseModel # getAlpha()\n  //============================================================\n  getAlpha() {\n    return this.alpha;\n  }\n\n  //============================================================\n  //    L2DBaseModel # isInitialized()\n  //============================================================\n  isInitialized() {\n    return this.initialized;\n  }\n\n  //============================================================\n  //    L2DBaseModel # setInitialized()\n  //============================================================\n  setInitialized(v /*boolean*/) {\n    this.initialized = v;\n  }\n\n  //============================================================\n  //    L2DBaseModel # isUpdating()\n  //============================================================\n  isUpdating() {\n    return this.updating;\n  }\n\n  //============================================================\n  //    L2DBaseModel # setUpdating()\n  //============================================================\n  setUpdating(v /*boolean*/) {\n    this.updating = v;\n  }\n\n  //============================================================\n  //    L2DBaseModel # getLive2DModel()\n  //============================================================\n  getLive2DModel() {\n    return this.live2DModel;\n  }\n\n  //============================================================\n  //    L2DBaseModel # setLipSync()\n  //============================================================\n  setLipSync(v /*boolean*/) {\n    this.lipSync = v;\n  }\n\n  //============================================================\n  //    L2DBaseModel # setLipSyncValue()\n  //============================================================\n  setLipSyncValue(v /*float*/) {\n    this.lipSyncValue = v;\n  }\n\n  //============================================================\n  //    L2DBaseModel # setAccel()\n  //============================================================\n  setAccel(x /*float*/, y /*float*/, z /*float*/) {\n    this.accelX = x;\n    this.accelY = y;\n    this.accelZ = z;\n  }\n\n  //============================================================\n  //    L2DBaseModel # setDrag()\n  //============================================================\n  setDrag(x /*float*/, y /*float*/) {\n    this.dragX = x;\n    this.dragY = y;\n  }\n\n  //============================================================\n  //    L2DBaseModel # getMainMotionManager()\n  //============================================================\n  getMainMotionManager() {\n    return this.mainMotionManager;\n  }\n\n  //============================================================\n  //    L2DBaseModel # getExpressionManager()\n  //============================================================\n  getExpressionManager() {\n    return this.expressionManager;\n  }\n\n  //============================================================\n  //    L2DBaseModel # loadModelData()\n  //============================================================\n  loadModelData(path /*String*/, callback) {\n    /*\n        if( this.live2DModel != null ) {\n            this.live2DModel.deleteTextures();\n        }\n        */\n    const pm = Live2DFramework.getPlatformManager(); //IPlatformManager\n    logger.info('Load model : ' + path);\n\n    pm.loadLive2DModel(path, (l2dModel) => {\n      this.live2DModel = l2dModel;\n      this.live2DModel.saveParam();\n\n      const _err = Live2D.getError();\n\n      if (_err != 0) {\n        logger.error('Error : Failed to loadModelData().');\n        return;\n      }\n\n      this.modelMatrix = new L2DModelMatrix(\n        this.live2DModel.getCanvasWidth(),\n        this.live2DModel.getCanvasHeight(),\n      ); //L2DModelMatrix\n      this.modelMatrix.setWidth(2);\n      this.modelMatrix.setCenterPosition(0, 0);\n\n      callback(this.live2DModel);\n    });\n  }\n\n  //============================================================\n  //    L2DBaseModel # loadTexture()\n  //============================================================\n  loadTexture(no /*int*/, path /*String*/, callback) {\n    texCounter++;\n\n    const pm = Live2DFramework.getPlatformManager(); //IPlatformManager\n\n    logger.info('Load Texture : ' + path);\n\n    pm.loadTexture(this.live2DModel, no, path, () => {\n      texCounter--;\n      if (texCounter == 0) this.isTexLoaded = true;\n      if (typeof callback == 'function') callback();\n    });\n  }\n\n  //============================================================\n  //    L2DBaseModel # loadMotion()\n  //============================================================\n  loadMotion(name /*String*/, path /*String*/, callback) {\n    const pm = Live2DFramework.getPlatformManager(); //IPlatformManager\n\n    logger.trace('Load Motion : ' + path);\n\n    let motion = null; //Live2DMotion\n\n    pm.loadBytes(path, (buf) => {\n      motion = Live2DMotion.loadMotion(buf);\n      if (name != null) {\n        this.motions[name] = motion;\n      }\n      callback(motion);\n    });\n  }\n\n  //============================================================\n  //    L2DBaseModel # loadExpression()\n  //============================================================\n  loadExpression(name /*String*/, path /*String*/, callback) {\n    const pm = Live2DFramework.getPlatformManager(); //IPlatformManager\n\n    logger.trace('Load Expression : ' + path);\n\n    pm.loadBytes(path, (buf) => {\n      if (name != null) {\n        this.expressions[name] = L2DExpressionMotion.loadJson(buf);\n      }\n      if (typeof callback == 'function') callback();\n    });\n  }\n\n  //============================================================\n  //    L2DBaseModel # loadPose()\n  //============================================================\n  loadPose(path /*String*/, callback) {\n    const pm = Live2DFramework.getPlatformManager(); //IPlatformManager\n    logger.trace('Load Pose : ' + path);\n    try {\n      pm.loadBytes(path, (buf) => {\n        this.pose = L2DPose.load(buf);\n        if (typeof callback == 'function') callback();\n      });\n    } catch (e) {\n      logger.warn(e);\n    }\n  }\n\n  //============================================================\n  //    L2DBaseModel # loadPhysics()\n  //============================================================\n  loadPhysics(path /*String*/) {\n    const pm = Live2DFramework.getPlatformManager(); //IPlatformManager\n    logger.trace('Load Physics : ' + path);\n    try {\n      pm.loadBytes(path, (buf) => {\n        this.physics = L2DPhysics.load(buf);\n      });\n    } catch (e) {\n      logger.warn(e);\n    }\n  }\n\n  //============================================================\n  //    L2DBaseModel # hitTestSimple()\n  //============================================================\n  hitTestSimple(drawID, testX, testY) {\n    const drawIndex = this.live2DModel.getDrawDataIndex(drawID);\n\n    if (drawIndex < 0) return false;\n\n    const points = this.live2DModel.getTransformedPoints(drawIndex);\n    let left = this.live2DModel.getCanvasWidth();\n    let right = 0;\n    let top = this.live2DModel.getCanvasHeight();\n    let bottom = 0;\n\n    for (let j = 0; j < points.length; j = j + 2) {\n      const x = points[j];\n      const y = points[j + 1];\n\n      if (x < left) left = x;\n      if (x > right) right = x;\n      if (y < top) top = y;\n      if (y > bottom) bottom = y;\n    }\n    const tx = this.modelMatrix.invertTransformX(testX);\n    const ty = this.modelMatrix.invertTransformY(testY);\n\n    return left <= tx && tx <= right && top <= ty && ty <= bottom;\n  }\n}\n\nlet texCounter = 0;\n\n/**\n *\n *  You can modify and use this source freely\n *  only for the development of application related Live2D.\n *\n *  (c) Live2D Inc. All rights reserved.\n */\n\n//============================================================\n//============================================================\n//  class L2DExpressionMotion  extends     AMotion\n//============================================================\n//============================================================\nclass L2DExpressionMotion extends AMotion {\n  constructor() {\n    super();\n    this.paramList = []; //ArrayList<L2DExpressionParam>\n  }\n\n  //============================================================\n  //    static L2DExpressionMotion.loadJson()\n  //============================================================\n  static loadJson(buf) {\n    const ret = new L2DExpressionMotion();\n\n    const pm = Live2DFramework.getPlatformManager();\n    const json = pm.jsonParseFromBytes(buf);\n\n    ret.setFadeIn(parseInt(json.fade_in) > 0 ? parseInt(json.fade_in) : 1000);\n    ret.setFadeOut(\n      parseInt(json.fade_out) > 0 ? parseInt(json.fade_out) : 1000,\n    );\n\n    if (json.params == null) {\n      return ret;\n    }\n\n    const params = json.params;\n    const paramNum = params.length;\n    ret.paramList = []; //ArrayList<L2DExpressionParam>\n    for (let i = 0; i < paramNum; i++) {\n      const param = params[i];\n      const paramID = param.id.toString();\n      let value = parseFloat(param.val);\n      let calcTypeInt = L2DExpressionMotion.TYPE_ADD;\n      const calc = param.calc != null ? param.calc.toString() : 'add';\n      if (calc === 'add') {\n        calcTypeInt = L2DExpressionMotion.TYPE_ADD;\n      } else if (calc === 'mult') {\n        calcTypeInt = L2DExpressionMotion.TYPE_MULT;\n      } else if (calc === 'set') {\n        calcTypeInt = L2DExpressionMotion.TYPE_SET;\n      } else {\n        calcTypeInt = L2DExpressionMotion.TYPE_ADD;\n      }\n      if (calcTypeInt == L2DExpressionMotion.TYPE_ADD) {\n        let defaultValue = param.def == null ? 0 : parseFloat(param.def);\n        value = value - defaultValue;\n      } else if (calcTypeInt == L2DExpressionMotion.TYPE_MULT) {\n        let defaultValue = param.def == null ? 1 : parseFloat(param.def);\n        if (defaultValue == 0) defaultValue = 1;\n        value = value / defaultValue;\n      }\n\n      const item = new L2DExpressionParam();\n      item.id = paramID;\n      item.type = calcTypeInt;\n      item.value = value;\n\n      ret.paramList.push(item);\n    }\n\n    return ret;\n  }\n\n  //============================================================\n  //    L2DExpressionMotion # updateParamExe()\n  //============================================================\n  updateParamExe(\n    model /*ALive2DModel*/,\n    timeMSec /*long*/,\n    weight /*float*/,\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    motionQueueEnt /*MotionQueueEnt*/,\n  ) {\n    for (let i = this.paramList.length - 1; i >= 0; --i) {\n      const param = this.paramList[i]; //L2DExpressionParam\n      // if (!param || !param.type) continue;\n      if (param.type == L2DExpressionMotion.TYPE_ADD) {\n        model.addToParamFloat(param.id, param.value, weight);\n      } else if (param.type == L2DExpressionMotion.TYPE_MULT) {\n        model.multParamFloat(param.id, param.value, weight);\n      } else if (param.type == L2DExpressionMotion.TYPE_SET) {\n        model.setParamFloat(param.id, param.value, weight);\n      }\n    }\n  }\n}\n\n//============================================================\nL2DExpressionMotion.EXPRESSION_DEFAULT = 'DEFAULT';\nL2DExpressionMotion.TYPE_SET = 0;\nL2DExpressionMotion.TYPE_ADD = 1;\nL2DExpressionMotion.TYPE_MULT = 2;\n\n//============================================================\n//============================================================\n//  class L2DExpressionParam\n//============================================================\n//============================================================\nfunction L2DExpressionParam() {\n  this.id = '';\n  this.type = -1;\n  this.value = null;\n}\n\n/**\n *\n *  You can modify and use this source freely\n *  only for the development of application related Live2D.\n *\n *  (c) Live2D Inc. All rights reserved.\n */\n\n//============================================================\n//============================================================\n//  class L2DEyeBlink\n//============================================================\n//============================================================\nclass L2DEyeBlink {\n  constructor() {\n    this.nextBlinkTime = null /* TODO NOT INIT */; //\n    this.stateStartTime = null /* TODO NOT INIT */; //\n    this.blinkIntervalMsec = null /* TODO NOT INIT */; //\n    this.eyeState = EYE_STATE.STATE_FIRST;\n    this.blinkIntervalMsec = 4000;\n    this.closingMotionMsec = 100;\n    this.closedMotionMsec = 50;\n    this.openingMotionMsec = 150;\n    this.closeIfZero = true;\n    this.eyeID_L = 'PARAM_EYE_L_OPEN';\n    this.eyeID_R = 'PARAM_EYE_R_OPEN';\n  }\n\n  //============================================================\n  //    L2DEyeBlink # calcNextBlink()\n  //============================================================\n  calcNextBlink() {\n    const time /*long*/ = UtSystem.getUserTimeMSec();\n    const r /*Number*/ = Math.random();\n    return /*(long)*/ time + r * (2 * this.blinkIntervalMsec - 1);\n  }\n\n  //============================================================\n  //    L2DEyeBlink # setInterval()\n  //============================================================\n  setInterval(blinkIntervalMsec /*int*/) {\n    this.blinkIntervalMsec = blinkIntervalMsec;\n  }\n\n  //============================================================\n  //    L2DEyeBlink # setEyeMotion()\n  //============================================================\n  setEyeMotion(\n    closingMotionMsec /*int*/,\n    closedMotionMsec /*int*/,\n    openingMotionMsec /*int*/,\n  ) {\n    this.closingMotionMsec = closingMotionMsec;\n    this.closedMotionMsec = closedMotionMsec;\n    this.openingMotionMsec = openingMotionMsec;\n  }\n\n  //============================================================\n  //    L2DEyeBlink # updateParam()\n  //============================================================\n  updateParam(model /*ALive2DModel*/) {\n    const time /*:long*/ = UtSystem.getUserTimeMSec();\n    let eyeParamValue /*:Number*/;\n    let t /*:Number*/ = 0;\n    switch (this.eyeState) {\n    case EYE_STATE.STATE_CLOSING:\n      t = (time - this.stateStartTime) / this.closingMotionMsec;\n      if (t >= 1) {\n        t = 1;\n        this.eyeState = EYE_STATE.STATE_CLOSED;\n        this.stateStartTime = time;\n      }\n      eyeParamValue = 1 - t;\n      break;\n    case EYE_STATE.STATE_CLOSED:\n      t = (time - this.stateStartTime) / this.closedMotionMsec;\n      if (t >= 1) {\n        this.eyeState = EYE_STATE.STATE_OPENING;\n        this.stateStartTime = time;\n      }\n      eyeParamValue = 0;\n      break;\n    case EYE_STATE.STATE_OPENING:\n      t = (time - this.stateStartTime) / this.openingMotionMsec;\n      if (t >= 1) {\n        t = 1;\n        this.eyeState = EYE_STATE.STATE_INTERVAL;\n        this.nextBlinkTime = this.calcNextBlink();\n      }\n      eyeParamValue = t;\n      break;\n    case EYE_STATE.STATE_INTERVAL:\n      if (this.nextBlinkTime < time) {\n        this.eyeState = EYE_STATE.STATE_CLOSING;\n        this.stateStartTime = time;\n      }\n      eyeParamValue = 1;\n      break;\n    case EYE_STATE.STATE_FIRST:\n    default:\n      this.eyeState = EYE_STATE.STATE_INTERVAL;\n      this.nextBlinkTime = this.calcNextBlink();\n      eyeParamValue = 1;\n      break;\n    }\n    if (!this.closeIfZero) eyeParamValue = -eyeParamValue;\n    model.setParamFloat(this.eyeID_L, eyeParamValue);\n    model.setParamFloat(this.eyeID_R, eyeParamValue);\n  }\n}\n\n//== enum EYE_STATE ==\nconst EYE_STATE = () => { };\n\nEYE_STATE.STATE_FIRST = 'STATE_FIRST';\nEYE_STATE.STATE_INTERVAL = 'STATE_INTERVAL';\nEYE_STATE.STATE_CLOSING = 'STATE_CLOSING';\nEYE_STATE.STATE_CLOSED = 'STATE_CLOSED';\nEYE_STATE.STATE_OPENING = 'STATE_OPENING';\n\n/**\n *\n *  You can modify and use this source freely\n *  only for the development of application related Live2D.\n *\n *  (c) Live2D Inc. All rights reserved.\n */\n\n//============================================================\n//============================================================\n//  class L2DMatrix44\n//============================================================\n//============================================================\nclass L2DMatrix44 {\n  constructor() {\n    this.tr = new Float32Array(16); //\n    this.identity();\n  }\n\n  //============================================================\n  //    static L2DMatrix44.mul()\n  //============================================================\n  static mul(a /*float[]*/, b /*float[]*/, dst /*float[]*/) {\n    const c = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n    const n = 4;\n    let i, j, k;\n    for (i = 0; i < n; i++) {\n      for (j = 0; j < n; j++) {\n        for (k = 0; k < n; k++) {\n          c[i + j * 4] += a[i + k * 4] * b[k + j * 4];\n        }\n      }\n    }\n    for (i = 0; i < 16; i++) {\n      dst[i] = c[i];\n    }\n  }\n\n  //============================================================\n  //    L2DMatrix44 # identity()\n  //============================================================\n  identity() {\n    for (let i /*:int*/ = 0; i < 16; i++) this.tr[i] = i % 5 == 0 ? 1 : 0;\n  }\n\n  //============================================================\n  //    L2DMatrix44 # getArray()\n  //============================================================\n  getArray() {\n    return this.tr;\n  }\n\n  //============================================================\n  //    L2DMatrix44 # getCopyMatrix()\n  //============================================================\n  getCopyMatrix() {\n    return new Float32Array(this.tr); // this.tr.clone();\n  }\n\n  //============================================================\n  //    L2DMatrix44 # setMatrix()\n  //============================================================\n  setMatrix(tr /*float[]*/) {\n    if (this.tr == null || this.tr.length != this.tr.length) return;\n    for (let i /*:int*/ = 0; i < 16; i++) this.tr[i] = tr[i];\n  }\n\n  //============================================================\n  //    L2DMatrix44 # getScaleX()\n  //============================================================\n  getScaleX() {\n    return this.tr[0];\n  }\n\n  //============================================================\n  //    L2DMatrix44 # getScaleY()\n  //============================================================\n  getScaleY() {\n    return this.tr[5];\n  }\n\n  //============================================================\n  //    L2DMatrix44 # transformX()\n  //============================================================\n  transformX(src /*float*/) {\n    return this.tr[0] * src + this.tr[12];\n  }\n\n  //============================================================\n  //    L2DMatrix44 # transformY()\n  //============================================================\n  transformY(src /*float*/) {\n    return this.tr[5] * src + this.tr[13];\n  }\n\n  //============================================================\n  //    L2DMatrix44 # invertTransformX()\n  //============================================================\n  invertTransformX(src /*float*/) {\n    return (src - this.tr[12]) / this.tr[0];\n  }\n\n  //============================================================\n  //    L2DMatrix44 # invertTransformY()\n  //============================================================\n  invertTransformY(src /*float*/) {\n    return (src - this.tr[13]) / this.tr[5];\n  }\n\n  //============================================================\n  //    L2DMatrix44 # multTranslate()\n  //============================================================\n  multTranslate(shiftX /*float*/, shiftY /*float*/) {\n    const tr1 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, shiftX, shiftY, 0, 1];\n    L2DMatrix44.mul(tr1, this.tr, this.tr);\n  }\n\n  //============================================================\n  //    L2DMatrix44 # translate()\n  //============================================================\n  translate(x /*float*/, y /*float*/) {\n    this.tr[12] = x;\n    this.tr[13] = y;\n  }\n\n  //============================================================\n  //    L2DMatrix44 # translateX()\n  //============================================================\n  translateX(x /*float*/) {\n    this.tr[12] = x;\n  }\n\n  //============================================================\n  //    L2DMatrix44 # translateY()\n  //============================================================\n  translateY(y /*float*/) {\n    this.tr[13] = y;\n  }\n\n  //============================================================\n  //    L2DMatrix44 # multScale()\n  //============================================================\n  multScale(scaleX /*float*/, scaleY /*float*/) {\n    const tr1 = [scaleX, 0, 0, 0, 0, scaleY, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];\n    L2DMatrix44.mul(tr1, this.tr, this.tr);\n  }\n\n  //============================================================\n  //    L2DMatrix44 # scale()\n  //============================================================\n  scale(scaleX /*float*/, scaleY /*float*/) {\n    this.tr[0] = scaleX;\n    this.tr[5] = scaleY;\n  }\n}\n\n/**\n *\n *  You can modify and use this source freely\n *  only for the development of application related Live2D.\n *\n *  (c) Live2D Inc. All rights reserved.\n */\n\n//============================================================\n//============================================================\n//  class L2DModelMatrix       extends     L2DMatrix44\n//============================================================\n//============================================================\nclass L2DModelMatrix extends L2DMatrix44 {\n  constructor(w /*float*/, h /*float*/) {\n    super();\n    this.width = w;\n    this.height = h;\n  }\n\n  //============================================================\n  //    L2DModelMatrix # setPosition()\n  //============================================================\n  setPosition(x /*float*/, y /*float*/) {\n    this.translate(x, y);\n  }\n\n  //============================================================\n  //    L2DModelMatrix # setCenterPosition()\n  //============================================================\n  setCenterPosition(x /*float*/, y /*float*/) {\n    const w = this.width * this.getScaleX();\n    const h = this.height * this.getScaleY();\n    this.translate(x - w / 2, y - h / 2);\n  }\n\n  //============================================================\n  //    L2DModelMatrix # top()\n  //============================================================\n  top(y /*float*/) {\n    this.setY(y);\n  }\n\n  //============================================================\n  //    L2DModelMatrix # bottom()\n  //============================================================\n  bottom(y /*float*/) {\n    const h = this.height * this.getScaleY();\n    this.translateY(y - h);\n  }\n\n  //============================================================\n  //    L2DModelMatrix # left()\n  //============================================================\n  left(x /*float*/) {\n    this.setX(x);\n  }\n\n  //============================================================\n  //    L2DModelMatrix # right()\n  //============================================================\n  right(x /*float*/) {\n    const w = this.width * this.getScaleX();\n    this.translateX(x - w);\n  }\n\n  //============================================================\n  //    L2DModelMatrix # centerX()\n  //============================================================\n  centerX(x /*float*/) {\n    const w = this.width * this.getScaleX();\n    this.translateX(x - w / 2);\n  }\n\n  //============================================================\n  //    L2DModelMatrix # centerY()\n  //============================================================\n  centerY(y /*float*/) {\n    const h = this.height * this.getScaleY();\n    this.translateY(y - h / 2);\n  }\n\n  //============================================================\n  //    L2DModelMatrix # setX()\n  //============================================================\n  setX(x /*float*/) {\n    this.translateX(x);\n  }\n\n  //============================================================\n  //    L2DModelMatrix # setY()\n  //============================================================\n  setY(y /*float*/) {\n    this.translateY(y);\n  }\n\n  //============================================================\n  //    L2DModelMatrix # setHeight()\n  //============================================================\n  setHeight(h /*float*/) {\n    const scaleX = h / this.height;\n    const scaleY = -scaleX;\n    this.scale(scaleX, scaleY);\n  }\n\n  //============================================================\n  //    L2DModelMatrix # setWidth()\n  //============================================================\n  setWidth(w /*float*/) {\n    const scaleX = w / this.width;\n    const scaleY = -scaleX;\n    this.scale(scaleX, scaleY);\n  }\n}\n\n/**\n *\n *  You can modify and use this source freely\n *  only for the development of application related Live2D.\n *\n *  (c) Live2D Inc. All rights reserved.\n */\n\n//============================================================\n//============================================================\n//  class L2DMotionManager     extends     MotionQueueManager\n//============================================================\n//============================================================\nclass L2DMotionManager extends MotionQueueManager {\n  constructor() {\n    super();\n    this.currentPriority = null;\n    this.reservePriority = null;\n\n    this.super = MotionQueueManager.prototype;\n  }\n\n  //============================================================\n  //    L2DMotionManager # getCurrentPriority()\n  //============================================================\n  getCurrentPriority() {\n    return this.currentPriority;\n  }\n\n  //============================================================\n  //    L2DMotionManager # getReservePriority()\n  //============================================================\n  getReservePriority() {\n    return this.reservePriority;\n  }\n\n  //============================================================\n  //    L2DMotionManager # reserveMotion()\n  //============================================================\n  reserveMotion(priority /*int*/) {\n    if (this.reservePriority >= priority) {\n      return false;\n    }\n    if (this.currentPriority >= priority) {\n      return false;\n    }\n\n    this.reservePriority = priority;\n\n    return true;\n  }\n\n  //============================================================\n  //    L2DMotionManager # setReservePriority()\n  //============================================================\n  setReservePriority(val /*int*/) {\n    this.reservePriority = val;\n  }\n\n  //============================================================\n  //    L2DMotionManager # updateParam()\n  //============================================================\n  updateParam(model /*ALive2DModel*/) {\n    const updated = MotionQueueManager.prototype.updateParam.call(this, model);\n\n    if (this.isFinished()) {\n      this.currentPriority = 0;\n    }\n\n    return updated;\n  }\n\n  //============================================================\n  //    L2DMotionManager # startMotionPrio()\n  //============================================================\n  startMotionPrio(motion /*AMotion*/, priority /*int*/) {\n    if (priority == this.reservePriority) {\n      this.reservePriority = 0;\n    }\n    this.currentPriority = priority;\n    return this.startMotion(motion, false);\n  }\n}\n\n/**\n *\n *  You can modify and use this source freely\n *  only for the development of application related Live2D.\n *\n *  (c) Live2D Inc. All rights reserved.\n */\n\n//============================================================\n//============================================================\n//  class L2DPhysics\n//============================================================\n//============================================================\nclass L2DPhysics {\n  constructor() {\n    this.physicsList = []; //ArrayList<PhysicsHair>\n    this.startTimeMSec = UtSystem.getUserTimeMSec();\n  }\n\n  //============================================================\n  //    static L2DPhysics.load()\n  //============================================================\n  static load(buf /*byte[]*/) {\n    const ret = new L2DPhysics(); //L2DPhysicsL2DPhysics\n    const pm = Live2DFramework.getPlatformManager();\n    const json = pm.jsonParseFromBytes(buf);\n    const params = json.physics_hair;\n    const paramNum = params.length;\n    for (let i = 0; i < paramNum; i++) {\n      const param = params[i]; //Value\n      const physics = new PhysicsHair(); //PhysicsHairPhysicsHair\n      const setup = param.setup; //Value\n      const length = parseFloat(setup.length);\n      const resist = parseFloat(setup.regist);\n      const mass = parseFloat(setup.mass);\n      physics.setup(length, resist, mass);\n      const srcList = param.src; //Value\n      const srcNum = srcList.length;\n      for (let j = 0; j < srcNum; j++) {\n        const src = srcList[j]; //Value\n        let id = src.id; //String\n        let type = PhysicsHair.Src.SRC_TO_X;\n        let typeStr = src.ptype; //String\n        if (typeStr === 'x') {\n          type = PhysicsHair.Src.SRC_TO_X;\n        } else if (typeStr === 'y') {\n          type = PhysicsHair.Src.SRC_TO_Y;\n        } else if (typeStr === 'angle') {\n          type = PhysicsHair.Src.SRC_TO_G_ANGLE;\n        } else {\n          UtDebug.error('live2d', 'Invalid parameter:PhysicsHair.Src');\n        }\n        let scale = parseFloat(src.scale);\n        let weight = parseFloat(src.weight);\n        physics.addSrcParam(type, id, scale, weight);\n      }\n      const targetList = param.targets; //Value\n      const targetNum = targetList.length;\n      for (let j = 0; j < targetNum; j++) {\n        const target = targetList[j]; //Value\n        let id = target.id; //String\n        let type = PhysicsHair.Target.TARGET_FROM_ANGLE;\n        let typeStr = target.ptype; //String\n        if (typeStr === 'angle') {\n          type = PhysicsHair.Target.TARGET_FROM_ANGLE;\n        } else if (typeStr === 'angle_v') {\n          type = PhysicsHair.Target.TARGET_FROM_ANGLE_V;\n        } else {\n          UtDebug.error('live2d', 'Invalid parameter:PhysicsHair.Target');\n        }\n        let scale = parseFloat(target.scale);\n        let weight = parseFloat(target.weight);\n        physics.addTargetParam(type, id, scale, weight);\n      }\n      ret.physicsList.push(physics);\n    }\n    return ret;\n  }\n\n  //============================================================\n  //    L2DPhysics # updateParam()\n  //============================================================\n  updateParam(model /*ALive2DModel*/) {\n    const timeMSec = UtSystem.getUserTimeMSec() - this.startTimeMSec;\n    for (let i = 0; i < this.physicsList.length; i++) {\n      this.physicsList[i].update(model, timeMSec);\n    }\n  }\n}\n\n/**\n *\n *  You can modify and use this source freely\n *  only for the development of application related Live2D.\n *\n *  (c) Live2D Inc. All rights reserved.\n */\n\n//============================================================\n//============================================================\n//  class L2DPose\n//============================================================\n//============================================================\nclass L2DPose {\n  constructor() {\n    this.lastTime = 0;\n    this.lastModel = null; //ALive2DModel\n    this.partsGroups = []; //ArrayList<L2DPartsParam[]>\n  }\n\n  //============================================================\n  //    static L2DPose.load()\n  //============================================================\n  static load(buf /*byte[]*/) {\n    const ret = new L2DPose(); //L2DPose\n    const pm = Live2DFramework.getPlatformManager();\n    const json = pm.jsonParseFromBytes(buf);\n    const poseListInfo = json.parts_visible; //Value\n    const poseNum = poseListInfo.length;\n    for (let i_pose = 0; i_pose < poseNum; i_pose++) {\n      const poseInfo = poseListInfo[i_pose]; //Value\n      const idListInfo = poseInfo.group; //Value\n      const idNum = idListInfo.length;\n      const partsGroup /*L2DPartsParam*/ = [];\n      for (let i_group = 0; i_group < idNum; i_group++) {\n        const partsInfo = idListInfo[i_group]; //Value\n        const parts = new L2DPartsParam(partsInfo.id); //L2DPartsParamL2DPartsParam\n        partsGroup[i_group] = parts;\n        if (partsInfo.link == null) continue;\n        const linkListInfo = partsInfo.link; //Value\n        const linkNum = linkListInfo.length;\n        parts.link = []; //ArrayList<L2DPartsParam>\n        for (let i_link = 0; i_link < linkNum; i_link++) {\n          const linkParts = new L2DPartsParam(linkListInfo[i_link]); //L2DPartsParamL2DPartsParam\n          parts.link.push(linkParts);\n        }\n      }\n      ret.partsGroups.push(partsGroup);\n    }\n\n    return ret;\n  }\n\n  //============================================================\n  //    L2DPose # updateParam()\n  //============================================================\n  updateParam(model /*ALive2DModel*/) {\n    if (model == null) return;\n\n    if (!(model == this.lastModel)) {\n      this.initParam(model);\n    }\n    this.lastModel = model;\n\n    const curTime = UtSystem.getUserTimeMSec();\n    let deltaTimeSec =\n      this.lastTime == 0 ? 0 : (curTime - this.lastTime) / 1000.0;\n    this.lastTime = curTime;\n    if (deltaTimeSec < 0) deltaTimeSec = 0;\n    for (let i = 0; i < this.partsGroups.length; i++) {\n      this.normalizePartsOpacityGroup(model, this.partsGroups[i], deltaTimeSec);\n      this.copyOpacityOtherParts(model, this.partsGroups[i]);\n    }\n  }\n\n  //============================================================\n  //    L2DPose # initParam()\n  //============================================================\n  initParam(model /*ALive2DModel*/) {\n    if (model == null) return;\n    for (let i = 0; i < this.partsGroups.length; i++) {\n      const partsGroup = this.partsGroups[i]; //L2DPartsParam\n      for (let j = 0; j < partsGroup.length; j++) {\n        partsGroup[j].initIndex(model);\n        const partsIndex = partsGroup[j].partsIndex;\n        const paramIndex = partsGroup[j].paramIndex;\n        if (partsIndex < 0) continue;\n        const v /*:Boolean*/ = model.getParamFloat(paramIndex) != 0;\n        model.setPartsOpacity(partsIndex, v ? 1.0 : 0.0);\n        model.setParamFloat(paramIndex, v ? 1.0 : 0.0);\n        if (partsGroup[j].link == null) continue;\n        for (let k = 0; k < partsGroup[j].link.length; k++) {\n          partsGroup[j].link[k].initIndex(model);\n        }\n      }\n    }\n  }\n\n  //============================================================\n  //    L2DPose # normalizePartsOpacityGroup()\n  //============================================================\n  normalizePartsOpacityGroup(\n    model /*ALive2DModel*/,\n    partsGroup /*L2DPartsParam[]*/,\n    deltaTimeSec /*float*/,\n  ) {\n    let visibleParts = -1;\n    let visibleOpacity = 1.0;\n    const CLEAR_TIME_SEC = 0.5;\n    const phi = 0.5;\n    const maxBackOpacity = 0.15;\n    for (let i = 0; i < partsGroup.length; i++) {\n      let partsIndex = partsGroup[i].partsIndex;\n      const paramIndex = partsGroup[i].paramIndex;\n      if (partsIndex < 0) continue;\n      if (model.getParamFloat(paramIndex) != 0) {\n        if (visibleParts >= 0) {\n          break;\n        }\n        visibleParts = i;\n        visibleOpacity = model.getPartsOpacity(partsIndex);\n        visibleOpacity += deltaTimeSec / CLEAR_TIME_SEC;\n        if (visibleOpacity > 1) {\n          visibleOpacity = 1;\n        }\n      }\n    }\n    if (visibleParts < 0) {\n      visibleParts = 0;\n      visibleOpacity = 1;\n    }\n    for (let i = 0; i < partsGroup.length; i++) {\n      let partsIndex = partsGroup[i].partsIndex;\n      if (partsIndex < 0) continue;\n      if (visibleParts == i) {\n        model.setPartsOpacity(partsIndex, visibleOpacity);\n      } else {\n        let opacity = model.getPartsOpacity(partsIndex);\n        let a1;\n        if (visibleOpacity < phi) {\n          a1 = (visibleOpacity * (phi - 1)) / phi + 1;\n        } else {\n          a1 = ((1 - visibleOpacity) * phi) / (1 - phi);\n        }\n        const backOp = (1 - a1) * (1 - visibleOpacity);\n        if (backOp > maxBackOpacity) {\n          a1 = 1 - maxBackOpacity / (1 - visibleOpacity);\n        }\n        if (opacity > a1) {\n          opacity = a1;\n        }\n        model.setPartsOpacity(partsIndex, opacity);\n      }\n    }\n  }\n\n  //============================================================\n  //    L2DPose # copyOpacityOtherParts()\n  //============================================================\n  copyOpacityOtherParts(\n    model /*ALive2DModel*/,\n    partsGroup /*L2DPartsParam[]*/,\n  ) {\n    for (let i_group = 0; i_group < partsGroup.length; i_group++) {\n      const partsParam = partsGroup[i_group]; //L2DPartsParam\n      if (partsParam.link == null) continue;\n      if (partsParam.partsIndex < 0) continue;\n      const opacity = model.getPartsOpacity(partsParam.partsIndex);\n      for (let i_link = 0; i_link < partsParam.link.length; i_link++) {\n        const linkParts = partsParam.link[i_link]; //L2DPartsParam\n        if (linkParts.partsIndex < 0) continue;\n        model.setPartsOpacity(linkParts.partsIndex, opacity);\n      }\n    }\n  }\n}\n\n//============================================================\n//============================================================\n//  class L2DPartsParam\n//============================================================\n//============================================================\nclass L2DPartsParam {\n  constructor(id /*String*/) {\n    this.paramIndex = -1;\n    this.partsIndex = -1;\n    this.link = null; // ArrayList<L2DPartsParam>\n    this.id = id;\n  }\n\n  //============================================================\n  //    L2DPartsParam # initIndex()\n  //============================================================\n  initIndex(model /*ALive2DModel*/) {\n    this.paramIndex = model.getParamIndex('VISIBLE:' + this.id);\n    this.partsIndex = model.getPartsDataIndex(PartsDataID.getID(this.id));\n    model.setParamFloat(this.paramIndex, 1);\n  }\n}\n\n/**\n *\n *  You can modify and use this source freely\n *  only for the development of application related Live2D.\n *\n *  (c) Live2D Inc. All rights reserved.\n */\n\n//============================================================\n//============================================================\n//  class L2DTargetPoint\n//============================================================\n//============================================================\nclass L2DTargetPoint {\n  constructor() {\n    this.EPSILON = 0.01; // 変化の最小値（この値以下は無視される）\n    this.faceTargetX = 0;\n    this.faceTargetY = 0;\n    this.faceX = 0;\n    this.faceY = 0;\n    this.faceVX = 0;\n    this.faceVY = 0;\n    this.lastTimeSec = 0;\n  }\n\n  //============================================================\n  //    L2DTargetPoint # set()\n  //============================================================\n  setPoint(x /*float*/, y /*float*/) {\n    this.faceTargetX = x;\n    this.faceTargetY = y;\n  }\n\n  //============================================================\n  //    L2DTargetPoint # getX()\n  //============================================================\n  getX() {\n    return this.faceX;\n  }\n\n  //============================================================\n  //    L2DTargetPoint # getY()\n  //============================================================\n  getY() {\n    return this.faceY;\n  }\n\n  //============================================================\n  //    L2DTargetPoint # update()\n  //============================================================\n  update() {\n    const TIME_TO_MAX_SPEED = 0.15;\n    const FACE_PARAM_MAX_V = 40.0 / 7.5;\n    const MAX_V = FACE_PARAM_MAX_V / L2DTargetPoint.FRAME_RATE;\n    if (this.lastTimeSec == 0) {\n      this.lastTimeSec = UtSystem.getUserTimeMSec();\n      return;\n    }\n    const curTimeSec = UtSystem.getUserTimeMSec();\n    const deltaTimeWeight =\n      ((curTimeSec - this.lastTimeSec) * L2DTargetPoint.FRAME_RATE) / 1000.0;\n    this.lastTimeSec = curTimeSec;\n    const FRAME_TO_MAX_SPEED = TIME_TO_MAX_SPEED * L2DTargetPoint.FRAME_RATE;\n    const MAX_A = (deltaTimeWeight * MAX_V) / FRAME_TO_MAX_SPEED;\n    const dx = this.faceTargetX - this.faceX;\n    const dy = this.faceTargetY - this.faceY;\n    // if(dx == 0 && dy == 0) return;\n    if (Math.abs(dx) <= this.EPSILON && Math.abs(dy) <= this.EPSILON) return;\n    const d = Math.sqrt(dx * dx + dy * dy);\n    const vx = (MAX_V * dx) / d;\n    const vy = (MAX_V * dy) / d;\n    let ax = vx - this.faceVX;\n    let ay = vy - this.faceVY;\n    let a = Math.sqrt(ax * ax + ay * ay);\n    if (a < -MAX_A || a > MAX_A) {\n      ax *= MAX_A / a;\n      ay *= MAX_A / a;\n      a = MAX_A;\n    }\n    this.faceVX += ax;\n    this.faceVY += ay;\n    {\n      const max_v =\n        0.5 *\n        (Math.sqrt(MAX_A * MAX_A + 16 * MAX_A * d - 8 * MAX_A * d) - MAX_A);\n      const cur_v = Math.sqrt(\n        this.faceVX * this.faceVX + this.faceVY * this.faceVY,\n      );\n      if (cur_v > max_v) {\n        this.faceVX *= max_v / cur_v;\n        this.faceVY *= max_v / cur_v;\n      }\n    }\n    this.faceX += this.faceVX;\n    this.faceY += this.faceVY;\n  }\n}\n\n//============================================================\nL2DTargetPoint.FRAME_RATE = 30;\n\n/**\n *\n *  You can modify and use this source freely\n *  only for the development of application related Live2D.\n *\n *  (c) Live2D Inc. All rights reserved.\n */\n\n//============================================================\n//============================================================\n//  class L2DViewMatrix        extends     L2DMatrix44\n//============================================================\n//============================================================\nclass L2DViewMatrix extends L2DMatrix44 {\n  constructor() {\n    super();\n    this.screenLeft = null;\n    this.screenRight = null;\n    this.screenTop = null;\n    this.screenBottom = null;\n    this.maxLeft = null;\n    this.maxRight = null;\n    this.maxTop = null;\n    this.maxBottom = null;\n    this.max = Number.MAX_VALUE;\n    this.min = 0;\n  }\n\n  //============================================================\n  //    L2DViewMatrix # getMaxScale()\n  //============================================================\n  getMaxScale() {\n    return this.max;\n  }\n\n  //============================================================\n  //    L2DViewMatrix # getMinScale()\n  //============================================================\n  getMinScale() {\n    return this.min;\n  }\n\n  //============================================================\n  //    L2DViewMatrix # setMaxScale()\n  //============================================================\n  setMaxScale(v /*float*/) {\n    this.max = v;\n  }\n\n  //============================================================\n  //    L2DViewMatrix # setMinScale()\n  //============================================================\n  setMinScale(v /*float*/) {\n    this.min = v;\n  }\n\n  //============================================================\n  //    L2DViewMatrix # isMaxScale()\n  //============================================================\n  isMaxScale() {\n    return this.getScaleX() == this.max;\n  }\n\n  //============================================================\n  //    L2DViewMatrix # isMinScale()\n  //============================================================\n  isMinScale() {\n    return this.getScaleX() == this.min;\n  }\n\n  //============================================================\n  //    L2DViewMatrix # adjustTranslate()\n  //============================================================\n  adjustTranslate(shiftX /*float*/, shiftY /*float*/) {\n    if (this.tr[0] * this.maxLeft + (this.tr[12] + shiftX) > this.screenLeft)\n      shiftX = this.screenLeft - this.tr[0] * this.maxLeft - this.tr[12];\n    if (this.tr[0] * this.maxRight + (this.tr[12] + shiftX) < this.screenRight)\n      shiftX = this.screenRight - this.tr[0] * this.maxRight - this.tr[12];\n    if (this.tr[5] * this.maxTop + (this.tr[13] + shiftY) < this.screenTop)\n      shiftY = this.screenTop - this.tr[5] * this.maxTop - this.tr[13];\n    if (\n      this.tr[5] * this.maxBottom + (this.tr[13] + shiftY) >\n      this.screenBottom\n    )\n      shiftY = this.screenBottom - this.tr[5] * this.maxBottom - this.tr[13];\n\n    const tr1 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, shiftX, shiftY, 0, 1];\n    L2DMatrix44.mul(tr1, this.tr, this.tr);\n  }\n\n  //============================================================\n  //    L2DViewMatrix # adjustScale()\n  //============================================================\n  adjustScale(cx /*float*/, cy /*float*/, scale /*float*/) {\n    const targetScale = scale * this.tr[0];\n    if (targetScale < this.min) {\n      if (this.tr[0] > 0) scale = this.min / this.tr[0];\n    } else if (targetScale > this.max) {\n      if (this.tr[0] > 0) scale = this.max / this.tr[0];\n    }\n    const tr1 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1];\n    const tr2 = [scale, 0, 0, 0, 0, scale, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];\n    const tr3 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -cx, -cy, 0, 1];\n    L2DMatrix44.mul(tr3, this.tr, this.tr);\n    L2DMatrix44.mul(tr2, this.tr, this.tr);\n    L2DMatrix44.mul(tr1, this.tr, this.tr);\n  }\n\n  //============================================================\n  //    L2DViewMatrix # setScreenRect()\n  //============================================================\n  setScreenRect(\n    left /*float*/,\n    right /*float*/,\n    bottom /*float*/,\n    top /*float*/,\n  ) {\n    this.screenLeft = left;\n    this.screenRight = right;\n    this.screenTop = top;\n    this.screenBottom = bottom;\n  }\n\n  //============================================================\n  //    L2DViewMatrix # setMaxScreenRect()\n  //============================================================\n  setMaxScreenRect(\n    left /*float*/,\n    right /*float*/,\n    bottom /*float*/,\n    top /*float*/,\n  ) {\n    this.maxLeft = left;\n    this.maxRight = right;\n    this.maxTop = top;\n    this.maxBottom = bottom;\n  }\n\n  //============================================================\n  //    L2DViewMatrix # getScreenLeft()\n  //============================================================\n  getScreenLeft() {\n    return this.screenLeft;\n  }\n\n  //============================================================\n  //    L2DViewMatrix # getScreenRight()\n  //============================================================\n  getScreenRight() {\n    return this.screenRight;\n  }\n\n  //============================================================\n  //    L2DViewMatrix # getScreenBottom()\n  //============================================================\n  getScreenBottom() {\n    return this.screenBottom;\n  }\n\n  //============================================================\n  //    L2DViewMatrix # getScreenTop()\n  //============================================================\n  getScreenTop() {\n    return this.screenTop;\n  }\n\n  //============================================================\n  //    L2DViewMatrix # getMaxLeft()\n  //============================================================\n  getMaxLeft() {\n    return this.maxLeft;\n  }\n\n  //============================================================\n  //    L2DViewMatrix # getMaxRight()\n  //============================================================\n  getMaxRight() {\n    return this.maxRight;\n  }\n\n  //============================================================\n  //    L2DViewMatrix # getMaxBottom()\n  //============================================================\n  getMaxBottom() {\n    return this.maxBottom;\n  }\n\n  //============================================================\n  //    L2DViewMatrix # getMaxTop()\n  //============================================================\n  getMaxTop() {\n    return this.maxTop;\n  }\n}\n\n/**\n *\n *  You can modify and use this source freely\n *  only for the development of application related Live2D.\n *\n *  (c) Live2D Inc. All rights reserved.\n */\n\n//============================================================\n//============================================================\n//  class Live2DFramework\n//============================================================\n//============================================================\nclass Live2DFramework {\n  //============================================================\n  //    static Live2DFramework.getPlatformManager()\n  //============================================================\n  static getPlatformManager() {\n    return Live2DFramework.platformManager;\n  }\n\n  //============================================================\n  //    static Live2DFramework.setPlatformManager()\n  //============================================================\n  static setPlatformManager(platformManager /*IPlatformManager*/) {\n    Live2DFramework.platformManager = platformManager;\n  }\n}\n\n//============================================================\nLive2DFramework.platformManager = null;\n\nexport {\n  L2DBaseModel,\n  L2DViewMatrix,\n  L2DEyeBlink,\n  Live2DFramework,\n  L2DMatrix44,\n  L2DTargetPoint\n}\n"
  },
  {
    "path": "src/cubism2/PlatformManager.js",
    "content": "/* global Image, Live2DModelWebGL, document, fetch */\n/**\n *\n *  You can modify and use this source freely\n *  only for the development of application related Live2D.\n *\n *  (c) Live2D Inc. All rights reserved.\n */\n\nimport logger from '../logger.js';\n//============================================================\n//============================================================\n//  class PlatformManager     extend IPlatformManager\n//============================================================\n//============================================================\nclass PlatformManager {\n  constructor() {\n    this.cache = {};\n  }\n  //============================================================\n  //    PlatformManager # loadBytes()\n  //============================================================\n  loadBytes(path /*String*/, callback) {\n    if (path in this.cache) {\n      return callback(this.cache[path]);\n    }\n    fetch(path)\n      .then(response => response.arrayBuffer())\n      .then(arrayBuffer => {\n        this.cache[path] = arrayBuffer;\n        callback(arrayBuffer);\n      });\n  }\n\n  //============================================================\n  //    PlatformManager # loadLive2DModel()\n  //============================================================\n  loadLive2DModel(path /*String*/, callback) {\n    let model = null;\n\n    // load moc\n    this.loadBytes(path, buf => {\n      model = Live2DModelWebGL.loadModel(buf);\n      callback(model);\n    });\n  }\n\n  //============================================================\n  //    PlatformManager # loadTexture()\n  //============================================================\n  loadTexture(model /*ALive2DModel*/, no /*int*/, path /*String*/, callback) {\n    // load textures\n    const loadedImage = new Image();\n    loadedImage.crossOrigin = 'anonymous';\n    loadedImage.src = path;\n\n    loadedImage.onload = () => {\n      // create texture\n      const canvas = document.getElementById('live2d');\n      const gl = canvas.getContext('webgl2', { premultipliedAlpha: true, preserveDrawingBuffer: true });\n      let texture = gl.createTexture();\n      if (!texture) {\n        logger.error('Failed to generate gl texture name.');\n        return -1;\n      }\n\n      if (model.isPremultipliedAlpha() == false) {\n        // 乗算済アルファテクスチャ以外の場合\n        gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);\n      }\n      gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);\n      gl.activeTexture(gl.TEXTURE0);\n      gl.bindTexture(gl.TEXTURE_2D, texture);\n      gl.texImage2D(\n        gl.TEXTURE_2D,\n        0,\n        gl.RGBA,\n        gl.RGBA,\n        gl.UNSIGNED_BYTE,\n        loadedImage,\n      );\n      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n      gl.texParameteri(\n        gl.TEXTURE_2D,\n        gl.TEXTURE_MIN_FILTER,\n        gl.LINEAR_MIPMAP_NEAREST,\n      );\n      gl.generateMipmap(gl.TEXTURE_2D);\n\n      model.setTexture(no, texture);\n\n      // テクスチャオブジェクトを解放\n      texture = null;\n\n      if (typeof callback == 'function') callback();\n    };\n\n    loadedImage.onerror = () => {\n      logger.error('Failed to load image : ' + path);\n    };\n  }\n\n  //============================================================\n  //    PlatformManager # parseFromBytes(buf)\n\n  //============================================================\n  jsonParseFromBytes(buf) {\n    let jsonStr;\n\n    const bomCode = new Uint8Array(buf, 0, 3);\n    if (bomCode[0] == 239 && bomCode[1] == 187 && bomCode[2] == 191) {\n      jsonStr = String.fromCharCode.apply(null, new Uint8Array(buf, 3));\n    } else {\n      jsonStr = String.fromCharCode.apply(null, new Uint8Array(buf));\n    }\n\n    const jsonObj = JSON.parse(jsonStr);\n\n    return jsonObj;\n  }\n}\n\nexport default PlatformManager;\n"
  },
  {
    "path": "src/cubism2/index.js",
    "content": "/* global document, window, Event, Live2D */\nimport { L2DMatrix44, L2DTargetPoint, L2DViewMatrix } from './Live2DFramework.js';\nimport LAppDefine from './LAppDefine.js';\nimport MatrixStack from './utils/MatrixStack.js';\nimport LAppLive2DManager from './LAppLive2DManager.js';\nimport logger from '../logger.js';\n\nfunction normalizePoint(x, y, x0, y0, w, h) {\n  const dx = x - x0;\n  const dy = y - y0;\n\n  let targetX = 0, targetY = 0;\n\n  if (dx >= 0) {\n    targetX = dx / (w - x0);\n  } else {\n    targetX = dx / x0;\n  }\n  if (dy >= 0) {\n    targetY = dy / (h - y0);\n  } else {\n    targetY = dy / y0;\n  }\n  return {\n    vx: targetX,\n    vy: -targetY\n  };\n}\n\nclass Cubism2Model {\n  constructor() {\n    this.live2DMgr = new LAppLive2DManager();\n\n    this.isDrawStart = false;\n\n    this.gl = null;\n    this.canvas = null;\n\n    this.dragMgr = null; /*new L2DTargetPoint();*/\n    this.viewMatrix = null; /*new L2DViewMatrix();*/\n    this.projMatrix = null; /*new L2DMatrix44()*/\n    this.deviceToScreen = null; /*new L2DMatrix44();*/\n\n    this.oldLen = 0;\n\n    this._boundMouseEvent = this.mouseEvent.bind(this);\n    this._boundTouchEvent = this.touchEvent.bind(this);\n  }\n\n  initL2dCanvas(canvasId) {\n    this.canvas = document.getElementById(canvasId);\n\n    if (this.canvas.addEventListener) {\n      this.canvas.addEventListener('mousewheel', this._boundMouseEvent, false);\n      this.canvas.addEventListener('click', this._boundMouseEvent, false);\n\n      document.addEventListener('mousemove', this._boundMouseEvent, false);\n\n      document.addEventListener('mouseout', this._boundMouseEvent, false);\n      this.canvas.addEventListener('contextmenu', this._boundMouseEvent, false);\n\n      this.canvas.addEventListener('touchstart', this._boundTouchEvent, false);\n      this.canvas.addEventListener('touchend', this._boundTouchEvent, false);\n      this.canvas.addEventListener('touchmove', this._boundTouchEvent, false);\n    }\n  }\n\n  async init(canvasId, modelSettingPath, modelSetting) {\n    this.initL2dCanvas(canvasId);\n    const width = this.canvas.width;\n    const height = this.canvas.height;\n\n    this.dragMgr = new L2DTargetPoint();\n\n    const ratio = height / width;\n    const left = LAppDefine.VIEW_LOGICAL_LEFT;\n    const right = LAppDefine.VIEW_LOGICAL_RIGHT;\n    const bottom = -ratio;\n    const top = ratio;\n\n    this.viewMatrix = new L2DViewMatrix();\n\n    this.viewMatrix.setScreenRect(left, right, bottom, top);\n\n    this.viewMatrix.setMaxScreenRect(\n      LAppDefine.VIEW_LOGICAL_MAX_LEFT,\n      LAppDefine.VIEW_LOGICAL_MAX_RIGHT,\n      LAppDefine.VIEW_LOGICAL_MAX_BOTTOM,\n      LAppDefine.VIEW_LOGICAL_MAX_TOP,\n    );\n\n    this.viewMatrix.setMaxScale(LAppDefine.VIEW_MAX_SCALE);\n    this.viewMatrix.setMinScale(LAppDefine.VIEW_MIN_SCALE);\n\n    this.projMatrix = new L2DMatrix44();\n    this.projMatrix.multScale(1, width / height);\n\n    this.deviceToScreen = new L2DMatrix44();\n    this.deviceToScreen.multTranslate(-width / 2.0, -height / 2.0);\n    this.deviceToScreen.multScale(2 / width, -2 / width);\n\n    // https://stackoverflow.com/questions/26783586/canvas-todataurl-returns-blank-image\n    this.gl = this.canvas.getContext('webgl2', { premultipliedAlpha: true, preserveDrawingBuffer: true });\n    if (!this.gl) {\n      logger.error('Failed to create WebGL context.');\n      return;\n    }\n\n    Live2D.setGL(this.gl);\n\n    this.gl.clearColor(0.0, 0.0, 0.0, 0.0);\n\n    await this.changeModelWithJSON(modelSettingPath, modelSetting);\n\n    this.startDraw();\n  }\n\n  destroy() {\n    // 1. Unbind canvas events\n    if (this.canvas) {\n      this.canvas.removeEventListener('mousewheel', this._boundMouseEvent, false);\n      this.canvas.removeEventListener('click', this._boundMouseEvent, false);\n      document.removeEventListener('mousemove', this._boundMouseEvent, false);\n      document.removeEventListener('mouseout', this._boundMouseEvent, false);\n      this.canvas.removeEventListener('contextmenu', this._boundMouseEvent, false);\n\n      this.canvas.removeEventListener('touchstart', this._boundTouchEvent, false);\n      this.canvas.removeEventListener('touchend', this._boundTouchEvent, false);\n      this.canvas.removeEventListener('touchmove', this._boundTouchEvent, false);\n    }\n\n    // 2. Stop animation\n    if (this._drawFrameId) {\n      window.cancelAnimationFrame(this._drawFrameId);\n      this._drawFrameId = null;\n    }\n    this.isDrawStart = false;\n\n    // 3. Release Live2D related resources\n    if (this.live2DMgr && typeof this.live2DMgr.release === 'function') {\n      this.live2DMgr.release();\n    }\n\n    // 4. Clean up WebGL resources (if any)\n    if (this.gl) {\n      // Implemented via resetCanvas\n    }\n\n    // 5. Clear references to assist GC\n    this.canvas = null;\n    this.gl = null;\n    // this.live2DMgr = null;\n    this.dragMgr = null;\n    this.viewMatrix = null;\n    this.projMatrix = null;\n    this.deviceToScreen = null;\n  }\n\n  startDraw() {\n    if (!this.isDrawStart) {\n      this.isDrawStart = true;\n      const tick = () => {\n        this.draw();\n        this._drawFrameId = window.requestAnimationFrame(tick, this.canvas);\n      };\n      tick();\n    }\n  }\n\n  draw() {\n    // logger.trace(\"--> draw()\");\n\n    MatrixStack.reset();\n    MatrixStack.loadIdentity();\n\n    this.dragMgr.update();\n    this.live2DMgr.setDrag(this.dragMgr.getX(), this.dragMgr.getY());\n\n    this.gl.clear(this.gl.COLOR_BUFFER_BIT);\n\n    MatrixStack.multMatrix(this.projMatrix.getArray());\n    MatrixStack.multMatrix(this.viewMatrix.getArray());\n    MatrixStack.push();\n\n    const model = this.live2DMgr.getModel();\n\n    if (model == null) return;\n\n    if (model.initialized && !model.updating) {\n      model.update();\n      model.draw(this.gl);\n    }\n\n    MatrixStack.pop();\n  }\n\n  async changeModel(modelSettingPath) {\n    await this.live2DMgr.changeModel(this.gl, modelSettingPath);\n  }\n\n  async changeModelWithJSON(modelSettingPath, modelSetting) {\n    await this.live2DMgr.changeModelWithJSON(this.gl, modelSettingPath, modelSetting);\n  }\n\n  modelScaling(scale) {\n    const isMaxScale = this.viewMatrix.isMaxScale();\n    const isMinScale = this.viewMatrix.isMinScale();\n\n    this.viewMatrix.adjustScale(0, 0, scale);\n\n    if (!isMaxScale) {\n      if (this.viewMatrix.isMaxScale()) {\n        this.live2DMgr.maxScaleEvent();\n      }\n    }\n\n    if (!isMinScale) {\n      if (this.viewMatrix.isMinScale()) {\n        this.live2DMgr.minScaleEvent();\n      }\n    }\n  }\n\n  modelTurnHead(event) {\n    const rect = this.canvas.getBoundingClientRect();\n\n    const { vx, vy } = normalizePoint(event.clientX, event.clientY, rect.left + rect.width / 2, rect.top + rect.height / 2, window.innerWidth, window.innerHeight);\n\n    logger.trace(\n      'onMouseDown device( x:' +\n      event.clientX +\n      ' y:' +\n      event.clientY +\n      ' ) view( x:' +\n      vx +\n      ' y:' +\n      vy +\n      ')',\n    );\n\n    this.dragMgr.setPoint(vx, vy);\n    this.live2DMgr.tapEvent(vx, vy);\n\n    if (this.live2DMgr?.model.hitTest(LAppDefine.HIT_AREA_BODY, vx, vy)) {\n      window.dispatchEvent(new Event('live2d:tapbody'));\n    }\n  }\n\n  followPointer(event) {\n    const rect = this.canvas.getBoundingClientRect();\n\n    const { vx, vy } = normalizePoint(event.clientX, event.clientY, rect.left + rect.width / 2, rect.top + rect.height / 2, window.innerWidth, window.innerHeight);\n\n    logger.trace(\n      'onMouseMove device( x:' +\n      event.clientX +\n      ' y:' +\n      event.clientY +\n      ' ) view( x:' +\n      vx +\n      ' y:' +\n      vy +\n      ')',\n    );\n\n    this.dragMgr.setPoint(vx, vy);\n\n    if (this.live2DMgr?.model.hitTest(LAppDefine.HIT_AREA_BODY, vx, vy)) {\n      window.dispatchEvent(new Event('live2d:hoverbody'));\n    }\n  }\n\n  lookFront() {\n    this.dragMgr.setPoint(0, 0);\n  }\n\n  mouseEvent(e) {\n    e.preventDefault();\n\n    if (e.type == 'mousewheel') {\n      if (e.wheelDelta > 0) this.modelScaling(1.1);\n      else this.modelScaling(0.9);\n    } else if (e.type == 'click' || e.type == 'contextmenu') {\n      this.modelTurnHead(e);\n    } else if (e.type == 'mousemove') {\n      this.followPointer(e);\n    } else if (e.type == 'mouseout') {\n      this.lookFront();\n    }\n  }\n\n  touchEvent(e) {\n    e.preventDefault();\n\n    const touch = e.touches[0];\n\n    if (e.type == 'touchstart') {\n      if (e.touches.length == 1) this.modelTurnHead(touch);\n      // onClick(touch);\n    } else if (e.type == 'touchmove') {\n      this.followPointer(touch);\n\n      if (e.touches.length == 2) {\n        const touch1 = e.touches[0];\n        const touch2 = e.touches[1];\n\n        const len =\n          Math.pow(touch1.pageX - touch2.pageX, 2) +\n          Math.pow(touch1.pageY - touch2.pageY, 2);\n        if (this.oldLen - len < 0) this.modelScaling(1.025);\n        else this.modelScaling(0.975);\n\n        this.oldLen = len;\n      }\n    } else if (e.type == 'touchend') {\n      this.lookFront();\n    }\n  }\n\n  transformViewX(deviceX) {\n    const screenX = this.deviceToScreen.transformX(deviceX);\n    return this.viewMatrix.invertTransformX(screenX);\n  }\n\n  transformViewY(deviceY) {\n    const screenY = this.deviceToScreen.transformY(deviceY);\n    return this.viewMatrix.invertTransformY(screenY);\n  }\n\n  transformScreenX(deviceX) {\n    return this.deviceToScreen.transformX(deviceX);\n  }\n\n  transformScreenY(deviceY) {\n    return this.deviceToScreen.transformY(deviceY);\n  }\n}\n\nexport default Cubism2Model;\n"
  },
  {
    "path": "src/cubism2/utils/MatrixStack.js",
    "content": "/**\n *\n *  You can modify and use this source freely\n *  only for the development of application related Live2D.\n *\n *  (c) Live2D Inc. All rights reserved.\n */\n\nclass MatrixStack {\n  static reset() {\n    this.depth = 0;\n  }\n\n  static loadIdentity() {\n    for (let i = 0; i < 16; i++) {\n      this.currentMatrix[i] = i % 5 == 0 ? 1 : 0;\n    }\n  }\n\n  static push() {\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    const offset = this.depth * 16;\n    const nextOffset = (this.depth + 1) * 16;\n\n    if (this.matrixStack.length < nextOffset + 16) {\n      this.matrixStack.length = nextOffset + 16;\n    }\n\n    for (let i = 0; i < 16; i++) {\n      this.matrixStack[nextOffset + i] = this.currentMatrix[i];\n    }\n\n    this.depth++;\n  }\n\n  static pop() {\n    this.depth--;\n    if (this.depth < 0) {\n      this.depth = 0;\n    }\n\n    const offset = this.depth * 16;\n    for (let i = 0; i < 16; i++) {\n      this.currentMatrix[i] = this.matrixStack[offset + i];\n    }\n  }\n\n  static getMatrix() {\n    return this.currentMatrix;\n  }\n\n  static multMatrix(matNew) {\n    let i, j, k;\n\n    for (i = 0; i < 16; i++) {\n      this.tmp[i] = 0;\n    }\n\n    for (i = 0; i < 4; i++) {\n      for (j = 0; j < 4; j++) {\n        for (k = 0; k < 4; k++) {\n          this.tmp[i + j * 4] +=\n            this.currentMatrix[i + k * 4] * matNew[k + j * 4];\n        }\n      }\n    }\n    for (i = 0; i < 16; i++) {\n      this.currentMatrix[i] = this.tmp[i];\n    }\n  }\n}\n\nMatrixStack.matrixStack = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];\n\nMatrixStack.depth = 0;\n\nMatrixStack.currentMatrix = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];\n\nMatrixStack.tmp = new Array(16);\n\nexport default MatrixStack;\n"
  },
  {
    "path": "src/cubism2/utils/ModelSettingJson.js",
    "content": "import { Live2DFramework } from '../Live2DFramework.js';\n\nclass ModelSettingJson {\n  constructor() {\n    this.NAME = 'name';\n    this.ID = 'id';\n    this.MODEL = 'model';\n    this.TEXTURES = 'textures';\n    this.HIT_AREAS = 'hit_areas';\n    this.HIT_AREAS_CUSTOM = 'hit_areas_custom';\n    this.PHYSICS = 'physics';\n    this.POSE = 'pose';\n    this.EXPRESSIONS = 'expressions';\n    this.MOTION_GROUPS = 'motions';\n    this.SOUND = 'sound';\n    this.FADE_IN = 'fade_in';\n    this.FADE_OUT = 'fade_out';\n    this.LAYOUT = 'layout';\n    this.INIT_PARAM = 'init_param';\n    this.INIT_PARTS_VISIBLE = 'init_parts_visible';\n    this.VALUE = 'val';\n    this.FILE = 'file';\n\n    this.json = {};\n  }\n\n  loadModelSetting(path, callback) {\n    const pm = Live2DFramework.getPlatformManager();\n    pm.loadBytes(path, buf => {\n      const str = String.fromCharCode.apply(null, new Uint8Array(buf));\n      this.json = JSON.parse(str);\n      callback();\n    });\n  }\n\n  getTextureFile(n) {\n    if (this.json[this.TEXTURES] == null || this.json[this.TEXTURES][n] == null)\n      return null;\n\n    return this.json[this.TEXTURES][n];\n  }\n\n  getModelFile() {\n    return this.json[this.MODEL];\n  }\n\n  getTextureNum() {\n    if (this.json[this.TEXTURES] == null) return 0;\n\n    return this.json[this.TEXTURES].length;\n  }\n\n  getHitAreaNum() {\n    if (this.json[this.HIT_AREAS] == null) return 0;\n\n    return this.json[this.HIT_AREAS].length;\n  }\n\n  getHitAreaCustom() {\n    return this.json[this.HIT_AREAS_CUSTOM];\n  }\n\n  getHitAreaID(n) {\n    if (\n      this.json[this.HIT_AREAS] == null ||\n      this.json[this.HIT_AREAS][n] == null\n    )\n      return null;\n\n    return this.json[this.HIT_AREAS][n][this.ID];\n  }\n\n  getHitAreaName(n) {\n    if (\n      this.json[this.HIT_AREAS] == null ||\n      this.json[this.HIT_AREAS][n] == null\n    )\n      return null;\n\n    return this.json[this.HIT_AREAS][n][this.NAME];\n  }\n\n  getPhysicsFile() {\n    return this.json[this.PHYSICS];\n  }\n\n  getPoseFile() {\n    return this.json[this.POSE];\n  }\n\n  getExpressionNum() {\n    return this.json[this.EXPRESSIONS] == null\n      ? 0\n      : this.json[this.EXPRESSIONS].length;\n  }\n\n  getExpressionFile(n) {\n    if (this.json[this.EXPRESSIONS] == null) return null;\n    return this.json[this.EXPRESSIONS][n][this.FILE];\n  }\n\n  getExpressionName(n) {\n    if (this.json[this.EXPRESSIONS] == null) return null;\n    return this.json[this.EXPRESSIONS][n][this.NAME];\n  }\n\n  getLayout() {\n    return this.json[this.LAYOUT];\n  }\n\n  getInitParamNum() {\n    return this.json[this.INIT_PARAM] == null\n      ? 0\n      : this.json[this.INIT_PARAM].length;\n  }\n\n  getMotionNum(name) {\n    if (\n      this.json[this.MOTION_GROUPS] == null ||\n      this.json[this.MOTION_GROUPS][name] == null\n    )\n      return 0;\n\n    return this.json[this.MOTION_GROUPS][name].length;\n  }\n\n  getMotionFile(name, n) {\n    if (\n      this.json[this.MOTION_GROUPS] == null ||\n      this.json[this.MOTION_GROUPS][name] == null ||\n      this.json[this.MOTION_GROUPS][name][n] == null\n    )\n      return null;\n\n    return this.json[this.MOTION_GROUPS][name][n][this.FILE];\n  }\n\n  getMotionSound(name, n) {\n    if (\n      this.json[this.MOTION_GROUPS] == null ||\n      this.json[this.MOTION_GROUPS][name] == null ||\n      this.json[this.MOTION_GROUPS][name][n] == null ||\n      this.json[this.MOTION_GROUPS][name][n][this.SOUND] == null\n    )\n      return null;\n\n    return this.json[this.MOTION_GROUPS][name][n][this.SOUND];\n  }\n\n  getMotionFadeIn(name, n) {\n    if (\n      this.json[this.MOTION_GROUPS] == null ||\n      this.json[this.MOTION_GROUPS][name] == null ||\n      this.json[this.MOTION_GROUPS][name][n] == null ||\n      this.json[this.MOTION_GROUPS][name][n][this.FADE_IN] == null\n    )\n      return 1000;\n\n    return this.json[this.MOTION_GROUPS][name][n][this.FADE_IN];\n  }\n\n  getMotionFadeOut(name, n) {\n    if (\n      this.json[this.MOTION_GROUPS] == null ||\n      this.json[this.MOTION_GROUPS][name] == null ||\n      this.json[this.MOTION_GROUPS][name][n] == null ||\n      this.json[this.MOTION_GROUPS][name][n][this.FADE_OUT] == null\n    )\n      return 1000;\n\n    return this.json[this.MOTION_GROUPS][name][n][this.FADE_OUT];\n  }\n\n  getInitParamID(n) {\n    if (\n      this.json[this.INIT_PARAM] == null ||\n      this.json[this.INIT_PARAM][n] == null\n    )\n      return null;\n\n    return this.json[this.INIT_PARAM][n][this.ID];\n  }\n\n  getInitParamValue(n) {\n    if (\n      this.json[this.INIT_PARAM] == null ||\n      this.json[this.INIT_PARAM][n] == null\n    )\n      return NaN;\n\n    return this.json[this.INIT_PARAM][n][this.VALUE];\n  }\n\n  getInitPartsVisibleNum() {\n    return this.json[this.INIT_PARTS_VISIBLE] == null\n      ? 0\n      : this.json[this.INIT_PARTS_VISIBLE].length;\n  }\n\n  getInitPartsVisibleID(n) {\n    if (\n      this.json[this.INIT_PARTS_VISIBLE] == null ||\n      this.json[this.INIT_PARTS_VISIBLE][n] == null\n    )\n      return null;\n    return this.json[this.INIT_PARTS_VISIBLE][n][this.ID];\n  }\n\n  getInitPartsVisibleValue(n) {\n    if (\n      this.json[this.INIT_PARTS_VISIBLE] == null ||\n      this.json[this.INIT_PARTS_VISIBLE][n] == null\n    )\n      return NaN;\n\n    return this.json[this.INIT_PARTS_VISIBLE][n][this.VALUE];\n  }\n}\n\nexport default ModelSettingJson;\n"
  },
  {
    "path": "src/cubism5/index.js",
    "content": "/* global document, window, Event */\n\nimport { LAppDelegate } from '@demo/lappdelegate.js';\nimport { LAppSubdelegate } from '@demo/lappsubdelegate.js';\nimport * as LAppDefine from '@demo/lappdefine.js';\nimport { LAppModel } from '@demo/lappmodel.js';\nimport { LAppPal } from '@demo/lapppal';\nimport logger from '../logger.js';\n\nLAppPal.printMessage = () => {};\n\n// Custom subdelegate class, responsible for Canvas-related initialization and rendering management\nclass AppSubdelegate extends LAppSubdelegate {\n  /**\n   * Initialize resources required by the application.\n   * @param {HTMLCanvasElement} canvas The canvas object passed in\n   */\n  initialize(canvas) {\n    // Initialize WebGL manager, return false if failed\n    if (!this._glManager.initialize(canvas)) {\n      return false;\n    }\n\n    this._canvas = canvas;\n\n    // Canvas size setting, supports auto and specified size\n    if (LAppDefine.CanvasSize === 'auto') {\n      this.resizeCanvas();\n    } else {\n      canvas.width = LAppDefine.CanvasSize.width;\n      canvas.height = LAppDefine.CanvasSize.height;\n    }\n\n    // Set the GL manager for the texture manager\n    this._textureManager.setGlManager(this._glManager);\n\n    const gl = this._glManager.getGl();\n\n    // If the framebuffer object is not initialized, get the current framebuffer binding\n    if (!this._frameBuffer) {\n      this._frameBuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);\n    }\n\n    // Enable blend mode for transparency\n    gl.enable(gl.BLEND);\n    gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);\n\n    // Initialize the view (AppView)\n    this._view.initialize(this);\n    this._view._gear = {\n      render: () => {},\n      isHit: () => {},\n      release: () => {}\n    };\n    this._view._back = {\n      render: () => {},\n      release: () => {}\n    };\n    // this._view.initializeSprite();\n\n    // Associate Live2D manager with the current subdelegate\n    // this._live2dManager.initialize(this);\n    this._live2dManager._subdelegate = this;\n\n    // Listen for canvas size changes for responsive adaptation\n    this._resizeObserver = new window.ResizeObserver(\n      (entries, observer) =>\n        this.resizeObserverCallback.call(this, entries, observer)\n    );\n    this._resizeObserver.observe(this._canvas);\n\n    return true;\n  }\n\n  /**\n   * Adjust and reinitialize the view when the canvas size changes\n   */\n  onResize() {\n    this.resizeCanvas();\n    this._view.initialize(this);\n    // this._view.initializeSprite();\n  }\n\n  /**\n   * Main render loop, called periodically to update the screen\n   */\n  update() {\n    // Check if the WebGL context is lost, if so, stop rendering\n    if (this._glManager.getGl().isContextLost()) {\n      return;\n    }\n\n    // If resize is needed, call onResize\n    if (this._needResize) {\n      this.onResize();\n      this._needResize = false;\n    }\n\n    const gl = this._glManager.getGl();\n\n    // Initialize the canvas as fully transparent\n    gl.clearColor(0.0, 0.0, 0.0, 0.0);\n\n    // Enable depth test to ensure correct model occlusion\n    gl.enable(gl.DEPTH_TEST);\n\n    // Set depth function so nearer objects cover farther ones\n    gl.depthFunc(gl.LEQUAL);\n\n    // Clear color and depth buffers\n    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n    gl.clearDepth(1.0);\n\n    // Enable blend mode again to ensure transparency\n    gl.enable(gl.BLEND);\n    gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);\n\n    // Render the view content\n    this._view.render();\n  }\n}\n\n// Main application delegate class, responsible for managing the main loop, canvas, model switching, and other global logic\nexport class AppDelegate extends LAppDelegate {\n  /**\n   * Start the main loop.\n   */\n  run() {\n    // Main loop function, responsible for updating time and all subdelegates\n    const loop = () => {\n      // Update time\n      LAppPal.updateTime();\n\n      // Iterate all subdelegates and call update for rendering\n      for (let i = 0; i < this._subdelegates.getSize(); i++) {\n        this._subdelegates.at(i).update();\n      }\n\n      // Recursive call for animation loop\n      this._drawFrameId = window.requestAnimationFrame(loop);\n    };\n    loop();\n  }\n\n  stop() {\n    if (this._drawFrameId) {\n      window.cancelAnimationFrame(this._drawFrameId);\n      this._drawFrameId = null;\n    }\n  }\n\n  release() {\n    this.stop();\n    this.releaseEventListener();\n    this._subdelegates.clear();\n\n    this._cubismOption = null;\n  }\n\n  transformOffset(e) {\n    const subdelegate = this._subdelegates.at(0);\n    const rect = subdelegate.getCanvas().getBoundingClientRect();\n    const localX = e.pageX - rect.left;\n    const localY = e.pageY - rect.top;\n    const posX = localX * window.devicePixelRatio;\n    const posY = localY * window.devicePixelRatio;\n    const x = subdelegate._view.transformViewX(posX);\n    const y = subdelegate._view.transformViewY(posY);\n    return {\n      x, y\n    };\n  }\n\n  onMouseMove(e) {\n    const lapplive2dmanager = this._subdelegates.at(0).getLive2DManager();\n    const { x, y } = this.transformOffset(e);\n    const model = lapplive2dmanager._models.at(0);\n\n    lapplive2dmanager.onDrag(x, y);\n    lapplive2dmanager.onTap(x, y);\n    if (model.hitTest(LAppDefine.HitAreaNameBody, x, y)) {\n      window.dispatchEvent(new Event('live2d:hoverbody'));\n    }\n  }\n\n  onMouseEnd(e) {\n    const lapplive2dmanager = this._subdelegates.at(0).getLive2DManager();\n    const { x, y } = this.transformOffset(e);\n    lapplive2dmanager.onDrag(0.0, 0.0);\n    lapplive2dmanager.onTap(x, y);\n  }\n\n  onTap(e) {\n    const lapplive2dmanager = this._subdelegates.at(0).getLive2DManager();\n    const { x, y } = this.transformOffset(e);\n    const model = lapplive2dmanager._models.at(0);\n\n    if (model.hitTest(LAppDefine.HitAreaNameBody, x, y)) {\n      window.dispatchEvent(new Event('live2d:tapbody'));\n    }\n  }\n\n  initializeEventListener() {\n    this.mouseMoveEventListener = this.onMouseMove.bind(this);\n    this.mouseEndedEventListener = this.onMouseEnd.bind(this);\n    this.tapEventListener = this.onTap.bind(this);\n\n    document.addEventListener('mousemove', this.mouseMoveEventListener, {\n      passive: true\n    });\n    document.addEventListener('mouseout', this.mouseEndedEventListener, {\n      passive: true\n    });\n    document.addEventListener('pointerdown', this.tapEventListener, {\n      passive: true\n    });\n  }\n\n  releaseEventListener() {\n    document.removeEventListener('mousemove', this.mouseMoveEventListener, {\n      passive: true\n    });\n    this.mouseMoveEventListener = null;\n    document.removeEventListener('mouseout', this.mouseEndedEventListener, {\n      passive: true\n    });\n    this.mouseEndedEventListener = null;\n    document.removeEventListener('pointerdown', this.tapEventListener, {\n      passive: true\n    });\n  }\n\n  /**\n   * Create canvas and initialize all Subdelegates\n   */\n  initializeSubdelegates() {\n    // Reserve space to improve performance\n    this._canvases.prepareCapacity(LAppDefine.CanvasNum);\n    this._subdelegates.prepareCapacity(LAppDefine.CanvasNum);\n\n    // Get the live2d canvas element from the page\n    const canvas = document.getElementById('live2d');\n    this._canvases.pushBack(canvas);\n\n    // Set canvas style size to match actual size\n    canvas.style.width = canvas.width;\n    canvas.style.height = canvas.height;\n\n    // For each canvas, create a subdelegate and complete initialization\n    for (let i = 0; i < this._canvases.getSize(); i++) {\n      const subdelegate = new AppSubdelegate();\n      const result = subdelegate.initialize(this._canvases.at(i));\n      if (!result) {\n        logger.error('Failed to initialize AppSubdelegate');\n        return;\n      }\n      this._subdelegates.pushBack(subdelegate);\n    }\n\n    // Check if the WebGL context of each subdelegate is lost\n    for (let i = 0; i < LAppDefine.CanvasNum; i++) {\n      if (this._subdelegates.at(i).isContextLost()) {\n        logger.error(\n          `The context for Canvas at index ${i} was lost, possibly because the acquisition limit for WebGLRenderingContext was reached.`\n        );\n      }\n    }\n  }\n\n  /**\n   * Switch model\n   * @param {string} modelSettingPath Path to the model setting file\n   */\n  changeModel(modelSettingPath) {\n    const segments = modelSettingPath.split('/');\n    const modelJsonName = segments.pop();\n    const modelPath = segments.join('/') + '/';\n    // Get the current Live2D manager\n    const live2dManager = this._subdelegates.at(0).getLive2DManager();\n    // Release all old models\n    live2dManager.releaseAllModel();\n    // Create a new model instance, set subdelegate and load resources\n    const instance = new LAppModel();\n    instance.setSubdelegate(live2dManager._subdelegate);\n    instance.loadAssets(modelPath, modelJsonName);\n    // Add the new model to the model list\n    live2dManager._models.pushBack(instance);\n  }\n\n  get subdelegates() {\n    return this._subdelegates;\n  }\n}\n"
  },
  {
    "path": "src/drag.ts",
    "content": "function registerDrag() {\n  const element = document.getElementById('waifu');\n  if (!element) return;\n  let winWidth = window.innerWidth,\n    winHeight = window.innerHeight;\n  const imgWidth = element.offsetWidth,\n    imgHeight = element.offsetHeight;\n  // Bind mousedown event to the element to be dragged\n  element.addEventListener('mousedown', event => {\n    if (event.button === 2) {\n      // Right mouse button, just return, do not handle\n      return;\n    }\n    const canvas = document.getElementById('live2d');\n    if (event.target !== canvas) return;\n    event.preventDefault();\n    // Record the coordinates of the cursor when pressing down on the image\n    const _offsetX = event.offsetX,\n      _offsetY = event.offsetY;\n    // Bind mousemove event\n    document.onmousemove = event => {\n      // Get the coordinates of the cursor in the viewport\n      const _x = event.clientX,\n        _y = event.clientY;\n      // Calculate the position of the dragged image\n      let _left = _x - _offsetX,\n        _top = _y - _offsetY;\n      // Check if within the window range\n      if (_top < 0) { // Top\n        _top = 0;\n      } else if (_top >= winHeight - imgHeight) { // Bottom\n        _top = winHeight - imgHeight;\n      }\n      if (_left < 0) { // Left\n        _left = 0;\n      } else if (_left >= winWidth - imgWidth) { // Right\n        _left = winWidth - imgWidth;\n      }\n      // Set the position of the element during dragging\n      element.style.top = _top + 'px';\n      element.style.left = _left + 'px';\n    }\n    // Bind mouseup event\n    document.onmouseup = () => {\n      document.onmousemove = null;\n    }\n  });\n  // Reset width and height when the browser window size changes\n  window.onresize = () => {\n    winWidth = window.innerWidth;\n    winHeight = window.innerHeight;\n  }\n}\n\nexport default registerDrag;\n"
  },
  {
    "path": "src/icons.ts",
    "content": "const fa_comment = '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 512 512\"><!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --><path d=\"M512 240c0 114.9-114.6 208-256 208c-37.1 0-72.3-6.4-104.1-17.9c-11.9 8.7-31.3 20.6-54.3 30.6C73.6 471.1 44.7 480 16 480c-6.5 0-12.3-3.9-14.8-9.9c-2.5-6-1.1-12.8 3.4-17.4c0 0 0 0 0 0s0 0 0 0s0 0 0 0c0 0 0 0 0 0l.3-.3c.3-.3 .7-.7 1.3-1.4c1.1-1.2 2.8-3.1 4.9-5.7c4.1-5 9.6-12.4 15.2-21.6c10-16.6 19.5-38.4 21.4-62.9C17.7 326.8 0 285.1 0 240C0 125.1 114.6 32 256 32s256 93.1 256 208z\"/></svg>';\n\nconst fa_paper_plane = '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 512 512\"><!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --><path d=\"M498.1 5.6c10.1 7 15.4 19.1 13.5 31.2l-64 416c-1.5 9.7-7.4 18.2-16 23s-18.9 5.4-28 1.6L284 427.7l-68.5 74.1c-8.9 9.7-22.9 12.9-35.2 8.1S160 493.2 160 480l0-83.6c0-4 1.5-7.8 4.2-10.8L331.8 202.8c5.8-6.3 5.6-16-.4-22s-15.7-6.4-22-.7L106 360.8 17.7 316.6C7.1 311.3 .3 300.7 0 288.9s5.9-22.8 16.1-28.7l448-256c10.7-6.1 23.9-5.5 34 1.4z\"/></svg>';\n\nconst fa_street_view = '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 512 512\"><!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --><path d=\"M320 64A64 64 0 1 0 192 64a64 64 0 1 0 128 0zm-96 96c-35.3 0-64 28.7-64 64l0 48c0 17.7 14.3 32 32 32l1.8 0 11.1 99.5c1.8 16.2 15.5 28.5 31.8 28.5l38.7 0c16.3 0 30-12.3 31.8-28.5L318.2 304l1.8 0c17.7 0 32-14.3 32-32l0-48c0-35.3-28.7-64-64-64l-64 0zM132.3 394.2c13-2.4 21.7-14.9 19.3-27.9s-14.9-21.7-27.9-19.3c-32.4 5.9-60.9 14.2-82 24.8c-10.5 5.3-20.3 11.7-27.8 19.6C6.4 399.5 0 410.5 0 424c0 21.4 15.5 36.1 29.1 45c14.7 9.6 34.3 17.3 56.4 23.4C130.2 504.7 190.4 512 256 512s125.8-7.3 170.4-19.6c22.1-6.1 41.8-13.8 56.4-23.4c13.7-8.9 29.1-23.6 29.1-45c0-13.5-6.4-24.5-14-32.6c-7.5-7.9-17.3-14.3-27.8-19.6c-21-10.6-49.5-18.9-82-24.8c-13-2.4-25.5 6.3-27.9 19.3s6.3 25.5 19.3 27.9c30.2 5.5 53.7 12.8 69 20.5c3.2 1.6 5.8 3.1 7.9 4.5c3.6 2.4 3.6 7.2 0 9.6c-8.8 5.7-23.1 11.8-43 17.3C374.3 457 318.5 464 256 464s-118.3-7-157.7-17.9c-19.9-5.5-34.2-11.6-43-17.3c-3.6-2.4-3.6-7.2 0-9.6c2.1-1.4 4.8-2.9 7.9-4.5c15.3-7.7 38.8-14.9 69-20.5z\"/></svg>';\n\nconst fa_shirt = '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 640 512\"><!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --><path d=\"M211.8 0c7.8 0 14.3 5.7 16.7 13.2C240.8 51.9 277.1 80 320 80s79.2-28.1 91.5-66.8C413.9 5.7 420.4 0 428.2 0l12.6 0c22.5 0 44.2 7.9 61.5 22.3L628.5 127.4c6.6 5.5 10.7 13.5 11.4 22.1s-2.1 17.1-7.8 23.6l-56 64c-11.4 13.1-31.2 14.6-44.6 3.5L480 197.7 480 448c0 35.3-28.7 64-64 64l-192 0c-35.3 0-64-28.7-64-64l0-250.3-51.5 42.9c-13.3 11.1-33.1 9.6-44.6-3.5l-56-64c-5.7-6.5-8.5-15-7.8-23.6s4.8-16.6 11.4-22.1L137.7 22.3C155 7.9 176.7 0 199.2 0l12.6 0z\"/></svg>';\n\nconst fa_camera_retro = '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 512 512\"><!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --><path d=\"M220.6 121.2L271.1 96 448 96l0 96-114.8 0c-21.9-15.1-48.5-24-77.2-24s-55.2 8.9-77.2 24L64 192l0-64 128 0c9.9 0 19.7-2.3 28.6-6.8zM0 128L0 416c0 35.3 28.7 64 64 64l384 0c35.3 0 64-28.7 64-64l0-320c0-35.3-28.7-64-64-64L271.1 32c-9.9 0-19.7 2.3-28.6 6.8L192 64l-32 0 0-16c0-8.8-7.2-16-16-16L80 32c-8.8 0-16 7.2-16 16l0 16C28.7 64 0 92.7 0 128zM168 304a88 88 0 1 1 176 0 88 88 0 1 1 -176 0z\"/></svg>';\n\nconst fa_info_circle = '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 512 512\"><!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --><path d=\"M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM216 336l24 0 0-64-24 0c-13.3 0-24-10.7-24-24s10.7-24 24-24l48 0c13.3 0 24 10.7 24 24l0 88 8 0c13.3 0 24 10.7 24 24s-10.7 24-24 24l-80 0c-13.3 0-24-10.7-24-24s10.7-24 24-24zm40-208a32 32 0 1 1 0 64 32 32 0 1 1 0-64z\"/></svg>';\n\nconst fa_xmark = '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 384 512\"><!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --><path d=\"M342.6 150.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L192 210.7 86.6 105.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L146.7 256 41.4 361.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0L192 301.3 297.4 406.6c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L237.3 256 342.6 150.6z\"/></svg>';\n\nconst fa_child = '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 320 512\"><!--! Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc. --><path d=\"M96 64a64 64 0 1 1 128 0A64 64 0 1 1 96 64zm48 320l0 96c0 17.7-14.3 32-32 32s-32-14.3-32-32l0-192.2L59.1 321c-9.4 15-29.2 19.4-44.1 10S-4.5 301.9 4.9 287l39.9-63.3C69.7 184 113.2 160 160 160s90.3 24 115.2 63.6L315.1 287c9.4 15 4.9 34.7-10 44.1s-34.7 4.9-44.1-10L240 287.8 240 480c0 17.7-14.3 32-32 32s-32-14.3-32-32l0-96-32 0z\"/></svg>';\n\nexport {\n  fa_comment,\n  fa_paper_plane,\n  fa_street_view,\n  fa_shirt,\n  fa_camera_retro,\n  fa_info_circle,\n  fa_xmark,\n  fa_child\n}\n"
  },
  {
    "path": "src/index.ts",
    "content": "/**\n * @file Main module.\n * @module index\n */\n\nexport { default as registerDrag } from './drag.js';\nexport { default as logger, LogLevel } from './logger.js';\nexport { default as Cubism2Model } from './cubism2/index.js';\n\nexport * from './tools.js';\nexport * from './message.js';\nexport * from './model.js';\nexport * from './utils.js';\nexport * from './widget.js';\n"
  },
  {
    "path": "src/logger.ts",
    "content": "type LogLevel = 'error' | 'warn' | 'info' | 'trace';\n\nclass Logger {\n  private static levelOrder: Record<LogLevel, number> = {\n    error: 0,\n    warn: 1,\n    info: 2,\n    trace: 3,\n  };\n\n  private level: LogLevel;\n\n  constructor(level: LogLevel = 'info') {\n    this.level = level;\n  }\n\n  setLevel(level: LogLevel | undefined) {\n    if (!level) return;\n    this.level = level;\n  }\n\n  private shouldLog(level: LogLevel): boolean {\n    return Logger.levelOrder[level] <= Logger.levelOrder[this.level];\n  }\n\n  error(message: string, ...args: any[]) {\n    if (this.shouldLog('error')) {\n      console.error('[Live2D Widget][ERROR]', message, ...args);\n    }\n  }\n\n  warn(message: string, ...args: any[]) {\n    if (this.shouldLog('warn')) {\n      console.warn('[Live2D Widget][WARN]', message, ...args);\n    }\n  }\n\n  info(message: string, ...args: any[]) {\n    if (this.shouldLog('info')) {\n      console.log('[Live2D Widget][INFO]', message, ...args);\n    }\n  }\n\n  trace(message: string, ...args: any[]) {\n    if (this.shouldLog('trace')) {\n      console.log('[Live2D Widget][TRACE]', message, ...args);\n    }\n  }\n}\n\nconst logger = new Logger();\n\nexport default logger;\nexport { LogLevel };\n"
  },
  {
    "path": "src/message.ts",
    "content": "/**\n * @file Contains functions for displaying waifu messages.\n * @module message\n */\n\nimport { randomSelection } from './utils.js';\n\ntype Time = {\n  /**\n   * Time period, format is \"HH-HH\", e.g. \"00-06\" means from 0 to 6 o'clock.\n   * @type {string}\n   */\n  hour: string;\n  /**\n   * Message to display during this time period.\n   * @type {string}\n   */\n  text: string;\n}[];\n\nlet messageTimer: NodeJS.Timeout | null = null;\n\n/**\n * Display waifu message.\n * @param {string | string[]} text - Message text or array of texts.\n * @param {number} timeout - Timeout for message display (ms).\n * @param {number} priority - Priority of the message.\n * @param {boolean} [override=true] - Whether to override existing message.\n */\nfunction showMessage(\n  text: string | string[],\n  timeout: number,\n  priority: number,\n  override: boolean = true\n) {\n  let currentPriority = parseInt(sessionStorage.getItem('waifu-message-priority'), 10);\n  if (isNaN(currentPriority)) {\n    currentPriority = 0;\n  }\n  if (\n    !text ||\n    (override && currentPriority > priority) ||\n    (!override && currentPriority >= priority)\n  )\n    return;\n  if (messageTimer) {\n    clearTimeout(messageTimer);\n    messageTimer = null;\n  }\n  text = randomSelection(text) as string;\n  sessionStorage.setItem('waifu-message-priority', String(priority));\n  const tips = document.getElementById('waifu-tips')!;\n  tips.innerHTML = text;\n  tips.classList.add('waifu-tips-active');\n  messageTimer = setTimeout(() => {\n    sessionStorage.removeItem('waifu-message-priority');\n    tips.classList.remove('waifu-tips-active');\n  }, timeout);\n}\n\n/**\n * Show welcome message based on time.\n * @param {Time} time - Time message configuration.\n * @param {string} [welcomeTemplate] - Welcome message template.\n * @param {string} [referrerTemplate] - Referrer message template.\n * @returns {string} Welcome message.\n */\nfunction welcomeMessage(time: Time, welcomeTemplate?: string, referrerTemplate?: string): string {\n  if (location.pathname === '/') {\n    // If on the homepage\n    for (const { hour, text } of time) {\n      const now = new Date(),\n        after = hour.split('-')[0],\n        before = hour.split('-')[1] || after;\n      if (\n        Number(after) <= now.getHours() &&\n        now.getHours() <= Number(before)\n      ) {\n        return text;\n      }\n    }\n  }\n  if (!welcomeTemplate) return '';\n  const text = i18n(welcomeTemplate, document.title);\n  if (document.referrer === '' || !referrerTemplate) return text;\n\n  const referrer = new URL(document.referrer);\n  if (location.hostname === referrer.hostname) return text;\n  return `${i18n(referrerTemplate, referrer.hostname)}<br>${text}`;\n}\n\nfunction i18n(template: string, ...args: string[]) {\n  return template.replace(/\\$(\\d+)/g, (_, idx) => {\n    const i = parseInt(idx, 10) - 1;\n    return args[i] ?? '';\n  });\n}\n\nexport { showMessage, welcomeMessage, i18n, Time };\n"
  },
  {
    "path": "src/model.ts",
    "content": "/**\n * @file Contains classes related to waifu model loading and management.\n * @module model\n */\n\nimport { showMessage } from './message.js';\nimport { loadExternalResource, randomOtherOption } from './utils.js';\nimport type Cubism2Model from './cubism2/index.js';\nimport type { AppDelegate as Cubism5Model } from './cubism5/index.js';\nimport logger, { LogLevel } from './logger.js';\n\ninterface ModelListCDN {\n  messages: string[];\n  models: string | string[];\n}\n\ninterface ModelList {\n  name: string;\n  paths: string[];\n  message: string;\n}\n\ninterface Config {\n  /**\n   * Path to the waifu configuration file.\n   * @type {string}\n   */\n  waifuPath: string;\n  /**\n   * Path to the API, if you need to load models via API.\n   * @type {string | undefined}\n   */\n  apiPath?: string;\n  /**\n   * Path to the CDN, if you need to load models via CDN.\n   * @type {string | undefined}\n   */\n  cdnPath?: string;\n  /**\n   * Path to Cubism 2 Core, if you need to load Cubism 2 models.\n   * @type {string | undefined}\n   */\n  cubism2Path?: string;\n  /**\n   * Path to Cubism 5 Core, if you need to load Cubism 3 and later models.\n   * @type {string | undefined}\n   */\n  cubism5Path?: string;\n  /**\n   * Default model id.\n   * @type {string | undefined}\n   */\n  modelId?: number;\n  /**\n   * List of tools to display.\n   * @type {string[] | undefined}\n   */\n  tools?: string[];\n  /**\n   * Support for dragging the waifu.\n   * @type {boolean | undefined}\n   */\n  drag?: boolean;\n  /**\n   * Log level.\n   * @type {LogLevel | undefined}\n   */\n  logLevel?: LogLevel;\n}\n\n/**\n * Waifu model class, responsible for loading and managing models.\n */\nclass ModelManager {\n  public readonly useCDN: boolean;\n  private readonly cdnPath: string;\n  private readonly cubism2Path: string;\n  private readonly cubism5Path: string;\n  private _modelId: number;\n  private _modelTexturesId: number;\n  private modelList: ModelListCDN | null = null;\n  private cubism2model: Cubism2Model | undefined;\n  private cubism5model: Cubism5Model | undefined;\n  private currentModelVersion: number;\n  private loading: boolean;\n  private modelJSONCache: Record<string, any>;\n  private models: ModelList[];\n\n  /**\n   * Create a Model instance.\n   * @param {Config} config - Configuration options\n   */\n  private constructor(config: Config, models: ModelList[] = []) {\n    let { apiPath, cdnPath } = config;\n    const { cubism2Path, cubism5Path } = config;\n    let useCDN = false;\n    if (typeof cdnPath === 'string') {\n      if (!cdnPath.endsWith('/')) cdnPath += '/';\n      useCDN = true;\n    } else if (typeof apiPath === 'string') {\n      if (!apiPath.endsWith('/')) apiPath += '/';\n      cdnPath = apiPath;\n      useCDN = true;\n      logger.warn('apiPath option is deprecated. Please use cdnPath instead.');\n    } else if (!models.length) {\n      throw 'Invalid initWidget argument!';\n    }\n    let modelId: number = parseInt(localStorage.getItem('modelId') as string, 10);\n    let modelTexturesId: number = parseInt(\n      localStorage.getItem('modelTexturesId') as string, 10\n    );\n    if (isNaN(modelId) || isNaN(modelTexturesId)) {\n      modelTexturesId = 0;\n    }\n    if (isNaN(modelId)) {\n      modelId = config.modelId ?? 0;\n    }\n    this.useCDN = useCDN;\n    this.cdnPath = cdnPath || '';\n    this.cubism2Path = cubism2Path || '';\n    this.cubism5Path = cubism5Path || '';\n    this._modelId = modelId;\n    this._modelTexturesId = modelTexturesId;\n    this.currentModelVersion = 0;\n    this.loading = false;\n    this.modelJSONCache = {};\n    this.models = models;\n  }\n\n  public static async initCheck(config: Config, models: ModelList[] = []) {\n    const model = new ModelManager(config, models);\n    if (model.useCDN) {\n      const response = await fetch(`${model.cdnPath}model_list.json`);\n      model.modelList = await response.json();\n      if (model.modelId >= model.modelList.models.length) {\n        model.modelId = 0;\n      }\n      const modelName = model.modelList.models[model.modelId];\n      if (Array.isArray(modelName)) {\n        if (model.modelTexturesId >= modelName.length) {\n          model.modelTexturesId = 0;\n        }\n      } else {\n        const modelSettingPath = `${model.cdnPath}model/${modelName}/index.json`;\n        const modelSetting = await model.fetchWithCache(modelSettingPath);\n        const version = model.checkModelVersion(modelSetting);\n        if (version === 2) {\n          const textureCache = await model.loadTextureCache(modelName);\n          if (model.modelTexturesId >= textureCache.length) {\n            model.modelTexturesId = 0;\n          }\n        }\n      }\n    } else {\n      if (model.modelId >= model.models.length) {\n        model.modelId = 0;\n      }\n      if (model.modelTexturesId >= model.models[model.modelId].paths.length) {\n        model.modelTexturesId = 0;\n      }\n    }\n    return model;\n  }\n\n  public set modelId(modelId: number) {\n    this._modelId = modelId;\n    localStorage.setItem('modelId', modelId.toString());\n  }\n\n  public get modelId() {\n    return this._modelId;\n  }\n\n  public set modelTexturesId(modelTexturesId: number) {\n    this._modelTexturesId = modelTexturesId;\n    localStorage.setItem('modelTexturesId', modelTexturesId.toString());\n  }\n\n  public get modelTexturesId() {\n    return this._modelTexturesId;\n  }\n\n  resetCanvas() {\n    document.getElementById('waifu-canvas').innerHTML = '<canvas id=\"live2d\" width=\"800\" height=\"800\"></canvas>';\n  }\n\n  async fetchWithCache(url: string) {\n    let result;\n    if (url in this.modelJSONCache) {\n      result = this.modelJSONCache[url];\n    } else {\n      try {\n        const response = await fetch(url);\n        result = await response.json();\n      } catch {\n        result = null;\n      }\n      this.modelJSONCache[url] = result;\n    }\n    return result;\n  }\n\n  checkModelVersion(modelSetting: any) {\n    if (modelSetting.Version === 3 || modelSetting.FileReferences) {\n      return 3;\n    }\n    return 2;\n  }\n\n  async loadLive2D(modelSettingPath: string, modelSetting: object) {\n    if (this.loading) {\n      logger.warn('Still loading. Abort.');\n      return;\n    }\n    this.loading = true;\n    try {\n      const version = this.checkModelVersion(modelSetting);\n      if (version === 2) {\n        if (!this.cubism2model) {\n          if (!this.cubism2Path) {\n            logger.error('No cubism2Path set, cannot load Cubism 2 Core.')\n            return;\n          }\n          await loadExternalResource(this.cubism2Path, 'js');\n          const { default: Cubism2Model } = await import('./cubism2/index.js');\n          this.cubism2model = new Cubism2Model();\n        }\n        if (this.currentModelVersion === 3) {\n          (this.cubism5model as any).release();\n          // Recycle WebGL resources\n          this.resetCanvas();\n        }\n        if (this.currentModelVersion === 3 || !this.cubism2model.gl) {\n          await this.cubism2model.init('live2d', modelSettingPath, modelSetting);\n        } else {\n          await this.cubism2model.changeModelWithJSON(modelSettingPath, modelSetting);\n        }\n      } else {\n        if (!this.cubism5Path) {\n          logger.error('No cubism5Path set, cannot load Cubism 5 Core.')\n          return;\n        }\n        await loadExternalResource(this.cubism5Path, 'js');\n        const { AppDelegate: Cubism5Model } = await import('./cubism5/index.js');\n        this.cubism5model = new (Cubism5Model as any)();\n        if (this.currentModelVersion === 2) {\n          this.cubism2model.destroy();\n          // Recycle WebGL resources\n          this.resetCanvas();\n        }\n        if (this.currentModelVersion === 2 || !this.cubism5model.subdelegates.at(0)) {\n          this.cubism5model.initialize();\n          this.cubism5model.changeModel(modelSettingPath);\n          this.cubism5model.run();\n        } else {\n          this.cubism5model.changeModel(modelSettingPath);\n        }\n      }\n      logger.info(`Model ${modelSettingPath} (Cubism version ${version}) loaded`);\n      this.currentModelVersion = version;\n    } catch (err) {\n      console.error('loadLive2D failed', err);\n    }\n    this.loading = false;\n  }\n\n  async loadTextureCache(modelName: string): Promise<any[]> {\n    const textureCache = await this.fetchWithCache(`${this.cdnPath}model/${modelName}/textures.cache`);\n    return textureCache || [];\n  }\n\n  /**\n   * Load the specified model.\n   * @param {string | string[]} message - Loading message.\n   */\n  async loadModel(message: string | string[]) {\n    let modelSettingPath, modelSetting;\n    if (this.useCDN) {\n      let modelName = this.modelList.models[this.modelId];\n      if (Array.isArray(modelName)) {\n        modelName = modelName[this.modelTexturesId];\n      }\n      modelSettingPath = `${this.cdnPath}model/${modelName}/index.json`;\n      modelSetting = await this.fetchWithCache(modelSettingPath);\n      const version = this.checkModelVersion(modelSetting);\n      if (version === 2) {\n        const textureCache = await this.loadTextureCache(modelName);\n        // this.loadTextureCache may return an empty array\n        if (textureCache.length > 0) {\n          let textures = textureCache[this.modelTexturesId];\n          if (typeof textures === 'string') textures = [textures];\n          modelSetting.textures = textures;\n        }\n      }\n    } else {\n      modelSettingPath = this.models[this.modelId].paths[this.modelTexturesId];\n      modelSetting = await this.fetchWithCache(modelSettingPath);\n    }\n    await this.loadLive2D(modelSettingPath, modelSetting);\n    showMessage(message, 4000, 10);\n  }\n\n  /**\n   * Load a random texture for the current model.\n   */\n  async loadRandTexture(successMessage: string | string[] = '', failMessage: string | string[] = '') {\n    const { modelId } = this;\n    let noTextureAvailable = false;\n    if (this.useCDN) {\n      const modelName = this.modelList.models[modelId];\n      if (Array.isArray(modelName)) {\n        this.modelTexturesId = randomOtherOption(modelName.length, this.modelTexturesId);\n      } else {\n        const modelSettingPath = `${this.cdnPath}model/${modelName}/index.json`;\n        const modelSetting = await this.fetchWithCache(modelSettingPath);\n        const version = this.checkModelVersion(modelSetting);\n        if (version === 2) {\n          const textureCache = await this.loadTextureCache(modelName);\n          if (textureCache.length <= 1) {\n            noTextureAvailable = true;\n          } else {\n            this.modelTexturesId = randomOtherOption(textureCache.length, this.modelTexturesId);\n          }\n        } else {\n          noTextureAvailable = true;\n        }\n      }\n    } else {\n      if (this.models[modelId].paths.length === 1) {\n        noTextureAvailable = true;\n      } else {\n        this.modelTexturesId = randomOtherOption(this.models[modelId].paths.length, this.modelTexturesId);\n      }\n    }\n    if (noTextureAvailable) {\n      showMessage(failMessage, 4000, 10);\n    } else {\n      await this.loadModel(successMessage);\n    }\n  }\n\n  /**\n   * Load the next character's model.\n   */\n  async loadNextModel() {\n    this.modelTexturesId = 0;\n    if (this.useCDN) {\n      this.modelId = (this.modelId + 1) % this.modelList.models.length;\n      await this.loadModel(this.modelList.messages[this.modelId]);\n    } else {\n      this.modelId = (this.modelId + 1) % this.models.length;\n      await this.loadModel(this.models[this.modelId].message);\n    }\n  }\n}\n\nexport { ModelManager, Config, ModelList };\n"
  },
  {
    "path": "src/tools.ts",
    "content": "/**\n * @file Contains the configuration and functions for waifu tools.\n * @module tools\n */\n\nimport {\n  fa_comment,\n  fa_paper_plane,\n  fa_street_view,\n  fa_shirt,\n  fa_camera_retro,\n  fa_info_circle,\n  fa_xmark\n} from './icons.js';\nimport { showMessage, i18n } from './message.js';\nimport type { Config, ModelManager } from './model.js';\nimport type { Tips } from './widget.js';\n\ninterface Tools {\n  /**\n   * Key-value pairs of tools, where the key is the tool name.\n   * @type {string}\n   */\n  [key: string]: {\n    /**\n     * Icon of the tool, usually an SVG string.\n     * @type {string}\n     */\n    icon: string;\n    /**\n     * Callback function for the tool.\n     * @type {() => void}\n     */\n    callback: (message: any) => void;\n  };\n}\n\n/**\n * Waifu tools manager.\n */\nclass ToolsManager {\n  tools: Tools;\n  config: Config;\n\n  constructor(model: ModelManager, config: Config, tips: Tips) {\n    this.config = config;\n    this.tools = {\n      hitokoto: {\n        icon: fa_comment,\n        callback: async () => {\n          // Add hitokoto.cn API\n          const response = await fetch('https://v1.hitokoto.cn');\n          const result = await response.json();\n          const template = tips.message.hitokoto;\n          const text = i18n(template, result.from, result.creator);\n          showMessage(result.hitokoto, 6000, 9);\n          setTimeout(() => {\n            showMessage(text, 4000, 9);\n          }, 6000);\n        }\n      },\n      asteroids: {\n        icon: fa_paper_plane,\n        callback: () => {\n          if (window.Asteroids) {\n            if (!window.ASTEROIDSPLAYERS) window.ASTEROIDSPLAYERS = [];\n            window.ASTEROIDSPLAYERS.push(new window.Asteroids());\n          } else {\n            const script = document.createElement('script');\n            script.src =\n              'https://fastly.jsdelivr.net/gh/stevenjoezhang/asteroids/asteroids.js';\n            document.head.appendChild(script);\n          }\n        }\n      },\n      'switch-model': {\n        icon: fa_street_view,\n        callback: () => model.loadNextModel()\n      },\n      'switch-texture': {\n        icon: fa_shirt,\n        callback: () => {\n          let successMessage = '', failMessage = '';\n          if (tips) {\n            successMessage = tips.message.changeSuccess;\n            failMessage = tips.message.changeFail;\n          }\n          model.loadRandTexture(successMessage, failMessage);\n        }\n      },\n      photo: {\n        icon: fa_camera_retro,\n        callback: () => {\n          const message = tips.message.photo;\n          showMessage(message, 6000, 9);\n          const canvas = document.getElementById('live2d') as HTMLCanvasElement;\n          if (!canvas) return;\n          const imageUrl = canvas.toDataURL();\n\n          const link = document.createElement('a');\n          link.style.display = 'none';\n          link.href = imageUrl;\n          link.download = 'live2d-photo.png';\n\n          document.body.appendChild(link);\n          link.click();\n          document.body.removeChild(link);\n        }\n      },\n      info: {\n        icon: fa_info_circle,\n        callback: () => {\n          open('https://github.com/stevenjoezhang/live2d-widget');\n        }\n      },\n      quit: {\n        icon: fa_xmark,\n        callback: () => {\n          localStorage.setItem('waifu-display', Date.now().toString());\n          const message = tips.message.goodbye;\n          showMessage(message, 2000, 11);\n          const waifu = document.getElementById('waifu');\n          if (!waifu) return;\n          waifu.classList.remove('waifu-active');\n          setTimeout(() => {\n            waifu.classList.add('waifu-hidden');\n            const waifuToggle = document.getElementById('waifu-toggle');\n            waifuToggle?.classList.add('waifu-toggle-active');\n          }, 3000);\n        }\n      }\n    };\n  }\n\n  registerTools() {\n    if (!Array.isArray(this.config.tools)) {\n      this.config.tools = Object.keys(this.tools);\n    }\n    for (const toolName of this.config.tools) {\n      if (this.tools[toolName]) {\n        const { icon, callback } = this.tools[toolName];\n        const element = document.createElement('span');\n        element.id = `waifu-tool-${toolName}`;\n        element.innerHTML = icon;\n        document\n          .getElementById('waifu-tool')\n          ?.insertAdjacentElement(\n            'beforeend',\n            element,\n          );\n        element.addEventListener('click', callback);\n      }\n    }\n  }\n}\n\nexport { ToolsManager, Tools };\n"
  },
  {
    "path": "src/types/index.d.ts",
    "content": "/**\n * @file Export all type definitions.\n * @module types/index\n */\nexport * from './live2dApi';\nexport * from './window';\n"
  },
  {
    "path": "src/types/live2dApi.d.ts",
    "content": "/**\n * @file Define types for Live2D API.\n * @module types/live2dApi\n */\ndeclare namespace Live2D {\n  /**\n   * Initialize the Live2D runtime environment.\n   */\n  export function init(): void;\n  /**\n   * Set the WebGL context\n   * @param gl WebGL rendering context\n   */\n  export function setGL(gl: WebGLRenderingContext): void;\n}\n\n/**\n * Static class related to Live2D models.\n */\ndeclare class Live2DModelWebGL {\n  /**\n   * Load a Live2D model from a binary buffer\n   * @param buf ArrayBuffer data of the model file\n   */\n  static loadModel(buf: ArrayBuffer): Live2DModelWebGL;\n\n  /**\n   * Bind a texture to the model\n   * @param index Texture index\n   * @param texture WebGL texture object\n   */\n  setTexture(index: number, texture: WebGLTexture): void;\n\n  /**\n   * Return the canvas width of the model\n   */\n  getCanvasWidth(): number;\n\n  /**\n   * Set the transformation matrix of the model\n   * @param matrix 4x4 matrix array\n   */\n  setMatrix(matrix: number[]): void;\n\n  /**\n   * Set parameter values (e.g., animation parameters)\n   * @param paramName Parameter name\n   * @param value Parameter value\n   */\n  setParamFloat(paramName: string, value: number): void;\n\n  /**\n   * Refresh the internal data of the model\n   */\n  update(): void;\n\n  /**\n   * Draw the current frame\n   */\n  draw(): void;\n\n  /**\n   * Whether the current mode is premultiplied alpha\n   */\n  isPremultipliedAlpha?(): boolean;\n}\n"
  },
  {
    "path": "src/types/window.d.ts",
    "content": "/**\n * @file Define the type of the global window object.\n * @module types/window\n */\ninterface Window {\n  /**\n   * Asteroids game class.\n   * @type {any}\n   */\n  Asteroids: any;\n   /**\n   * Asteroids game player array.\n   * @type {any[]}\n   */\n  ASTEROIDSPLAYERS: any[];\n  /**\n   * Function to initialize the Live2D widget.\n   * @type {(config: Config) => void}\n   */\n  initWidget: (config: Config) => void;\n}\n"
  },
  {
    "path": "src/utils.ts",
    "content": "/**\n * @file Contains utility functions.\n * @module utils\n */\n\n/**\n * Randomly select an element from an array, or return the original value if not an array.\n * @param {string[] | string} obj - The object or array to select from.\n * @returns {string} The randomly selected element or the original value.\n */\nfunction randomSelection(obj: string[] | string): string {\n  return Array.isArray(obj) ? obj[Math.floor(Math.random() * obj.length)] : obj;\n}\n\nfunction randomOtherOption(total: number, excludeIndex: number): number {\n  const idx = Math.floor(Math.random() * (total - 1));\n  return idx >= excludeIndex ? idx + 1 : idx;\n}\n\n/**\n * Asynchronously load external resources.\n * @param {string} url - Resource path.\n * @param {string} type - Resource type.\n */\nfunction loadExternalResource(url: string, type: string): Promise<string> {\n  return new Promise((resolve: any, reject: any) => {\n    let tag;\n\n    if (type === 'css') {\n      tag = document.createElement('link');\n      tag.rel = 'stylesheet';\n      tag.href = url;\n    }\n    else if (type === 'js') {\n      tag = document.createElement('script');\n      tag.src = url;\n    }\n    if (tag) {\n      tag.onload = () => resolve(url);\n      tag.onerror = () => reject(url);\n      document.head.appendChild(tag);\n    }\n  });\n}\n\nexport { randomSelection, loadExternalResource, randomOtherOption };\n"
  },
  {
    "path": "src/waifu-tips.ts",
    "content": "/**\n * @file Export initWidget function to window.\n * @module waifu-tips\n */\n\nimport { initWidget } from './widget.js';\n\nwindow.initWidget = initWidget;\n"
  },
  {
    "path": "src/widget.ts",
    "content": "/**\n * @file Contains functions for initializing the waifu widget.\n * @module widget\n */\n\nimport { ModelManager, Config, ModelList } from './model.js';\nimport { showMessage, welcomeMessage, Time } from './message.js';\nimport { randomSelection } from './utils.js';\nimport { ToolsManager } from './tools.js';\nimport logger from './logger.js';\nimport registerDrag from './drag.js';\nimport { fa_child } from './icons.js';\n\ninterface Tips {\n  /**\n   * Default message configuration.\n   */\n  message: {\n    /**\n     * Default message array.\n     * @type {string[]}\n     */\n    default: string[];\n    /**\n     * Console message.\n     * @type {string}\n     */\n    console: string;\n    /**\n     * Copy message.\n     * @type {string}\n     */\n    copy: string;\n    /**\n     * Visibility change message.\n     * @type {string}\n     */\n    visibilitychange: string;\n    changeSuccess: string;\n    changeFail: string;\n    photo: string;\n    goodbye: string;\n    hitokoto: string;\n    welcome: string;\n    referrer: string;\n    hoverBody: string | string[];\n    tapBody: string | string[];\n  };\n  /**\n   * Time configuration.\n   * @type {Time}\n   */\n  time: Time;\n  /**\n   * Mouseover message configuration.\n   * @type {Array<{selector: string, text: string | string[]}>}\n   */\n  mouseover: {\n    selector: string;\n    text: string | string[];\n  }[];\n  /**\n   * Click message configuration.\n   * @type {Array<{selector: string, text: string | string[]}>}\n   */\n  click: {\n    selector: string;\n    text: string | string[];\n  }[];\n  /**\n   * Season message configuration.\n   * @type {Array<{date: string, text: string | string[]}>}\n   */\n  seasons: {\n    date: string;\n    text: string | string[];\n  }[];\n  models: ModelList[];\n}\n\n/**\n * Register event listeners.\n * @param {Tips} tips - Result configuration.\n */\nfunction registerEventListener(tips: Tips) {\n  // Detect user activity and display messages when idle\n  let userAction = false;\n  let userActionTimer: any;\n  const messageArray = tips.message.default;\n  tips.seasons.forEach(({ date, text }) => {\n    const now = new Date(),\n      after = date.split('-')[0],\n      before = date.split('-')[1] || after;\n    if (\n      Number(after.split('/')[0]) <= now.getMonth() + 1 &&\n      now.getMonth() + 1 <= Number(before.split('/')[0]) &&\n      Number(after.split('/')[1]) <= now.getDate() &&\n      now.getDate() <= Number(before.split('/')[1])\n    ) {\n      text = randomSelection(text);\n      text = (text as string).replace('{year}', String(now.getFullYear()));\n      messageArray.push(text);\n    }\n  });\n  let lastHoverElement: any;\n  window.addEventListener('mousemove', () => (userAction = true));\n  window.addEventListener('keydown', () => (userAction = true));\n  setInterval(() => {\n    if (userAction) {\n      userAction = false;\n      clearInterval(userActionTimer);\n      userActionTimer = null;\n    } else if (!userActionTimer) {\n      userActionTimer = setInterval(() => {\n        showMessage(messageArray, 6000, 9);\n      }, 20000);\n    }\n  }, 1000);\n\n  window.addEventListener('mouseover', (event) => {\n    // eslint-disable-next-line prefer-const\n    for (let { selector, text } of tips.mouseover) {\n      if (!(event.target as HTMLElement)?.closest(selector)) continue;\n      if (lastHoverElement === selector) return;\n      lastHoverElement = selector;\n      text = randomSelection(text);\n      text = (text as string).replace(\n        '{text}',\n        (event.target as HTMLElement).innerText,\n      );\n      showMessage(text, 4000, 8);\n      return;\n    }\n  });\n  window.addEventListener('click', (event) => {\n    // eslint-disable-next-line prefer-const\n    for (let { selector, text } of tips.click) {\n      if (!(event.target as HTMLElement)?.closest(selector)) continue;\n      text = randomSelection(text);\n      text = (text as string).replace(\n        '{text}',\n        (event.target as HTMLElement).innerText,\n      );\n      showMessage(text, 4000, 8);\n      return;\n    }\n  });\n  window.addEventListener('live2d:hoverbody', () => {\n    const text = randomSelection(tips.message.hoverBody);\n    showMessage(text, 4000, 8, false);\n  });\n  window.addEventListener('live2d:tapbody', () => {\n    const text = randomSelection(tips.message.tapBody);\n    showMessage(text, 4000, 9);\n  });\n\n  const devtools = () => {};\n  console.log('%c', devtools);\n  devtools.toString = () => {\n    showMessage(tips.message.console, 6000, 9);\n  };\n  window.addEventListener('copy', () => {\n    showMessage(tips.message.copy, 6000, 9);\n  });\n  window.addEventListener('visibilitychange', () => {\n    if (!document.hidden)\n      showMessage(tips.message.visibilitychange, 6000, 9);\n  });\n}\n\n/**\n * Load the waifu widget.\n * @param {Config} config - Waifu configuration.\n */\nasync function loadWidget(config: Config) {\n  localStorage.removeItem('waifu-display');\n  sessionStorage.removeItem('waifu-message-priority');\n  document.body.insertAdjacentHTML(\n    'beforeend',\n    `<div id=\"waifu\">\n       <div id=\"waifu-tips\"></div>\n       <div id=\"waifu-canvas\">\n         <canvas id=\"live2d\" width=\"800\" height=\"800\"></canvas>\n       </div>\n       <div id=\"waifu-tool\"></div>\n     </div>`,\n  );\n  let models: ModelList[] = [];\n  let tips: Tips | null;\n  if (config.waifuPath) {\n    const response = await fetch(config.waifuPath);\n    tips = await response.json();\n    models = tips.models;\n    registerEventListener(tips);\n    showMessage(welcomeMessage(tips.time, tips.message.welcome, tips.message.referrer), 7000, 11);\n  }\n  const model = await ModelManager.initCheck(config, models);\n  await model.loadModel('');\n  new ToolsManager(model, config, tips).registerTools();\n  if (config.drag) registerDrag();\n  document.getElementById('waifu')?.classList.add('waifu-active');\n}\n\n/**\n * Initialize the waifu widget.\n * @param {string | Config} config - Waifu configuration or configuration path.\n */\nfunction initWidget(config: string | Config) {\n  if (typeof config === 'string') {\n    logger.error('Your config for Live2D initWidget is outdated. Please refer to https://github.com/stevenjoezhang/live2d-widget/blob/master/dist/autoload.js');\n    return;\n  }\n  logger.setLevel(config.logLevel);\n  document.body.insertAdjacentHTML(\n    'beforeend',\n    `<div id=\"waifu-toggle\">\n       ${fa_child}\n     </div>`,\n  );\n  const toggle = document.getElementById('waifu-toggle');\n  toggle?.addEventListener('click', () => {\n    toggle?.classList.remove('waifu-toggle-active');\n    if (toggle?.getAttribute('first-time')) {\n      loadWidget(config as Config);\n      toggle?.removeAttribute('first-time');\n    } else {\n      localStorage.removeItem('waifu-display');\n      document.getElementById('waifu')?.classList.remove('waifu-hidden');\n      setTimeout(() => {\n        document.getElementById('waifu')?.classList.add('waifu-active');\n      }, 0);\n    }\n  });\n  if (\n    localStorage.getItem('waifu-display') &&\n    Date.now() - Number(localStorage.getItem('waifu-display')) <= 86400000\n  ) {\n    toggle?.setAttribute('first-time', 'true');\n    setTimeout(() => {\n      toggle?.classList.add('waifu-toggle-active');\n    }, 0);\n  } else {\n    loadWidget(config as Config);\n  }\n}\n\nexport { initWidget, Tips };\n"
  },
  {
    "path": "tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"es2017\",\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"declaration\": true,\n    \"outDir\": \"build\",\n    \"esModuleInterop\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"strict\": false,\n    \"skipLibCheck\": true,\n    \"removeComments\": true,\n    \"allowJs\": true,\n    \"paths\": {\n      \"@framework/*\": [\n        \"./src/CubismSdkForWeb-5-r.4/Framework/src/*\"\n      ],\n      \"@demo/*\": [\n        \"./src/CubismSdkForWeb-5-r.4/Samples/TypeScript/Demo/src/*\"\n      ]\n    }\n  },\n  \"include\": [\"src\"],\n  \"exclude\": [\"node_modules\", \"build\", \"dist\"]\n}\n"
  }
]