diff --git a/plugins.json b/plugins.json index 55ada5e6..2f26c96d 100644 --- a/plugins.json +++ b/plugins.json @@ -955,5 +955,23 @@ "dependencies": ["cem_template_loader"], "creation_date": "2024-06-05", "has_changelog": true + }, + "pbr_preview": { + "title": "PBR Tools", + "author": "Jason J. Gardner", + "await_loading": true, + "creation_date": "2024-06-10", + "icon": "icon.png", + "description": "Create and view PBR materials in Blockbench. Export textures for Java and RenderDragon shaders.", + "has_changelog": true, + "website": "https://github.com/jasonjgardner/blockbench-plugins/", + "variant": "both", + "version": "1.1.0", + "tags": [ + "Minecraft: Java Edition", + "Minecraft: Bedrock Edition", + "PBR" + ], + "min_version": "4.10.4" } } diff --git a/plugins/pbr_preview/LICENSE.MD b/plugins/pbr_preview/LICENSE.MD new file mode 100644 index 00000000..f288702d --- /dev/null +++ b/plugins/pbr_preview/LICENSE.MD @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/plugins/pbr_preview/about.md b/plugins/pbr_preview/about.md new file mode 100644 index 00000000..31b01c5b --- /dev/null +++ b/plugins/pbr_preview/about.md @@ -0,0 +1,206 @@ +**Create and view PBR textures in Blockbench. Exports [USDZ](https://openusd.org/release/index.html) and in formats for labPBR +(Java) or RenderDragon (Bedrock) shaders** + +> **_PBR:_ Physically based rendering**\ +> Read the +> _[Intoduction to Physically Based Rendering](https://learn.microsoft.com/en-us/minecraft/creator/documents/rtxpbrintro?view=minecraft-bedrock-stable "View Minecraft Creator documentation article.")_ +> article in the Minecraft Creator documentation if you are not already familiar +> with creating PBR content for Bedrock Edition. Visit the +> [shaderLABS wiki](https://shaderlabs.org/wiki/Main_Page) for more information +> on the labPBR material standard. + +## Blockbench PBR Plugin Features + +### PBR Material Preview + +- Preview PBR textures in Edit, Paint, and Animate mode. +- Infers texture channels based on naming conventions when no channel has been + explicitly defined. Intended for previewing imported existing Bedrock and Java + PBR textures. +- Uses Blockbench's preview scenes as model environment map. +- PBR materials are updated with every edit to provide a live painting preview + of the material in Blockbench. + +### MER Maps + +> _MER:_ Metallic, emissive, and roughness maps assigned to red, green, and blue +> channels respectively. It is the format used in Bedrock texture sets. + +#### Decode MER + +- MERs can be inferred and decoded automatically when PBR mode is enabled. +- Decoding can be _slow_ on large textures (1024x+). +- Assign an albedo map prior to decoding a MER to extract the emissive color. +- Channels extracted from a MER can be saved as either separate textures or into + separate layers in a single texture. + +#### Export MER + +- Compiles metal, emissive and roughness channels into MER texture. +- (Emissive colors will be lost upon export. Use grayscale values in emissive + channels for accurate brightness levels.) + +### Generate Normal Map + +- Calculate normal map based on the assigned or inferred height map for the + currently selected material/texture. + +### Generate Ambient Occlusion Map + +- Generate an AO map from the material's normal map. (AO available in some + labPBR shaders.) + +### Texture Baking + +- Bake a normal and emissive maps onto the base color channel. +- Output multiple light positions. +- Choose ambient light settings before baking. + +### Export Texture Set + +- Create a `.texture_set.json` file for the project textures. +- Dialog allows defining values which can not be inferred from project. +- Exports MER and normal maps in the process. + +### labPBR Specular/Normal Maps + +- Export `_s` and `_n` files for PBR textures created in Blockbench. +- Decode existing, imported labPBR textures into PBR material channels. + +### Material Brush + +- Paint across multiple PBR channels simultaneously for a consistent material + output. +- Save material brush presets to a collection. +- Automatic PBR preview updates after every brush stroke. + +### Export USDZ Scenes + +- Adds new codec for exporting in USDZ format. + +### `.bbmat` Codec + +Reuse and share PBR materials in Blockbench with this custom file format. + +## Usage + +### PBR Controls + +This plugin adds the _PBR Controls_ panel, which controls enabling and disabling +PBR materials in Blockbench previews. + +#### Toggle PBR + +- Use the _PBR Preview_ toggle to toggle or refresh the PBR preview. Also found + in the _View_ menu. + +>
+> Usage Tip +> Toggling the PBR preview off and on may solve any texture discrepancies. Allowing the scene to render again will ensure all textures are up-to-date in the preview. +>
+ +#### Toggle Corrected Lighting + +- Use the _Correct Lights_ toggle to enable or disable physically-corrected + lighting in the preview scene. This may improve the appearance of reflective + and emissive materials in the preview scene, but will dim the albedo/base + color texture. + +#### Tone Mapping + +- The _Tone Mapping_ select will apply various tone mapping techniques to the + preview scene. Use the _Linear_ option to match the tone map used by most + Bedrock shaders. + +#### Exposure + +- The scene exposure can be adjusted once a tone map technique is selected. + Values range from -2.0 to 2.0. + +### Channel Management + +Control which textures or texture layers are used for PBR channels using the +following methods: + +#### Create Material Texture + +- Use the _Create Material Texture_ action to create a blank texture with PBR + material layers initialized.\ + If an existing texture is selected, it will be used as the albedo channel in + the PBR material. If the project has other textures, include those textures in + the selection to have them automatically assigned to the new material's PBR + channels. + +Follow these naming conventions to ensure the textures are assigned to the +appropriate channels when creating a new material: + +#### Channel Naming Convention + +The plugin will assume that textures and layers which end in an underscore and a +channel name are intended to be used as that channel. For example, +`texture_roughness` will be used as the roughness map unless the channel has +been manually assigned a texture. + +##### Supported Channels + +| Channel | Description | Colorspace | +| ----------- | --------------------- | ----------------------------------------------------------------- | +| `ao` | Ambient Occlusion | **BW** | +| `albedo` | Albedo / Base Color | **RGB** | +| `normal` | DirectX Normal Map | **RGB** | +| `metalness` | Metallic map | **BW** | +| `roughness` | Roughness map | **BW** | +| `emissive` | Emissive map | Displayed in **RGB**; Exported as **BW** in MER | +| `sss` | Subsurface Scattering | **BW**; Not supported by shader but exported in MER alpha channel | + +###### Supported Minecraft Shader Channels + +RenderDragon and labPBR textures are automatically decoded and displayed when +the channels can be inferred based on the existence of MER, specular, or normal +maps. Some features are not supported by the Blockbench preview's shader, such +as AO and POM, but can still be decoded/encoded during texture import/export + +#### Explicit Channel Assignment + +Create a Texture Layer in Blockbench to enable channel assignment in PBR +previews. Each channel can be selected from a menu and applied to the current +material. The menu is visible in the _PBR Controls_ panel when in Paint mode. +The menu options are available in the _Image_ menu, as well as in the context +menu of a texture or layer, and in the Layers panel. + +#### Removing Channel Assignment + +Channels can be disabled by hiding or deleting the layer, or un-assigning the +channel in the menu. Texture layers cannot be assigned to more than one channel. +Assigning a layer to a new channel will clear the layer's current channel. + +#### Finding Assigned Channels + +Select a texture with material layers assigned to reveal the _PBR Channels_ +panel. This panel displays the channels currently assigned in the selected +texture. Click a channel in the menu to have it selected in the Layers panel. + +### Material Brush Tool + +Use the _Material Brush Tool_ to paint across multiple PBR channels. The +controls found in the _Material Brush Panel_. + +- Set the metallic, roughness and height values on a scale of 0% - 100% +- Use the color picker in the _Material Brush Panel_ to set the emissive color. +- The current color selected in the main color picker is used as the albedo + color. +- Only visible layers with channels assigned will be updated by the brush. +- Blockbench's paint brush size and smoothness settings control the material + brush's settings as well. + +#### Material Brush Presets + +Open the _Material Brush Presets_ dialog to define and save new brush settings, +or to select and apply existing presets. A material preview is generated upon +saving a preset. Select a preset to populate its values in the Material Brush +input controls. + +### `.bbmat` Files +- Import Blockbench PBR materials by dropping a `.bbmat` file into a Blockbench project. + - The import option is also available in the _File_ menu. +- Export existing materials from texture content menu to save its assigned channels together in one file. \ No newline at end of file diff --git a/plugins/pbr_preview/changelog.json b/plugins/pbr_preview/changelog.json new file mode 100644 index 00000000..d8f93e67 --- /dev/null +++ b/plugins/pbr_preview/changelog.json @@ -0,0 +1,51 @@ +{ + "1.0.0": { + "title": "1.0.0", + "date": "2024-05-25", + "author": "Jason J. Gardner", + "categories": [ + { + "title": "PBR plugin", + "list": [ + "Initial release 🚀" + ] + } + ] + }, + "1.1.0": { + "title": "1.1.0", + "date": "2024-06-10", + "author": "Jason J. Gardner", + "categories": [ + { + "title": "Java Support", + "list": [ + "Added labPBR export option", + "Added labPBR texture decoding" + ] + }, + { + "title": "Material Brush", + "list": [ + "Added material brush tool", + "Added material brush preset dialog" + ] + } + ] + }, + "1.2.0": { + "title": "1.2.0", + "date": "2024-06-20", + "author": "Jason J. Gardner", + "categories": [ + { + "title": "USDZ Export", + "list": [ + "Added USDZ export option", + "Added normal map orientation options", + "Created `.bbmat` codec" + ] + } + ] + } +} \ No newline at end of file diff --git a/plugins/pbr_preview/icon.png b/plugins/pbr_preview/icon.png new file mode 100644 index 00000000..273eda51 Binary files /dev/null and b/plugins/pbr_preview/icon.png differ diff --git a/plugins/pbr_preview/members.yml b/plugins/pbr_preview/members.yml new file mode 100644 index 00000000..438a1942 --- /dev/null +++ b/plugins/pbr_preview/members.yml @@ -0,0 +1,4 @@ +maintainers: + - jasonjgardner +developers: + - jasonjgardner diff --git a/plugins/pbr_preview/pbr_preview.js b/plugins/pbr_preview/pbr_preview.js new file mode 100644 index 00000000..96e1f533 --- /dev/null +++ b/plugins/pbr_preview/pbr_preview.js @@ -0,0 +1,291 @@ +"use strict";(()=>{var _=THREE,ie=Vue,le=window.JSZip;var F="1.2.0",K="1.0.0",N="_NONE_",h={albedo:{id:"albedo",label:"Albedo",description:"The color of the material",map:"map",icon:"tonality",default:new _.Color(16777215),regex:new RegExp("(s|_)*(basecolor|color|albedo)","i")},metalness:{id:"metalness",label:"Metalness",description:"The material's metalness map",map:"metalnessMap",icon:"brightness_6",default:new _.Color(0),regex:new RegExp("[ _]*metal(lic|ness)?","i")},emissive:{id:"emissive",label:"Emissive",description:"The material's emissive map",map:"emissiveMap",icon:"wb_twilight",default:new _.Color(0),regex:new RegExp("[ _]*(emissive|emission)","i")},roughness:{id:"roughness",label:"Roughness",description:"The material's roughness map",map:"roughnessMap",icon:"grain",default:new _.Color(16777215),regex:new RegExp("[ _]*rough(ness)?","i")},height:{id:"height",label:"Height",description:"The material's height map",map:"bumpMap",icon:"landscape",default:new _.Color(16777215),regex:new RegExp("[ _]*(height|bump)","i")},normal:{id:"normal",label:"Normal",description:"The material's normal map",map:"normalMap",icon:"looks",default:new _.Color("rgb(128, 128, 255)"),regex:new RegExp("[ _]*normal","i")},ao:{id:"ao",label:"Ambient Occlusion",description:"The material's ambient occlusion map",map:"aoMap",icon:"motion_mode",default:new _.Color(16777215),regex:new RegExp("[ _]*(ao|ambientocclusion|ambient occlusion)","i")}},o={},y=[],C=[];var ce=[...Object.keys(h).map(e=>h[e].id),N];y.push(()=>{o.channelProp=new Property(TextureLayer,"enum","channel",{default:N,values:ce,label:"PBR Channel",exposed:!1}),o.textureChannelProp=new Property(Texture,"enum","channel",{default:N,values:ce,label:"PBR Channel",exposed:!1}),o.materialTextureProp=new Property(Texture,"boolean","material",{default:!1,label:"Material Texture"}),o.pbrMaterialsProp=new Property(ModelProject,"object","pbr_materials",{default:{},exposed:!1,label:"PBR Materials"}),o.projectMaterialsProp=new Property(ModelProject,"object","bb_materials",{default:{},exposed:!1,label:"Project Materials"}),o.projectPbrModeProp=new Property(ModelProject,"boolean","pbr_active",{default:!1,exposed:!1,values:[],label:"PBR Mode"})});function E(){return Texture.selected?Texture.selected:TextureLayer.selected?TextureLayer.selected.texture:Project?Project.selected_texture?Project.selected_texture:Project.textures.find(e=>e.selected)??null:Texture.all.find(e=>e.selected)??Texture.getDefault()}function R(){return TextureLayer.selected?TextureLayer.selected:Texture.selected?.selected_layer?Texture.selected.selected_layer:Project.selected_texture!==null&&Project.selected_texture?.layers_enabled===!0?Project.selected_texture.layers.find(e=>e.selected)??Project.selected_texture.layers[0]:E()?.getActiveLayer()??null}function G(){return Project?Project.model_identifier.length>0?Project.model_identifier:Project.getDisplayName():pathToName(E()?.name??"texture")}function ue(e,a){let t;return function(...r){let n=()=>{t=void 0,e.apply(this,r)};clearTimeout(t),t=setTimeout(n,a)}}function z(e){let a=MediaPreview.renderer??new _.WebGLRenderer({alpha:!0,antialias:!0}),t=new _.Scene,r=new _.PerspectiveCamera(75,96/96,.1,1e3),n=new _.AmbientLight(16777215,.75);t.add(n);let i=new _.PointLight(16777215,1,100);i.position.set(5,5,5),t.add(i);let s=new _.SphereGeometry(1,32,32),l=e instanceof _.MeshStandardMaterial&&e.isMeshStandardMaterial?e:new _.MeshStandardMaterial({color:e.albedo,metalness:e.metalness??0,roughness:e.roughness??1,emissive:e.emissive,bumpScale:e.height??0,envMap:PreviewScene.active?.cubemap??null,envMapIntensity:.5}),u=new _.Mesh(s,l);t.add(u),r.position.x=0,r.position.y=0,r.position.z=2,a.setSize(96,96),a.render(t,r);let m=a.domElement.toDataURL();return l.dispose(),MediaPreview.renderer||(a.clear(),a.dispose()),m}function Y(e,a){let t=a??document.createElement("canvas"),r=t.getContext("2d");if(!r)return t.remove(),null;let n=Math.max(Project?Project.texture_width:16,16),i=Math.max(Project?Project.texture_height:16,16);t.width=n,t.height=i,r.fillStyle=`rgb(${e.r*255}, ${e.g*255}, ${e.b*255})`,r.fillRect(0,0,n,i);let s=t.toDataURL();return a||t.remove(),s}var Ve=(e=!0)=>{let a=Project?Project.textures??Texture.all:Texture.all;return e?a.filter(t=>t.layers_enabled&&t.layers.length>0).flatMap(t=>t.layers):a},D=class e{constructor(a,t){this._scope=a??Ve(),this._materialUuid=t}merToCanvas(){let a=this.getTexture(h.emissive),t=this.getTexture(h.roughness),r=this.getTexture(h.metalness);if(!a&&!t&&!r){let{metalness:n,emissive:i,roughness:s}=this.decodeMer();n&&(r=e.makePixelatedCanvas(n)),i&&(a=e.makePixelatedCanvas(i)),s&&(t=e.makePixelatedCanvas(s))}return{emissiveMap:a,roughnessMap:t,metalnessMap:r}}getMaterial(a={}){let{emissiveMap:t,roughnessMap:r,metalnessMap:n}=Format.id.startsWith("bedrock")?this.merToCanvas():{emissiveMap:this.getTexture(h.emissive),roughnessMap:this.getTexture(h.roughness),metalnessMap:this.getTexture(h.metalness)},i=this.getTexture(h.normal);return new _.MeshStandardMaterial({map:this.getTexture(h.albedo)??e.makePixelatedCanvas(TextureLayer.selected?.canvas??Texture.all.find(s=>s.selected)?.canvas??Texture.getDefault().canvas),aoMap:this.getTexture(h.ao),bumpMap:this.getTexture(h.height),normalMap:i,metalnessMap:n,metalness:n?1:0,roughnessMap:r,roughness:1,emissiveMap:t,emissiveIntensity:t?1:0,emissive:t?16777215:0,envMap:PreviewScene.active?.cubemap??null,envMapIntensity:.95,alphaTest:.1,transparent:!0,...a})}renderMaterialPreview(){return z(this.getMaterial())}saveTexture(a,t){Project&&(Project.pbr_materials||(Project.pbr_materials={}),Project.pbr_materials[this._materialUuid]||(Project.pbr_materials[this._materialUuid]={}),Project.pbr_materials[this._materialUuid][a.id]=t.uuid,t.extend({channel:a.id}))}findTexture(a,t=!0){if(!Project)return null;let r=this._scope.find(u=>u.channel&&(u.channel===a||u.channel===a.id));if(r)return r;let[n,i]=typeof a=="string"?[a,new RegExp(`_*${a}(.[^.]+)?$`,"i")]:[a.id,a.regex??new RegExp(`_*${a.id}(.[^.]+)?$`,"i")];Project.pbr_materials=Project.pbr_materials??{};let s=Project.pbr_materials[this._materialUuid];if(t&&!s?.length&&n!==N)return this._scope.find(u=>i.test(u.name))??null;let l=s?.[n];return l?this._scope.find(u=>u.uuid===l)??null:null}static makePixelatedCanvas(a){let t=new _.CanvasTexture(a,void 0,void 0,void 0,_.NearestFilter,_.NearestFilter);return t.needsUpdate=!0,t}getTexture(a){let t=this.findTexture(a);return t?e.makePixelatedCanvas(t.canvas):null}static extractChannel(a,t){let r=a.canvas,{width:n,height:i}=r,s=r.getContext("2d");if(!s||!n||!i)return null;let l=document.createElement("canvas");l.width=n,l.height=i;let u=l.getContext("2d");if(!u)return null;let m={r:0,g:1,b:2,a:3}[t],{data:d}=s.getImageData(0,0,n,i),c=new Uint8ClampedArray(n*i*4);for(let g=0;ga){x[f]=v.data[f],x[f+1]=v.data[f+1],x[f+2]=v.data[f+2],x[f+3]=255;continue}x[f]=0,x[f+1]=0,x[f+2]=0,x[f+3]=255}return m.putImageData(new ImageData(x,l.width,l.height),0,0),{metalness:r,emissive:l,emissiveLevel:n,roughness:i,sss:s}}createMer(a=!1){let t=this.findTexture(h.metalness,a),r=this.findTexture(h.emissive,a),n=this.findTexture(h.roughness,a),i=this.findTexture("sss",!1),s=Math.max(t?.img.width??0,r?.img.width??0,n?.img.width??0,Project?Project.texture_width:0,16),l=Math.max(t?.img.height??0,r?.img.height??0,n?.img.height??0,Project?Project.texture_height:0,16),u=document.createElement("canvas");u.width=s,u.height=l;let m=u.getContext("2d");if(!m)return null;let d=t?.img?e.extractChannel(t,"r"):null,c=r?.img?e.extractChannel(r,"g"):null,v=n?.img?e.extractChannel(n,"b"):null,g=i&&i?.img?e.extractChannel(i,"a"):null,x=d?.getContext("2d")?.getImageData(0,0,s,l)??new ImageData(s,l),f=c?.getContext("2d")?.getImageData(0,0,s,l)??new ImageData(s,l),p=v?.getContext("2d")?.getImageData(0,0,s,l)??new ImageData(s,l),b=g?.getContext("2d")?.getImageData(0,0,s,l)??new ImageData(new Uint8ClampedArray(s*l*4).fill(255),s,l),M=new Uint8ClampedArray(s*l*4);for(let w=0;w{n&&new Texture({name:`${a.name}_${r}`,saved:!1,particle:!1,keep_size:!1}).fromDataURL(n.toDataURL()).add()}),t}createTexturesFromNormal(a){let t=this.decodeLabPbrNormal(a);return Object.entries(t).forEach(([r,n])=>{n&&new Texture({name:`${a.name}_${r}`,saved:!1,particle:!1,keep_size:!1}).fromDataURL(n.toDataURL()).add()}),t}};var V=class{constructor({lightHeight:a=.66,ambientLight:t=[.1,.1,.1],minLightIntensity:r=0,lightDiffuse:n=[1,1,1]}={}){this.lightHeight=a,this.ambientLight=t,this.minLightIntensity=r,this.lightDiffuse=n}bake(a,t,r){let n=t instanceof HTMLCanvasElement?t:this.createCanvas(t.width,t.height),i=r instanceof HTMLCanvasElement?r:this.createCanvas(r.width,r.height),s=n.getContext("2d"),l=i.getContext("2d");s.drawImage(t,0,0),l.drawImage(r,0,0);let u=s.getImageData(0,0,t.width,t.height),m=l.getImageData(0,0,r.width,r.height),d=[],c=[];for(let g=0;g{let x=this.createCanvas(t.width,t.height),f=x.getContext("2d"),p=f.getImageData(0,0,x.width,x.height),b=[Math.cos(g),Math.sin(g),this.lightHeight];for(let M=0;M{if(!Project)return;let r=Project.selected_texture??Texture.getDefault(),n=new D(r.layers_enabled?r.layers:Project.textures,r.uuid),i=n.findTexture(h.albedo);if(!i){Blockbench.showStatusMessage("Can not bake without a base color assigned.",3e3);return}let s=n.findTexture(h.normal);if(!s){Blockbench.showStatusMessage("Can not bake without a normal map assigned.",3e3);return}let u=new V(e).bake(a,i.canvas,s.canvas),m=new Texture({name:`${i.name}_baked`,saved:!1,particle:!1,keep_size:!1,layers_enabled:!0}).fromDataURL(u[0].toDataURL()),d=t?c=>{let v=n.findTexture(h.emissive);if(!v)return c;let g=v.canvas;if(!g.getContext("2d"))return c;let f=Math.max(c.width,g.width,Project?Project.texture_width:16),p=Math.max(c.height,g.height,Project?Project.texture_height:16),b=document.createElement("canvas");b.width=f,b.height=p;let M=b.getContext("2d");return M?(M.drawImage(c,0,0),M.globalCompositeOperation="screen",M.drawImage(g,0,0),b):c}:c=>c;u.forEach((c,v)=>{new TextureLayer({name:`baked_${v+1}`,data_url:d(c).toDataURL()},m).addForEditing()}),m.add().select(),Blockbench.showQuickMessage("Textures baked \u{1F950}",2e3)};y.push(()=>{o.bakeTexturesDialog=new Dialog("bake_textures",{id:"bake_textures",title:"Bake Textures",buttons:["Bake","Cancel"],form:{ambientLight:{type:"color",label:"Ambient Light",value:"#1f1f1f"},lightDiffuse:{type:"color",label:"Light Diffuse",value:"#ffffff"},lightHeight:{type:"range",label:"Light Height",min:0,max:1,step:.01,value:.66},minLightIntensity:{type:"range",label:"Minimum Light Intensity",min:0,max:1,step:.01,value:0},directions:{type:"number",label:"Directions",value:8,min:1,max:360,step:1},blendEmissive:{type:"checkbox",label:"Blend Emissive",value:!1}},onConfirm(e){let a=new _.Color(e.ambientLight.toString()),t=new _.Color(e.lightDiffuse.toString());me({ambientLight:[a.r,a.g,a.b],lightDiffuse:[t.r,t.g,t.b],lightHeight:Number(e.lightHeight),minLightIntensity:Number(e.minLightIntensity)},e.directions??8,e.blendEmissive??!1)}}),o.bakeTexturesAction=new Action("bake_textures",{icon:"cake",name:"Bake Textures",description:"Bakes textures for the selected PBR material",click(){o.bakeTexturesDialog?.show()}}),MenuBar.addAction(o.bakeTexturesAction,"tools")});C.push(()=>{MenuBar.removeAction("tools.bake_textures")});function de(e,a){let t=e.getTexture();if(!t||!Project)return null;let r=Project.materials[t.uuid];r.isShaderMaterial&&!Project.bb_materials[t.uuid]?Project.bb_materials[t.uuid]=r:r.isMeshStandardMaterial&&r.dispose();let n=new D(t.layers_enabled?t.layers.filter(i=>i.visible)??null:Project.textures,t.uuid).getMaterial({side:Canvas.getRenderSide(t),...a});return Project.materials[t.uuid]=_.ShaderMaterial.prototype.copy.call(n,r),t}function Qe(e){return Object.values(e).filter(a=>a?(Canvas.updateAllFaces(a),!0):!1).length>0}function Je(e,a){let t={};return e.forAllFaces(r=>{let n=de(r,a);n&&(t[n.uuid]=n)}),t}function Xe(e,a){let t={};return Object.keys(e.faces).forEach(r=>{let n=e.faces[r],i=de(n,a);i&&(t[i.uuid]=i)}),t}var B=(e={})=>{if(!Project)return;let t=Project.elements.map(r=>r instanceof Mesh&&Je(r,e)||r instanceof Cube&&Xe(r,e)).reduce((r,n)=>({...r,...n}),{});Project.pbr_active=Texture.all.length>0&&t&&Qe(t)},A=(e=100)=>ue(B,e);var te={},ee=()=>Condition({modes:["edit","paint"],selected:{texture:!0},project:!0,method(){let e=E();return e&&!e.material?!0:e?.material===!0&&R()!==null&&Modes.paint}}),he=()=>Condition({modes:["paint","edit"],selected:{texture:!0},method(){let e=E();if(e?.material&&Modes.edit)return!1;let a=R()??e;return a?.channel&&a.channel!==N}});y.push(()=>{Object.entries(h).forEach(([e,a])=>{te[e]=new Action(`assign_channel_${e}`,{icon:a.icon??"tv_options_edit_channels",name:`Assign to ${a.label.toLocaleLowerCase()} channel`,description:`Assign the selected layer to the ${a.label} channel`,category:"textures",condition:ee,click(){let t=TextureLayer.selected??(Project?Project.selected_texture:null);if(!t)return;Undo.initEdit({layers:[t]}),t.extend({channel:a.id});let r=t instanceof TextureLayer?t.texture:t;r.updateChangesAfterEdit(),Project.pbr_materials[r.uuid]||(Project.pbr_materials[r.uuid]={}),Object.entries(Project.pbr_materials[r.uuid]).forEach(([n,i])=>{i===t.uuid&&(delete Project.pbr_materials[r.uuid][n],t.channel=N)}),r.uuid===t.uuid&&(Project.pbr_materials[r.uuid]={}),Project.pbr_materials[r.uuid][e]=t.uuid,Undo.finishEdit("Change channel assignment"),Blockbench.showQuickMessage(`Assigned "${t.name}" to ${a.label} channel`,2e3),B()}})})});C.push(()=>{Object.values(te).forEach(e=>{e.delete()})});y.push(()=>{o.unassignChannel=new Action("unassign_channel",{icon:"cancel",name:"Unassign Channel",description:"Unassign the selected layer from the channel",category:"textures",condition:he,click(){let e=TextureLayer.selected??(Project?Project.selected_texture:null);if(!e)return;Undo.initEdit({layers:[e]});let a=e instanceof TextureLayer?e.texture:e,t=e.channel;Project.pbr_materials[a.uuid]={},e.channel=N,a.updateChangesAfterEdit(),Undo.finishEdit("Unassign channel"),Blockbench.showQuickMessage(`Unassigned "${e.name}" from ${t} channel`,2e3),A()}}),o.channelMenu=new Menu("channel_menu",[...Object.keys(h).map(e=>`assign_channel_${e}`),"unassign_channel"],{onOpen(){A()}}),o.openChannelMenu=new Action("pbr_channel_menu",{name:"Assign to PBR Channel",icon:"texture",condition:()=>ee()||he(),click(e){o.channelMenu?.open(e)},children:[...Object.values(te),o.unassignChannel]}),o.showChannelMenu=new Action("show_channel_menu",{icon:"texture",name:"Assign to PBR Channel",description:"Assign the selected layer to a channel",category:"textures",condition:ee,click(e){o.channelMenu?.open(e)}}),o.openChannelMenu&&(MenuBar.addAction(o.openChannelMenu,"image.0"),Texture.prototype.menu.addAction(o.openChannelMenu,"0"),TextureLayer.prototype.menu.addAction(o.openChannelMenu,"0")),Toolbars.layers.add(o.showChannelMenu,1)});C.push(()=>{MenuBar.removeAction("image.pbr_channel_menu"),Texture.prototype.menu.removeAction("pbr_channel_menu"),TextureLayer.prototype.menu.removeAction("pbr_channel_menu"),Toolbars.layers.remove(o.showChannelMenu)});function $(e,a="DirectX",t=!1){let r=e.canvas.getContext("2d");if(!r)return null;let n=Math.max(e.img.width??e.canvas.width,Project?Project.texture_width:0,16),i=Math.max(e.img.height??e.canvas.height,Project?Project.texture_height:0,16),{data:s}=r.getImageData(0,0,n,i),l=document.createElement("canvas"),u=l.getContext("2d");if(!u)return null;let m=(p,b)=>{let M=(p+b*n)*4;return s[M]/255};l.width=n,l.height=i,u.drawImage(e.img,0,0,n,i);let d=u.getImageData(0,0,n,i),c=d.data,v=p=>{let b=Math.sqrt(p[0]*p[0]+p[1]*p[1]+p[2]*p[2]);return[p[0]/b,p[1]/b,p[2]/b]};for(let p=0;p{let f=(g+x*t)*4;return n[f]/255};i.width=t,i.height=r,s.drawImage(e.img,0,0,t,r);let u=s.getImageData(0,0,t,r),m=u.data;for(let g=0;g{let t=R()??E()??Texture.getDefault();if(!t)return;let r=$(t,a,!1);if(!r){Blockbench.showQuickMessage("Failed to generate normal map",2e3);return}r.select(e),new D(t instanceof Texture&&t.layers_enabled?t.layers:null,t.uuid).saveTexture(h.normal,r),Blockbench.showQuickMessage("Normal map generated",2e3)};y.push(()=>{o.generateDirectXNormal=new Action("generate_dx_normal",{icon:h.normal.icon??"altitude",name:"Generate DirectX Normal Map",description:"Generates a DirectX normal map from the height map",condition:()=>(R()??E())!==null,click:e=>ge(e)}),o.generateOpenGlNormal=new Action("generate_opengl_normal",{icon:h.normal.icon??"altitude",name:"Generate OpenGL Normal Map",description:"Generates an OpenGL normal map from the height map",condition:()=>(R()??E())!==null,click:e=>ge(e,"OpenGL")}),o.generateAo=new Action("generate_ao",{icon:h.ao.icon??"motion_mode",name:"Generate Ambient Occlusion Map",description:"Generates an ambient occlusion map from the height map",condition:{selected:{texture:!0},project:!0},click(){let e=R()??E()??Texture.getDefault();if(!e)return;let a=new D(e instanceof Texture&&e.layers_enabled?e.layers:null,e.uuid),t=a.findTexture(h.normal)??$(e);if(!t){Blockbench.showQuickMessage("Unable to generate ambient occlusion map without a normal map",2e3);return}let r=pe(t);if(r){a.saveTexture(h.ao,r),r.select(),Blockbench.showQuickMessage("Ambient occlusion map generated",2e3);return}Blockbench.showQuickMessage("Failed to generate ambient occlusion map",2e3)}}),o.generateNormal=new Action("generate_normal",{children:[o.generateDirectXNormal,o.generateOpenGlNormal],name:"Generate Normal Map",description:"Generates a normal map from the height map",condition:()=>(R()??E())!==null,click(){},icon:h.normal.icon??"altitude"}),MenuBar.addAction(o.generateNormal,"tools"),MenuBar.addAction(o.generateAo,"tools")});C.push(()=>{MenuBar.removeAction("tools.generate_normal"),MenuBar.removeAction("tools.generate_ao")});var Ze=(e,a="texture")=>{e.toBlob(async t=>{t&&Blockbench.export({content:await t.arrayBuffer(),type:"PNG",name:`${a}_n`,extensions:["png"],resource_id:"normal_map",savetype:"image"})})},We=(e,a="texture")=>{e.toBlob(async t=>{t&&Blockbench.export({content:await t.arrayBuffer(),type:"PNG",name:`${a}_s`,extensions:["png"],resource_id:"specular_map",savetype:"image"})})};y.push(()=>{o.generateLabPbr=new Action("generate_lab_pbr",{icon:"experiment",name:"Generate labPBR textures",description:"Generate a specular and normal map in labPBR format for Java shaders",condition:{formats:["java_block"],project:!0},async click(){let e=E();if(!e)return;let t=new D(e.layers_enabled?e.layers:[e],e.uuid).createLabPbrOutput();if(t===null)return;let r=e.name??(Project?Project.getDisplayName():"texture");await Promise.all([Ze(t.normalMap,pathToName(r)),We(t.specular,pathToName(r))]),Blockbench.showQuickMessage("Exported labPBR textures")}}),o.decodeLabPbr=new Action("decode_lab_pbr",{icon:"frame_source",name:"Decode labPBR textures",description:"Decodes the selected texture into a specular or normal map in labPBR format",condition:{formats:["java"],project:!0,selected:{texture:!0}},click(){let e=TextureLayer.selected?.texture??Texture.all.find(t=>t.selected)??Texture.getDefault(),a=new D(e.layers_enabled?e.layers:[e],e.uuid);if(pathToName(e.name).endsWith("_n")){a.createTexturesFromNormal(e);return}if(pathToName(e.name).endsWith("_s")){a.createTexturesFromSpecular(e);return}Blockbench.showQuickMessage("Failed to decode labPBR texture")}}),MenuBar.addAction(o.generateLabPbr,"file.export"),MenuBar.addAction(o.decodeLabPbr,"tools")});C.push(()=>{MenuBar.removeAction("file.export.generate_lab_pbr")});y.push(()=>{o.createMaterialTexture=new Action("create_material_texture",{icon:"deployed_code",name:"Create Material Texture",description:"Creates a new texture for a PBR material",condition:{modes:["edit","paint"],project:!0},click(){if(!Project)return;let e={...h},a=new Texture({name:"New Material",saved:!1,particle:!1});a.extend({material:!0});let t=Texture.all.filter(s=>(s.selected||s.multi_selected)&&!s.material)??Texture.all,r=E(),n=r?new D(t,r.uuid):null;try{let s=n?.findTexture(h.albedo,!0)?.canvas.toDataURL()??r?.canvas.toDataURL()??Y(new _.Color(8421504),a.canvas);if(!s)return;a.fromDataURL(s);let l=new TextureLayer({name:e.albedo.label,visible:!0,data_url:s,keep_size:!0},a);l.extend({channel:e.albedo.id}),l.addForEditing(),l.texture.updateChangesAfterEdit(),n?.saveTexture(e.albedo,l),delete e.albedo}catch(s){console.warn("Failed to create base color texture",s),Blockbench.showStatusMessage("Failed to create base color texture in new material",3e3)}let i=Object.keys(e).reverse().map(s=>{let l=h[s],u=n?.findTexture(l,!0),m=u?u.canvas.toDataURL():Y(l.default??new _.Color(0));if(!m)return;let d=new TextureLayer({name:l.label,visible:!0,data_url:m,keep_size:!0},a);return d.extend({channel:l.id}),n?.saveTexture(l,d),d}).filter(Boolean);Undo.initEdit({textures:Texture.all,layers:i}),a.add().select(),a.activateLayers(),i.map(s=>{s.addForEditing(),a.width=Math.max(a.width,s.img.width),a.height=Math.max(a.height,s.img.height)}),a.updateChangesAfterEdit(),Undo.finishEdit("Create Material Texture")}}),MenuBar.addAction(o.createMaterialTexture,"tools"),Toolbars.texturelist.add(o.createMaterialTexture,3)});C.push(()=>{MenuBar.removeAction("tools.create_material_texture"),Toolbars.texturelist.remove("create_material_texture")});var Q=(e,a)=>{let t=E()??Texture.getDefault(),r=new D(t.layers_enabled?t.layers:Project?Project.textures:null,t.uuid).createMer(!0);if(!r)throw new Error("Failed to generate MER map from selected texture.");r.toBlob(async n=>{if(!n)throw new Error("Failed to save MER map.");let[i,s]=Project?[e?`${e}_mer`:`${t.name??Project.getDisplayName()}_mer`,Project.export_path]:["mer"];Blockbench.export({content:await n.arrayBuffer(),type:"PNG",name:i,extensions:["png"],resource_id:"mer",savetype:"image",startpath:s},a)})};y.push(()=>{o.generateMer=new Action("create_mer",{icon:"lightbulb_circle",name:"Export MER",description:"Exports a texture map from the metalness, emissive, and roughness channels. (For use in Bedrock resource packs.)",condition:{formats:["bedrock","bedrock_block"],project:!0},click(){try{Q()}catch(e){console.error("Failed to export MER map:",e),Blockbench.showStatusMessage("Failed to export MER map",3e3)}}}),o.decodeMer=new Action("decode_mer",{name:"Decode MER",icon:"arrow_split",condition:{formats:["bedrock","bedrock_block"],project:!0,selected:{texture:!0}},children:[{icon:"move_item",name:"Decode MER to Textures",description:"Decodes a MER texture map into metalness, emissive, and roughness channels into separate textures",click(){let e=E()??Texture.getDefault(),a=new D([e],e.uuid),t=a.decodeMer(),r=[h.metalness,h.emissive,h.roughness];Undo.initEdit({textures:[e]}),r.forEach(n=>{let i=n.id,s=t[i];if(!s){Blockbench.showStatusMessage(`Failed to decode ${n.label} channel`,3e3);return}let l=new Texture({name:`${e?.name}_${i}`,keep_size:!1}).fromDataURL(s.toDataURL());l.add(!0),a.saveTexture(n,l)}),Undo.finishEdit("Decode MER to textures")}},{icon:"move_group",name:"Decode MER to Layers",description:"Decodes a MER texture map into metalness, emissive, and roughness channels into material layers",condition:()=>E()?.layers_enabled===!0,click(){let e=E()??Texture.getDefault(),a=new D(e.layers_enabled?e.layers:[e],e.uuid),t=a.decodeMer(),r=[h.metalness,h.emissive,h.roughness];Undo.initEdit({textures:[e]}),r.forEach(n=>{let i=n.id,s=t[i];if(!s){Blockbench.showStatusMessage(`Failed to decode ${n.label} channel`,3e3);return}let l=new TextureLayer({name:`${e?.name}_${i}`,data_url:s.toDataURL()},e);a.saveTexture(n,l),l.addForEditing()}),Undo.finishEdit("Decode MER to layers")}}],click(){}}),MenuBar.addAction(o.decodeMer,"tools"),MenuBar.addAction(o.generateMer,"file.export")});C.push(()=>{MenuBar.removeAction("file.export.create_mer"),MenuBar.removeAction("tools.decode_mer")});var qe=()=>{Project&&Project.textures.forEach(e=>{let a=new D(null,e.uuid),t=a.findTexture(h.normal,!1),r=a.findTexture(h.height,!1),n=a.findTexture(h.albedo,!1),i=a.findTexture(h.metalness,!1)?.name,s=a.findTexture(h.emissive,!1)?.name,l=a.findTexture(h.roughness,!1)?.name,u={};return n||(u.baseColor={type:"color",label:"Base Color",value:"#ff00ff"}),!i&&!s&&!l&&(u.metalness={label:"Metalness",type:"range",min:0,max:255,step:1,value:0},u.emissive={label:"Emissive",type:"range",min:0,max:255,step:1,value:0},u.roughness={label:"Roughness",type:"range",min:0,max:255,step:1,value:0}),t&&(u.depthMap={type:"checkbox",label:"Normal Map",value:"normal"}),r&&(u.depthMap={type:"checkbox",label:"Height Map",value:"heightmap"}),t&&r&&(u.depthMap={type:"radio",label:"Depth Map",options:{normal:"Normal Map",heightmap:"Height"},value:"normal"}),o.textureSetDialog=new Dialog("texture_set",{id:"texture_set",title:"Create Texture Set JSON",buttons:["Create","Cancel"],form:u,cancelIndex:1,onConfirm(m){let d=G(),c=i||s||l,v={format_version:"1.16.100","minecraft:texture_set":{color:(n?d:m.baseColor?.toHexString())??d,metalness_emissive_roughness:[m.metalness??0,m.emissive??0,m.roughness??255]}};m.depthMap==="normal"&&t||!r&&t?v["minecraft:texture_set"].normal=`${d}_normal`:(!t||m.depthMap==="heightmap")&&r&&(v["minecraft:texture_set"].heightmap=`${d}_heightmap`);let g=p=>{if(!m.depthMap)return p();let b=m.depthMap==="normal"||m.depthMap&&!r,M=b?t:r;if(!M)return p();Blockbench.export({content:M.canvas.toDataURL()??"",type:"PNG",name:`${d}_${b?"normal":"heightmap"}`,extensions:["png"],resource_id:m.depthMap,startpath:Project.export_path,savetype:"image"},w=>{v["minecraft:texture_set"][b?"normal":"heightmap"]=pathToName(w,!1),p()})},x=p=>{if(!n)return p();Blockbench.export({content:n.canvas.toDataURL(),extensions:["png"],type:"PNG",name:d,startpath:Project.export_path,savetype:"image"},b=>{v["minecraft:texture_set"].color=pathToName(b,!1),p()})},f=()=>g(()=>{x(()=>{Blockbench.export({content:JSON.stringify(v,null,2),type:"JSON",name:`${d}.texture_set`,extensions:["json"],resource_id:"texture_set",startpath:Project.export_path,savetype:"text"},()=>{Blockbench.showQuickMessage("Texture set created",2e3),o.textureSetDialog?.hide()})})});if(c){try{Q(d,p=>{v["minecraft:texture_set"].metalness_emissive_roughness=pathToName(p,!1),f()})}catch(p){console.warn("Failed to export MER map:",p),Blockbench.showStatusMessage("Failed to export MER map",3e3)}return}f()}}),o.textureSetDialog.show()})};y.push(()=>{o.createTextureSet=new Action("create_texture_set",{name:"Create Texture Set",icon:"layers",description:"Creates a texture set JSON file. Generates a MER when metalness, emissive, or roughness channels are set.",click(){qe()},condition:{formats:["bedrock","bedrock_block"],project:!0}}),MenuBar.addAction(o.createTextureSet,"file.export")});C.push(()=>{MenuBar.removeAction("file.export.create_texture_set")});y.push(()=>{o.toggleCorrectLights=new Toggle("correct_lights",{category:"preview",name:"Correct Lights",description:"Corrects the lighting in the preview",icon:"fluorescent",default:!1,onChange(e){Preview.all.forEach(a=>{a.renderer.physicallyCorrectLights=e}),Preview.selected.renderer.physicallyCorrectLights=e,Blockbench.showQuickMessage(`Physically corrected lighting is now ${e?"enabled":"disabled"}`,2e3),e&&o.togglePbr?.set(!0),B()},click(){}}),MenuBar.addAction(o.toggleCorrectLights,"preview")});C.push(()=>{MenuBar.removeAction("preview.correct_lights")});var J=()=>{!Project||!Project.bb_materials||(Project.elements.forEach(e=>{e instanceof Cube&&Object.keys(e.faces).forEach(a=>{let r=e.faces[a].getTexture();if(!r)return;let n=Project.bb_materials[r.uuid];n&&(Project.materials[r.uuid]=n)})}),Project.pbr_active=!1,Canvas.updateAll())};var fe=["undo","redo","add_texture","finish_edit","finished_edit","load_project","select_preview_scene","change_texture_path","select_project","load_undo_save","add_cube"],xe=()=>Project&&Project.pbr_active&&B(),Ke=()=>{Blockbench.on(fe.join(" "),xe)},be=()=>{fe.forEach(e=>{Blockbench.removeListener(e,xe)})};y.push(()=>{o.togglePbr=new Toggle("toggle_pbr",{name:"PBR Preview",description:"Toggle PBR Preview",icon:"panorama_photosphere",category:"view",default:!1,click(){},onChange(e){if(e){B(),Ke(),Blockbench.showQuickMessage("PBR Preview is now enabled");return}J(),be(),Blockbench.showQuickMessage("PBR Preview is now disabled")}}),MenuBar.addAction(o.togglePbr,"view")});C.push(()=>{be(),MenuBar.removeAction("view.toggle_pbr")});var ve=e=>{let a=Math.max(-2,Math.min(2,e));Preview.all.forEach(t=>{t.renderer.toneMappingExposure=a}),Preview.selected.renderer.toneMappingExposure=a};y.push(()=>{o.exposureSlider=new NumSlider("display_settings_exposure",{category:"preview",name:"Exposure",description:"Adjusts the exposure of the scene",type:"number",value:1,icon:"exposure",settings:{min:-2,max:2,step:.01,default:1},onBefore(){Number(o.tonemappingSelect?.get())===_.NoToneMapping&&o.tonemappingSelect.change(_.LinearToneMapping.toString()),o.togglePbr?.set(!0)},onChange(e){ve(Number(e))},onAfter(){A()}}),o.resetExposureButton=new Action("display_settings_reset_exposure",{category:"preview",name:"Reset Exposure",description:"Resets the exposure of the scene",icon:"exposure_plus_1",condition:()=>o.exposureSlider!==void 0&&Number(o.exposureSlider?.get())!==1,click(){ve(1),o.exposureSlider?.setValue(1,!0),A()}}),o.tonemappingSelect=new BarSelect("display_settings_tone_mapping",{category:"preview",name:"Tone Mapping",description:"Changes the tone mapping of the preview",type:"select",default_value:_.NoToneMapping,value:Preview.selected.renderer.toneMapping??_.NoToneMapping,icon:"monochrome_photos",options:{[_.NoToneMapping]:"No Tone Mapping",[_.LinearToneMapping]:"Linear",[_.ReinhardToneMapping]:"Reinhard",[_.CineonToneMapping]:"Cineon",[_.ACESFilmicToneMapping]:"ACES"},onChange({value:e}){Preview.selected.renderer.toneMapping=Number(e);let a=1;Preview.selected.renderer.toneMapping===_.NoToneMapping?o.exposureSlider?.setValue(a,!0):a=Number(o.exposureSlider?.get()??1),Preview.all.forEach(t=>{t.renderer.toneMapping=Number(e),t.renderer.toneMappingExposure=a}),Preview.selected.renderer.toneMappingExposure=a,Blockbench.showQuickMessage(`Tone mapping set to ${this.getNameFor(e)}`,2e3),o.togglePbr&&!o.togglePbr.value&&o.togglePbr.set(!0),B()}})});var ae=class{async parse(a){let t=new le,r="model.usda";t.file(r,"");let n=we(),i={},s={};a.traverseVisible(m=>{if(!m.isMesh)return;let d=m;if(!d.material.isMeshStandardMaterial){console.warn("THREE.USDZExporter: Unsupported material type (USDZ only supports MeshStandardMaterial)",m);return}let c=d.geometry,v=d.material,g="geometries/Geometry_"+c.id+".usd";if(!t.file(g)){let x=rt(c);t.file(g,et(x))}v.uuid in i||(i[v.uuid]=v),n+=tt(d,c,v)}),n+=lt(i,s),t.file(r,n),n=null;for(let m in s){let d=s[m],c=m.split("_")[1],v=d.format===_.RGBAFormat,g=Ye(d.image,c),f=await(await new Promise(p=>g.toBlob(b=>b&&p(b),v?"image/png":"image/jpeg",1))).arrayBuffer();t.file(`textures/Texture_${m}.${v?"png":"jpg"}`,f)}let l=0;t.forEach(async m=>{let d=34+m.length;l+=d;let c=l&63,v=await t.file(m).async("uint8array");if(c!==4){let g=64-c,x=new Uint8Array(g),f=new Uint8Array(v.length+g);f.set(v,0),f.set(x,v.length),t.file(m,f)}l+=v.length});let u=await t.generateAsync({type:"blob",compression:"STORE"});return new Uint8Array(await u.arrayBuffer())}};function Ye(e,a){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){let t=1024/Math.max(e.width,e.height),r=document.createElement("canvas");r.width=e.width*Math.min(1,t),r.height=e.height*Math.min(1,t);let n=r.getContext("2d");if(n.imageSmoothingEnabled=!1,n.drawImage(e,0,0,r.width,r.height),a!==void 0){let i=parseInt(a,16),s=(i>>16&255)/255,l=(i>>8&255)/255,u=(i&255)/255,m=n.getImageData(0,0,r.width,r.height),d=m.data;for(let c=0;c +) +{ + matrix4d xformOp:transform = ${n} + uniform token[] xformOpOrder = ["xformOp:transform"] + + rel material:binding = +} + +`}function at(e){let a=e.elements;return`( ${X(a,0)}, ${X(a,4)}, ${X(a,8)}, ${X(a,12)} )`}function X(e,a){return`(${e[a+0]}, ${e[a+1]}, ${e[a+2]}, ${e[a+3]})`}function rt(e){return` +def "Geometry" +{ + ${nt(e)} +} +`}function nt(e){let a="Geometry",t=e.attributes,r=t.position.count;return` + def Mesh "${a}" + { + int[] faceVertexCounts = [${st(e)}] + int[] faceVertexIndices = [${ot(e)}] + normal3f[] normals = [${_e(t.normal,r)}] ( + interpolation = "vertex" + ) + point3f[] points = [${_e(t.position,r)}] + float2[] primvars:st = [${it(t.uv,r)}] ( + interpolation = "vertex" + ) + uniform token subdivisionScheme = "none" + } +`}function st(e){let a=e.index!==null?e.index.count:e.attributes.position.count;return Array(a/3).fill(3).join(", ")}function ot(e){let a=e.index,t=[];if(a!==null)for(let r=0;r + float2 inputs:scale = ${ye(l.repeat)} + float2 inputs:translation = ${ye(l.offset)} + float2 outputs:result + } + + def Shader "Texture_${l.id}_${u}" + { + uniform token info:id = "UsdUVTexture" + asset inputs:file = @textures/Texture_${d}.${c?"png":"jpg"}@ + float2 inputs:st.connect = + token inputs:wrapS = "repeat" + token inputs:wrapT = "repeat" + float outputs:r + float outputs:g + float outputs:b + float3 outputs:rgb + }`}let s=e;if(s.map!==null?(r.push(`${t}color3f inputs:diffuseColor.connect = `),n.push(i(s.map,"diffuse",s.color))):r.push(`${t}color3f inputs:diffuseColor = ${Me(s.color)}`),s.emissiveMap!==null?(r.push(`${t}color3f inputs:emissiveColor.connect = `),n.push(i(s.emissiveMap,"emissive"))):s.emissive.getHex()>0&&r.push(`${t}color3f inputs:emissiveColor = ${Me(s.emissive)}`),s.normalMap!==null&&(r.push(`${t}normal3f inputs:normal.connect = `),n.push(i(s.normalMap,"normal"))),s.aoMap!==null&&(r.push(`${t}float inputs:occlusion.connect = `),n.push(i(s.aoMap,"occlusion"))),s.roughnessMap!==null&&s.roughness===1?(r.push(`${t}float inputs:roughness.connect = `),n.push(i(s.roughnessMap,"roughness"))):r.push(`${t}float inputs:roughness = ${s.roughness}`),s.metalnessMap!==null&&s.metalness===1?(r.push(`${t}float inputs:metallic.connect = `),n.push(i(s.metalnessMap,"metallic"))):r.push(`${t}float inputs:metallic = ${s.metalness}`),s.alphaMap!==null?(r.push(`${t}float inputs:opacity.connect = `),r.push(`${t}float inputs:opacityThreshold = 0.0001`),n.push(i(s.alphaMap,"opacity"))):r.push(`${t}float inputs:opacity = ${s.opacity}`),s.isMeshPhysicalMaterial){let l=s;r.push(`${t}float inputs:clearcoat = ${l.clearcoat}`),r.push(`${t}float inputs:clearcoatRoughness = ${l.clearcoatRoughness}`),r.push(`${t}float inputs:ior = ${l.ior}`)}return` + def Material "Material_${s.id}" + { + def Shader "PreviewSurface" + { + uniform token info:id = "UsdPreviewSurface" +${r.join(` +`)} + int inputs:useSpecularWorkflow = 0 + token outputs:surface + } + + token outputs:surface.connect = + token inputs:frame:stPrimvarName = "st" + + def Shader "uvReader_st" + { + uniform token info:id = "UsdPrimvarReader_float2" + token inputs:varname.connect = + float2 inputs:fallback = (0.0, 0.0) + float2 outputs:result + } + +${n.join(` +`)} + + } +`}function Me(e){return`(${e.r}, ${e.g}, ${e.b})`}function ye(e){return`(${e.x}, ${e.y})`}var Te=ae;y.push(()=>{let e=new Codec("usdz",{extension:"usdz",name:"USDZ",remember:!0,export_options:{normal_type:{type:"select",label:"Normal Map Type",default:"opengl",options:{opengl:"OpenGL",directx:"DirectX"}}},fileName(){return G()+".usdz"},async compile(a={}){if(!Project)throw new Error("No project loaded");let t=Object.assign(this.getExportOptions(),a);Project.textures.forEach(s=>{if(!s.material)return;let l=new D(s.layers,s.uuid),u=l.findTexture("normal",!0);if(!u)return;let m=$(u,t.normal_type);m&&l.saveTexture(h.normal,m)}),B();let r=new Te,n=new _.Scene;n.name="blockbench_export",n.add(Project.model_3d);let i=await r.parse(n);return this.dispatchEvent("compile",{model:i,options:t}),Canvas.scene.add(Project.model_3d),i},async export(a={}){let t=await this.compile(a);Blockbench.export({content:t,name:this.fileName(),startpath:this.startPath(),resource_id:"usdz",type:this.name,extensions:["usdz"],savetype:"buffer"},r=>this.afterDownload(r))}});o.exportUsdz=new Action("export_usdz",{category:"file",name:"Export USDZ",description:"Exports the current model as a USDZ file",icon:"stacks",async click(){if(!e)return;let a=await e.promptExportOptions();await e.export(a)}}),o.usdz=e,MenuBar.addAction(o.exportUsdz,"file.export")});C.push(()=>{MenuBar.removeAction("file.export_usdz")});y.push(()=>{o.bbmat=new Codec("material",{name:"Blockbench Material",extension:"bbmat",remember:!1,load_filter:{extensions:["bbmat"],type:"json"},compile(){if(!Texture.selected?.material||!Texture.selected?.layers_enabled)return;let e=Texture.selected.layers.map(a=>{let t=a.channel,r=a.canvas.toDataURL();return[t,r]});return JSON.stringify({version:K,channels:Object.fromEntries(e)})},parse(e,a){return e=typeof e=="string"?JSON.parse(e):e,e.version!==K?(Blockbench.showMessageBox({title:"Invalid Blockbench Material Version",message:`The material file "${a}" is not compatible with version ${F} of the PBR plugin.`,buttons:["OK"],confirm:0,width:400,cancel:0,checkboxes:{}},()=>null),{}):e.channels},load(e,a,t){if(!Project)return;let r=this.parse(e,a.path),n=Object.keys(r);if(!n.length)throw new Error("No valid channels found in the material");let i=r[h.albedo.id]??r[n[0]];n.includes("preview")&&(i=r.preview);let s=new Texture({name:pathToName(a.name),saved:!0,particle:!1,source:i,layers_enabled:!0});s.extend({material:!0});let l=n.map(u=>{if(!(u in h))return null;let m=r[u],d=new TextureLayer({name:u,data_url:m,visible:!0},s);return d.extend({channel:u}),d}).filter(Boolean);if(!l.length)throw new Error("No valid channel layers found in the material");i||s.fromDataURL(l[0].canvas.toDataURL()),s.add().select(),l.forEach(u=>{u.addForEditing(),s.width=Math.max(s.width,u.img.width),s.height=Math.max(s.height,u.img.height)}),s.updateChangesAfterEdit()},export(){Blockbench.export({resource_id:"material",type:this.name,extensions:[this.extension],name:`${Texture.selected?.name??this.fileName??"material"}.bbmat`,startpath:this.startPath(),content:this.compile()},e=>this.afterDownload(e))}}),o.bbMatExport=new Action("export_bbmat",{icon:"stacks",name:"Save as .bbmat",category:"file",condition:{project:!0,selected:{texture:!0},method(){return Texture.selected?.material}},click(){o.bbmat?.export?.()}}),o.bbMatImport=new Action("import_bbmat",{icon:"stacks",name:"Import .bbmat",category:"file",condition:{project:!0},click(){Blockbench.import({extensions:["bbmat"],type:"json",title:"Import .bbmat",multiple:!0},e=>{o.bbmat?.load&&e.forEach(a=>{o.bbmat.load(a.content,a,!0)})})}}),o.bbmat.export_action=o.bbMatExport,Texture.prototype.menu.addAction(o.bbMatExport),MenuBar.addAction(o.bbMatImport,"file.import")});C.push(()=>{Texture.prototype.menu.removeAction("export_bbmat"),MenuBar.removeAction("file.import.import_bbmat")});var Z=class e{constructor({colors:a}){this._colors={...Object.fromEntries(Object.keys(h).map(t=>[t,h[t].default??new _.Color(4294967040)])),...a}}get colors(){return this._colors}set colors(a){this._colors={...this._colors,...a}}toString(){let a=Object.entries(this._colors).map(([t,r])=>[t,r.getHexString()]);return JSON.stringify(a)}getChannel(a){return this._colors[a]}static makeLinearColor(a){let t=Math.min(1,Math.max(0,a));return new _.Color(t,t,t).convertSRGBToLinear()}static fromSettings(){let a="#000000",t=Number(o.brushMetalnessSlider?.get()),r=Number(o.brushRoughnessSlider?.get()??1),n=(o.brushEmissiveColor?.get()??a).toString(),i=Number(o.brushHeightSlider?.get()),s=ColorPanel.get(),l={[h.albedo.id]:new _.Color(s),[h.metalness.id]:e.makeLinearColor(t),[h.roughness.id]:e.makeLinearColor(r),[h.emissive.id]:new _.Color(n??a),[h.height.id]:e.makeLinearColor(i)};return new e({colors:l})}};var Ce="materialBrushPresets",re=()=>JSON.parse(localStorage.getItem(Ce)||"{}"),ut=(e,a)=>{let t=re(),r=a??guid(),n=o.userMaterialBrushPresets?.getFormResult()??{},i={};return n.albedo&&(i.albedo=n.albedo.toString()),n.metalness&&(i.metalness=Number(n.metalness)),n.roughness&&(i.roughness=Number(n.roughness)),n.emissive&&(i.emissive=n.emissive.toString()),n.height&&(i.height=Number(n.height)),t[r]=[i,e??"New Preset",z(i)],localStorage.setItem(Ce,JSON.stringify(t)),r},Ee=({metalness:e,roughness:a,emissive:t,height:r,albedo:n})=>{e!==void 0&&o.brushMetalnessSlider?.setValue(e||0,!0),a!==void 0&&o.brushRoughnessSlider?.setValue(a??1,!0),t!==void 0&&o.brushEmissiveColor?.set(t??"#000000"),r!==void 0&&o.brushHeightSlider?.setValue(Math.max(0,Math.min(1,r??.5)),!0),n!==void 0&&ColorPanel.set(n)},W=({id:e})=>Condition({project:!0,tools:["material_brush"],method(){let a=E();return(a?.layers_enabled&&a.layers.find(({channel:t})=>t&&t===e)!==void 0)===!0}}),mt=ie.extend({name:"UserPresetsDialog",data(){return{userPresets:{},channels:h}},methods:{applyPreset(e){try{let[a,t]=this.userPresets[e],{metalness:r,roughness:n,emissive:i,height:s,albedo:l}=a;Ee({metalness:Number(r),roughness:Number(n),emissive:i.toString(),height:Number(s),albedo:l.toString()}),o.userMaterialBrushPresets?.hide(),Blockbench.showQuickMessage(`Preset "${t}" applied`,2e3)}catch{Blockbench.showQuickMessage("Failed to apply preset",2e3)}},deletePreset(e){Blockbench.showMessageBox({title:"Delete Preset",message:"Are you sure you want to delete this preset?",confirm:1,cancel:0,buttons:["Cancel","Delete"],checkboxes:{},width:400},a=>{if(a){let t=re(),r=this.userPresets[e][1]??e;delete t[e],localStorage.setItem("materialBrushPresets",JSON.stringify(t)),this.userPresets=t,Blockbench.showQuickMessage(`Preset "${r}" deleted`,2e3)}})},editPreset(e){o.userMaterialBrushPresets?.setFormValues({name:this.userPresets[e][1]??e,...this.userPresets[e][0]})},getSummary(e){return Object.entries(e).filter(([a])=>a in this.channels).map(([a,t])=>a==="albedo"||a==="emissive"?`${this.channels[a]?.label??a}: ${t}`:`${this.channels[a]?.label??a}: ${Number(t).toFixed(1)}`).join(` +`)}},computed:{presets(){return Object.entries(this.userPresets)}},mounted(){this.userPresets=re()},template:` +
+
    +
  • +
    + +
    {{ name }}
    +
    +
    +
    {{ name }}
    +
    +
    + +
    +
  • +
+
`});y.push(()=>{o.materialBrushStyles=Blockbench.addCSS(` + .preset_list { + display: grid; + grid-template-columns: repeat(auto-fill, 96px); + grid-gap: 8px; + justify-content: start; + align-items: start; + margin: 0 auto; + padding: 8px; + } + + .user_preset { + display: flex; + justify-content: start; + align-items: center; + width: 100%; + padding: 8px; + position: relative; + } + + .preset_title { + font-size: 1em; + color: var(--color-text); + } + + .user_preset:hover .preset_title { + color: var(--color-accent); + } + + .preset_preview { + display: flex; + flex-direction: column; + flex-wrap: nowrap; + justify-content: center; + align-items: center; + text-align: center; + } + + .preset_buttons { + display: flex; + flex-direction: row; + align-items: center; + font-size: 0.8em; + padding: 0 4px; + } + + .preset_channel { + display: flex; + flex-direction: row; + align-items: center; + margin: 0 8px; + font-size: 0.8em; + } + + .delete_preset { + margin-left: 8px; + padding: 4px; + height: 24px; + width: 24px; + min-width: 24px; + background-color: transparent; + color: var(--color-text); + border: none; + border-radius: 100%; + position: absolute; + right: -8px; + top: 0; + filter: drop-shadow(0 0 2px var(--color-shadow)); + } + + .delete_preset:hover { + background: transparent; + color: var(--color-accent); + } + + .delete_preset .material-icons { + font-size: 0.825em; + } + + .delete_preset:hover .material-icons { + color: var(--color-accent); + }`),o.brushMetalnessSlider=new NumSlider("slider_brush_metalness",{category:"paint",name:"Metalness",description:"Adjust the metalness of the brush",tool_setting:"brush_metalness",settings:{min:0,max:1,step:.01,default:0},condition:()=>W(h.metalness)}),o.brushRoughnessSlider=new NumSlider("slider_brush_roughness",{category:"paint",name:"Roughness",description:"Adjust the roughness of the brush",tool_setting:"brush_roughness",settings:{min:0,max:1,step:.01,default:1},condition:()=>W(h.roughness)}),o.brushEmissiveColor=new ColorPicker("brush_emissive_color",{category:"paint",name:"Emissive",description:"Adjust the emissive color of the brush",value:"#000000",tool_setting:"brush_emissive",condition:()=>W(h.emissive)}),o.brushHeightSlider=new NumSlider("slider_brush_height",{category:"paint",name:"Height",description:"Adjust the height of the brush",tool_setting:"brush_height",settings:{min:0,max:1,step:.01,default:.5},condition:()=>W(h.height)}),o.materialBrushTool=new Tool("material_brush",{name:"Material Brush",description:"Paints across multiple texture layers",icon:"view_in_ar",paintTool:!0,cursor:"cell",category:"tools",toolbar:"brush",condition:{project:!0,selected:{texture:!0},modes:["paint"],method(){return E()?.layers_enabled??!1}},allowed_view_modes:"textured",tool_settings:{brush_metalness:0,brush_roughness:1,brush_emissive:"#000000",brush_height:.5},brush:{blend_modes:!1,shapes:!0,size:!0,softness:!0,opacity:!0,offset_even_radius:!0,floor_coordinates:!0,changePixel(e,a,t,r,{size:n,softness:i,texture:s,x:l,y:u}){let m=Z.fromSettings(),d=Object.keys(m.colors),c=Math.floor(n-i*n/100),v=t;return s.layers.forEach(g=>{if(!g.visible||!d.includes(g.channel))return;let x=m.getChannel(g.channel);if(!x)return;let f=Math.sqrt((l-e)**2+(u-a)**2),p=Math.min(1,f/c);if(l%c<=p&&u%c<=p){let b=g.ctx.getImageData(e,a,1,1).data,M=new _.Color(`rgb(${b[0]}, ${b[1]}, ${b[2]})`);x.lerp(M,1)}g.ctx.fillStyle=x.getStyle(),g.ctx.fillRect(e,a,1,1),g.selected&&(v={r:x.r*255,g:x.g*255,b:x.b*255,a:r*255})}),v},onStrokeStart({texture:e}){return Undo.initEdit({layers:e.layers}),!0},onStrokeEnd({texture:e}){return Undo.finishEdit("Material Brush Stroke"),!0}},onCanvasClick(e){Painter.startPaintToolCanvas(e,e.event)},onSelect(){Painter.updateNslideValues(),B()},click(){A()}}),o.loadBrushPreset=new Action("load_brush_preset",{icon:"stroke_full",name:"Material Brush Presets",description:"Load or save a brush preset",category:"paint",condition:{project:!0},click(){o.userMaterialBrushPresets=new Dialog("user_brush_presets",{id:"user_brush_presets",title:"Edit Material Brush",component:mt,part_order:["lines","component","form"],form:{albedo:{type:"color",label:"Albedo",value:ColorPanel.get(),toggle_enabled:!0},metalness:{type:"number",label:"Metalness",min:0,max:1,step:.01,full_width:!1,toggle_enabled:!0},roughness:{type:"number",label:"Roughness",min:0,max:1,step:.01,toggle_enabled:!0,full_width:!1},emissive:{type:"color",label:"Emissive",value:"#000000",toggle_enabled:!0},height:{type:"number",label:"Height",min:0,max:1,step:.01,toggle_enabled:!0}},onConfirm(e){Ee({metalness:Number(e.metalness??o.brushMetalnessSlider?.get()),roughness:Number(e.roughness??o.brushRoughnessSlider?.get()),emissive:(e.emissive??o.brushEmissiveColor?.get()).toString(),height:Number(e.height??o.brushHeightSlider?.get()),albedo:(e.albedo??ColorPanel.get()).toString()})},buttons:["Close","Save","Apply"],cancelIndex:0,confirmIndex:2,onButton(e,a){o.materialBrushTool?.select(),e===1&&Blockbench.textPrompt("Save Preset","New Preset",t=>{t&&(ut(t),Blockbench.showQuickMessage(`Preset "${t}" saved`,2e3))})}}).show()}}),MenuBar.addAction(o.materialBrushTool,"tools.0")});C.push(()=>{MenuBar.removeAction("tools.material_brush")});y.push(()=>{o.materialBrushPanel=new Panel("material_brush_panel",{name:"Material Brush",id:"material_brush_panel",icon:"view_in_ar",toolbars:[new Toolbar("material_brush_toolbar",{id:"material_brush_toolbar",children:["material_brush","load_brush_preset","slider_brush_metalness","slider_brush_roughness","brush_emissive_color","slider_brush_height"],name:"Material Settings"})],condition:{modes:["paint"],project:!0},component:{},expand_button:!0,growable:!1,onFold(){},onResize(){},default_side:"right",default_position:{slot:"right_bar",float_position:[0,0],float_size:[400,300],height:300,folded:!1},insert_after:"color",insert_before:"outliner"})});y.push(()=>{o.displaySettingsPanel=new Panel("display_settings",{name:"PBR Controls",id:"display_settings_panel",icon:"display_settings",toolbars:[new Toolbar("controls_toolbar",{id:"controls_toolbar",children:["toggle_pbr","correct_lights","display_settings_tone_mapping","display_settings_exposure","display_settings_reset_exposure","show_channel_select_menu"],name:"Display Settings"})],display_condition:{modes:["edit","paint","animate"],project:!0},component:{},expand_button:!0,growable:!1,onFold(){},onResize(){},default_side:"left",default_position:{slot:"left_bar",float_position:[0,0],float_size:[400,300],height:300,folded:!1},insert_after:"textures",insert_before:"color"})});var q=e=>e.visible&&e.channel&&e.channel!==N,dt=()=>{let e=R();if(e)return e.texture.layers.filter(q);let a=E();return a?a.layers_enabled?a.layers.filter(q):Texture.all.map(t=>t.layers_enabled?[...t.layers.filter(q)]:[q(t)?t:null]).flat().filter(Boolean):[]},Pe=["select_texture","update_texture_selection","finish_edit","add_texture"],Le=()=>{Panels.channels_panel.inside_vue.textures=dt()};y.push(()=>{o.channelsPanelStyle=Blockbench.addCSS(` + .texture_channel { + color: var(--color-text); + flex: 1; + font-size: 1em; + margin: 0 0 0 auto; + padding: 0 8px; + text-align: right; + } + + .texture_channel + .texture_particle_icon { + padding-right: 8px; + } + + .texture_channel_description { + background-color: var(--color-back); + display: flex; + flex-direction: row; + flex-wrap: nowrap; + justify-content: space-between; + } + + .texture_channel_wrapper { + align-items: center; + background-color: var(--color-ui); + border-left: 1px solid var(--color-border); + display: flex; + flex: 1; + flex-direction: row; + align-items: center; + flex-wrap: nowrap; + padding: 0 8px; + } + + .texture_channel_wrapper:hover { + background-color: var(--color-button); + } + + .texture_channel_description .texture_name { + flex-direction: column; + flex-wrap: nowrap; + color: var(--color-subtle_text); + display: flex; + flex: 1; + justify-content: center; + align-items: start; + } + + .texture_parent { + color: var(--color-subtle_text); + font-size: 0.8em; + } + + .texture_channel_description:hover .texture_channel { + color: var(--color-accent); + } + + #pbr_channel_list { + display: flex; + flex-direction: column; + } + + #pbr_channel_list .texture { + border-top: 1px solid var(--color-border); + padding-right: 0; + } + `),o.channelsPanel=new Panel("channels_panel",{name:"PBR Channels",id:"channels_panel",icon:"gallery_thumbnail",condition:{project:!0,selected:{texture:!0},modes:["paint","edit"]},toolbars:[],component:{name:"ChannelsPanel",data(){return{channels:h,textures:[]}},methods:{openMenu(e){o.channelMenu?.open(e)},selectTexture(e){Modes.options.paint.select(),e.select(),e.scrollTo()},channelEnabled(e){return e.channel&&e.channel!==N&&e.channel in this.channels},getImgSrc(e){return e.img?.src??`data:image/png;base64,${e.canvas.toDataURL()}`}},template:` +
+
    +
  • + +
    +
    +
    {{ texture.name }}
    +
    + {{ texture.texture.name }} +
    +
    +
    +
    {{ channels[texture.channel].label }}
    + {{ channels[texture.channel].icon }} +
    +
    +
  • +
+
`},expand_button:!0,growable:!0,onFold(){},onResize(){},default_side:"left",default_position:{slot:"left_bar",float_position:[0,0],float_size:[400,300],height:350,folded:!0},insert_after:"layers",insert_before:"color"}),Blockbench.on(Pe.join(" "),Le)});C.push(()=>{Pe.forEach(e=>{Blockbench.removeListener(e,Le)})});(()=>{let e=()=>{y.forEach(t=>t())},a=()=>{J(),C.forEach(t=>t()),Object.entries(o).forEach(([t,r])=>{try{r?.delete()}catch(n){console.warn(`Failed to delete ${t} action:`,n)}})};BBPlugin.register("pbr_preview",{version:F,title:"PBR Tools",author:"Jason J. Gardner",description:"Create and view PBR materials in Blockbench. Export USDZ scenes and textures for Java or RenderDragon shaders.",tags:["Minecraft: Java Edition","Minecraft: Bedrock Edition","PBR"],icon:"icon.png",variant:"both",await_loading:!0,repository:"https://github.com/jasonjgardner/blockbench-plugins",has_changelog:!0,min_version:"4.10.3",onload:e,onunload:a})})();})(); diff --git a/src/pbr_preview/.prettierignore b/src/pbr_preview/.prettierignore new file mode 100644 index 00000000..737bc52b --- /dev/null +++ b/src/pbr_preview/.prettierignore @@ -0,0 +1,3 @@ +node_modules/ +dist/ +package-lock.json \ No newline at end of file diff --git a/src/pbr_preview/.prettierrc b/src/pbr_preview/.prettierrc new file mode 100644 index 00000000..e66b3328 --- /dev/null +++ b/src/pbr_preview/.prettierrc @@ -0,0 +1,12 @@ +{ + "semi": true, + "trailingComma": "es5", + "singleQuote": false, + "printWidth": 80, + "tabWidth": 2, + "vueIndentScriptAndStyle": true, + "bracketSameLine": false, + "arrowParens": "always", + "endOfLine": "lf", + "quoteProps": "as-needed" +} \ No newline at end of file diff --git a/src/pbr_preview/changelog.mjs b/src/pbr_preview/changelog.mjs new file mode 100644 index 00000000..a2bacf35 --- /dev/null +++ b/src/pbr_preview/changelog.mjs @@ -0,0 +1,108 @@ +import readline from "node:readline/promises"; +import { writeFile, readFile } from "node:fs/promises"; + +const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, +}); + +const changelog = "./plugins/pbr_preview/changelog.json"; + +function createChangelog(version, changes, author, title = null, date = null) { + const changelog = { + [version.toString()]: { + title: title ?? `Version ${version}`, + date: date || new Date().toISOString().split("T")[0], + author, + categories: [], + }, + }; + + for (const change of changes) { + changelog[version].categories.push({ + title: "", + list: [], + ...change, + }); + } + + return changelog; +} + +async function amendChangelog( + version, + changes, + author, + title = null, + date = null, +) { + const data = JSON.parse(await readFile(changelog, "utf-8")); + const newChangelog = createChangelog(version, changes, author, title, date); + const mergedChangelog = { ...data, ...newChangelog }; + + await writeFile(changelog, JSON.stringify(mergedChangelog, null, 4)); +} + +async function main() { + const version = await rl.question("Enter the version number: "); + const author = await rl.question("Enter the author: "); + const title = await rl.question( + "Enter the title (leave blank for default): ", + ); + + const changes = []; + let makingChanges = true; + let writingDescriptions = false; + + while (makingChanges) { + const change = await rl.question( + "Enter a change title (leave blank to exit): ", + ); + + makingChanges = change.length > 0; + + if (!makingChanges) { + break; + } + + const descriptions = []; + writingDescriptions = true; + + while (writingDescriptions) { + const description = await rl.question( + "Enter a description (leave blank to finish): ", + ); + + writingDescriptions = description.length > 0; + + if (!writingDescriptions) { + break; + } + + descriptions.push(description); + } + + changes.push({ + title: change, + list: descriptions, + }); + } + + await amendChangelog( + version, + changes, + author, + title ?? `Version ${version}`, + new Date().toISOString().split("T")[0], + ); +} + +main() + .then(() => { + console.log("Changelog updated!"); + process.exit(0); + }) + .catch((err) => { + console.error(err); + process.exit(1); + }); diff --git a/src/pbr_preview/package.json b/src/pbr_preview/package.json new file mode 100644 index 00000000..ffcc0b20 --- /dev/null +++ b/src/pbr_preview/package.json @@ -0,0 +1,23 @@ +{ + "name": "blockbench-pbr", + "version": "1.0.0", + "description": "PBR support for Blockbench", + "main": "./src/index.ts", + "scripts": { + "build": "esbuild src/index.ts --bundle --minify --outfile=../../plugins/pbr_preview/pbr_preview.js", + "build:watch": "esbuild src/index.ts --bundle --minify --outfile=../../plugins/pbr_preview/pbr_preview.js --watch", + "dev": "esbuild src/index.ts --bundle --sourcemap --outfile=../../plugins/pbr_preview/pbr_preview.js --watch" + }, + "keywords": [ + "blockbench" + ], + "author": "Jason Gardner", + "license": "MIT", + "devDependencies": { + "@types/three": "^0.157.0", + "blockbench-types": "4.9.0", + "esbuild": "0.19.4", + "prettier": "^3.2.5", + "typescript": "^5.2.2" + } +} \ No newline at end of file diff --git a/src/pbr_preview/src/constants.ts b/src/pbr_preview/src/constants.ts new file mode 100644 index 00000000..07a00a55 --- /dev/null +++ b/src/pbr_preview/src/constants.ts @@ -0,0 +1,80 @@ +import type { IChannel, IRegistry } from "./types"; +import { three as THREE } from "./deps"; + +export const PLUGIN_VERSION = "1.2.0"; +export const BBMAT_VERSION = "1.0.0"; +export const NA_CHANNEL = "_NONE_"; +export const CHANNELS: Record = { + albedo: { + id: "albedo", + label: "Albedo", + description: "The color of the material", + map: "map", + icon: "tonality", + default: new THREE.Color(0xffffff), + regex: new RegExp("(s|_)*(basecolor|color|albedo)", "i"), + }, + metalness: { + id: "metalness", + label: "Metalness", + description: "The material's metalness map", + map: "metalnessMap", + icon: "brightness_6", + default: new THREE.Color(0), + regex: new RegExp("[ _]*metal(lic|ness)?", "i"), + }, + emissive: { + id: "emissive", + label: "Emissive", + description: "The material's emissive map", + map: "emissiveMap", + icon: "wb_twilight", + default: new THREE.Color(0), + regex: new RegExp("[ _]*(emissive|emission)", "i"), + }, + roughness: { + id: "roughness", + label: "Roughness", + description: "The material's roughness map", + map: "roughnessMap", + icon: "grain", + default: new THREE.Color(0xffffff), + regex: new RegExp("[ _]*rough(ness)?", "i"), + }, + height: { + id: "height", + label: "Height", + description: "The material's height map", + map: "bumpMap", + icon: "landscape", + default: new THREE.Color(0xffffff), + regex: new RegExp("[ _]*(height|bump)", "i"), + }, + normal: { + id: "normal", + label: "Normal", + description: "The material's normal map", + map: "normalMap", + icon: "looks", + default: new THREE.Color("rgb(128, 128, 255)"), + regex: new RegExp("[ _]*normal", "i"), + }, + ao: { + id: "ao", + label: "Ambient Occlusion", + description: "The material's ambient occlusion map", + map: "aoMap", + icon: "motion_mode", + default: new THREE.Color(0xffffff), + regex: new RegExp("[ _]*(ao|ambientocclusion|ambient occlusion)", "i"), + }, +}; + +/** + * Collection of registered Blockbench UI elements + * Used for component communication as well as to simplify cleanup + */ +export const registry: Partial = {}; + +export const setups: Array<() => void> = []; +export const teardowns: Array<() => void> = []; diff --git a/src/pbr_preview/src/deps.ts b/src/pbr_preview/src/deps.ts new file mode 100644 index 00000000..854430ee --- /dev/null +++ b/src/pbr_preview/src/deps.ts @@ -0,0 +1,10 @@ +// @ts-expect-error THREE UMD is OK +const three = THREE; +// @ts-expect-error Vue UMD is OK +const vue = Vue; +// const bb = Blockbench; + +// @ts-expect-error JSZip is on window +const jszip = window.JSZip; + +export { three, vue, jszip }; diff --git a/src/pbr_preview/src/index.ts b/src/pbr_preview/src/index.ts new file mode 100644 index 00000000..b66fc9cc --- /dev/null +++ b/src/pbr_preview/src/index.ts @@ -0,0 +1,56 @@ +/** + * @author jasonjgardner + * @discord jason.gardner + * @github https://github.com/jasonjgardner + */ +/// +/// +/// + +import { + registry, + setups, + teardowns, + PLUGIN_VERSION as version, +} from "./constants"; +import "./lib/properties"; +import "./lib/actions"; +import "./lib/tools"; +import "./lib/panels"; +import { disablePbr } from "./lib/disablePbr"; + +(() => { + const onload = () => { + setups.forEach((setup) => setup()); + }; + + const onunload = () => { + disablePbr(); + teardowns.forEach((teardown) => teardown()); + Object.entries(registry).forEach(([key, value]) => { + try { + value?.delete(); + } catch (err) { + console.warn(`Failed to delete ${key} action:`, err); + } + }); + }; + + BBPlugin.register("pbr_preview", { + // @ts-expect-error Version does exist in PluginOptions + version, + title: "PBR Tools", + author: "Jason J. Gardner", + description: + "Create and view PBR materials in Blockbench. Export USDZ scenes and textures for Java or RenderDragon shaders.", + tags: ["Minecraft: Java Edition", "Minecraft: Bedrock Edition", "PBR"], + icon: "icon.png", + variant: "both", + await_loading: true, + repository: "https://github.com/jasonjgardner/blockbench-plugins", + has_changelog: true, + min_version: "4.10.3", + onload, + onunload, + }); +})(); diff --git a/src/pbr_preview/src/lib/Lightr.ts b/src/pbr_preview/src/lib/Lightr.ts new file mode 100644 index 00000000..f68da3f0 --- /dev/null +++ b/src/pbr_preview/src/lib/Lightr.ts @@ -0,0 +1,135 @@ +import type { ILightrParams } from "../types"; +/** + * Adapted from Lightr by phosphoer + * @see https://github.com/phosphoer/lightr + */ +export class Lightr { + lightHeight: number; + ambientLight: [number, number, number]; + minLightIntensity: number; + lightDiffuse: [number, number, number]; + + constructor({ + lightHeight = 0.66, + ambientLight = [0.1, 0.1, 0.1], + minLightIntensity = 0.0, + lightDiffuse = [1, 1, 1], + }: ILightrParams = {}) { + this.lightHeight = lightHeight; + this.ambientLight = ambientLight; + this.minLightIntensity = minLightIntensity; + this.lightDiffuse = lightDiffuse; + } + + bake( + numDirs: number, + diffuseMap: HTMLImageElement | HTMLCanvasElement, + normalMap: HTMLImageElement | HTMLCanvasElement, + ): HTMLCanvasElement[] { + const canvasDiffuse = + diffuseMap instanceof HTMLCanvasElement + ? diffuseMap + : this.createCanvas(diffuseMap.width, diffuseMap.height); + const canvasNormals = + normalMap instanceof HTMLCanvasElement + ? normalMap + : this.createCanvas(normalMap.width, normalMap.height); + + const contextDiffuse = canvasDiffuse.getContext("2d")!; + const contextNormals = canvasNormals.getContext("2d")!; + + contextDiffuse.drawImage(diffuseMap, 0, 0); + contextNormals.drawImage(normalMap, 0, 0); + + const bufferDiffuse = contextDiffuse.getImageData( + 0, + 0, + diffuseMap.width, + diffuseMap.height, + ); + const bufferNormals = contextNormals.getImageData( + 0, + 0, + normalMap.width, + normalMap.height, + ); + + const bakedImages: HTMLCanvasElement[] = []; + const normals: [number, number, number][][] = []; + + for (let x = 0; x < bufferNormals.width; ++x) { + normals[x] = []; + for (let y = 0; y < bufferNormals.height; ++y) { + const idx = (x + y * bufferNormals.width) * 4; + + const normal = [ + (bufferNormals.data[idx + 0] / 255 - 0.5) * 2, + (bufferNormals.data[idx + 1] / 255 - 0.5) * 2, + (bufferNormals.data[idx + 2] / 255 - 0.5) * 2, + ]; + + const len = Math.sqrt(normal[0] ** 2 + normal[1] ** 2 + normal[2] ** 2); + normals[x][y] = [normal[0] / len, normal[1] / len, normal[2] / len]; + } + } + + const bakeDirection = (dir: number): HTMLCanvasElement => { + const canvas = this.createCanvas(diffuseMap.width, diffuseMap.height); + const context = canvas.getContext("2d")!; + const buffer = context.getImageData(0, 0, canvas.width, canvas.height); + + const lightDir = [Math.cos(dir), Math.sin(dir), this.lightHeight]; + + for (let x = 0; x < bufferNormals.width; ++x) { + for (let y = 0; y < bufferNormals.height; ++y) { + const normal = normals[x][y]; + const index = (x + y * bufferNormals.width) * 4; + const diffuse = [ + bufferDiffuse.data[index + 0] / 255, + bufferDiffuse.data[index + 1] / 255, + bufferDiffuse.data[index + 2] / 255, + bufferDiffuse.data[index + 3], + ]; + + let intensity = + normal[0] * lightDir[0] + + normal[1] * lightDir[1] + + normal[2] * lightDir[2]; + intensity = Math.min(1, Math.max(this.minLightIntensity, intensity)); + + const out = [ + intensity * diffuse[0] * this.lightDiffuse[0] + + this.ambientLight[0], + intensity * diffuse[1] * this.lightDiffuse[1] + + this.ambientLight[1], + intensity * diffuse[2] * this.lightDiffuse[2] + + this.ambientLight[2], + diffuse[3], + ]; + + buffer.data[index + 0] = Math.floor(out[0] * 255); + buffer.data[index + 1] = Math.floor(out[1] * 255); + buffer.data[index + 2] = Math.floor(out[2] * 255); + buffer.data[index + 3] = out[3]; + } + } + + context.putImageData(buffer, 0, 0); + return canvas; + }; + + for (let i = 0; i < numDirs; ++i) { + const lightDir = ((Math.PI * 2) / numDirs) * i; + bakedImages.push(bakeDirection(lightDir)); + } + + return bakedImages; + } + + private createCanvas(width: number, height: number): HTMLCanvasElement { + const canvas = document.createElement("canvas"); + canvas.width = width; + canvas.height = height; + return canvas; + } +} diff --git a/src/pbr_preview/src/lib/MaterialBrush.ts b/src/pbr_preview/src/lib/MaterialBrush.ts new file mode 100644 index 00000000..6f2eb2dd --- /dev/null +++ b/src/pbr_preview/src/lib/MaterialBrush.ts @@ -0,0 +1,75 @@ +import type { IChannel } from "../types"; +import { CHANNELS, registry } from "../constants"; +import { three as THREE } from "../deps"; + +/** + * ### Material Brush + * Class for painting across multiple TextureLayers in a Texture + * Used to iterate over PBR channels and apply a brush value to each layer + * at the same UV coordinates + */ +export class MaterialBrush { + private _colors: Record; + + constructor({ colors }: { colors?: Record }) { + this._colors = { + ...Object.fromEntries( + Object.keys(CHANNELS).map((key) => [ + key, + CHANNELS[key].default ?? new THREE.Color(0xffffff00), + ]) + ), + ...colors, + }; + } + + get colors() { + return this._colors; + } + + set colors(colors: Record) { + this._colors = { ...this._colors, ...colors }; + } + + toString() { + const colors = Object.entries(this._colors).map(([key, color]) => [ + key, + color.getHexString(), + ]); + return JSON.stringify(colors); + } + + getChannel(channel: IChannel["id"]) { + return this._colors[channel]; + } + + static makeLinearColor(value: number) { + const clamped = Math.min(1, Math.max(0, value)); + return new THREE.Color(clamped, clamped, clamped).convertSRGBToLinear(); + } + + static fromSettings() { + const defaultEmissive = "#000000"; + const metalnessValue = Number(registry.brushMetalnessSlider?.get()); + const roughnessValue = Number(registry.brushRoughnessSlider?.get() ?? 1); + const emissiveValue = ( + registry.brushEmissiveColor?.get() ?? defaultEmissive + ).toString(); + const heightValue = Number(registry.brushHeightSlider?.get()); + // @ts-expect-error ColorPanel global is not typed + const currentColor = ColorPanel.get(); + + const colors = { + [CHANNELS.albedo.id]: new THREE.Color(currentColor), + [CHANNELS.metalness.id]: MaterialBrush.makeLinearColor(metalnessValue), + [CHANNELS.roughness.id]: MaterialBrush.makeLinearColor(roughnessValue), + [CHANNELS.emissive.id]: new THREE.Color(emissiveValue ?? defaultEmissive), + [CHANNELS.height.id]: MaterialBrush.makeLinearColor(heightValue), + // TODO: Add normal map color input + // [CHANNELS.normal.id]: + // CHANNELS.normal.default ?? new THREE.Color("#8080ff"), + }; + + return new MaterialBrush({ colors }); + } +} diff --git a/src/pbr_preview/src/lib/PbrMaterials.ts b/src/pbr_preview/src/lib/PbrMaterials.ts new file mode 100644 index 00000000..09f3492b --- /dev/null +++ b/src/pbr_preview/src/lib/PbrMaterials.ts @@ -0,0 +1,805 @@ +import type { IChannel } from "../types"; +import { CHANNELS, NA_CHANNEL } from "../constants"; +import { three as THREE } from "../deps"; +import { generatePreviewImage } from "./util"; + +const getProjectTextures = (layers = true) => { + const allTextures = Project ? Project.textures ?? Texture.all : Texture.all; + + if (!layers) { + return allTextures; + } + + return allTextures + .filter((t: Texture) => t.layers_enabled && t.layers.length > 0) + .flatMap((t: Texture) => t.layers); +}; + +/** + * ### PBR Material + * Class for handling PBR materials in Blockbench + * + * Uses a texture's layers to generate a PBR material, + * or a project's textures if no layers are available. + */ +export default class PbrMaterial { + private _scope: Array; + private _materialUuid: string; + + constructor( + scope: Array | null, + materialUuid: string + ) { + this._scope = scope ?? getProjectTextures(); + this._materialUuid = materialUuid; + } + + merToCanvas() { + let emissiveMap = this.getTexture(CHANNELS.emissive); + let roughnessMap = this.getTexture(CHANNELS.roughness); + let metalnessMap = this.getTexture(CHANNELS.metalness); + + if (!emissiveMap && !roughnessMap && !metalnessMap) { + const { metalness, emissive, roughness } = this.decodeMer(); + + if (metalness) { + metalnessMap = PbrMaterial.makePixelatedCanvas(metalness); + } + + if (emissive) { + emissiveMap = PbrMaterial.makePixelatedCanvas(emissive); + } + + if (roughness) { + roughnessMap = PbrMaterial.makePixelatedCanvas(roughness); + } + } + + return { + emissiveMap, + roughnessMap, + metalnessMap, + }; + } + + getMaterial(options: THREE.MeshStandardMaterialParameters = {}) { + const { emissiveMap, roughnessMap, metalnessMap } = Format.id.startsWith( + "bedrock" + ) + ? this.merToCanvas() + : { + emissiveMap: this.getTexture(CHANNELS.emissive), + roughnessMap: this.getTexture(CHANNELS.roughness), + metalnessMap: this.getTexture(CHANNELS.metalness), + }; + + const normalMap = this.getTexture(CHANNELS.normal); + + return new THREE.MeshStandardMaterial({ + map: + this.getTexture(CHANNELS.albedo) ?? + PbrMaterial.makePixelatedCanvas( + TextureLayer.selected?.canvas ?? + Texture.all.find((t) => t.selected)?.canvas ?? + Texture.getDefault().canvas + ), + aoMap: this.getTexture(CHANNELS.ao), + bumpMap: this.getTexture(CHANNELS.height), + normalMap, + // TODO: Use project settings to determine if normal map should be flipped + //normalScale: new THREE.Vector2(-1, 1), + metalnessMap, + metalness: metalnessMap ? 1 : 0, + roughnessMap, + roughness: 1, + emissiveMap, + emissiveIntensity: emissiveMap ? 1 : 0, + emissive: emissiveMap ? 0xffffff : 0, + envMap: PreviewScene.active?.cubemap ?? null, + envMapIntensity: 0.95, + alphaTest: 0.1, + transparent: true, + ...options, + }); + } + + renderMaterialPreview() { + const previewImage = generatePreviewImage(this.getMaterial()); + return previewImage; + } + + saveTexture(channel: IChannel, texture: Texture | TextureLayer) { + if (!Project) { + return; + } + + if (!Project.pbr_materials) { + Project.pbr_materials = {}; + } + + if (!Project.pbr_materials[this._materialUuid]) { + Project.pbr_materials[this._materialUuid] = {}; + } + + Project.pbr_materials[this._materialUuid][channel.id] = texture.uuid; + texture.extend({ channel: channel.id }); + } + + /** + * ### Find channel texture + * @param name Channel to find + * @param inference Whether or not to infer the texture based on the channel name + * @returns The channel if it exists in the project, otherwise `null` + */ + findTexture( + name: string | IChannel, + inference = true + ): Texture | TextureLayer | null { + if (!Project) { + return null; + } + + const materialChannel = this._scope.find( + (t) => t.channel && (t.channel === name || t.channel === name.id) + ); + + if (materialChannel) { + return materialChannel; + } + + const [channel, regex] = + typeof name === "string" + ? [name, new RegExp(`_*${name}(\.[^.]+)?$`, "i")] + : [name.id, name.regex ?? new RegExp(`_*${name.id}(\.[^.]+)?$`, "i")]; + + Project.pbr_materials = Project.pbr_materials ?? {}; + const materialData = Project.pbr_materials[this._materialUuid]; + + // Don't infer the channel if it has already been assigned to NA_CHANNEL + if (inference && !materialData?.length && channel !== NA_CHANNEL) { + return this._scope.find((t) => regex.test(t.name)) ?? null; + } + + const textureUuid = materialData?.[channel]; + + if (!textureUuid) { + return null; + } + + return this._scope.find((t) => t.uuid === textureUuid) ?? null; + } + + /** + * Helper function to create a canvas texture with pixelated filtering + * @param canvas Texture canvas source + * @returns `THREE.CanvasTexture` with pixelated filtering + */ + static makePixelatedCanvas(canvas: HTMLCanvasElement) { + const texture = new THREE.CanvasTexture( + canvas, + undefined, + undefined, + undefined, + THREE.NearestFilter, + THREE.NearestFilter + ); + + texture.needsUpdate = true; + + return texture; + } + + /** + * Searches for a texture and creates a canvas element with the texture data if found + * @param name The name of the texture to search for. Use a channel or a texture name or UUID + * @param scope An array of textures to search in. Defaults to all textures in the project + */ + getTexture(name: string | IChannel) { + const texture = this.findTexture(name); + return texture ? PbrMaterial.makePixelatedCanvas(texture.canvas) : null; + } + + static extractChannel( + texture: Texture | TextureLayer, + channel: "r" | "g" | "b" | "a" + ) { + const canvas = texture.canvas; + const { width, height } = canvas; + + const ctx = canvas.getContext("2d"); + + if (!ctx || !width || !height) { + return null; + } + + const channelCanvas = document.createElement("canvas"); + channelCanvas.width = width; + channelCanvas.height = height; + + const channelCtx = channelCanvas.getContext("2d"); + + if (!channelCtx) { + return null; + } + + const channelIdx = { r: 0, g: 1, b: 2, a: 3 }[channel]; + + const { data } = ctx.getImageData(0, 0, width, height); + + const channelData = new Uint8ClampedArray(width * height * 4); + + for (let idx = 0; idx < data.length; idx += 4) { + const value = data[idx + channelIdx]; + channelData[idx] = value; + channelData[idx + 1] = value; + channelData[idx + 2] = value; + channelData[idx + 3] = 255; + } + + const imageData = new ImageData(channelData, width, height); + + channelCtx.putImageData(imageData, 0, 0); + + return channelCanvas; + } + + decodeMer(emissiveThreshold = 1): { + metalness?: HTMLCanvasElement | null; + emissive?: HTMLCanvasElement | null; + emissiveLevel?: HTMLCanvasElement | null; + roughness?: HTMLCanvasElement | null; + sss?: HTMLCanvasElement | null; + } { + const texture = this.findTexture("mer", true); + + if (!texture) { + return { + metalness: null, + emissive: null, + emissiveLevel: null, + roughness: null, + sss: null, + }; + } + + const metalness = PbrMaterial.extractChannel(texture, "r"); + const emissiveLevel = PbrMaterial.extractChannel(texture, "g"); + const roughness = PbrMaterial.extractChannel(texture, "b"); + const sss = PbrMaterial.extractChannel(texture, "a"); + + const emissive = document.createElement("canvas"); + emissive.width = texture.img.width ?? 16; + emissive.height = texture.img.height ?? 16; + + // Use emissiveLevel as mask for getting emissive color from albedo channel + const albedo = this.findTexture(CHANNELS.albedo); + + if (albedo) { + emissive.width = albedo.img.width ?? 16; + emissive.height = albedo.img.height ?? 16; + } + + const emissiveCtx = emissive.getContext("2d"); + const emissiveLevelCtx = emissiveLevel?.getContext("2d"); + const albedoCtx = albedo?.canvas?.getContext("2d"); + + if (!emissiveCtx || !albedoCtx || !emissiveLevelCtx) { + return { + metalness, + emissive: emissiveLevel, + roughness, + sss, + }; + } + + // Write the albedo color to the emissive canvas where the emissive level is greater than a certain threshold + const albedoData = albedoCtx.getImageData( + 0, + 0, + emissive.width, + emissive.height + ); + const emissiveLevelData = emissiveLevelCtx.getImageData( + 0, + 0, + emissive.width, + emissive.height + ); + + const emissiveData = new Uint8ClampedArray( + emissive.width * emissive.height * 4 + ); + + for (let idx = 0; idx < albedoData.data.length; idx += 4) { + if (emissiveLevelData.data[idx] > emissiveThreshold) { + emissiveData[idx] = albedoData.data[idx]; + emissiveData[idx + 1] = albedoData.data[idx + 1]; + emissiveData[idx + 2] = albedoData.data[idx + 2]; + emissiveData[idx + 3] = 255; + continue; + } + + emissiveData[idx] = 0; + emissiveData[idx + 1] = 0; + emissiveData[idx + 2] = 0; + emissiveData[idx + 3] = 255; + } + + emissiveCtx.putImageData( + new ImageData(emissiveData, emissive.width, emissive.height), + 0, + 0 + ); + + return { + metalness, + emissive, + emissiveLevel, + roughness, + sss, + }; + } + + createMer(inference = false) { + const metalness = this.findTexture(CHANNELS.metalness, inference); + const emissive = this.findTexture(CHANNELS.emissive, inference); + const roughness = this.findTexture(CHANNELS.roughness, inference); + const sss = this.findTexture("sss", false); + + const width = Math.max( + metalness?.img.width ?? 0, + emissive?.img.width ?? 0, + roughness?.img.width ?? 0, + Project ? Project.texture_width : 0, + 16 + ); + + const height = Math.max( + metalness?.img.height ?? 0, + emissive?.img.height ?? 0, + roughness?.img.height ?? 0, + Project ? Project.texture_height : 0, + 16 + ); + + const canvas = document.createElement("canvas"); + canvas.width = width; + canvas.height = height; + + const ctx = canvas.getContext("2d"); + + if (!ctx) { + return null; + } + + const metalnessCanvas = metalness?.img + ? PbrMaterial.extractChannel(metalness, "r") + : null; + const emissiveCanvas = emissive?.img + ? PbrMaterial.extractChannel(emissive, "g") + : null; + const roughnessCanvas = roughness?.img + ? PbrMaterial.extractChannel(roughness, "b") + : null; + const sssCanvas = + sss && sss?.img ? PbrMaterial.extractChannel(sss, "a") : null; + + const metalnessData = + metalnessCanvas?.getContext("2d")?.getImageData(0, 0, width, height) ?? + new ImageData(width, height); + const emissiveData = + emissiveCanvas?.getContext("2d")?.getImageData(0, 0, width, height) ?? + new ImageData(width, height); + const roughnessData = + roughnessCanvas?.getContext("2d")?.getImageData(0, 0, width, height) ?? + new ImageData(width, height); + const sssData = + sssCanvas?.getContext("2d")?.getImageData(0, 0, width, height) ?? + new ImageData( + new Uint8ClampedArray(width * height * 4).fill(255), + width, + height + ); + + const data = new Uint8ClampedArray(width * height * 4); + + for (let idx = 0; idx < data.length; idx += 4) { + data[idx] = metalnessData.data[idx]; + data[idx + 1] = emissiveData.data[idx]; + data[idx + 2] = roughnessData.data[idx]; + data[idx + 3] = sssData.data[idx]; + } + + ctx.putImageData(new ImageData(data, width, height), 0, 0); + + return canvas; + } + + createLabPbrOutput(inference = true) { + const metalness = this.findTexture(CHANNELS.metalness, inference); + const emissive = this.findTexture(CHANNELS.emissive, inference); + const roughness = this.findTexture(CHANNELS.roughness, inference); + const normal = this.findTexture(CHANNELS.normal, inference); + const heightmap = this.findTexture(CHANNELS.height, inference); + const ao = this.findTexture(CHANNELS.ao, false); + const sss = this.findTexture("sss", true); + const porosity = this.findTexture("porosity", true); + + const width = Math.max( + metalness?.img.width ?? 0, + emissive?.img.width ?? 0, + roughness?.img.width ?? 0, + Project ? Project.texture_width : 0, + 16 + ); + + const height = Math.max( + metalness?.img.height ?? 0, + emissive?.img.height ?? 0, + roughness?.img.height ?? 0, + Project ? Project.texture_height : 0, + 16 + ); + + const specularCanvas = document.createElement("canvas"); + specularCanvas.width = width; + specularCanvas.height = height; + + const specularCtx = specularCanvas.getContext("2d"); + + const normalMapCanvas = document.createElement("canvas"); + normalMapCanvas.width = width; + normalMapCanvas.height = height; + + const normalMapCtx = normalMapCanvas.getContext("2d"); + + if (!specularCtx || !normalMapCtx) { + return null; + } + + const specularData = new Uint8ClampedArray(width * height * 4); + const normalData = new Uint8ClampedArray(width * height * 4); + + // Specular texture output "_s" + // Red channel: Convert linear roughness to perceptual smoothness with: perceptualSmoothness = 1.0 - sqrt(roughness). + // Green channel: Values from 0 to 229 represent F0. Stored linearly. Values from 230 to 255 represent various different metals. + // Blue channel: Values from 0 to 64 represent porosity. Values from 65 to 255 represent subsurface scattering. Both porosity and subsurface scattering are stored linearly. + // Alpha channel: It can have values ranging from 0 to 254; 0 being 0% emissiveness and 254 being 100%. Stored linearly. + const metalnessCanvas = metalness?.canvas; + const emissiveCanvas = emissive?.canvas; + const roughnessCanvas = roughness?.canvas; + const sssCanvas = sss?.canvas; + const porosityCanvas = porosity?.canvas; + + const metalnessCtx = metalnessCanvas?.getContext("2d"); + const emissiveCtx = emissiveCanvas?.getContext("2d"); + const roughnessCtx = roughnessCanvas?.getContext("2d"); + const sssCtx = sssCanvas?.getContext("2d"); + const porosityCtx = porosityCanvas?.getContext("2d"); + + const metalnessData = metalnessCtx?.getImageData(0, 0, width, height); + const emissiveData = emissiveCtx?.getImageData(0, 0, width, height); + const roughnessData = roughnessCtx?.getImageData(0, 0, width, height); + const sssData = sssCtx?.getImageData(0, 0, width, height); + const porosityData = porosityCtx?.getImageData(0, 0, width, height); + + for (let idx = 0; idx < specularData.length; idx += 4) { + const smoothness = roughnessData + ? 1.0 - Math.sqrt(roughnessData.data[idx] / 255) + : 0; + // const f0 = Math.min(229, Math.max(0, Math.round(smoothness * 229))); + + // Convert metalness to F0 + const f0 = Math.min( + 229, + Math.max(0, Math.round((metalnessData?.data[idx] ?? smoothness) * 229)) + ); + + const porosity = porosityData?.data[idx]; + const sss = sssData?.data[idx]; + + specularData[idx] = smoothness * 255; + specularData[idx + 1] = f0; + + // Merge porosity and sss in blue channel because they are mutually exclusive + specularData[idx + 2] = sss ?? porosity ?? 0; + + // Add emissive to alpha + // But first convert emissive channel from color to grayscale + + if (!emissiveData) { + specularData[idx + 3] = 255; + continue; + } + + const emissiveLevel = Math.round( + (emissiveData?.data[idx] + + emissiveData?.data[idx + 1] + + emissiveData?.data[idx + 2]) / + 3 + ); + + specularData[idx + 3] = emissiveLevel || 255; + } + + specularCtx.putImageData(new ImageData(specularData, width, height), 0, 0); + + // Normal map output "_n" + // AO is stored in blue channel + // Height map is stored in alpha channel + const normalCanvas = normal?.canvas; + const aoCanvas = ao?.canvas; + const heightmapCanvas = heightmap?.canvas; + + const normalCtx = normalCanvas?.getContext("2d"); + const aoCtx = aoCanvas?.getContext("2d"); + const heightmapCtx = heightmapCanvas?.getContext("2d"); + + const normalMapData = normalCtx?.getImageData(0, 0, width, height); + const aoData = aoCtx?.getImageData(0, 0, width, height); + const heightmapData = heightmapCtx?.getImageData(0, 0, width, height); + + for (let idx = 0; idx < normalData.length; idx += 4) { + normalData[idx] = normalMapData?.data[idx] ?? 0; + normalData[idx + 1] = normalMapData?.data[idx + 1] ?? 0; + normalData[idx + 2] = aoData?.data[idx + 2] ?? 255; + normalData[idx + 3] = heightmapData?.data[idx + 3] || 255; + } + + normalMapCtx.putImageData(new ImageData(normalData, width, height), 0, 0); + + return { + specular: specularCanvas, + normalMap: normalMapCanvas, + }; + } + + decodeLabPbrNormal(texture: Texture | TextureLayer): { + ao?: HTMLCanvasElement | null; + normal?: HTMLCanvasElement | null; + heightmap?: HTMLCanvasElement | null; + } { + const width = texture.img.width ?? 16; + const height = texture.img.height ?? 16; + + const ctx = texture.canvas.getContext("2d"); + + if (!ctx) { + return {}; + } + + const aoCanvas = document.createElement("canvas"); + aoCanvas.width = width; + aoCanvas.height = height; + + const normalCanvas = document.createElement("canvas"); + normalCanvas.width = width; + normalCanvas.height = height; + + const heightmapCanvas = document.createElement("canvas"); + heightmapCanvas.width = width; + heightmapCanvas.height = height; + + const aoCtx = aoCanvas.getContext("2d"); + const normalCtx = normalCanvas.getContext("2d"); + const heightmapCtx = heightmapCanvas.getContext("2d"); + + const { data } = ctx.getImageData(0, 0, width, height); + + if (!data || !aoCtx || !normalCtx || !heightmapCtx) { + return {}; + } + + const aoData = new Uint8ClampedArray(width * height * 4); + const normalData = new Uint8ClampedArray(width * height * 4); + const heightmapData = new Uint8ClampedArray(width * height * 4); + + for (let r = 0; r < data.length; r += 4) { + const g = r + 1; + const b = r + 2; + const a = r + 3; + + aoData[r] = data[b]; + aoData[g] = data[b]; + aoData[b] = data[b]; + aoData[a] = 255; + + normalData[r] = data[r]; + normalData[g] = data[g]; + normalData[b] = 255; + normalData[a] = 255; + + heightmapData[r] = data[a]; + heightmapData[g] = data[a]; + heightmapData[b] = data[a]; + heightmapData[a] = 255; + } + + aoCtx.putImageData(new ImageData(aoData, width, height), 0, 0); + normalCtx.putImageData(new ImageData(normalData, width, height), 0, 0); + heightmapCtx.putImageData( + new ImageData(heightmapData, width, height), + 0, + 0 + ); + + return { + ao: aoCanvas, + normal: normalCanvas, + heightmap: heightmapCanvas, + }; + } + + decodeLabPbrSpecular(texture: Texture | TextureLayer): { + metalness?: HTMLCanvasElement | null; + emissive?: HTMLCanvasElement | null; + roughness?: HTMLCanvasElement | null; + sss?: HTMLCanvasElement | null; + porosity?: HTMLCanvasElement | null; + } { + const width = texture.img.width ?? 16; + const height = texture.img.height ?? 16; + + const ctx = texture.canvas.getContext("2d"); + + if (!ctx) { + return {}; + } + const metalnessCanvas = document.createElement("canvas"); + metalnessCanvas.width = width; + metalnessCanvas.height = height; + + const emissiveCanvas = document.createElement("canvas"); + emissiveCanvas.width = width; + emissiveCanvas.height = height; + + const roughnessCanvas = document.createElement("canvas"); + roughnessCanvas.width = width; + roughnessCanvas.height = height; + + const sssCanvas = document.createElement("canvas"); + sssCanvas.width = width; + sssCanvas.height = height; + + const porosityCanvas = document.createElement("canvas"); + porosityCanvas.width = width; + porosityCanvas.height = height; + + const metalnessCtx = metalnessCanvas.getContext("2d"); + const emissiveCtx = emissiveCanvas.getContext("2d"); + const roughnessCtx = roughnessCanvas.getContext("2d"); + const sssCtx = sssCanvas.getContext("2d"); + const porosityCtx = porosityCanvas.getContext("2d"); + + const { data } = ctx.getImageData(0, 0, width, height); + + if ( + !data || + !metalnessCtx || + !emissiveCtx || + !roughnessCtx || + !sssCtx || + !porosityCtx + ) { + return {}; + } + + const metalnessData = new Uint8ClampedArray(width * height * 4); + const emissiveData = new Uint8ClampedArray(width * height * 4); + const roughnessData = new Uint8ClampedArray(width * height * 4); + const sssData = new Uint8ClampedArray(width * height * 4); + const porosityData = new Uint8ClampedArray(width * height * 4); + + for (let r = 0; r < data.length; r += 4) { + // Roughness is inverted smoothness in red channel + // Metalness is F0 in green channel + // SSS and porosity are stored in blue channel linearly + // Emissive is stored in alpha channel linearly + + const g = r + 1; + const b = r + 2; + const a = r + 3; + + roughnessData[r] = 255 - data[r]; + roughnessData[g] = 255 - data[r]; + roughnessData[b] = 255 - data[r]; + roughnessData[a] = 255; + + metalnessData[r] = data[g]; + metalnessData[g] = data[g]; + metalnessData[b] = data[g]; + metalnessData[a] = 255; + + emissiveData[r] = data[a]; + emissiveData[g] = data[a]; + emissiveData[b] = data[a]; + emissiveData[a] = 255; + + sssData[r] = 0; + sssData[g] = 0; + sssData[b] = 0; + sssData[a] = 255; + + porosityData[r] = data[b]; + porosityData[g] = data[b]; + porosityData[b] = data[b]; + porosityData[a] = 255; + + if (data[b] < 65) { + sssData[r] = data[b]; + sssData[g] = data[b]; + sssData[b] = data[b]; + sssData[a] = 255; + + porosityData[r] = 0; + porosityData[g] = 0; + porosityData[b] = 0; + porosityData[a] = 255; + } + } + + metalnessCtx.putImageData( + new ImageData(metalnessData, width, height), + 0, + 0 + ); + + emissiveCtx.putImageData(new ImageData(emissiveData, width, height), 0, 0); + + roughnessCtx.putImageData( + new ImageData(roughnessData, width, height), + 0, + 0 + ); + + sssCtx.putImageData(new ImageData(sssData, width, height), 0, 0); + + porosityCtx.putImageData(new ImageData(porosityData, width, height), 0, 0); + + return { + metalness: metalnessCanvas, + emissive: emissiveCanvas, + roughness: roughnessCanvas, + sss: sssCanvas, + porosity: porosityCanvas, + }; + } + + createTexturesFromSpecular(texture: Texture | TextureLayer) { + const maps = this.decodeLabPbrSpecular(texture); + + Object.entries(maps).forEach(([name, map]) => { + if (map) { + const textureMap = new Texture({ + name: `${texture.name}_${name}`, + saved: false, + particle: false, + keep_size: false, + }).fromDataURL(map.toDataURL()); + + textureMap.add(); + } + }); + + return maps; + } + + createTexturesFromNormal(texture: Texture | TextureLayer) { + const maps = this.decodeLabPbrNormal(texture); + + Object.entries(maps).forEach(([name, map]) => { + if (map) { + const textureMap = new Texture({ + name: `${texture.name}_${name}`, + saved: false, + particle: false, + keep_size: false, + }).fromDataURL(map.toDataURL()); + + textureMap.add(); + } + }); + + return maps; + } +} diff --git a/src/pbr_preview/src/lib/actions/bakeTextures.ts b/src/pbr_preview/src/lib/actions/bakeTextures.ts new file mode 100644 index 00000000..5af7cae1 --- /dev/null +++ b/src/pbr_preview/src/lib/actions/bakeTextures.ts @@ -0,0 +1,81 @@ +import { three as THREE } from "../../deps"; +import { registry, setups, teardowns } from "../../constants"; +import { bakeTextures } from "../bakery"; + +setups.push(() => { + registry.bakeTexturesDialog = new Dialog("bake_textures", { + id: "bake_textures", + title: "Bake Textures", + buttons: ["Bake", "Cancel"], + form: { + ambientLight: { + type: "color", + label: "Ambient Light", + value: "#1f1f1f", + }, + lightDiffuse: { + type: "color", + label: "Light Diffuse", + value: "#ffffff", + }, + lightHeight: { + type: "range", + label: "Light Height", + min: 0, + max: 1, + step: 0.01, + value: 0.66, + }, + minLightIntensity: { + type: "range", + label: "Minimum Light Intensity", + min: 0, + max: 1, + step: 0.01, + value: 0, + }, + directions: { + type: "number", + label: "Directions", + value: 8, + min: 1, + max: 360, + step: 1, + }, + blendEmissive: { + type: "checkbox", + label: "Blend Emissive", + value: false, + }, + }, + onConfirm(formResult: Record) { + const ambientLight = new THREE.Color(formResult.ambientLight.toString()); + const lightDiffuse = new THREE.Color(formResult.lightDiffuse.toString()); + bakeTextures( + { + ambientLight: [ambientLight.r, ambientLight.g, ambientLight.b], + lightDiffuse: [lightDiffuse.r, lightDiffuse.g, lightDiffuse.b], + lightHeight: Number(formResult.lightHeight), + minLightIntensity: Number(formResult.minLightIntensity), + }, + formResult.directions ?? 8, + formResult.blendEmissive ?? false, + ); + }, + }); + + registry.bakeTexturesAction = new Action("bake_textures", { + icon: "cake", + name: "Bake Textures", + description: "Bakes textures for the selected PBR material", + click() { + registry.bakeTexturesDialog?.show(); + }, + }); + + MenuBar.addAction(registry.bakeTexturesAction, "tools"); +}); + +teardowns.push(() => { + MenuBar.removeAction("tools.bake_textures"); +}); diff --git a/src/pbr_preview/src/lib/actions/channelAssignment.ts b/src/pbr_preview/src/lib/actions/channelAssignment.ts new file mode 100644 index 00000000..72b4cb73 --- /dev/null +++ b/src/pbr_preview/src/lib/actions/channelAssignment.ts @@ -0,0 +1,214 @@ +import type { IChannel } from "../../types"; +import { + CHANNELS, + NA_CHANNEL, + registry, + setups, + teardowns, +} from "../../constants"; +import { + applyPbrMaterial, + debounceApplyPbrMaterial, +} from "../applyPbrMaterial"; +import { getSelectedLayer, getSelectedTexture } from "../util"; + +/** + * Registry of channel actions\ + * (Not in the same registry as the other actions. Needs its own teardown.) + */ +const channelAssignmentActions: Record = {}; + +const canShowChannelAssignment = () => + Condition({ + modes: ["edit", "paint"], + selected: { + texture: true, + }, + project: true, + method() { + const selected = getSelectedTexture(); + + if (selected && !selected.material) { + return true; + } + + return ( + selected?.material === true && + getSelectedLayer() !== null && + Modes.paint + ); + }, + }); + +const canUnassignChannel = () => + Condition({ + modes: ["paint", "edit"], + selected: { + texture: true, + }, + method() { + const texture = getSelectedTexture(); + + if (texture?.material && Modes.edit) { + // Don't show Action on material textures in edit mode + return false; + } + + const layer = getSelectedLayer() ?? texture; + + return layer?.channel && layer.channel !== NA_CHANNEL; + }, + }); + +setups.push(() => { + Object.entries(CHANNELS).forEach(([key, channel]) => { + channelAssignmentActions[key] = new Action(`assign_channel_${key}`, { + icon: channel.icon ?? "tv_options_edit_channels", + name: `Assign to ${channel.label.toLocaleLowerCase()} channel`, + description: `Assign the selected layer to the ${channel.label} channel`, + category: "textures", + condition: canShowChannelAssignment, + click() { + const layer = + TextureLayer.selected ?? (Project ? Project.selected_texture : null); + + if (!layer) { + return; + } + + Undo.initEdit({ layers: [layer] }); + + layer.extend({ channel: channel.id }); + + const texture = layer instanceof TextureLayer ? layer.texture : layer; + + texture.updateChangesAfterEdit(); + + if (!Project.pbr_materials[texture.uuid]) { + Project.pbr_materials[texture.uuid] = {}; + } + + // If the layer uuid is already assigned to another channel, unassign it first + Object.entries(Project.pbr_materials[texture.uuid]).forEach( + ([assignedChannel, assignedLayerUuid]) => { + if (assignedLayerUuid === layer.uuid) { + delete Project.pbr_materials[texture.uuid][assignedChannel]; + layer.channel = NA_CHANNEL; + } + } + ); + + // If the layer uuid is equal to the texture uuid, the texture can not be assigned to any other channels + if (texture.uuid === layer.uuid) { + Project.pbr_materials[texture.uuid] = {}; + } + + Project.pbr_materials[texture.uuid][key] = layer.uuid; + + Undo.finishEdit("Change channel assignment"); + + Blockbench.showQuickMessage( + `Assigned "${layer.name}" to ${channel.label} channel`, + 2000 + ); + + applyPbrMaterial(); + }, + }); + }); +}); + +teardowns.push(() => { + Object.values(channelAssignmentActions).forEach((action) => { + action.delete(); + }); +}); + +setups.push(() => { + registry.unassignChannel = new Action("unassign_channel", { + icon: "cancel", + name: "Unassign Channel", + description: "Unassign the selected layer from the channel", + category: "textures", + condition: canUnassignChannel, + click() { + const layer = + TextureLayer.selected ?? (Project ? Project.selected_texture : null); + + if (!layer) { + return; + } + + Undo.initEdit({ layers: [layer] }); + + const texture = layer instanceof TextureLayer ? layer.texture : layer; + const prevChannel = layer.channel; + + Project.pbr_materials[texture.uuid] = {}; + + layer.channel = NA_CHANNEL; + + texture.updateChangesAfterEdit(); + Undo.finishEdit("Unassign channel"); + + Blockbench.showQuickMessage( + `Unassigned "${layer.name}" from ${prevChannel} channel`, + 2000 + ); + + debounceApplyPbrMaterial(); + }, + }); + + registry.channelMenu = new Menu( + "channel_menu", + [ + ...Object.keys(CHANNELS).map((key) => `assign_channel_${key}`), + ...["unassign_channel"], + ], + { + onOpen() { + debounceApplyPbrMaterial(); + }, + } + ); + + registry.openChannelMenu = new Action("pbr_channel_menu", { + name: "Assign to PBR Channel", + icon: "texture", + condition: () => canShowChannelAssignment() || canUnassignChannel(), + click(event) { + registry.channelMenu?.open(event as MouseEvent); + }, + children: [ + ...Object.values(channelAssignmentActions), + registry.unassignChannel, + ], + }); + + registry.showChannelMenu = new Action("show_channel_menu", { + icon: "texture", + name: "Assign to PBR Channel", + description: "Assign the selected layer to a channel", + category: "textures", + condition: canShowChannelAssignment, + click(event) { + registry.channelMenu?.open(event as MouseEvent); + }, + }); + + if (registry.openChannelMenu) { + MenuBar.addAction(registry.openChannelMenu, "image.0"); + Texture.prototype.menu.addAction(registry.openChannelMenu, "0"); + TextureLayer.prototype.menu.addAction(registry.openChannelMenu, "0"); + } + + Toolbars.layers.add(registry.showChannelMenu, 1); +}); + +teardowns.push(() => { + MenuBar.removeAction("image.pbr_channel_menu"); + Texture.prototype.menu.removeAction("pbr_channel_menu"); + TextureLayer.prototype.menu.removeAction("pbr_channel_menu"); + Toolbars.layers.remove(registry.showChannelMenu); +}); diff --git a/src/pbr_preview/src/lib/actions/generateNormal.ts b/src/pbr_preview/src/lib/actions/generateNormal.ts new file mode 100644 index 00000000..dcc0d36e --- /dev/null +++ b/src/pbr_preview/src/lib/actions/generateNormal.ts @@ -0,0 +1,123 @@ +import { registry, setups, teardowns } from "../../constants"; +import { CHANNELS } from "../../constants"; +import PbrMaterial from "../PbrMaterials"; +import { getSelectedLayer, getSelectedTexture } from "../util"; +import { createNormalMap, createAoMap } from "../normalMap"; + +const generateNormal = ( + e: Event, + orientation: "OpenGL" | "DirectX" = "DirectX" +) => { + const texture: Texture | TextureLayer = + getSelectedLayer() ?? getSelectedTexture() ?? Texture.getDefault(); + + if (!texture) { + return; + } + + const normalMap = createNormalMap(texture, orientation, false); + + if (!normalMap) { + Blockbench.showQuickMessage("Failed to generate normal map", 2000); + return; + } + + normalMap.select(e); + + new PbrMaterial( + texture instanceof Texture && texture.layers_enabled + ? texture.layers + : null, + texture.uuid + ).saveTexture(CHANNELS.normal, normalMap); + + Blockbench.showQuickMessage("Normal map generated", 2000); +}; + +setups.push(() => { + registry.generateDirectXNormal = new Action("generate_dx_normal", { + icon: CHANNELS.normal.icon ?? "altitude", + name: "Generate DirectX Normal Map", + description: "Generates a DirectX normal map from the height map", + condition: () => (getSelectedLayer() ?? getSelectedTexture()) !== null, + click: (e) => generateNormal(e), + }); + + registry.generateOpenGlNormal = new Action("generate_opengl_normal", { + icon: CHANNELS.normal.icon ?? "altitude", + name: "Generate OpenGL Normal Map", + description: "Generates an OpenGL normal map from the height map", + condition: () => (getSelectedLayer() ?? getSelectedTexture()) !== null, + click: (e) => generateNormal(e, "OpenGL"), + }); + + registry.generateAo = new Action("generate_ao", { + icon: CHANNELS.ao.icon ?? "motion_mode", + name: "Generate Ambient Occlusion Map", + description: "Generates an ambient occlusion map from the height map", + condition: { + selected: { + texture: true, + }, + project: true, + }, + click() { + const texture: Texture | TextureLayer = + getSelectedLayer() ?? getSelectedTexture() ?? Texture.getDefault(); + + if (!texture) { + return; + } + + const mat = new PbrMaterial( + texture instanceof Texture && texture.layers_enabled + ? texture.layers + : null, + texture.uuid + ); + + const normalMap = + mat.findTexture(CHANNELS.normal) ?? createNormalMap(texture); + + if (!normalMap) { + // TODO: Use Validator + Blockbench.showQuickMessage( + "Unable to generate ambient occlusion map without a normal map", + 2000 + ); + return; + } + + const aoMap = createAoMap(normalMap); + + if (aoMap) { + mat.saveTexture(CHANNELS.ao, aoMap); + aoMap.select(); + Blockbench.showQuickMessage("Ambient occlusion map generated", 2000); + return; + } + + Blockbench.showQuickMessage( + "Failed to generate ambient occlusion map", + 2000 + ); + }, + }); + + registry.generateNormal = new Action("generate_normal", { + children: [registry.generateDirectXNormal, registry.generateOpenGlNormal], + name: "Generate Normal Map", + description: "Generates a normal map from the height map", + condition: () => (getSelectedLayer() ?? getSelectedTexture()) !== null, + click() {}, + icon: CHANNELS.normal.icon ?? "altitude", + }); + + MenuBar.addAction(registry.generateNormal, "tools"); + MenuBar.addAction(registry.generateAo, "tools"); +}); + +teardowns.push(() => { + MenuBar.removeAction(`tools.generate_normal`); + MenuBar.removeAction(`tools.generate_ao`); +}); diff --git a/src/pbr_preview/src/lib/actions/index.ts b/src/pbr_preview/src/lib/actions/index.ts new file mode 100644 index 00000000..61a720a4 --- /dev/null +++ b/src/pbr_preview/src/lib/actions/index.ts @@ -0,0 +1,12 @@ +import "./bakeTextures"; +import "./channelAssignment"; +import "./generateNormal"; +import "./labPbr"; +import "./materialTexture"; +import "./mer"; +import "./textureSet"; +import "./toggleLights"; +import "./togglePbr"; +import "./tonemapping"; +import "./usdz"; +import "../io/bbmat"; diff --git a/src/pbr_preview/src/lib/actions/labPbr.ts b/src/pbr_preview/src/lib/actions/labPbr.ts new file mode 100644 index 00000000..2b4ea9c8 --- /dev/null +++ b/src/pbr_preview/src/lib/actions/labPbr.ts @@ -0,0 +1,128 @@ +import { registry, setups, teardowns } from "../../constants"; +import PbrMaterial from "../PbrMaterials"; +import { getSelectedTexture } from "../util"; + +const exportNormalMap = ( + normalMap: HTMLCanvasElement, + baseName = "texture", +) => { + normalMap.toBlob(async (blob) => { + if (!blob) { + return; + } + + Blockbench.export({ + content: await blob.arrayBuffer(), + type: "PNG", + name: `${baseName}_n`, + extensions: ["png"], + resource_id: "normal_map", + savetype: "image", + }); + }); +}; + +const exportSpecularMap = ( + specularMap: HTMLCanvasElement, + baseName = "texture", +) => { + specularMap.toBlob(async (blob) => { + if (!blob) { + return; + } + + Blockbench.export({ + content: await blob.arrayBuffer(), + type: "PNG", + name: `${baseName}_s`, + extensions: ["png"], + resource_id: "specular_map", + savetype: "image", + }); + }); +}; + +setups.push(() => { + registry.generateLabPbr = new Action("generate_lab_pbr", { + icon: "experiment", + name: "Generate labPBR textures", + description: + "Generate a specular and normal map in labPBR format for Java shaders", + condition: { + formats: ["java_block"], + project: true, + }, + async click() { + const selected = getSelectedTexture(); + + if (!selected) { + return; + } + + const mat = new PbrMaterial( + selected.layers_enabled ? selected.layers : [selected], + selected.uuid + ); + + const outputs = mat.createLabPbrOutput(); + + if (outputs === null) { + return; + } + + const baseName = + selected.name ?? (!!Project ? Project.getDisplayName() : "texture"); + + await Promise.all([ + exportNormalMap(outputs.normalMap, pathToName(baseName)), + exportSpecularMap(outputs.specular, pathToName(baseName)), + ]); + + Blockbench.showQuickMessage("Exported labPBR textures"); + }, + }); + + registry.decodeLabPbr = new Action("decode_lab_pbr", { + icon: "frame_source", + name: "Decode labPBR textures", + description: + "Decodes the selected texture into a specular or normal map in labPBR format", + condition: { + formats: ["java"], + project: true, + selected: { + texture: true, + }, + }, + click() { + const selected = + TextureLayer.selected?.texture ?? + Texture.all.find((t) => t.selected) ?? + Texture.getDefault(); + + const mat = new PbrMaterial( + selected.layers_enabled ? selected.layers : [selected], + selected.uuid, + ); + + if (pathToName(selected.name).endsWith("_n")) { + mat.createTexturesFromNormal(selected); + return; + } + + if (pathToName(selected.name).endsWith("_s")) { + mat.createTexturesFromSpecular(selected); + return; + } + + Blockbench.showQuickMessage("Failed to decode labPBR texture"); + }, + }); + + MenuBar.addAction(registry.generateLabPbr, "file.export"); + MenuBar.addAction(registry.decodeLabPbr, "tools"); +}); + +teardowns.push(() => { + MenuBar.removeAction("file.export.generate_lab_pbr"); +}); diff --git a/src/pbr_preview/src/lib/actions/materialTexture.ts b/src/pbr_preview/src/lib/actions/materialTexture.ts new file mode 100644 index 00000000..792ce31a --- /dev/null +++ b/src/pbr_preview/src/lib/actions/materialTexture.ts @@ -0,0 +1,142 @@ +import { + registry, + CHANNELS, + setups, + teardowns, + NA_CHANNEL, +} from "../../constants"; +import { three as THREE } from "../../deps"; +import PbrMaterial from "../PbrMaterials"; +import { + colorDataUrl, + generatePreviewImage, + getSelectedTexture, +} from "../util"; + +setups.push(() => { + registry.createMaterialTexture = new Action("create_material_texture", { + icon: "deployed_code", + name: "Create Material Texture", + description: "Creates a new texture for a PBR material", + condition: { + modes: ["edit", "paint"], + project: true, + }, + click() { + if (!Project) { + return; + } + + const channels = { + ...CHANNELS, + }; + + const texture = new Texture({ + name: "New Material", + saved: false, + particle: false, + }); + + texture.extend({ material: true }); + + const scope = + Texture.all.filter( + (t) => (t.selected || t.multi_selected) && !t.material + ) ?? Texture.all; + + const selected = getSelectedTexture(); + + const mat = selected ? new PbrMaterial(scope, selected.uuid) : null; + + try { + const baseColor = + mat?.findTexture(CHANNELS.albedo, true)?.canvas.toDataURL() ?? + selected?.canvas.toDataURL() ?? + colorDataUrl(new THREE.Color(0x808080), texture.canvas); + + if (!baseColor) { + return; + } + + texture.fromDataURL(baseColor); + + const layer = new TextureLayer( + { + name: channels.albedo.label, + visible: true, + data_url: baseColor, + keep_size: true, + }, + texture + ); + + layer.extend({ channel: channels.albedo.id }); + layer.addForEditing(); + layer.texture.updateChangesAfterEdit(); + mat?.saveTexture(channels.albedo, layer); + delete channels.albedo; + } catch (e) { + console.warn("Failed to create base color texture", e); + Blockbench.showStatusMessage( + "Failed to create base color texture in new material", + 3000 + ); + } + + // Create PBR channels as texture layers for the new texture + const layers = Object.keys(channels) + .reverse() + .map((key) => { + const channel = CHANNELS[key]; + const channelTexture = mat?.findTexture(channel, true); + + const data = channelTexture + ? channelTexture.canvas.toDataURL() + : colorDataUrl(channel.default ?? new THREE.Color(0)); + + if (!data) { + return; + } + + const layer = new TextureLayer( + { + name: channel.label, + visible: true, + data_url: data, + keep_size: true, + }, + texture + ); + + layer.extend({ channel: channel.id }); + + mat?.saveTexture(channel, layer); + + return layer; + }) + .filter(Boolean) as TextureLayer[]; + + Undo.initEdit({ textures: Texture.all, layers }); + + texture.add().select(); + texture.activateLayers(); + layers.map((layer) => { + layer.addForEditing(); + + texture.width = Math.max(texture.width, layer.img.width); + texture.height = Math.max(texture.height, layer.img.height); + }); + texture.updateChangesAfterEdit(); + + Undo.finishEdit("Create Material Texture"); + }, + }); + + MenuBar.addAction(registry.createMaterialTexture, "tools"); + Toolbars.texturelist.add(registry.createMaterialTexture, 3); +}); + +teardowns.push(() => { + MenuBar.removeAction("tools.create_material_texture"); + Toolbars.texturelist.remove("create_material_texture"); +}); diff --git a/src/pbr_preview/src/lib/actions/mer.ts b/src/pbr_preview/src/lib/actions/mer.ts new file mode 100644 index 00000000..af1984af --- /dev/null +++ b/src/pbr_preview/src/lib/actions/mer.ts @@ -0,0 +1,143 @@ +import { CHANNELS, registry, setups, teardowns } from "../../constants"; +import PbrMaterial from "../PbrMaterials"; +import { exportMer } from "../mer"; +import { getSelectedTexture } from "../util"; + +setups.push(() => { + registry.generateMer = new Action("create_mer", { + icon: "lightbulb_circle", + name: "Export MER", + description: + "Exports a texture map from the metalness, emissive, and roughness channels. (For use in Bedrock resource packs.)", + condition: { + formats: ["bedrock", "bedrock_block"], + project: true, + }, + click() { + try { + exportMer(); + } catch (err) { + console.error("Failed to export MER map:", err); + Blockbench.showStatusMessage("Failed to export MER map", 3000); + } + }, + }); + + registry.decodeMer = new Action("decode_mer", { + name: "Decode MER", + icon: "arrow_split", + condition: { + formats: ["bedrock", "bedrock_block"], + project: true, + selected: { + texture: true, + }, + }, + children: [ + { + icon: "move_item", + name: "Decode MER to Textures", + description: + "Decodes a MER texture map into metalness, emissive, and roughness channels into separate textures", + click() { + const selected = getSelectedTexture() ?? Texture.getDefault(); + + const mat = new PbrMaterial([selected], selected.uuid); + + const mer = mat.decodeMer(); + const merChannels = [ + CHANNELS.metalness, + CHANNELS.emissive, + CHANNELS.roughness, + ]; + + Undo.initEdit({ textures: [selected] }); + + merChannels.forEach((channel) => { + const key = channel.id as keyof typeof mer; + const canvas = mer[key]; + + if (!canvas) { + Blockbench.showStatusMessage( + `Failed to decode ${channel.label} channel`, + 3000 + ); + return; + } + + const texture = new Texture({ + name: `${selected?.name}_${key}`, + keep_size: false, + }).fromDataURL(canvas.toDataURL()); + + texture.add(true); + + mat.saveTexture(channel, texture); + }); + + Undo.finishEdit("Decode MER to textures"); + }, + }, + { + icon: "move_group", + name: "Decode MER to Layers", + description: + "Decodes a MER texture map into metalness, emissive, and roughness channels into material layers", + condition: () => getSelectedTexture()?.layers_enabled === true, + click() { + const selected = getSelectedTexture() ?? Texture.getDefault(); + + const mat = new PbrMaterial( + selected.layers_enabled ? selected.layers : [selected], + selected.uuid + ); + + const mer = mat.decodeMer(); + const merChannels = [ + CHANNELS.metalness, + CHANNELS.emissive, + CHANNELS.roughness, + ]; + + Undo.initEdit({ textures: [selected] }); + + merChannels.forEach((channel) => { + const key = channel.id as keyof typeof mer; + const canvas = mer[key]; + + if (!canvas) { + Blockbench.showStatusMessage( + `Failed to decode ${channel.label} channel`, + 3000 + ); + return; + } + + const layer = new TextureLayer( + { + name: `${selected?.name}_${key}`, + data_url: canvas.toDataURL(), + }, + selected + ); + + mat.saveTexture(channel, layer); + + layer.addForEditing(); + }); + + Undo.finishEdit("Decode MER to layers"); + }, + }, + ], + click() {}, + }); + + MenuBar.addAction(registry.decodeMer, "tools"); + MenuBar.addAction(registry.generateMer, "file.export"); +}); + +teardowns.push(() => { + MenuBar.removeAction(`file.export.create_mer`); + MenuBar.removeAction(`tools.decode_mer`); +}); diff --git a/src/pbr_preview/src/lib/actions/textureSet.ts b/src/pbr_preview/src/lib/actions/textureSet.ts new file mode 100644 index 00000000..af3fd2bf --- /dev/null +++ b/src/pbr_preview/src/lib/actions/textureSet.ts @@ -0,0 +1,262 @@ +import { CHANNELS, registry, setups, teardowns } from "../../constants"; +import { exportMer } from "../mer"; +import PbrMaterial from "../PbrMaterials"; +import { getOutputBaseName } from "../util"; + +const createTextureSetDialog = () => { + if (!Project) { + return; + } + Project.textures.forEach((t) => { + const mat = new PbrMaterial(null, t.uuid); + + const projectNormalMap = mat.findTexture(CHANNELS.normal, false); + const projectHeightMap = mat.findTexture(CHANNELS.height, false); + const projectColorMap = mat.findTexture(CHANNELS.albedo, false); + const projectMetalnessMap = mat.findTexture( + CHANNELS.metalness, + false + )?.name; + const projectEmissiveMap = mat.findTexture(CHANNELS.emissive, false)?.name; + const projectRoughnessMap = mat.findTexture( + CHANNELS.roughness, + false + )?.name; + + const form: DialogOptions["form"] = {}; + + if (!projectColorMap) { + form.baseColor = { + type: "color", + label: "Base Color", + value: "#ff00ff", + }; + } + + if (!projectMetalnessMap && !projectEmissiveMap && !projectRoughnessMap) { + form.metalness = { + label: "Metalness", + type: "range", + min: 0, + max: 255, + step: 1, + value: 0, + }; + + form.emissive = { + label: "Emissive", + type: "range", + min: 0, + max: 255, + step: 1, + value: 0, + }; + + form.roughness = { + label: "Roughness", + type: "range", + min: 0, + max: 255, + step: 1, + value: 0, + }; + } + + if (projectNormalMap) { + form.depthMap = { + type: "checkbox", + label: "Normal Map", + value: "normal", + }; + } + + if (projectHeightMap) { + form.depthMap = { + type: "checkbox", + label: "Height Map", + value: "heightmap", + }; + } + + if (projectNormalMap && projectHeightMap) { + form.depthMap = { + type: "radio", + label: "Depth Map", + options: { + normal: "Normal Map", + heightmap: "Height", + }, + value: "normal", + }; + } + + registry.textureSetDialog = new Dialog("texture_set", { + id: "texture_set", + title: "Create Texture Set JSON", + buttons: ["Create", "Cancel"], + form, + cancelIndex: 1, + onConfirm(formResult: Record) { + const baseName = getOutputBaseName(); + + const hasMer = + projectMetalnessMap || projectEmissiveMap || projectRoughnessMap; + + const textureSet: { + format_version: string; + "minecraft:texture_set": { + color: string; + metalness_emissive_roughness: [number, number, number]; + normal?: string; + heightmap?: string; + }; + } = { + format_version: "1.16.100", + "minecraft:texture_set": { + color: + (projectColorMap + ? baseName // pathToName(projectColorMap.name, false) + : formResult.baseColor?.toHexString()) ?? baseName, + metalness_emissive_roughness: [ + formResult.metalness ?? 0, + formResult.emissive ?? 0, + formResult.roughness ?? 255, + ], + }, + }; + + if ( + (formResult.depthMap === "normal" && projectNormalMap) || + (!projectHeightMap && projectNormalMap) + ) { + textureSet["minecraft:texture_set"].normal = `${baseName}_normal`; + } else if ( + (!projectNormalMap || formResult.depthMap === "heightmap") && + projectHeightMap + ) { + textureSet["minecraft:texture_set"].heightmap = + `${baseName}_heightmap`; + } + + const exportDepthMap = (cb: () => void) => { + if (!formResult.depthMap) { + return cb(); + } + + const useNormalMap = + formResult.depthMap === "normal" || + (formResult.depthMap && !projectHeightMap); + + const depthMap = useNormalMap ? projectNormalMap : projectHeightMap; + + if (!depthMap) { + return cb(); + } + + Blockbench.export( + { + content: depthMap.canvas.toDataURL() ?? "", + type: "PNG", + name: `${baseName}_${useNormalMap ? "normal" : "heightmap"}`, + extensions: ["png"], + resource_id: formResult.depthMap, + startpath: Project.export_path, + savetype: "image", + }, + (filePath) => { + textureSet["minecraft:texture_set"][ + useNormalMap ? "normal" : "heightmap" + ] = pathToName(filePath, false); + cb(); + } + ); + }; + + const exportBaseColor = (cb: () => void) => { + if (!projectColorMap) { + return cb(); + } + + Blockbench.export( + { + content: projectColorMap.canvas.toDataURL(), + extensions: ["png"], + type: "PNG", + name: baseName, + startpath: Project.export_path, + savetype: "image", + }, + (filePath) => { + textureSet["minecraft:texture_set"].color = pathToName( + filePath, + false + ); + cb(); + } + ); + }; + + const exportTextureSet = () => + exportDepthMap(() => { + exportBaseColor(() => { + Blockbench.export( + { + content: JSON.stringify(textureSet, null, 2), + type: "JSON", + name: `${baseName}.texture_set`, + extensions: ["json"], + resource_id: "texture_set", + startpath: Project.export_path, + savetype: "text", + }, + () => { + Blockbench.showQuickMessage("Texture set created", 2000); + registry.textureSetDialog?.hide(); + } + ); + }); + }); + + if (hasMer) { + try { + exportMer(baseName, (filePath) => { + textureSet["minecraft:texture_set"].metalness_emissive_roughness = + pathToName(filePath, false); + exportTextureSet(); + }); + } catch (err) { + console.warn("Failed to export MER map:", err); + Blockbench.showStatusMessage("Failed to export MER map", 3000); + } + return; + } + + exportTextureSet(); + }, + }); + + return registry.textureSetDialog.show(); + }); +}; + +setups.push(() => { + registry.createTextureSet = new Action("create_texture_set", { + name: "Create Texture Set", + icon: "layers", + description: + "Creates a texture set JSON file. Generates a MER when metalness, emissive, or roughness channels are set.", + click() { + createTextureSetDialog(); + }, + condition: { + formats: ["bedrock", "bedrock_block"], + project: true, + }, + }); + + MenuBar.addAction(registry.createTextureSet, "file.export"); +}); + +teardowns.push(() => { + MenuBar.removeAction(`file.export.create_texture_set`); +}); diff --git a/src/pbr_preview/src/lib/actions/toggleLights.ts b/src/pbr_preview/src/lib/actions/toggleLights.ts new file mode 100644 index 00000000..995d07b7 --- /dev/null +++ b/src/pbr_preview/src/lib/actions/toggleLights.ts @@ -0,0 +1,38 @@ +import { registry, setups, teardowns } from "../../constants"; +import { applyPbrMaterial } from "../applyPbrMaterial"; + +setups.push(() => { + registry.toggleCorrectLights = new Toggle("correct_lights", { + category: "preview", + name: "Correct Lights", + description: "Corrects the lighting in the preview", + icon: "fluorescent", + default: false, + onChange(value) { + Preview.all.forEach((preview) => { + preview.renderer.physicallyCorrectLights = value; + }); + + Preview.selected.renderer.physicallyCorrectLights = value; + + Blockbench.showQuickMessage( + `Physically corrected lighting is now ${value ? "enabled" : "disabled"}`, + 2000 + ); + + if (value) { + // @ts-expect-error Set method exists on the toggle + registry.togglePbr?.set(true); + } + + applyPbrMaterial(); + }, + click() {}, + }); + + MenuBar.addAction(registry.toggleCorrectLights, "preview"); +}); + +teardowns.push(() => { + MenuBar.removeAction("preview.correct_lights"); +}); diff --git a/src/pbr_preview/src/lib/actions/togglePbr.ts b/src/pbr_preview/src/lib/actions/togglePbr.ts new file mode 100644 index 00000000..9401fdc8 --- /dev/null +++ b/src/pbr_preview/src/lib/actions/togglePbr.ts @@ -0,0 +1,69 @@ +import { registry, setups, teardowns } from "../../constants"; +import { applyPbrMaterial } from "../applyPbrMaterial"; +import { disablePbr } from "../disablePbr"; + +/** + * List of Blockbench events which trigger a PBR material update + */ +const subscribeToEvents: EventName[] = [ + "undo", + "redo", + "add_texture", + "finish_edit", + "finished_edit", + "load_project", + "select_preview_scene", + "change_texture_path", + "select_project", + "load_undo_save", + "add_cube", +]; + +/** + * Conditionally triggers the PBR material update based on the `pbr_active` setting + * @returns void + */ +const renderPbrScene = () => + Project && Project.pbr_active && applyPbrMaterial(); + +const enableListeners = () => { + Blockbench.on(subscribeToEvents.join(" ") as EventName, renderPbrScene); +}; + +const disableListeners = () => { + subscribeToEvents.forEach((event) => { + Blockbench.removeListener(event as EventName, renderPbrScene); + }); +}; + +setups.push(() => { + registry.togglePbr = new Toggle("toggle_pbr", { + name: "PBR Preview", + description: "Toggle PBR Preview", + icon: "panorama_photosphere", + category: "view", + default: false, + click() {}, + onChange(value) { + if (value) { + applyPbrMaterial(); + enableListeners(); + + Blockbench.showQuickMessage("PBR Preview is now enabled"); + + return; + } + disablePbr(); + disableListeners(); + + Blockbench.showQuickMessage("PBR Preview is now disabled"); + }, + }); + + MenuBar.addAction(registry.togglePbr, "view"); +}); + +teardowns.push(() => { + disableListeners(); + MenuBar.removeAction("view.toggle_pbr"); +}); diff --git a/src/pbr_preview/src/lib/actions/tonemapping.ts b/src/pbr_preview/src/lib/actions/tonemapping.ts new file mode 100644 index 00000000..de1c0ef6 --- /dev/null +++ b/src/pbr_preview/src/lib/actions/tonemapping.ts @@ -0,0 +1,110 @@ +import { registry, setups } from "../../constants"; +import { three as THREE } from "../../deps"; +import { + applyPbrMaterial, + debounceApplyPbrMaterial, +} from "../applyPbrMaterial"; + +const setPreviewExposure = (value: number) => { + const exposureValue = Math.max(-2, Math.min(2, value)); + Preview.all.forEach((preview) => { + preview.renderer.toneMappingExposure = exposureValue; + }); + + Preview.selected.renderer.toneMappingExposure = exposureValue; +}; + +setups.push(() => { + registry.exposureSlider = new NumSlider("display_settings_exposure", { + category: "preview", + name: "Exposure", + description: "Adjusts the exposure of the scene", + type: "number", + value: 1, + icon: "exposure", + settings: { + min: -2, + max: 2, + step: 0.01, + default: 1, + }, + // condition: () => Number(tonemappingSelect.get()) !== THREE.NoToneMapping, + onBefore() { + if (Number(registry.tonemappingSelect?.get()) === THREE.NoToneMapping) { + // @ts-expect-error `.change()` does not require an Event for its value + registry.tonemappingSelect.change(THREE.LinearToneMapping.toString()); + } + // @ts-expect-error Set method exists on the toggle + registry.togglePbr?.set(true); + }, + onChange(value) { + setPreviewExposure(Number(value)); + }, + onAfter() { + debounceApplyPbrMaterial(); + }, + }); + + registry.resetExposureButton = new Action("display_settings_reset_exposure", { + category: "preview", + name: "Reset Exposure", + description: "Resets the exposure of the scene", + icon: "exposure_plus_1", + condition: () => + registry.exposureSlider !== undefined && + Number(registry.exposureSlider?.get()) !== 1, + click() { + setPreviewExposure(1); + registry.exposureSlider?.setValue(1, true); + + debounceApplyPbrMaterial(); + }, + }); + + registry.tonemappingSelect = new BarSelect("display_settings_tone_mapping", { + category: "preview", + name: "Tone Mapping", + description: "Changes the tone mapping of the preview", + type: "select", + default_value: THREE.NoToneMapping, + value: Preview.selected.renderer.toneMapping ?? THREE.NoToneMapping, + icon: "monochrome_photos", + options: { + [THREE.NoToneMapping]: "No Tone Mapping", + [THREE.LinearToneMapping]: "Linear", + [THREE.ReinhardToneMapping]: "Reinhard", + [THREE.CineonToneMapping]: "Cineon", + [THREE.ACESFilmicToneMapping]: "ACES", + }, + onChange({ value }) { + Preview.selected.renderer.toneMapping = Number( + value + ) as THREE.ToneMapping; + + let currentExposure = 1; + if (Preview.selected.renderer.toneMapping === THREE.NoToneMapping) { + registry.exposureSlider?.setValue(currentExposure, true); + } else { + currentExposure = Number(registry.exposureSlider?.get() ?? 1); + } + + Preview.all.forEach((preview) => { + preview.renderer.toneMapping = Number(value) as THREE.ToneMapping; + preview.renderer.toneMappingExposure = currentExposure; + }); + + Preview.selected.renderer.toneMappingExposure = currentExposure; + + Blockbench.showQuickMessage( + `Tone mapping set to ${this.getNameFor(value)}`, + 2000, + ); + + if (registry.togglePbr && !registry.togglePbr.value) { + registry.togglePbr.set(true); + } + + applyPbrMaterial(); + }, + }); +}); diff --git a/src/pbr_preview/src/lib/actions/usdz.ts b/src/pbr_preview/src/lib/actions/usdz.ts new file mode 100644 index 00000000..27f6a7ca --- /dev/null +++ b/src/pbr_preview/src/lib/actions/usdz.ts @@ -0,0 +1,107 @@ +import { CHANNELS, registry, setups, teardowns } from "../../constants"; +import { three as THREE } from "../../deps"; +import { getOutputBaseName } from "../util"; +import USDZExporter from "../io/UsdzExporter"; +import { applyPbrMaterial } from "../applyPbrMaterial"; +import PbrMaterial from "../PbrMaterials"; +import { createNormalMap } from "../normalMap"; + +setups.push(() => { + const usdz = new Codec("usdz", { + extension: "usdz", + name: "USDZ", + remember: true, + export_options: { + normal_type: { + type: "select", + label: "Normal Map Type", + default: "opengl", + options: { + opengl: "OpenGL", + directx: "DirectX", + }, + }, + }, + fileName() { + return getOutputBaseName() + ".usdz"; + }, + async compile(compileOptions = {}) { + if (!Project) { + throw new Error("No project loaded"); + } + const options = Object.assign(this.getExportOptions(), compileOptions); + + Project.textures.forEach((texture) => { + if (!texture.material) { + return; + } + + const mat = new PbrMaterial(texture.layers, texture.uuid); + const normal = mat.findTexture("normal", true); + + if (!normal) { + return; + } + + const normalMap = createNormalMap(normal, options.normal_type); + + if (normalMap) { + mat.saveTexture(CHANNELS.normal, normalMap); + } + }); + + applyPbrMaterial(); + + const exporter = new USDZExporter(); + const scene = new THREE.Scene(); + + scene.name = "blockbench_export"; + scene.add(Project.model_3d); + + const result = await exporter.parse(scene); + + this.dispatchEvent("compile", { model: result, options }); + + Canvas.scene.add(Project.model_3d); + + return result; + }, + async export(options = {}) { + const content = await this.compile(options); + Blockbench.export( + { + content, + name: this.fileName(), + startpath: this.startPath(), + resource_id: "usdz", + type: this.name, + extensions: ["usdz"], + savetype: "buffer", + }, + (path) => this.afterDownload(path) + ); + }, + }); + + registry.exportUsdz = new Action("export_usdz", { + category: "file", + name: "Export USDZ", + description: "Exports the current model as a USDZ file", + icon: "stacks", + async click() { + if (!usdz) { + return; + } + const options = await usdz.promptExportOptions(); + await usdz.export(options); + }, + }); + + registry.usdz = usdz; + + MenuBar.addAction(registry.exportUsdz, "file.export"); +}); + +teardowns.push(() => { + MenuBar.removeAction("file.export_usdz"); +}); diff --git a/src/pbr_preview/src/lib/applyPbrMaterial.ts b/src/pbr_preview/src/lib/applyPbrMaterial.ts new file mode 100644 index 00000000..294f0e9e --- /dev/null +++ b/src/pbr_preview/src/lib/applyPbrMaterial.ts @@ -0,0 +1,118 @@ +import { three as THREE } from "../deps"; +import PbrMaterial from "./PbrMaterials"; +import { debounce } from "./util"; + +function applyToFace( + face: CubeFace | MeshFace, + materialParams: THREE.MeshStandardMaterialParameters +) { + const texture = face.getTexture(); + + if (!texture || !Project) { + return null; + } + + const projectMaterial = Project.materials[texture.uuid]; + + if (projectMaterial.isShaderMaterial && !Project.bb_materials[texture.uuid]) { + Project.bb_materials[texture.uuid] = projectMaterial; + } else if (projectMaterial.isMeshStandardMaterial) { + projectMaterial.dispose(); + } + + const material = new PbrMaterial( + texture.layers_enabled + ? texture.layers.filter((layer) => layer.visible) ?? null + : Project.textures, + texture.uuid + ).getMaterial({ + side: Canvas.getRenderSide(texture) as THREE.Side, + ...materialParams, + }); + + Project.materials[texture.uuid] = THREE.ShaderMaterial.prototype.copy.call( + material, + projectMaterial + ); + + return texture; +} + +function updateFaces(applied: Record) { + return ( + Object.values(applied).filter((texture) => { + if (texture) { + Canvas.updateAllFaces(texture); + return true; + } + + return false; + }).length > 0 + ); +} + +function applyToMesh( + mesh: Mesh, + materialParams: THREE.MeshStandardMaterialParameters +) { + const applied: Record = {}; + mesh.forAllFaces((face) => { + const texture = applyToFace(face, materialParams); + + if (texture) { + applied[texture.uuid] = texture; + } + }); + + return applied; +} + +function applyToCube( + cube: Cube, + materialParams: THREE.MeshStandardMaterialParameters +) { + const applied: Record = {}; + + Object.keys(cube.faces).forEach((key) => { + const face = cube.faces[key]; + const texture = applyToFace(face, materialParams); + + if (texture) { + applied[texture.uuid] = texture; + } + }); + + return applied; +} + +/** + * ### Apply PBR Material + * Iterates over all faces in the project and applies a PBR material to each face + * @param materialParams Parameters to extend the base material with + * @returns `THREE.MeshStandardMaterial` with PBR textures applied + */ +export const applyPbrMaterial = ( + materialParams: THREE.MeshStandardMaterialParameters = {} +) => { + if (!Project) { + return; + } + + const appliedTextures = Project.elements.map( + (item) => + (item instanceof Mesh && applyToMesh(item, materialParams)) || + (item instanceof Cube && applyToCube(item, materialParams)) + ); + + const allTextures = appliedTextures.reduce( + (acc, val) => ({ ...acc, ...val }), + {} + ); + + // @ts-expect-error - Property 'pbr_active' does not exist on type 'Project' + Project.pbr_active = + Texture.all.length > 0 && allTextures && updateFaces(allTextures); +}; + +export const debounceApplyPbrMaterial = (wait = 100) => + debounce(applyPbrMaterial, wait); diff --git a/src/pbr_preview/src/lib/bakery.ts b/src/pbr_preview/src/lib/bakery.ts new file mode 100644 index 00000000..2c26e4b7 --- /dev/null +++ b/src/pbr_preview/src/lib/bakery.ts @@ -0,0 +1,119 @@ +import type { ILightrParams } from "../types"; +import { CHANNELS } from "../constants"; +import PbrMaterial from "./PbrMaterials"; +import { Lightr } from "./Lightr"; + +export const bakeTextures = ( + params: ILightrParams, + directions = 8, + blendEmissive = false, +) => { + if (!Project) { + return; + } + + const selected = Project.selected_texture ?? Texture.getDefault(); + + const mat = new PbrMaterial( + selected.layers_enabled ? selected.layers : Project.textures, + selected.uuid, + ); + + const texture = mat.findTexture(CHANNELS.albedo); + + if (!texture) { + Blockbench.showStatusMessage( + "Can not bake without a base color assigned.", + 3000, + ); + return; + } + + let normalMap = mat.findTexture(CHANNELS.normal); + + // TODO: Generate normal map automatically when needed and possible + // const heightmap = mat.findTexture(CHANNELS.height); + // if (!normalMap && heightmap) { + // normalMap = PbrMaterial.createNormalMap(heightmap, false); + // } + + if (!normalMap) { + Blockbench.showStatusMessage( + "Can not bake without a normal map assigned.", + 3000, + ); + return; + } + + const lightr = new Lightr(params); + const bakedImages = lightr.bake(directions, texture.canvas, normalMap.canvas); + + const bakedTexture = new Texture({ + name: `${texture.name}_baked`, + saved: false, + particle: false, + keep_size: false, + // @ts-expect-error Layers enabled can be set here + layers_enabled: true, + }).fromDataURL(bakedImages[0].toDataURL()); + + const addEmissive = blendEmissive + ? (canvas: HTMLCanvasElement) => { + const emissive = mat.findTexture(CHANNELS.emissive); + + if (!emissive) { + return canvas; + } + + const emissiveCanvas = emissive.canvas; + const emissiveCtx = emissiveCanvas.getContext("2d"); + + if (!emissiveCtx) { + return canvas; + } + + const width = Math.max( + canvas.width, + emissiveCanvas.width, + Project ? Project.texture_width : 16, + ); + const height = Math.max( + canvas.height, + emissiveCanvas.height, + Project ? Project.texture_height : 16, + ); + + const mergedCanvas = document.createElement("canvas"); + mergedCanvas.width = width; + mergedCanvas.height = height; + + const mergedCtx = mergedCanvas.getContext("2d"); + + if (!mergedCtx) { + return canvas; + } + + mergedCtx.drawImage(canvas, 0, 0); + mergedCtx.globalCompositeOperation = "screen"; + mergedCtx.drawImage(emissiveCanvas, 0, 0); + + return mergedCanvas; + } + : (canvas: HTMLCanvasElement) => canvas; + + bakedImages.forEach((image, idx) => { + const layer = new TextureLayer( + { + name: `baked_${idx + 1}`, + data_url: addEmissive(image).toDataURL(), + }, + bakedTexture, + ); + + layer.addForEditing(); + }); + + bakedTexture.add().select(); + + Blockbench.showQuickMessage("Textures baked 🥐", 2000); +}; diff --git a/src/pbr_preview/src/lib/disablePbr.ts b/src/pbr_preview/src/lib/disablePbr.ts new file mode 100644 index 00000000..453bb28e --- /dev/null +++ b/src/pbr_preview/src/lib/disablePbr.ts @@ -0,0 +1,36 @@ +/** + * ### Disable PBR + * Reverts all faces in the project to their original materials + * @returns void + */ +export const disablePbr = () => { + if (!Project || !Project.bb_materials) { + return; + } + + Project.elements.forEach((item) => { + if (!(item instanceof Cube)) { + return; + } + + Object.keys(item.faces).forEach((key) => { + const face = item.faces[key]; + const texture = face.getTexture(); + + if (!texture) { + return; + } + + const projectMaterial = Project.bb_materials[texture.uuid]; + + if (!projectMaterial) { + return; + } + + Project.materials[texture.uuid] = projectMaterial; + }); + }); + + Project.pbr_active = false; + Canvas.updateAll(); +}; diff --git a/src/pbr_preview/src/lib/io/UsdzExporter.ts b/src/pbr_preview/src/lib/io/UsdzExporter.ts new file mode 100644 index 00000000..d7fd6b68 --- /dev/null +++ b/src/pbr_preview/src/lib/io/UsdzExporter.ts @@ -0,0 +1,472 @@ +import { three as THREE, jszip as JSZip } from "../../deps"; + +class USDZExporter { + async parse(scene: THREE.Scene): Promise { + const zip = new JSZip(); + const modelFileName = "model.usda"; // model file should be first in USDZ archive so we init it here + + zip.file(modelFileName, ""); + let output: string | null = buildHeader(); + const materials: Record = {}; + const textures: Record = {}; + scene.traverseVisible((object) => { + if (!(object as THREE.Mesh).isMesh) { + return; + } + const mesh = object as THREE.Mesh; + if ( + !(mesh.material as THREE.MeshStandardMaterial).isMeshStandardMaterial + ) { + console.warn( + "THREE.USDZExporter: Unsupported material type (USDZ only supports MeshStandardMaterial)", + object + ); + return; + } + const geometry = mesh.geometry; + const material = mesh.material as THREE.MeshStandardMaterial; + const geometryFileName = "geometries/Geometry_" + geometry.id + ".usd"; + + if (!zip.file(geometryFileName)) { + const meshObject = buildMeshObject(geometry); + zip.file(geometryFileName, buildUSDFileAsString(meshObject)); + } + + if (!(material.uuid in materials)) { + materials[material.uuid] = material; + } + + output += buildXform(mesh, geometry, material); + }); + output += buildMaterials(materials, textures); + zip.file(modelFileName, output); + output = null; + + for (const id in textures) { + const texture = textures[id]; + const color = id.split("_")[1]; + const isRGBA = texture.format === THREE.RGBAFormat; + const canvas = imageToCanvas(texture.image, color); + const blob = await new Promise((resolve) => + canvas.toBlob( + (v) => v && resolve(v), + isRGBA ? "image/png" : "image/jpeg", + 1 + ) + ); + const arrayBuffer = await blob.arrayBuffer(); + zip.file(`textures/Texture_${id}.${isRGBA ? "png" : "jpg"}`, arrayBuffer); + } + + // 64 byte alignment + let offset = 0; + + zip.forEach(async (relativePath: string) => { + const headerSize = 34 + relativePath.length; + offset += headerSize; + const offsetMod64 = offset & 63; + const content = await zip.file(relativePath)!.async("uint8array"); + + if (offsetMod64 !== 4) { + const padLength = 64 - offsetMod64; + const padding = new Uint8Array(padLength); + const newContent = new Uint8Array(content.length + padLength); + newContent.set(content, 0); + newContent.set(padding, content.length); + zip.file(relativePath, newContent); + } + + offset += content.length; + }); + + const zipBlob = await zip.generateAsync({ + type: "blob", + compression: "STORE", + }); + return new Uint8Array(await zipBlob.arrayBuffer()); + } +} + +function imageToCanvas( + image: HTMLImageElement | HTMLCanvasElement | OffscreenCanvas | ImageBitmap, + color?: string +): HTMLCanvasElement { + if ( + (typeof HTMLImageElement !== "undefined" && + image instanceof HTMLImageElement) || + (typeof HTMLCanvasElement !== "undefined" && + image instanceof HTMLCanvasElement) || + (typeof OffscreenCanvas !== "undefined" && + image instanceof OffscreenCanvas) || + (typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) + ) { + const scale = 1024 / Math.max(image.width, image.height); + const canvas = document.createElement("canvas"); + canvas.width = image.width * Math.min(1, scale); + canvas.height = image.height * Math.min(1, scale); + const context = canvas.getContext("2d")!; + + // Use nearest neighbor for scaling + context.imageSmoothingEnabled = false; + + context.drawImage(image, 0, 0, canvas.width, canvas.height); + + if (color !== undefined) { + const hex = parseInt(color, 16); + const r = ((hex >> 16) & 255) / 255; + const g = ((hex >> 8) & 255) / 255; + const b = (hex & 255) / 255; + const imagedata = context.getImageData(0, 0, canvas.width, canvas.height); + const data = imagedata.data; + + for (let i = 0; i < data.length; i += 4) { + data[i + 0] = data[i + 0] * r; + data[i + 1] = data[i + 1] * g; + data[i + 2] = data[i + 2] * b; + } + + context.putImageData(imagedata, 0, 0); + } + + return canvas; + } + + throw new Error("Unsupported image type"); +} + +const PRECISION = 7; + +function buildHeader(): string { + return `#usda 1.0 +( + customLayerData = { + string creator = "Blockbench USDZExporter" + } + metersPerUnit = 1 + upAxis = "Y" +) + +`; +} + +function buildUSDFileAsString(dataToInsert: string): string { + let output = buildHeader(); + output += dataToInsert; + return output; +} + +function buildXform( + object: THREE.Object3D, + geometry: THREE.BufferGeometry, + material: THREE.Material +): string { + const name = "Object_" + object.id; + const transform = buildMatrix(object.matrixWorld); + + if (object.matrixWorld.determinant() < 0) { + console.warn( + "THREE.USDZExporter: USDZ does not support negative scales", + object + ); + } + + return `def Xform "${name}" ( + prepend references = @./geometries/Geometry_${geometry.id}.usd@ +) +{ + matrix4d xformOp:transform = ${transform} + uniform token[] xformOpOrder = ["xformOp:transform"] + + rel material:binding = +} + +`; +} + +function buildMatrix(matrix: THREE.Matrix4): string { + const array = matrix.elements; + return `( ${buildMatrixRow(array, 0)}, ${buildMatrixRow(array, 4)}, ${buildMatrixRow(array, 8)}, ${buildMatrixRow(array, 12)} )`; +} + +function buildMatrixRow(array: number[], offset: number): string { + return `(${array[offset + 0]}, ${array[offset + 1]}, ${array[offset + 2]}, ${array[offset + 3]})`; +} + +function buildMeshObject(geometry: THREE.BufferGeometry): string { + const mesh = buildMesh(geometry); + return ` +def "Geometry" +{ + ${mesh} +} +`; +} + +function buildMesh(geometry: THREE.BufferGeometry): string { + const name = "Geometry"; + const attributes = geometry.attributes; + const count = attributes.position.count; + return ` + def Mesh "${name}" + { + int[] faceVertexCounts = [${buildMeshVertexCount(geometry)}] + int[] faceVertexIndices = [${buildMeshVertexIndices(geometry)}] + normal3f[] normals = [${buildVector3Array(attributes.normal as THREE.BufferAttribute, count)}] ( + interpolation = "vertex" + ) + point3f[] points = [${buildVector3Array(attributes.position as THREE.BufferAttribute, count)}] + float2[] primvars:st = [${buildVector2Array(attributes.uv as THREE.BufferAttribute, count)}] ( + interpolation = "vertex" + ) + uniform token subdivisionScheme = "none" + } +`; +} + +function buildMeshVertexCount(geometry: THREE.BufferGeometry): string { + const count = + geometry.index !== null + ? geometry.index.count + : geometry.attributes.position.count; + return Array(count / 3) + .fill(3) + .join(", "); +} + +function buildMeshVertexIndices(geometry: THREE.BufferGeometry): string { + const index = geometry.index; + const array: number[] = []; + + if (index !== null) { + for (let i = 0; i < index.count; i++) { + array.push(index.getX(i)); + } + } else { + const length = geometry.attributes.position.count; + + for (let i = 0; i < length; i++) { + array.push(i); + } + } + + return array.join(", "); +} + +function buildVector3Array( + attribute: THREE.BufferAttribute, + count: number +): string { + if (attribute === undefined) { + console.warn("USDZExporter: Normals missing."); + return Array(count).fill("(0, 0, 0)").join(", "); + } + + const array: string[] = []; + + for (let i = 0; i < attribute.count; i++) { + const x = attribute.getX(i); + const y = attribute.getY(i); + const z = attribute.getZ(i); + array.push( + `(${x.toPrecision(PRECISION)}, ${y.toPrecision(PRECISION)}, ${z.toPrecision(PRECISION)})` + ); + } + + return array.join(", "); +} + +function buildVector2Array( + attribute: THREE.BufferAttribute, + count: number +): string { + if (attribute === undefined) { + console.warn("USDZExporter: UVs missing."); + return Array(count).fill("(0, 0)").join(", "); + } + + const array: string[] = []; + + for (let i = 0; i < attribute.count; i++) { + const x = attribute.getX(i); + const y = attribute.getY(i); + array.push( + `(${x.toPrecision(PRECISION)}, ${Number(y.toPrecision(PRECISION))})` + ); + } + return array.join(", "); +} + +function buildMaterials( + materials: { [key: string]: THREE.Material }, + textures: { [key: string]: THREE.Texture } +): string { + const array: string[] = []; + + for (const uuid in materials) { + const material = materials[uuid]; + array.push(buildMaterial(material, textures)); + } + + return `def "Materials" +{ +${array.join("")} +} + +`; +} + +function buildMaterial( + material: THREE.Material, + textures: { [key: string]: THREE.Texture } +): string { + // https://graphics.pixar.com/usd/docs/UsdPreviewSurface-Proposal.html + const pad = " "; + const inputs: string[] = []; + const samplers: string[] = []; + + function buildTexture( + texture: THREE.Texture, + mapType: string, + color?: THREE.Color + ): string { + const id = texture.id + (color ? "_" + color.getHexString() : ""); + const isRGBA = texture.format === THREE.RGBAFormat; + textures[id] = texture; + return ` + def Shader "Transform2d_${mapType}" ( + sdrMetadata = { + string role = "math" + } + ) + { + uniform token info:id = "UsdTransform2d" + float2 inputs:in.connect = + float2 inputs:scale = ${buildVector2(texture.repeat)} + float2 inputs:translation = ${buildVector2(texture.offset)} + float2 outputs:result + } + + def Shader "Texture_${texture.id}_${mapType}" + { + uniform token info:id = "UsdUVTexture" + asset inputs:file = @textures/Texture_${id}.${isRGBA ? "png" : "jpg"}@ + float2 inputs:st.connect = + token inputs:wrapS = "repeat" + token inputs:wrapT = "repeat" + float outputs:r + float outputs:g + float outputs:b + float3 outputs:rgb + }`; + } + + const mat = material as THREE.MeshStandardMaterial; + + if (mat.map !== null) { + inputs.push( + `${pad}color3f inputs:diffuseColor.connect = ` + ); + samplers.push(buildTexture(mat.map, "diffuse", mat.color)); + } else { + inputs.push(`${pad}color3f inputs:diffuseColor = ${buildColor(mat.color)}`); + } + + if (mat.emissiveMap !== null) { + inputs.push( + `${pad}color3f inputs:emissiveColor.connect = ` + ); + samplers.push(buildTexture(mat.emissiveMap, "emissive")); + } else if (mat.emissive.getHex() > 0) { + inputs.push( + `${pad}color3f inputs:emissiveColor = ${buildColor(mat.emissive)}` + ); + } + + if (mat.normalMap !== null) { + inputs.push( + `${pad}normal3f inputs:normal.connect = ` + ); + samplers.push(buildTexture(mat.normalMap, "normal")); + } + + if (mat.aoMap !== null) { + inputs.push( + `${pad}float inputs:occlusion.connect = ` + ); + samplers.push(buildTexture(mat.aoMap, "occlusion")); + } + + if (mat.roughnessMap !== null && mat.roughness === 1) { + inputs.push( + `${pad}float inputs:roughness.connect = ` + ); + samplers.push(buildTexture(mat.roughnessMap, "roughness")); + } else { + inputs.push(`${pad}float inputs:roughness = ${mat.roughness}`); + } + + if (mat.metalnessMap !== null && mat.metalness === 1) { + inputs.push( + `${pad}float inputs:metallic.connect = ` + ); + samplers.push(buildTexture(mat.metalnessMap, "metallic")); + } else { + inputs.push(`${pad}float inputs:metallic = ${mat.metalness}`); + } + + if (mat.alphaMap !== null) { + inputs.push( + `${pad}float inputs:opacity.connect = ` + ); + inputs.push(`${pad}float inputs:opacityThreshold = 0.0001`); + samplers.push(buildTexture(mat.alphaMap, "opacity")); + } else { + inputs.push(`${pad}float inputs:opacity = ${mat.opacity}`); + } + + if ((mat as any).isMeshPhysicalMaterial) { + const physicalMat = mat as any; + inputs.push(`${pad}float inputs:clearcoat = ${physicalMat.clearcoat}`); + inputs.push( + `${pad}float inputs:clearcoatRoughness = ${physicalMat.clearcoatRoughness}` + ); + inputs.push(`${pad}float inputs:ior = ${physicalMat.ior}`); + } + + return ` + def Material "Material_${mat.id}" + { + def Shader "PreviewSurface" + { + uniform token info:id = "UsdPreviewSurface" +${inputs.join("\n")} + int inputs:useSpecularWorkflow = 0 + token outputs:surface + } + + token outputs:surface.connect = + token inputs:frame:stPrimvarName = "st" + + def Shader "uvReader_st" + { + uniform token info:id = "UsdPrimvarReader_float2" + token inputs:varname.connect = + float2 inputs:fallback = (0.0, 0.0) + float2 outputs:result + } + +${samplers.join("\n")} + + } +`; +} + +function buildColor(color: THREE.Color): string { + return `(${color.r}, ${color.g}, ${color.b})`; +} + +function buildVector2(vector: THREE.Vector2): string { + return `(${vector.x}, ${vector.y})`; +} + +export default USDZExporter; diff --git a/src/pbr_preview/src/lib/io/bbmat.ts b/src/pbr_preview/src/lib/io/bbmat.ts new file mode 100644 index 00000000..f30909bb --- /dev/null +++ b/src/pbr_preview/src/lib/io/bbmat.ts @@ -0,0 +1,198 @@ +import { + registry, + setups, + teardowns, + CHANNELS, + BBMAT_VERSION, + PLUGIN_VERSION, +} from "../../constants"; +import type { Channel, IBbMat } from "../../types"; + +setups.push(() => { + registry.bbmat = new Codec("material", { + name: "Blockbench Material", + extension: "bbmat", + remember: false, + load_filter: { + extensions: ["bbmat"], + type: "json", + }, + compile() { + if (!Texture.selected?.material || !Texture.selected?.layers_enabled) { + return; + } + + const channels = Texture.selected.layers.map((layer: TextureLayer) => { + const channel = layer.channel; + const map = layer.canvas.toDataURL(); + return [channel, map]; + }); + + return JSON.stringify({ + version: BBMAT_VERSION, + channels: Object.fromEntries(channels), + }); + }, + parse(content, path) { + content = typeof content === "string" ? JSON.parse(content) : content; + const version = content.version; + + if (version !== BBMAT_VERSION) { + Blockbench.showMessageBox( + { + title: "Invalid Blockbench Material Version", + message: `The material file "${path}" is not compatible with version ${PLUGIN_VERSION} of the PBR plugin.`, + buttons: ["OK"], + confirm: 0, + width: 400, + cancel: 0, + checkboxes: {}, + }, + () => null + ); + return {}; + } + + return content.channels as IBbMat["channels"]; + }, + load(content, file, add) { + if (!Project) { + return; + } + + const data = this.parse( + content, + file.path + ) as unknown as IBbMat["channels"]; + + const channelKeys = Object.keys(data); + + if (!channelKeys.length) { + throw new Error("No valid channels found in the material"); + } + + let baseColor = + data[CHANNELS.albedo.id as Channel] ?? data[channelKeys[0] as Channel]; + + if (channelKeys.includes("preview")) { + baseColor = data["preview"]; + } + + const material = new Texture({ + name: pathToName(file.name), + saved: true, + particle: false, + source: baseColor, + layers_enabled: true, + }); + material.extend({ material: true }); + + const layers = channelKeys + .map((channel) => { + if (!(channel in CHANNELS)) { + return null; + } + + const map = data[channel as Channel]; + const layer = new TextureLayer( + { + name: channel, + data_url: map, + visible: true, + }, + material + ); + + layer.extend({ channel }); + + return layer; + }) + .filter(Boolean) as TextureLayer[]; + + if (!layers.length) { + throw new Error("No valid channel layers found in the material"); + } + + if (!baseColor) { + material.fromDataURL(layers[0].canvas.toDataURL()); + } + + material.add().select(); + + layers.forEach((layer) => { + layer.addForEditing(); + material.width = Math.max(material.width, layer.img.width); + material.height = Math.max(material.height, layer.img.height); + }); + material.updateChangesAfterEdit(); + }, + export() { + Blockbench.export( + { + resource_id: "material", + type: this.name, + extensions: [this.extension], + name: `${Texture.selected?.name ?? this.fileName ?? "material"}.bbmat`, + startpath: this.startPath(), + content: this.compile(), + }, + (path) => this.afterDownload(path) + ); + }, + }); + + registry.bbMatExport = new Action("export_bbmat", { + icon: "stacks", + name: "Save as .bbmat", + category: "file", + condition: { + project: true, + selected: { + texture: true, + }, + method() { + return Texture.selected?.material; + }, + }, + click() { + registry.bbmat?.export?.(); + }, + }); + + registry.bbMatImport = new Action("import_bbmat", { + icon: "stacks", + name: "Import .bbmat", + category: "file", + condition: { + project: true, + }, + click() { + Blockbench.import( + { + extensions: ["bbmat"], + type: "json", + title: "Import .bbmat", + multiple: true, + }, + (files) => { + if (!registry.bbmat?.load) { + return; + } + + files.forEach((file) => { + registry.bbmat!.load!(file.content, file, true); + }); + } + ); + }, + }); + + registry.bbmat.export_action = registry.bbMatExport; + Texture.prototype.menu.addAction(registry.bbMatExport); + MenuBar.addAction(registry.bbMatImport, "file.import"); +}); + +teardowns.push(() => { + Texture.prototype.menu.removeAction("export_bbmat"); + MenuBar.removeAction("file.import.import_bbmat"); +}); diff --git a/src/pbr_preview/src/lib/mer.ts b/src/pbr_preview/src/lib/mer.ts new file mode 100644 index 00000000..235edccb --- /dev/null +++ b/src/pbr_preview/src/lib/mer.ts @@ -0,0 +1,56 @@ +import PbrMaterial from "./PbrMaterials"; +import { getSelectedTexture } from "./util"; + +/** + * ### Export MER map + * Generates a MER map from the currently selected texture and exports it as a PNG file + * @param cb Callback function to run after the MER file is exported + * @returns void + */ +export const exportMer = ( + baseName?: string, + cb?: (filePath: string) => void +) => { + const selected = getSelectedTexture() ?? Texture.getDefault(); + + const mer = new PbrMaterial( + selected.layers_enabled + ? selected.layers + : Project + ? Project.textures + : null, + selected.uuid + ).createMer(true); + + if (!mer) { + throw new Error("Failed to generate MER map from selected texture."); + } + + mer.toBlob(async (blob) => { + if (!blob) { + throw new Error("Failed to save MER map."); + } + + const [name, startpath] = Project + ? [ + baseName + ? `${baseName}_mer` + : `${selected.name ?? Project.getDisplayName()}_mer`, + Project.export_path, + ] + : ["mer"]; + + Blockbench.export( + { + content: await blob.arrayBuffer(), + type: "PNG", + name, + extensions: ["png"], + resource_id: "mer", + savetype: "image", + startpath, + }, + cb + ); + }); +}; diff --git a/src/pbr_preview/src/lib/normalMap.ts b/src/pbr_preview/src/lib/normalMap.ts new file mode 100644 index 00000000..d93c92d5 --- /dev/null +++ b/src/pbr_preview/src/lib/normalMap.ts @@ -0,0 +1,279 @@ +/** + * ### Generate Normal Map + * Generates a normal map from a height map texture + * @param texture Height map texture + * @param heightInAlpha Whether or not to store the height map in the alpha channel (Used in labPBR shaders for POM) + * @param orientation Whether or not to flip the normal map vertically + * @returns Normal map texture or layer if successful, otherwise `null` + */ +export function createNormalMap( + texture: Texture | TextureLayer, + orientation: "DirectX" | "OpenGL" = "DirectX", + heightInAlpha = false +): Texture | TextureLayer | null { + const textureCtx = texture.canvas.getContext("2d"); + + if (!textureCtx) { + return null; + } + + const width = Math.max( + texture.img.width ?? texture.canvas.width, + Project ? Project.texture_width : 0, + 16 + ); + const height = Math.max( + texture.img.height ?? texture.canvas.height, + Project ? Project.texture_height : 0, + 16 + ); + + const { data: textureData } = textureCtx.getImageData(0, 0, width, height); + + const canvas = document.createElement("canvas"); + const ctx = canvas.getContext("2d"); + + if (!ctx) { + return null; + } + + const getHeight = (x: number, y: number): number => { + const idx = (x + y * width) * 4; + return textureData[idx] / 255; + }; + + canvas.width = width; + canvas.height = height; + + ctx.drawImage(texture.img, 0, 0, width, height); + + const imageData = ctx.getImageData(0, 0, width, height); + + const data = imageData.data; + + const normalize = (v: number[]): number[] => { + const length = Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); + return [v[0] / length, v[1] / length, v[2] / length]; + }; + + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const left = getHeight(Math.max(x - 1, 0), y); + const right = getHeight(Math.min(x + 1, width - 1), y); + const top = getHeight(x, Math.max(y - 1, 0)); + const bottom = getHeight(x, Math.min(y + 1, height - 1)); + + const dx = right - left; + const dy = bottom - top; + const vector = orientation === "DirectX" ? [dx, dy, 1] : [-dx, -dy, 1]; + const normal = normalize(vector); + + const idx = (y * width + x) * 4; + data[idx] = ((normal[0] + 1) / 2) * 255; + data[idx + 1] = ((normal[1] + 1) / 2) * 255; + data[idx + 2] = ((normal[2] + 1) / 2) * 255; + data[idx + 3] = heightInAlpha ? getHeight(x, y) * 255 : 255; + } + } + + ctx.putImageData(imageData, 0, 0); + + const dataUrl = canvas.toDataURL(); + + const name = `${texture.name.replace(/_height(map)?/i, "")}_normal`; + + if (texture instanceof TextureLayer) { + const normalMapLayer = new TextureLayer( + { + name, + data_url: dataUrl, + visible: true, + }, + texture.texture + ); + + normalMapLayer.addForEditing(); + + return normalMapLayer; + } + + const normalMapTexture = new Texture({ + name, + saved: false, + particle: false, + }).fromDataURL(dataUrl); + + if (Project) { + normalMapTexture.add(); + } + + return normalMapTexture; +} + +export function createAoMap( + texture: Texture | TextureLayer +): Texture | TextureLayer | null { + const textureCtx = texture.canvas.getContext("2d"); + + if (!textureCtx) { + return null; + } + + const width = Math.max( + texture.img.width ?? texture.canvas.width, + Project ? Project.texture_width : 0, + 16 + ); + const height = Math.max( + texture.img.height ?? texture.canvas.height, + Project ? Project.texture_height : 0, + 16 + ); + + const { data: textureData } = textureCtx.getImageData(0, 0, width, height); + + const canvas = document.createElement("canvas"); + const ctx = canvas.getContext("2d"); + + if (!ctx) { + return null; + } + + const getHeight = (x: number, y: number): number => { + const idx = (x + y * width) * 4; + return textureData[idx] / 255; + }; + + canvas.width = width; + canvas.height = height; + + ctx.drawImage(texture.img, 0, 0, width, height); + + const imageData = ctx.getImageData(0, 0, width, height); + + const data = imageData.data; + + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const left = getHeight(Math.max(x - 1, 0), y); + const right = getHeight(Math.min(x + 1, width - 1), y); + const top = getHeight(x, Math.max(y - 1, 0)); + const bottom = getHeight(x, Math.min(y + 1, height - 1)); + + const dx = right - left; + const dy = bottom - top; + + const ao = Math.sqrt(dx * dx + dy * dy) * 255; + + const idx = (y * width + x) * 4; + data[idx] = ao; + data[idx + 1] = ao; + data[idx + 2] = ao; + data[idx + 3] = 255; + } + } + + ctx.putImageData(imageData, 0, 0); + + const dataUrl = canvas.toDataURL(); + + const name = `${texture.name.replace(/_height(map)?/i, "")}_ao`; + + if (texture instanceof TextureLayer) { + const aoMapLayer = new TextureLayer( + { + name, + data_url: dataUrl, + visible: true, + }, + texture.texture + ); + + aoMapLayer.addForEditing(); + + return aoMapLayer; + } + + const aoMapTexture = new Texture({ + name, + saved: false, + particle: false, + keep_size: false, + }).fromDataURL(dataUrl); + + if (Project) { + aoMapTexture.add(); + } + + return aoMapTexture; +} + +export function convertNormalMap( + texture: Texture | TextureLayer, + orientation: "DirectX" | "OpenGL" = "DirectX" +): string | null { + const textureCtx = texture.canvas.getContext("2d"); + + if (!textureCtx) { + return null; + } + + const width = Math.max( + texture.img.width ?? texture.canvas.width, + Project ? Project.texture_width : 0, + 16 + ); + const height = Math.max( + texture.img.height ?? texture.canvas.height, + Project ? Project.texture_height : 0, + 16 + ); + + const { data: textureData } = textureCtx.getImageData(0, 0, width, height); + + const canvas = document.createElement("canvas"); + const ctx = canvas.getContext("2d"); + + if (!ctx) { + return null; + } + + const getNormal = (x: number, y: number): number[] => { + const idx = (x + y * width) * 4; + return [ + (textureData[idx] / 255) * 2 - 1, + (textureData[idx + 1] / 255) * 2 - 1, + (textureData[idx + 2] / 255) * 2 - 1, + ]; + }; + + canvas.width = width; + canvas.height = height; + + ctx.drawImage(texture.img, 0, 0, width, height); + + const imageData = ctx.getImageData(0, 0, width, height); + + const data = imageData.data; + + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const normal = getNormal(x, y); + + const [dx, dy] = + orientation === "DirectX" + ? [normal[0], normal[1]] + : [-normal[0], -normal[1]]; + + const idx = (y * width + x) * 4; + data[idx] = ((dx + 1) / 2) * 255; + data[idx + 1] = ((dy + 1) / 2) * 255; + data[idx + 2] = 0; + data[idx + 3] = 255; + } + } + + ctx.putImageData(imageData, 0, 0); + + return canvas.toDataURL(); +} diff --git a/src/pbr_preview/src/lib/panels/channels.ts b/src/pbr_preview/src/lib/panels/channels.ts new file mode 100644 index 00000000..479bb6de --- /dev/null +++ b/src/pbr_preview/src/lib/panels/channels.ts @@ -0,0 +1,221 @@ +import type { IChannel } from "../../types"; +import { + registry, + setups, + CHANNELS, + NA_CHANNEL, + teardowns, +} from "../../constants"; +import { getSelectedLayer, getSelectedTexture } from "../util"; + +const filterLayers = (layer: Texture | TextureLayer) => + layer.visible && layer.channel && layer.channel !== NA_CHANNEL; + +const getChannels = () => { + const selectedLayer = getSelectedLayer(); + + if (selectedLayer) { + return selectedLayer.texture.layers.filter(filterLayers); + } + + const selectedTexture = getSelectedTexture(); + + if (!selectedTexture) { + return []; + } + + return selectedTexture.layers_enabled + ? selectedTexture.layers.filter(filterLayers) + : Texture.all + .map((t) => + t.layers_enabled + ? [...t.layers.filter(filterLayers)] + : [filterLayers(t) ? t : null] + ) + .flat() + .filter(Boolean); +}; + +const events: EventName[] = [ + "select_texture" as EventName, + "update_texture_selection" as EventName, + "finish_edit", + "add_texture", +]; + +const refresh = () => { + Panels.channels_panel.inside_vue.textures = getChannels(); +}; + +setups.push(() => { + registry.channelsPanelStyle = Blockbench.addCSS(/* css */ ` + .texture_channel { + color: var(--color-text); + flex: 1; + font-size: 1em; + margin: 0 0 0 auto; + padding: 0 8px; + text-align: right; + } + + .texture_channel + .texture_particle_icon { + padding-right: 8px; + } + + .texture_channel_description { + background-color: var(--color-back); + display: flex; + flex-direction: row; + flex-wrap: nowrap; + justify-content: space-between; + } + + .texture_channel_wrapper { + align-items: center; + background-color: var(--color-ui); + border-left: 1px solid var(--color-border); + display: flex; + flex: 1; + flex-direction: row; + align-items: center; + flex-wrap: nowrap; + padding: 0 8px; + } + + .texture_channel_wrapper:hover { + background-color: var(--color-button); + } + + .texture_channel_description .texture_name { + flex-direction: column; + flex-wrap: nowrap; + color: var(--color-subtle_text); + display: flex; + flex: 1; + justify-content: center; + align-items: start; + } + + .texture_parent { + color: var(--color-subtle_text); + font-size: 0.8em; + } + + .texture_channel_description:hover .texture_channel { + color: var(--color-accent); + } + + #pbr_channel_list { + display: flex; + flex-direction: column; + } + + #pbr_channel_list .texture { + border-top: 1px solid var(--color-border); + padding-right: 0; + } + `); + + registry.channelsPanel = new Panel("channels_panel", { + name: "PBR Channels", + id: "channels_panel", + icon: "gallery_thumbnail", + condition: { + project: true, + selected: { + texture: true, + }, + modes: ["paint", "edit"], + }, + toolbars: [ + // new Toolbar("channel_assignment_toolbar", { + // id: "channel_assignment_toolbar", + // children: ["create_material_texture", "show_channel_menu"], + // name: "PBR Channel Controls", + // }), + ], + component: { + name: "ChannelsPanel", + data(): { + channels: Record; + textures: Array; + } { + return { + channels: CHANNELS, + textures: [], + }; + }, + methods: { + openMenu(event: MouseEvent) { + registry.channelMenu?.open(event); + }, + selectTexture(texture: Texture | TextureLayer) { + Modes.options.paint.select(); + texture.select(); + texture.scrollTo(); + }, + channelEnabled(texture: Texture) { + return ( + texture.channel && + texture.channel !== NA_CHANNEL && + texture.channel in this.channels + ); + }, + getImgSrc(texture: Texture | TextureLayer) { + return ( + texture.img?.src ?? + `data:image/png;base64,${texture.canvas.toDataURL()}` + ); + }, + }, + template: /* html */ ` +
+
    +
  • + +
    +
    +
    {{ texture.name }}
    +
    + {{ texture.texture.name }} +
    +
    +
    +
    {{ channels[texture.channel].label }}
    + {{ channels[texture.channel].icon }} +
    +
    +
  • +
+
`, + }, + expand_button: true, + growable: true, + onFold() {}, + onResize() {}, + default_side: "left", + default_position: { + slot: "left_bar", + float_position: [0, 0], + float_size: [400, 300], + height: 350, + folded: true, + }, + insert_after: "layers", + insert_before: "color", + }); + + Blockbench.on(events.join(" ") as EventName, refresh); +}); + +teardowns.push(() => { + events.forEach((event) => { + Blockbench.removeListener(event, refresh); + }); +}); diff --git a/src/pbr_preview/src/lib/panels/index.ts b/src/pbr_preview/src/lib/panels/index.ts new file mode 100644 index 00000000..d490932a --- /dev/null +++ b/src/pbr_preview/src/lib/panels/index.ts @@ -0,0 +1,3 @@ +import "./materialBrush"; +import "./pbrSettings"; +import "./channels"; diff --git a/src/pbr_preview/src/lib/panels/materialBrush.ts b/src/pbr_preview/src/lib/panels/materialBrush.ts new file mode 100644 index 00000000..11ec525a --- /dev/null +++ b/src/pbr_preview/src/lib/panels/materialBrush.ts @@ -0,0 +1,42 @@ +import { registry, setups } from "../../constants"; + +setups.push(() => { + registry.materialBrushPanel = new Panel("material_brush_panel", { + name: "Material Brush", + id: "material_brush_panel", + icon: "view_in_ar", + toolbars: [ + new Toolbar("material_brush_toolbar", { + id: "material_brush_toolbar", + children: [ + "material_brush", + "load_brush_preset", + "slider_brush_metalness", + "slider_brush_roughness", + "brush_emissive_color", + "slider_brush_height", + ], + name: "Material Settings", + }), + ], + condition: { + modes: ["paint"], + project: true, + }, + component: {}, + expand_button: true, + growable: false, + onFold() {}, + onResize() {}, + default_side: "right", + default_position: { + slot: "right_bar", + float_position: [0, 0], + float_size: [400, 300], + height: 300, + folded: false, + }, + insert_after: "color", + insert_before: "outliner", + }); +}); diff --git a/src/pbr_preview/src/lib/panels/pbrSettings.ts b/src/pbr_preview/src/lib/panels/pbrSettings.ts new file mode 100644 index 00000000..f5c34d24 --- /dev/null +++ b/src/pbr_preview/src/lib/panels/pbrSettings.ts @@ -0,0 +1,44 @@ +import { registry, setups } from "../../constants"; + +// TODO: Teardown toolbars + +setups.push(() => { + registry.displaySettingsPanel = new Panel("display_settings", { + name: "PBR Controls", + id: "display_settings_panel", + icon: "display_settings", + toolbars: [ + new Toolbar("controls_toolbar", { + id: "controls_toolbar", + children: [ + "toggle_pbr", + "correct_lights", + "display_settings_tone_mapping", + "display_settings_exposure", + "display_settings_reset_exposure", + "show_channel_select_menu", + ], + name: "Display Settings", + }), + ], + display_condition: { + modes: ["edit", "paint", "animate"], + project: true, + }, + component: {}, + expand_button: true, + growable: false, + onFold() {}, + onResize() {}, + default_side: "left", + default_position: { + slot: "left_bar", + float_position: [0, 0], + float_size: [400, 300], + height: 300, + folded: false, + }, + insert_after: "textures", + insert_before: "color", + }); +}); diff --git a/src/pbr_preview/src/lib/properties.ts b/src/pbr_preview/src/lib/properties.ts new file mode 100644 index 00000000..f2008bf4 --- /dev/null +++ b/src/pbr_preview/src/lib/properties.ts @@ -0,0 +1,64 @@ +import { registry, CHANNELS, NA_CHANNEL, setups } from "../constants"; + +const channelsEnum = [ + ...Object.keys(CHANNELS).map((key) => CHANNELS[key].id), + NA_CHANNEL, +]; + +setups.push(() => { + registry.channelProp = new Property(TextureLayer, "enum", "channel", { + default: NA_CHANNEL, + values: channelsEnum, + label: "PBR Channel", + exposed: false, + }); + + registry.textureChannelProp = new Property(Texture, "enum", "channel", { + default: NA_CHANNEL, + values: channelsEnum, + label: "PBR Channel", + exposed: false, + }); + + // @ts-expect-error Boolean values not required + registry.materialTextureProp = new Property(Texture, "boolean", "material", { + default: false, + label: "Material Texture", + }); + + registry.pbrMaterialsProp = new Property( + ModelProject, + // @ts-expect-error "object" is a valid type for a property + "object", + "pbr_materials", + { + default: {}, + exposed: false, + label: "PBR Materials", + } + ); + + registry.projectMaterialsProp = new Property( + ModelProject, + // @ts-expect-error "object" is a valid type for a property + "object", + "bb_materials", + { + default: {}, + exposed: false, + label: "Project Materials", + } + ); + + registry.projectPbrModeProp = new Property( + ModelProject, + "boolean", + "pbr_active", + { + default: false, + exposed: false, + values: [], + label: "PBR Mode", + } + ); +}); diff --git a/src/pbr_preview/src/lib/tools/index.ts b/src/pbr_preview/src/lib/tools/index.ts new file mode 100644 index 00000000..e4c04bf9 --- /dev/null +++ b/src/pbr_preview/src/lib/tools/index.ts @@ -0,0 +1 @@ +import "./materialBrush"; diff --git a/src/pbr_preview/src/lib/tools/materialBrush.ts b/src/pbr_preview/src/lib/tools/materialBrush.ts new file mode 100644 index 00000000..8822e2ee --- /dev/null +++ b/src/pbr_preview/src/lib/tools/materialBrush.ts @@ -0,0 +1,570 @@ +import type { IChannel } from "../../types"; +import { registry, CHANNELS, setups, teardowns } from "../../constants"; +import { + applyPbrMaterial, + debounceApplyPbrMaterial, +} from "../applyPbrMaterial"; +import { MaterialBrush } from "../MaterialBrush"; +import { vue as Vue, three as THREE } from "../../deps"; +import { getSelectedTexture, generatePreviewImage } from "../util"; + +const STORAGE_NAMESPACE = "materialBrushPresets"; + +const getPresets = () => { + return JSON.parse(localStorage.getItem(STORAGE_NAMESPACE) || "{}"); +}; + +const savePreset = (name?: string, id?: string) => { + const presets = getPresets(); + const uuid = id ?? guid(); + const results = registry.userMaterialBrushPresets?.getFormResult() ?? {}; + const settings = {}; + + if (results.albedo) { + settings.albedo = results.albedo.toString(); + } + + if (results.metalness) { + settings.metalness = Number(results.metalness); + } + + if (results.roughness) { + settings.roughness = Number(results.roughness); + } + + if (results.emissive) { + settings.emissive = results.emissive.toString(); + } + + if (results.height) { + settings.height = Number(results.height); + } + + presets[uuid] = [ + settings, + name ?? "New Preset", + generatePreviewImage(settings), + ]; + + localStorage.setItem(STORAGE_NAMESPACE, JSON.stringify(presets)); + + return uuid; +}; + +const applyPreset = ({ + metalness, + roughness, + emissive, + height, + albedo, +}: { + metalness?: number; + roughness?: number; + emissive?: string; + height?: number; + albedo?: string; +}) => { + if (metalness !== undefined) { + registry.brushMetalnessSlider?.setValue(metalness || 0, true); + } + + if (roughness !== undefined) { + registry.brushRoughnessSlider?.setValue(roughness ?? 1, true); + } + + if (emissive !== undefined) { + registry.brushEmissiveColor?.set(emissive ?? "#000000"); + } + + if (height !== undefined) { + registry.brushHeightSlider?.setValue( + Math.max(0, Math.min(1, height ?? 0.5)), + true + ); + } + + if (albedo !== undefined) { + // @ts-expect-error ColorPanel global is not typed + ColorPanel.set(albedo); + } +}; + +const materialBrushSliderCondition = ({ id }: IChannel) => + Condition({ + project: true, + tools: ["material_brush"], + method() { + const texture = getSelectedTexture(); + + return ( + (texture?.layers_enabled && + texture.layers.find(({ channel }) => channel && channel === id) !== + undefined) === true + ); + }, + }); + +const userPresetsDialogComponent = Vue.extend({ + name: "UserPresetsDialog", + data(): { + userPresets: Record, string]>; + channels: typeof CHANNELS; + } { + return { + userPresets: {}, + channels: CHANNELS, + }; + }, + methods: { + applyPreset(preset: string) { + try { + const [settings, name] = this.userPresets[preset]; + + const { metalness, roughness, emissive, height, albedo } = settings; + + applyPreset({ + metalness: Number(metalness), + roughness: Number(roughness), + emissive: emissive.toString(), + height: Number(height), + albedo: albedo.toString(), + }); + + registry.userMaterialBrushPresets?.hide(); + Blockbench.showQuickMessage(`Preset "${name}" applied`, 2000); + } catch { + Blockbench.showQuickMessage("Failed to apply preset", 2000); + } + }, + deletePreset(preset: string) { + Blockbench.showMessageBox( + { + title: "Delete Preset", + message: "Are you sure you want to delete this preset?", + confirm: 1, + cancel: 0, + buttons: ["Cancel", "Delete"], + checkboxes: {}, + width: 400, + }, + (btn) => { + if (btn) { + const presets = getPresets(); + const friendlyName = this.userPresets[preset][1] ?? preset; + + delete presets[preset]; + + localStorage.setItem( + "materialBrushPresets", + JSON.stringify(presets) + ); + + this.userPresets = presets; + + Blockbench.showQuickMessage( + `Preset "${friendlyName}" deleted`, + 2000 + ); + } + } + ); + }, + editPreset(preset: string) { + registry.userMaterialBrushPresets?.setFormValues({ + name: this.userPresets[preset][1] ?? preset, + ...this.userPresets[preset][0], + }); + }, + getSummary(settings: Record) { + return Object.entries(settings) + .filter(([channel]) => channel in this.channels) + .map(([channel, value]) => { + if (channel === "albedo" || channel === "emissive") { + return `${this.channels[channel]?.label ?? channel}: ${value}`; + } + + return `${this.channels[channel]?.label ?? channel}: ${Number(value).toFixed(1)}`; + }) + .join("\n"); + }, + }, + computed: { + presets() { + return Object.entries(this.userPresets); + }, + }, + mounted() { + this.userPresets = getPresets(); + }, + template: /* html */ ` +
+
    +
  • +
    + +
    {{ name }}
    +
    +
    +
    {{ name }}
    +
    +
    + +
    +
  • +
+
`, +}); + +setups.push(() => { + registry.materialBrushStyles = Blockbench.addCSS(/* css */ ` + .preset_list { + display: grid; + grid-template-columns: repeat(auto-fill, 96px); + grid-gap: 8px; + justify-content: start; + align-items: start; + margin: 0 auto; + padding: 8px; + } + + .user_preset { + display: flex; + justify-content: start; + align-items: center; + width: 100%; + padding: 8px; + position: relative; + } + + .preset_title { + font-size: 1em; + color: var(--color-text); + } + + .user_preset:hover .preset_title { + color: var(--color-accent); + } + + .preset_preview { + display: flex; + flex-direction: column; + flex-wrap: nowrap; + justify-content: center; + align-items: center; + text-align: center; + } + + .preset_buttons { + display: flex; + flex-direction: row; + align-items: center; + font-size: 0.8em; + padding: 0 4px; + } + + .preset_channel { + display: flex; + flex-direction: row; + align-items: center; + margin: 0 8px; + font-size: 0.8em; + } + + .delete_preset { + margin-left: 8px; + padding: 4px; + height: 24px; + width: 24px; + min-width: 24px; + background-color: transparent; + color: var(--color-text); + border: none; + border-radius: 100%; + position: absolute; + right: -8px; + top: 0; + filter: drop-shadow(0 0 2px var(--color-shadow)); + } + + .delete_preset:hover { + background: transparent; + color: var(--color-accent); + } + + .delete_preset .material-icons { + font-size: 0.825em; + } + + .delete_preset:hover .material-icons { + color: var(--color-accent); + }`); + + registry.brushMetalnessSlider = new NumSlider("slider_brush_metalness", { + category: "paint", + name: "Metalness", + description: "Adjust the metalness of the brush", + tool_setting: "brush_metalness", + settings: { + min: 0, + max: 1, + step: 0.01, + default: 0, + }, + condition: () => materialBrushSliderCondition(CHANNELS.metalness), + }); + + registry.brushRoughnessSlider = new NumSlider("slider_brush_roughness", { + category: "paint", + name: "Roughness", + description: "Adjust the roughness of the brush", + tool_setting: "brush_roughness", + settings: { + min: 0, + max: 1, + step: 0.01, + default: 1, + }, + condition: () => materialBrushSliderCondition(CHANNELS.roughness), + }); + + registry.brushEmissiveColor = new ColorPicker("brush_emissive_color", { + category: "paint", + name: "Emissive", + description: "Adjust the emissive color of the brush", + value: "#000000", + tool_setting: "brush_emissive", + condition: () => materialBrushSliderCondition(CHANNELS.emissive), + }); + + registry.brushHeightSlider = new NumSlider("slider_brush_height", { + category: "paint", + name: "Height", + description: "Adjust the height of the brush", + tool_setting: "brush_height", + settings: { + min: 0, + max: 1, + step: 0.01, + default: 0.5, + }, + condition: () => materialBrushSliderCondition(CHANNELS.height), + }); + + registry.materialBrushTool = new Tool("material_brush", { + name: "Material Brush", + description: "Paints across multiple texture layers", + icon: "view_in_ar", + paintTool: true, + cursor: "cell", + category: "tools", + toolbar: "brush", + condition: { + project: true, + selected: { + texture: true, + }, + modes: ["paint"], + method() { + return getSelectedTexture()?.layers_enabled ?? false; + }, + }, + allowed_view_modes: "textured", + tool_settings: { + brush_metalness: 0, + brush_roughness: 1, + brush_emissive: "#000000", + brush_height: 0.5, + }, + brush: { + blend_modes: false, + shapes: true, + size: true, + softness: true, + opacity: true, + offset_even_radius: true, + floor_coordinates: true, + changePixel( + pxX, // Pixel that is changing + pxY, + px, + alpha, + { size, softness, texture, x, y } + ) { + const mat = MaterialBrush.fromSettings(); + + const matChannels = Object.keys(mat.colors); + + const brushSize = Math.floor(size - (softness * size) / 100); + + let rgba = px; + + texture.layers.forEach((layer) => { + // @ts-expect-error Channel property is an extension of TextureLayer + if (!layer.visible || !matChannels.includes(layer.channel)) { + return; + } + + // @ts-expect-error Channel property is an extension of TextureLayer + const fill = mat.getChannel(layer.channel); + + if (!fill) { + return; + } + + const distance = Math.sqrt((x - pxX) ** 2 + (y - pxY) ** 2); + const fallOff = Math.min(1, distance / brushSize); + + // Transition colors at soft edges + if (x % brushSize <= fallOff && y % brushSize <= fallOff) { + const currentPixel = layer.ctx.getImageData(pxX, pxY, 1, 1).data; + const currentFill = new THREE.Color( + `rgb(${currentPixel[0]}, ${currentPixel[1]}, ${currentPixel[2]})` + ); + + // Set the fill color to the lerp between the current pixel and the new color + fill.lerp(currentFill, 1); + } + + layer.ctx.fillStyle = fill.getStyle(); + layer.ctx.fillRect(pxX, pxY, 1, 1); + + if (layer.selected) { + rgba = { + r: fill.r * 255, + g: fill.g * 255, + b: fill.b * 255, + a: alpha * 255, + }; + } + }); + + return rgba; + }, + onStrokeStart({ texture }) { + Undo.initEdit({ + layers: texture.layers, + }); + + return true; + }, + onStrokeEnd({ texture }) { + Undo.finishEdit("Material Brush Stroke"); + + return true; + }, + }, + onCanvasClick(data: any) { + Painter.startPaintToolCanvas(data, data.event); + }, + onSelect() { + Painter.updateNslideValues(); + applyPbrMaterial(); + }, + click() { + debounceApplyPbrMaterial(); + }, + }); + + registry.loadBrushPreset = new Action("load_brush_preset", { + icon: "stroke_full", + name: "Material Brush Presets", + description: "Load or save a brush preset", + category: "paint", + condition: { + project: true, + }, + click() { + registry.userMaterialBrushPresets = new Dialog("user_brush_presets", { + id: "user_brush_presets", + title: "Edit Material Brush", + component: userPresetsDialogComponent, + part_order: ["lines", "component", "form"], + form: { + albedo: { + type: "color", + label: "Albedo", + value: ColorPanel.get(), + toggle_enabled: true, + }, + metalness: { + type: "number", + label: "Metalness", + min: 0, + max: 1, + step: 0.01, + full_width: false, + toggle_enabled: true, + }, + roughness: { + type: "number", + label: "Roughness", + min: 0, + max: 1, + step: 0.01, + toggle_enabled: true, + full_width: false, + }, + emissive: { + type: "color", + label: "Emissive", + value: "#000000", + toggle_enabled: true, + }, + height: { + type: "number", + label: "Height", + min: 0, + max: 1, + step: 0.01, + toggle_enabled: true, + }, + }, + onConfirm(formResult) { + applyPreset({ + metalness: Number( + formResult.metalness ?? registry.brushMetalnessSlider?.get() + ), + roughness: Number( + formResult.roughness ?? registry.brushRoughnessSlider?.get() + ), + emissive: ( + formResult.emissive ?? registry.brushEmissiveColor?.get() + ).toString(), + height: Number( + formResult.height ?? registry.brushHeightSlider?.get() + ), + albedo: (formResult.albedo ?? ColorPanel.get()).toString(), + }); + }, + buttons: ["Close", "Save", "Apply"], + cancelIndex: 0, + confirmIndex: 2, + onButton(idx, event) { + registry.materialBrushTool?.select(); + + if (idx !== 1) { + return; + } + + Blockbench.textPrompt("Save Preset", "New Preset", (name) => { + if (name) { + savePreset(name); + Blockbench.showQuickMessage(`Preset "${name}" saved`, 2000); + } + }); + }, + }).show(); + }, + }); + + MenuBar.addAction(registry.materialBrushTool, "tools.0"); +}); +teardowns.push(() => { + MenuBar.removeAction("tools.material_brush"); +}); diff --git a/src/pbr_preview/src/lib/util.ts b/src/pbr_preview/src/lib/util.ts new file mode 100644 index 00000000..f2dc9794 --- /dev/null +++ b/src/pbr_preview/src/lib/util.ts @@ -0,0 +1,194 @@ +import { three as THREE } from "../deps"; + +/** + * Attempts to find the selected texture/layer using various methods + * @returns Texture | null + */ +export function getSelectedTexture(): Texture | null { + if (Texture.selected) { + return Texture.selected; + } + + if (TextureLayer.selected) { + return TextureLayer.selected.texture; + } + + if (!Project) { + return Texture.all.find((t) => t.selected) ?? Texture.getDefault(); + } + + if (Project.selected_texture) { + return Project.selected_texture; + } + + return Project.textures.find((t) => t.selected) ?? null; // Texture.getDefault(); +} + +/** + * Attempts to find the currently selected layer + * @returns TextureLayer | null + */ +export function getSelectedLayer(): TextureLayer | null { + if (TextureLayer.selected) { + return TextureLayer.selected; + } + + if (Texture.selected?.selected_layer) { + return Texture.selected.selected_layer; + } + + if ( + Project.selected_texture !== null && + Project.selected_texture?.layers_enabled === true + ) { + return ( + Project.selected_texture.layers.find((l: TextureLayer) => l.selected) ?? + Project.selected_texture.layers[0] + ); + } + + return getSelectedTexture()?.getActiveLayer() ?? null; +} + +export function getOutputBaseName() { + if (!Project) { + return pathToName(getSelectedTexture()?.name ?? "texture"); + } + + return Project.model_identifier.length > 0 + ? Project.model_identifier + : Project.getDisplayName(); +} + +export function getMaterialsFromProject() { + const materials: Record = {}; + + if (!Project) { + return materials; + } + + Project.elements.forEach((item) => { + if (!(item instanceof Cube)) { + return; + } + + Object.keys(item.faces).forEach((key) => { + const face = item.faces[key]; + const texture = face.getTexture(); + + if (!texture) { + return; + } + + const projectMaterial = Project.materials[texture.uuid]; + + if (projectMaterial.isMeshStandardMaterial) { + materials[texture.uuid] = projectMaterial; + } + }); + }); + + return materials; +} + +export function debounce(func: Function, wait: number) { + let timeout: number | undefined; + return function (this: any, ...args: any[]) { + const later = () => { + timeout = undefined; + func.apply(this, args); + }; + clearTimeout(timeout); + timeout = setTimeout(later, wait); + }; +} + +export function generatePreviewImage( + settings: + | THREE.MeshStandardMaterial + | (THREE.MeshStandardMaterialParameters & { + albedo: THREE.ColorRepresentation; + emissive: THREE.ColorRepresentation; + height?: number; + }) +): string { + const renderer = + MediaPreview.renderer ?? + new THREE.WebGLRenderer({ + alpha: true, + antialias: true, + }); + const scene = new THREE.Scene(); + const camera = new THREE.PerspectiveCamera(75, 96 / 96, 0.1, 1000); + + const ambientLight = new THREE.AmbientLight(0xffffff, 0.75); + scene.add(ambientLight); + + const pointLight = new THREE.PointLight(0xffffff, 1, 100); + pointLight.position.set(5, 5, 5); + scene.add(pointLight); + const geometry = new THREE.SphereGeometry(1, 32, 32); + + const material = + settings instanceof THREE.MeshStandardMaterial && + settings.isMeshStandardMaterial + ? settings + : new THREE.MeshStandardMaterial({ + color: settings.albedo, + metalness: settings.metalness ?? 0, + roughness: settings.roughness ?? 1, + emissive: settings.emissive, + bumpScale: settings.height ?? 0, + envMap: PreviewScene.active?.cubemap ?? null, + envMapIntensity: 0.5, + }); + + const sphere = new THREE.Mesh(geometry, material); + scene.add(sphere); + + camera.position.x = 0; + camera.position.y = 0; + camera.position.z = 2; + + renderer.setSize(96, 96); + + renderer.render(scene, camera); + + const data = renderer.domElement.toDataURL(); + + material.dispose(); + + if (!MediaPreview.renderer) { + renderer.clear(); + renderer.dispose(); + } + + return data; +} + +export function colorDataUrl(color: THREE.Color, src?: HTMLCanvasElement) { + const canvas = src ?? document.createElement("canvas"); + const ctx = canvas.getContext("2d"); + + if (!ctx) { + canvas.remove(); + return null; + } + + const width = Math.max(Project ? Project.texture_width : 16, 16); + const height = Math.max(Project ? Project.texture_height : 16, 16); + + canvas.width = width; + canvas.height = height; + + ctx.fillStyle = `rgb(${color.r * 255}, ${color.g * 255}, ${color.b * 255})`; + ctx.fillRect(0, 0, width, height); + + const data = canvas.toDataURL(); + + if (!src) { + canvas.remove(); + } + + return data; +} diff --git a/src/pbr_preview/src/types.d.ts b/src/pbr_preview/src/types.d.ts new file mode 100644 index 00000000..c5708024 --- /dev/null +++ b/src/pbr_preview/src/types.d.ts @@ -0,0 +1,79 @@ +export type Channel = + | "albedo" + | "metalness" + | "emissive" + | "roughness" + | "height" + | "normal" + | "ao"; + +export interface IChannel { + label: string; + description: string; + map: string; + id: string; + icon?: string; + default?: THREE.Color; + regex?: RegExp; +} + +export interface ILightrParams { + lightHeight?: number; + ambientLight?: [number, number, number]; + minLightIntensity?: number; + lightDiffuse?: [number, number, number]; +} + +export interface IPbrMaterials { + [materialUuid: string]: { + [channelId: string]: string; + }; +} + +export interface IBbMat { + version: number; + channels: Record; +} + +export interface IRegistry { + bakeTexturesAction: Action; + bakeTexturesDialog: Dialog; + brushEmissiveColor: ColorPicker; + brushHeightSlider: NumSlider; + brushMetalnessSlider: NumSlider; + brushRoughnessSlider: NumSlider; + channelMenu: Menu; + channelProp: Property; + createMaterialTexture: Action; + createTextureSet: Action; + decodeMer: Action; + displaySettingsPanel: Panel; + exposureSlider: NumSlider; + resetExposure: Action; + generateMer: Action; + generateNormal: Action; + generateAo: Action; + generateLabPbr: Action; + decodeLabPbr: Action; + materialBrushPanel: Panel; + materialBrushTool: Tool; + openChannelMenu: Action; + pbrMaterialsProp: Property; + projectMaterialsProp: Property; + projectPbrModeProp: Property; + setBrushMaterial: Action; + showChannelMenu: Action; + textureChannelProp: Property; + textureSetDialog: Dialog; + toggleCorrectLights: Toggle; + togglePbr: Toggle; + tonemappingSelect: BarSelect; + unassignChannel: Action; + userMaterialBrushPresets: Dialog; + exportUsdz: Action; + usdz: Codec; + bbmat: Codec; + bbMatExport: Action; + bbMatImport: Action; + [key: string]: Deletable; +} diff --git a/src/pbr_preview/tsconfig.json b/src/pbr_preview/tsconfig.json new file mode 100644 index 00000000..591a2bd3 --- /dev/null +++ b/src/pbr_preview/tsconfig.json @@ -0,0 +1,111 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + /* Projects */ + // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ + // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ + // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ + // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ + // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ + /* Language and Environment */ + "target": "ES2019" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "jsx": "preserve", /* Specify what JSX code is generated. */ + // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ + // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ + // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ + // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ + // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ + // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + /* Modules */ + "module": "ES2022" /* Specify what module code is generated. */, + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ + // "types": [], /* Specify type package names to be included without being referenced in a source file. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ + // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ + // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ + // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ + // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ + // "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ + /* JavaScript Support */ + // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + /* Emit */ + // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + // "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + "inlineSourceMap": true /* Include sourcemap files inside the emitted JavaScript. */, + // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ + // "outDir": "./", /* Specify an output folder for all emitted files. */ + // "removeComments": true, /* Disable emitting comments. */ + // "noEmit": true, /* Disable emitting files from a compilation. */ + // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ + // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ + // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ + "sourceRoot": "./src" /* Specify the root path for debuggers to find the reference source code. */, + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + "inlineSources": true /* Include source code in the sourcemaps inside the emitted JavaScript. */, + // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ + // "newLine": "crlf", /* Set the newline character for emitting files. */ + // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ + // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ + // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ + // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ + // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ + // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ + /* Interop Constraints */ + // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ + // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ + // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */, + // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ + "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, + /* Type Checking */ + "strict": true /* Enable all strict type-checking options. */, + // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ + // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ + // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ + // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ + // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ + // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ + // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ + // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ + // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ + // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ + /* Completeness */ + // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ + "lib": [ + "ES2019", + "DOM" + ], + "rootDir": "src" /* Specify the root folder within your source files. */, + "allowJs": true /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */, + "declaration": false /* Generate .d.ts files from TypeScript and JavaScript files in your project. */, + // "sourceMap": true /* Create source map files for emitted JavaScript files. */, + "outDir": "dist" /* Specify an output folder for all emitted files. */, + "noImplicitAny": true /* Enable error reporting for expressions and declarations with an implied 'any' type. */, + "skipLibCheck": true /* Skip type checking all .d.ts files. */, + "removeComments": true + } +} \ No newline at end of file