├── .gitattributes ├── .github └── workflows │ ├── release.yml │ └── test.yml ├── .gitignore ├── Assets ├── custom_properties_example.png ├── icon.png ├── lightshaft_test_ref.png ├── panel.png ├── raw-mode.png └── shaderspanel.png ├── FUNDING.yml ├── LICENSE ├── MeddleTools.code-workspace ├── MeddleTools ├── __init__.py ├── blend_import.py ├── blender_manifest.toml ├── gltf_import.py ├── node_groups.py ├── panel.py ├── shader_fix.py ├── shaders.blend └── shaders.blend1 └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | # Add a concurrency group incase a tag is created, deleted, and then recreated while a release is in progress. 4 | concurrency: 5 | group: ${{ github.workflow }}-${{ github.ref }} 6 | cancel-in-progress: true 7 | 8 | # Only run this workflow when a tag is pushed when the tag starts with "v". 9 | on: 10 | push: 11 | tags: 12 | - "*" 13 | 14 | # So we can use the GitHub API to create releases with the run token. 15 | permissions: 16 | contents: write 17 | 18 | jobs: 19 | Release: 20 | runs-on: ubuntu-latest 21 | defaults: 22 | run: 23 | shell: bash 24 | 25 | steps: 26 | - name: Checkout Repository 27 | uses: actions/checkout@v4 28 | 29 | - name: Update blender_manifest.toml 30 | working-directory: MeddleTools/ 31 | run: | 32 | sed -i "s/^version = .*/version = \"${{ github.ref_name }}\"/" blender_manifest.toml 33 | 34 | - name: Zip Blender Plugin 35 | run: | 36 | ls 37 | zip -r MeddleTools-${{ github.ref_name }}.zip MeddleTools/ 38 | 39 | - name: Create GitHub Release 40 | uses: softprops/action-gh-release@v1 41 | with: 42 | files: | 43 | MeddleTools-${{ github.ref_name }}.zip 44 | prerelease: false 45 | append_body: true # Append the release notes to the release body 46 | generate_release_notes: true # Automatically makes a release body from PRs since the last release. 47 | fail_on_unmatched_files: true # If the files arent found, fail the workflow and abort the release. 48 | 49 | - name: Upload Artifacts 50 | uses: actions/upload-artifact@v4 51 | with: 52 | name: Release Artifacts 53 | path: | 54 | MeddleTools-${{ github.ref_name }}.zip 55 | 56 | - name: Push Changes to Main 57 | working-directory: MeddleTools/ 58 | run: | 59 | git add blender_manifest.toml 60 | 61 | git config --local user.name "github-actions [bot]" 62 | git config --local user.email "github-actions@users.noreply.github.com" 63 | git commit -m "Update blender_manifest.toml for ${{ github.ref_name }}" 64 | 65 | git push origin HEAD:main 66 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | # Add a concurrency group incase a tag is created, deleted, and then recreated while a release is in progress. 4 | concurrency: 5 | group: ${{ github.workflow }}-${{ github.ref }} 6 | cancel-in-progress: true 7 | 8 | # on every commit to the main branch 9 | on: 10 | push: 11 | branches: 12 | - main 13 | 14 | # So we can use the GitHub API to create releases with the run token. 15 | permissions: 16 | contents: write 17 | 18 | jobs: 19 | Test: 20 | runs-on: ubuntu-latest 21 | defaults: 22 | run: 23 | shell: bash 24 | 25 | steps: 26 | - name: Checkout Repository 27 | uses: actions/checkout@v4 28 | 29 | - name: Update blender_manifest.toml 30 | working-directory: MeddleTools/ 31 | run: | 32 | sed -i "s/^version = .*/version = \"${{ github.ref_name }}\"/" blender_manifest.toml 33 | 34 | - name: Zip Blender Plugin 35 | run: | 36 | ls 37 | zip -r MeddleTools-${{ github.ref_name }}.zip MeddleTools/ 38 | 39 | - name: Upload Artifacts 40 | uses: actions/upload-artifact@v4 41 | with: 42 | name: Release Artifacts 43 | path: | 44 | MeddleTools-${{ github.ref_name }}.zip 45 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | -------------------------------------------------------------------------------- /Assets/custom_properties_example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PassiveModding/MeddleTools/55d10fb8c188b1ad12e9dc7d983fab2a8b3bb17f/Assets/custom_properties_example.png -------------------------------------------------------------------------------- /Assets/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PassiveModding/MeddleTools/55d10fb8c188b1ad12e9dc7d983fab2a8b3bb17f/Assets/icon.png -------------------------------------------------------------------------------- /Assets/lightshaft_test_ref.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PassiveModding/MeddleTools/55d10fb8c188b1ad12e9dc7d983fab2a8b3bb17f/Assets/lightshaft_test_ref.png -------------------------------------------------------------------------------- /Assets/panel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PassiveModding/MeddleTools/55d10fb8c188b1ad12e9dc7d983fab2a8b3bb17f/Assets/panel.png -------------------------------------------------------------------------------- /Assets/raw-mode.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PassiveModding/MeddleTools/55d10fb8c188b1ad12e9dc7d983fab2a8b3bb17f/Assets/raw-mode.png -------------------------------------------------------------------------------- /Assets/shaderspanel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PassiveModding/MeddleTools/55d10fb8c188b1ad12e9dc7d983fab2a8b3bb17f/Assets/shaderspanel.png -------------------------------------------------------------------------------- /FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [PassiveModding] 2 | ko_fi: ramen_au 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /MeddleTools.code-workspace: -------------------------------------------------------------------------------- 1 | { 2 | "folders": [ 3 | { 4 | "path": "." 5 | } 6 | ] 7 | } -------------------------------------------------------------------------------- /MeddleTools/__init__.py: -------------------------------------------------------------------------------- 1 | from . import panel 2 | 3 | def register(): 4 | panel.register() 5 | 6 | def unregister(): 7 | panel.unregister() 8 | 9 | if __name__ == "__main__": 10 | register() -------------------------------------------------------------------------------- /MeddleTools/blend_import.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | from os import path 3 | from . import node_groups 4 | 5 | 6 | 7 | def import_shaders(): 8 | blendfile = path.join(path.dirname(path.abspath(__file__)), "shaders.blend") 9 | 10 | with bpy.data.libraries.load(blendfile, link=False) as (data_from, data_to): 11 | for node_group in data_from.node_groups: 12 | if node_group in bpy.data.node_groups: 13 | print(f"Node group {node_group} already exists") 14 | continue 15 | bpy.ops.wm.append(filename=node_group, directory=blendfile + "/NodeTree/", do_reuse_local_id=True) 16 | 17 | class ImportShaders(bpy.types.Operator): 18 | 19 | bl_idname = "meddle.import_shaders" 20 | bl_label = "Import Shaders" 21 | 22 | def execute(self, context): 23 | import_shaders() 24 | 25 | return {'FINISHED'} 26 | 27 | def replace_shaders(): 28 | blendfile = path.join(path.dirname(path.abspath(__file__)), "shaders.blend") 29 | 30 | with bpy.data.libraries.load(blendfile, link=False) as (data_from, data_to): 31 | for node_group in data_from.node_groups: 32 | if node_group in bpy.data.node_groups: 33 | print(f"Node group {node_group} already exists, replacing") 34 | bpy.data.node_groups.remove(bpy.data.node_groups[node_group]) 35 | bpy.ops.wm.append(filename=node_group, directory=blendfile + "/NodeTree/", do_reuse_local_id=True) 36 | 37 | class ReplaceShaders(bpy.types.Operator): 38 | 39 | bl_idname = "meddle.replace_shaders" 40 | bl_label = "Replace Shaders" 41 | 42 | def execute(self, context): 43 | replace_shaders() 44 | 45 | return {'FINISHED'} 46 | 47 | 48 | class ShaderHelper(bpy.types.Operator): 49 | 50 | bl_idname = "meddle.shader_helper" 51 | bl_label = "map selected" 52 | 53 | def execute(self, context): 54 | 55 | if context is None: 56 | return {'CANCELLED'} 57 | 58 | if context.active_object is None or context.active_object.active_material is None or context.active_object.active_material.node_tree is None: 59 | return {'CANCELLED'} 60 | 61 | 62 | # if group is selected, get selected noded within group 63 | node_group: bpy.types.ShaderNodeGroup | None = None 64 | for n in context.active_object.active_material.node_tree.nodes: 65 | if n.select: 66 | if n.type == "GROUP" and isinstance(n, bpy.types.ShaderNodeGroup): 67 | node_group = n 68 | 69 | if node_group is None: 70 | print("No group selected") 71 | return {'CANCELLED'} 72 | 73 | selected_bsdf: bpy.types.ShaderNodeBsdfPrincipled | None = None 74 | for n in node_group.node_tree.nodes: 75 | if n.select: 76 | if n.type == "BSDF_PRINCIPLED": 77 | selected_bsdf = n 78 | 79 | if selected_bsdf is None: 80 | print("No bsdf selected") 81 | return {'CANCELLED'} 82 | 83 | group_output = None 84 | for n in node_group.node_tree.nodes: 85 | if n.type == "GROUP_OUTPUT": 86 | group_output = n 87 | 88 | # get selected bsdf inputs 89 | inputs = selected_bsdf.inputs 90 | 91 | for i in inputs: 92 | if not isinstance(i, bpy.types.NodeSocket): 93 | continue 94 | if i.hide or not i.enabled: 95 | print(f"Input {i.name} is hidden or disabled") 96 | continue 97 | 98 | print(f"Mapping {i.name}") 99 | 100 | if i.name in node_group.inputs: 101 | print(f"Input {i.name} already exists") 102 | continue 103 | 104 | mappedType = self.mapType(i.type) 105 | output = node_group.node_tree.interface.new_socket(name=i.name, socket_type=mappedType, in_out='OUTPUT') 106 | # set default value of output to value of i 107 | mapped_value = i.default_value 108 | node_group.outputs[i.name].default_value = mapped_value 109 | group_output.inputs[i.name].default_value = mapped_value 110 | output.default_value = mapped_value 111 | if i.is_linked: 112 | node_group.node_tree.links.new(i.links[0].from_socket, group_output.inputs[i.name]) 113 | 114 | 115 | return {'FINISHED'} 116 | 117 | raise Exception(f"Unknown type: {i.type}, {type(i)}") 118 | 119 | def mapType(self, type: str): 120 | # ('NodeSocketBool', 'NodeSocketVector', 'NodeSocketInt', 'NodeSocketShader', 'NodeSocketFloat', 'NodeSocketColor') 121 | if (type == "RGBA"): 122 | return "NodeSocketColor" 123 | 124 | if (type == "VALUE"): 125 | return "NodeSocketFloat" 126 | 127 | if (type == "VECTOR"): 128 | return "NodeSocketVector" 129 | 130 | error = "Unknown type: " + type 131 | print(error) 132 | raise Exception(error) -------------------------------------------------------------------------------- /MeddleTools/blender_manifest.toml: -------------------------------------------------------------------------------- 1 | schema_version = "0.0.1" 2 | 3 | id = "meddle_tools" 4 | version = "0.0.30" 5 | name = "Meddle Tools" 6 | tagline = "This is another extension" 7 | maintainer = "PassiveModding" 8 | type = "add-on" 9 | website = "https://github.com/PassiveModding/MeddleTools" 10 | 11 | tags = ["Material"] 12 | 13 | blender_version_min = "4.2.0" 14 | 15 | license = [ 16 | "SPDX:AGPL-3.0-or-later", 17 | ] 18 | 19 | [permissions] 20 | files = "Import files from meddle cache directory" -------------------------------------------------------------------------------- /MeddleTools/gltf_import.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | from os import path 3 | 4 | from . import shader_fix 5 | from . import blend_import 6 | 7 | def registerModelImportSettings(): 8 | bpy.utils.register_class(ModelImportSettings) 9 | bpy.utils.register_class(ModelImportHelpHover) 10 | bpy.types.Scene.model_import_settings = bpy.props.PointerProperty(type=ModelImportSettings) 11 | 12 | def unregisterModelImportSettings(): 13 | bpy.utils.unregister_class(ModelImportSettings) 14 | bpy.utils.unregister_class(ModelImportHelpHover) 15 | del bpy.types.Scene.model_import_settings 16 | 17 | def drawModelImportHelp(layout): 18 | box = layout.box() 19 | col = box.column() 20 | col.label(text="Import and automatically apply shaders") 21 | col.label(text="Navigate to your Meddle export folder") 22 | col.label(text="and select the .gltf or .glb file") 23 | col.separator() 24 | col.label(text="Make sure you exported in 'raw' mode") 25 | col.label(text="from the Meddle ffxiv plugin") 26 | 27 | class ModelImportHelpHover(bpy.types.Operator): 28 | bl_idname = "meddle.model_import_help_hover" 29 | bl_label = "Import Help" 30 | bl_description = "Import and automatically apply shaders. Navigate to your Meddle export folder and select the .gltf or .glb file. Make sure you exported in 'raw' mode from the Meddle ffxiv plugin." 31 | 32 | def execute(self, context): 33 | # toggle the display of the import help 34 | context.scene.model_import_settings.displayImportHelp = not context.scene.model_import_settings.displayImportHelp 35 | return {'FINISHED'} 36 | 37 | 38 | class ModelImportSettings(bpy.types.PropertyGroup): 39 | gltfImportMode: bpy.props.EnumProperty( 40 | items=[ 41 | ('BLENDER', 'Blender', 'Blender (Bone tips are placed on their local +Y axis (In gLTF space))'), 42 | ('TEMPERANCE', 'Temperance', 'Temperance (A bone with one child has its tip placed on the axis closest to its child)'), 43 | ], 44 | name='Import Mode', 45 | default='BLENDER', 46 | ) 47 | 48 | displayImportHelp: bpy.props.BoolProperty( 49 | name="Display Import Help", 50 | default=False, 51 | ) 52 | 53 | deduplicateMaterials: bpy.props.BoolProperty( 54 | name="Deduplicate Materials", 55 | default=True, 56 | ) 57 | 58 | class ModelImport(bpy.types.Operator): 59 | bl_idname = "meddle.import_gltf" 60 | bl_label = "Import Model" 61 | bl_description = "Import GLTF/GLB files exported from Meddle, automatically applying shaders" 62 | #filepath: bpy.props.StringProperty(subtype='FILE_PATH') 63 | files: bpy.props.CollectionProperty(name="File Path Collection", type=bpy.types.OperatorFileListElement) 64 | directory: bpy.props.StringProperty(subtype='DIR_PATH') 65 | filter_glob: bpy.props.StringProperty(default='*.gltf;*.glb', options={'HIDDEN'}) 66 | 67 | def invoke(self, context, event): 68 | if context is None: 69 | return {'CANCELLED'} 70 | 71 | context.window_manager.fileselect_add(self) 72 | return {'RUNNING_MODAL'} 73 | 74 | def execute(self, context): 75 | if context is None: 76 | return {'CANCELLED'} 77 | 78 | bpy.context.window.cursor_set('WAIT') 79 | try: 80 | blend_import.import_shaders() 81 | 82 | def import_gltf(filepath): 83 | print(f"GLTF Path: {filepath}") 84 | 85 | cache_dir = path.join(path.dirname(filepath), "cache") 86 | 87 | #bpy.ops.import_scene.gltf(filepath=self.filepath, disable_bone_shape=True) 88 | if context.scene.model_import_settings.gltfImportMode == 'BLENDER': 89 | bpy.ops.import_scene.gltf(filepath=filepath, disable_bone_shape=True) 90 | elif context.scene.model_import_settings.gltfImportMode == 'TEMPERANCE': 91 | bpy.ops.import_scene.gltf(filepath=filepath, bone_heuristic='TEMPERANCE') 92 | 93 | imported_meshes = [obp for obp in context.selected_objects if obp.type == 'MESH'] 94 | deduplicate: bool = context.scene.model_import_settings.deduplicateMaterials 95 | 96 | # for obj in context.selected_objects: 97 | # if "RealScale" in obj: 98 | # obj.scale = [obj["RealScale"]["X"], obj["RealScale"]["Y"], obj["RealScale"]["Z"]] 99 | 100 | for mesh in imported_meshes: 101 | if mesh is None: 102 | continue 103 | 104 | for slot in mesh.material_slots: 105 | if slot.material is not None: 106 | try: 107 | shader_fix.handleShaderFix(mesh, slot.material, deduplicate, cache_dir) 108 | except Exception as e: 109 | print(e) 110 | 111 | imported_lights = [obp for obp in context.selected_objects if obp.name.startswith("Light")] 112 | 113 | for light in imported_lights: 114 | if light is None: 115 | continue 116 | 117 | try: 118 | shader_fix.handleLightFix(light) 119 | except Exception as e: 120 | print(e) 121 | 122 | for file in self.files: 123 | filepath = path.join(self.directory, file.name) 124 | import_gltf(filepath) 125 | 126 | return {'FINISHED'} 127 | finally: 128 | bpy.context.window.cursor_set('DEFAULT') -------------------------------------------------------------------------------- /MeddleTools/node_groups.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | from os import path 3 | 4 | def setInputSafe(node, input_name: str, value): 5 | if node is None: 6 | print("Node is None") 7 | return 8 | 9 | if input_name is None: 10 | print("Input name is None") 11 | return 12 | 13 | if input_name in node.inputs: 14 | node.inputs[input_name].default_value = value 15 | else: 16 | print(f"Input {input_name} not found in node {node.name}") 17 | 18 | def linkInputSafe(material, source, groupNode, input_name): 19 | if input_name in groupNode.inputs: 20 | material.links.new(source, groupNode.inputs[input_name]) 21 | else: 22 | print(f"Input {input_name} not found in group node {groupNode.name}") 23 | 24 | class NodeGroup: 25 | def __init__(self, name: str, mapping_definitions: list): 26 | self.name = name 27 | self.mapping_definitions = mapping_definitions 28 | 29 | class PngMapping: 30 | def __init__(self, property_name: str, color_dest: str | None, alpha_dest: str | None, color_space: str, interpolation: str = 'Linear', optional: bool = False): 31 | self.property_name = property_name 32 | self.color_dest = color_dest 33 | self.alpha_dest = alpha_dest 34 | self.color_space = color_space 35 | self.interpolation = interpolation 36 | self.optional = optional 37 | 38 | def __repr__(self): 39 | return f"PngMapping({self.property_name}, {self.color_dest}, {self.alpha_dest}, {self.color_space})" 40 | 41 | def apply(self, material, groupNode, properties, directory, node_height): 42 | if self.color_dest is not None and self.color_dest not in groupNode.inputs: 43 | print(f"Property {self.color_dest} not found in group node") 44 | return node_height - 300 45 | 46 | if self.alpha_dest is not None and self.alpha_dest not in groupNode.inputs: 47 | print(f"Property {self.alpha_dest} not found in group node") 48 | return node_height - 300 49 | 50 | if self.property_name not in properties: 51 | if self.optional: 52 | return node_height 53 | print(f"Property {self.property_name} not found in material") 54 | return node_height - 300 55 | 56 | pathStr = bpy.path.native_pathsep(properties[self.property_name]) 57 | 58 | if pathStr is None or not isinstance(pathStr, str): 59 | print(f"Property {self.property_name} is not a string") 60 | return node_height - 300 61 | 62 | if pathStr.endswith('.tex'): 63 | print(f"Property {self.property_name} is a .tex file, amending to .png") 64 | pathStr = pathStr + '.png' 65 | 66 | texture = material.nodes.new('ShaderNodeTexImage') 67 | 68 | # if image exists in scene, use that instead of loading from file 69 | for img in bpy.data.images: 70 | if img.filepath == path.join(directory, pathStr) and img.colorspace_settings.name == self.color_space: 71 | texture.image = img 72 | break 73 | else: 74 | if not path.exists(path.join(directory, pathStr)): 75 | print(f"Texture {path.join(directory, pathStr)} not found") 76 | return node_height - 300 77 | texture.image = bpy.data.images.load(path.join(directory, pathStr)) 78 | texture.name = self.property_name 79 | texture.label = self.property_name 80 | texture.location = (-500, node_height) 81 | texture.image.colorspace_settings.name = self.color_space 82 | texture.interpolation = self.interpolation 83 | 84 | if self.alpha_dest is not None: 85 | #material.links.new(texture.outputs['Alpha'], groupNode.inputs[self.alpha_dest]) 86 | linkInputSafe(material, texture.outputs['Alpha'], groupNode, self.alpha_dest) 87 | if self.color_dest is not None: 88 | #material.links.new(texture.outputs['Color'], groupNode.inputs[self.color_dest]) 89 | linkInputSafe(material, texture.outputs['Color'], groupNode, self.color_dest) 90 | 91 | return node_height - 300 92 | 93 | class VertexPropertyMapping: 94 | def __init__(self, property_name: str, color_dest: str | None, alpha_dest: str | None, default_color: tuple = (0.5, 0.5, 0.5, 1.0)): 95 | self.property_name = property_name 96 | self.color_dest = color_dest 97 | self.alpha_dest = alpha_dest 98 | self.default_color = default_color 99 | 100 | def __repr__(self): 101 | return f"VertexPropertyMapping({self.property_name}, {self.color_dest})" 102 | 103 | def apply(self, material, mesh, groupNode, node_height): 104 | if mesh is None: 105 | return node_height - 300 106 | 107 | if not isinstance(mesh, bpy.types.Mesh): 108 | print(f"Object {mesh.name} is not a Mesh") 109 | return node_height - 300 110 | 111 | use_default_colors = False 112 | if self.property_name not in mesh.vertex_colors: 113 | use_default_colors = True 114 | 115 | 116 | if use_default_colors: 117 | if self.color_dest is not None: 118 | #groupNode.inputs[self.color_dest].default_value = self.default_color 119 | setInputSafe(groupNode, self.color_dest, self.default_color) 120 | if self.alpha_dest is not None: 121 | #groupNode.inputs[self.alpha_dest].default_value = self.default_color[3] 122 | setInputSafe(groupNode, self.alpha_dest, self.default_color[3]) 123 | return node_height - 300 124 | else: 125 | vertexColor = material.nodes.new('ShaderNodeVertexColor') 126 | if not isinstance(vertexColor, bpy.types.ShaderNodeVertexColor): 127 | print(f"Node {vertexColor.name} is not a ShaderNodeVertexColor") 128 | return node_height - 300 129 | 130 | vertexColor.layer_name = self.property_name 131 | vertexColor.location = (-500, node_height) 132 | 133 | if self.color_dest is not None: 134 | #material.links.new(vertexColor.outputs['Color'], groupNode.inputs[self.color_dest]) 135 | linkInputSafe(material, vertexColor.outputs['Color'], groupNode, self.color_dest) 136 | if self.alpha_dest is not None: 137 | #material.links.new(vertexColor.outputs['Alpha'], groupNode.inputs[self.alpha_dest]) 138 | linkInputSafe(material, vertexColor.outputs['Alpha'], groupNode, self.alpha_dest) 139 | return node_height - 300 140 | 141 | 142 | class FloatRgbMapping: 143 | def __init__(self, property_name: str, color_dest: str): 144 | self.property_name = property_name 145 | self.color_dest = color_dest 146 | 147 | def __repr__(self): 148 | return f"FloatRgbMapping({self.property_name}, {self.color_dest})" 149 | 150 | def apply(self, groupNode, properties): 151 | value_arr = [0.5, 0.5, 0.5, 1.0] 152 | if self.property_name in properties: 153 | value_arr = properties[self.property_name].to_list() 154 | else: 155 | print(f"Property {self.property_name} not found in material") 156 | return 157 | 158 | if len(value_arr) == 3: 159 | value_arr.append(1.0) 160 | 161 | #groupNode.inputs[self.color_dest].default_value = value_arr 162 | setInputSafe(groupNode, self.color_dest, value_arr) 163 | 164 | class FloatArrayMapping: 165 | def __init__(self, property_name: str, dest: str, destLength: int): 166 | self.property_name = property_name 167 | self.dest = dest 168 | self.destLength = destLength 169 | 170 | def __repr__(self) -> str: 171 | return f"FloatArrayMapping({self.property_name}, {self.dest})" 172 | 173 | def apply(self, groupNode, properties): 174 | if self.property_name not in properties: 175 | print(f"Property {self.property_name} not found in material") 176 | return 177 | 178 | value_arr = properties[self.property_name].to_list() 179 | 180 | # pad to destLength 181 | while len(value_arr) < self.destLength: 182 | value_arr.append(0.0) 183 | 184 | #groupNode.inputs[self.dest].default_value = value_arr 185 | setInputSafe(groupNode, self.dest, value_arr) 186 | 187 | class FloatRgbaAlphaMapping: 188 | def __init__(self, property_name: str, color_dest: str): 189 | self.property_name = property_name 190 | self.color_dest = color_dest 191 | 192 | def __repr__(self): 193 | return f"FloatRgbAlphaMapping({self.property_name}, {self.color_dest})" 194 | 195 | def apply(self, groupNode, properties): 196 | value_arr = [0.5, 0.5, 0.5, 1.0] 197 | if self.property_name in properties: 198 | value_arr = properties[self.property_name].to_list() 199 | else: 200 | print(f"Property {self.property_name} not found in material") 201 | return 202 | 203 | if len(value_arr) == 3: 204 | value_arr.append(1.0) 205 | 206 | #groupNode.inputs[self.color_dest].default_value = value_arr[3] 207 | setInputSafe(groupNode, self.color_dest, value_arr[3]) 208 | 209 | class FloatValueMapping: 210 | def __init__(self, value: float, property_dest: str): 211 | self.value = value 212 | self.property_dest = property_dest 213 | 214 | def __repr__(self): 215 | return f"FloatValueMappping({self.value}, {self.property_dest})" 216 | 217 | def apply(self, groupNode): 218 | #groupNode.inputs[self.property_dest].default_value = self.value 219 | setInputSafe(groupNode, self.property_dest, self.value) 220 | 221 | class ColorSetMapping2: 222 | def __init__(self, index_texture_name: str = 'g_SamplerIndex_PngCachePath', color_table_name: str = 'ColorTable'): 223 | self.index_texture_name = index_texture_name 224 | self.color_table_name = color_table_name 225 | 226 | def apply(self, material, groupNode, properties, directory, node_height): 227 | if self.color_table_name not in properties: 228 | print(f"Property ColorTable not found in material") 229 | return node_height - 300 230 | 231 | colorTableProp = properties[self.color_table_name] 232 | if 'ColorTable' not in colorTableProp: 233 | print(f"Property ColorTable does not contain ColorTable") 234 | return node_height - 300 235 | 236 | colorSet = colorTableProp['ColorTable'] 237 | 238 | if 'Rows' not in colorSet: 239 | print(f"Property ColorTable does not contain Rows") 240 | return node_height - 300 241 | 242 | rows = colorSet['Rows'] 243 | if len(rows) == 0: 244 | print(f"Property ColorTable contains no Rows") 245 | return node_height - 300 246 | 247 | # spawn index texture 248 | texture = material.nodes.new('ShaderNodeTexImage') 249 | pathStr = bpy.path.native_pathsep(properties[self.index_texture_name]) 250 | if pathStr is None or not isinstance(pathStr, str): 251 | return node_height - 300 252 | 253 | texture.image = bpy.data.images.load(path.join(directory, pathStr)) 254 | texture.location = (-500, node_height) 255 | texture.name = self.index_texture_name 256 | # set to closest 257 | texture.interpolation = 'Closest' 258 | texture.image.colorspace_settings.name = 'Non-Color' 259 | 260 | # separate color 261 | textureSeparate = material.nodes.new('ShaderNodeSeparateColor') 262 | textureSeparate.location = (-300, node_height) 263 | #material.links.new(texture.outputs['Color'], textureSeparate.inputs['Color']) 264 | linkInputSafe(material, texture.outputs['Color'], textureSeparate, 'Color') 265 | 266 | odds = [] 267 | evens = [] 268 | for i, row in enumerate(rows): 269 | if i % 2 == 0: 270 | evens.append(row) 271 | else: 272 | odds.append(row) 273 | 274 | pairGroups = [] 275 | pairHorizontalPos = 0 276 | pairPositions = [] 277 | for i, row in enumerate(evens): 278 | even = evens[i] 279 | odd = odds[i] 280 | 281 | # spawn colortablepair group 282 | pairNode = material.nodes.new('ShaderNodeGroup') 283 | pairNodeData = bpy.data.node_groups['meddle colortablepair'] 284 | pairNode.node_tree = pairNodeData 285 | pairGroups.append(pairNode) 286 | pairNode.location = (pairHorizontalPos, node_height) 287 | pairPositions.append(pairHorizontalPos) 288 | 289 | # link index green to id_mix 290 | #material.links.new(textureSeparate.outputs['Green'], pairNode.inputs['id_mix']) 291 | linkInputSafe(material, textureSeparate.outputs['Green'], pairNode, 'id_mix') 292 | 293 | # map inputs 294 | # 'Diffuse': {'X': 0.03692627, 'Y': 0.029800415, 'Z': 0.012779236}, 'Specular': {'X': 0.48999023, 'Y': 0.48999023, 'Z': 0.48999023}, 'Emissive': {'X': 0, 'Y': 0, 'Z': 0}, 'SheenRate': 0.099975586, 'SheenTint': 0.19995117, 'SheenAptitude': 5, 'Roughness': 0.5, 'Metalness': 0, 'Anisotropy': 0, 'SphereMask': 0, 'ShaderId': 0, 'TileIndex': 12, 'TileAlpha': 1, 'SphereIndex': 0, 'TileMatrix': {'UU': 4.3320312, 'UV': 2.5, 'VU': -50, 'VV': 86.625}} 295 | evenInputs = self.getRowInputs(even, '_0') 296 | oddInputs = self.getRowInputs(odd, '_1') 297 | 298 | tileIndex0 = even['TileIndex'] 299 | tileIndex1 = odd['TileIndex'] 300 | # lookup tile index textures under 301 | # array_textures\chara\common\texture\tile_norm_array\tile_norm_array.{index}.png 302 | # array_textures\chara\common\texture\tile_orb_array\tile_orb_array.{index}.png 303 | # create texture nodes for each if not already in nodes 304 | # link to pairNode inputs 305 | tileIndexNormPath0 = path.join(directory, f'array_textures/chara/common/texture/tile_norm_array/tile_norm_array.{tileIndex0}.png') 306 | tileIndexOrbPath0 = path.join(directory, f'array_textures/chara/common/texture/tile_orb_array/tile_orb_array.{tileIndex0}.png') 307 | tileIndexNormPath1 = path.join(directory, f'array_textures/chara/common/texture/tile_norm_array/tile_norm_array.{tileIndex1}.png') 308 | tileIndexOrbPath1 = path.join(directory, f'array_textures/chara/common/texture/tile_orb_array/tile_orb_array.{tileIndex1}.png') 309 | 310 | def loadImage(path): 311 | for img in bpy.data.images: 312 | if img.filepath == path: 313 | return img 314 | return bpy.data.images.load(path) 315 | 316 | def setupImageNode(path, location, name): 317 | img = loadImage(path) 318 | node = material.nodes.new('ShaderNodeTexImage') 319 | node.image = img 320 | node.location = location 321 | node.name = name 322 | node.image.colorspace_settings.name = 'Non-Color' 323 | return node 324 | 325 | tileIndexNorm0Node = setupImageNode(tileIndexNormPath0, (pairHorizontalPos - 300, node_height), f'tile_norm_array_{tileIndex0}') 326 | tileIndexOrb0Node = setupImageNode(tileIndexOrbPath0, (pairHorizontalPos - 300, node_height - 300), f'tile_orb_array_{tileIndex0}') 327 | tileIndexNorm1Node = setupImageNode(tileIndexNormPath1, (pairHorizontalPos - 300, node_height - 600), f'tile_norm_array_{tileIndex1}') 328 | tileIndexOrb1Node = setupImageNode(tileIndexOrbPath1, (pairHorizontalPos - 300, node_height - 900), f'tile_orb_array_{tileIndex1}') 329 | 330 | # material.links.new(tileIndexNorm0Node.outputs['Color'], pairNode.inputs['tile_norm_array_texture_0']) 331 | # material.links.new(tileIndexOrb0Node.outputs['Color'], pairNode.inputs['tile_orb_array_texture_0']) 332 | # material.links.new(tileIndexNorm1Node.outputs['Color'], pairNode.inputs['tile_norm_array_texture_1']) 333 | # material.links.new(tileIndexOrb1Node.outputs['Color'], pairNode.inputs['tile_orb_array_texture_1']) 334 | linkInputSafe(material, tileIndexNorm0Node.outputs['Color'], pairNode, 'tile_norm_array_texture_0') 335 | linkInputSafe(material, tileIndexOrb0Node.outputs['Color'], pairNode, 'tile_orb_array_texture_0') 336 | linkInputSafe(material, tileIndexNorm1Node.outputs['Color'], pairNode, 'tile_norm_array_texture_1') 337 | linkInputSafe(material, tileIndexOrb1Node.outputs['Color'], pairNode, 'tile_orb_array_texture_1') 338 | 339 | for key, value in evenInputs.items(): 340 | if key in pairNode.inputs: 341 | #pairNode.inputs[key].default_value = value 342 | setInputSafe(pairNode, key, value) 343 | for key, value in oddInputs.items(): 344 | if key in pairNode.inputs: 345 | #pairNode.inputs[key].default_value = value 346 | setInputSafe(pairNode, key, value) 347 | 348 | pairHorizontalPos += 600 349 | 350 | # map outputs of pairGroups to pairMixer i.e. pair0 -> tile_norm_array_texture_0, pair1 -> tile_norm_array_texture_1, use red channel of index texture as factor 351 | # set idx_0 to index of pair0, idx_1 to index of pair1 352 | # set id_mix to mapIndex 353 | # if id_mix == idx_0, use pair0, if id_mix == idx_1, use pair1, otherwise use pair0 354 | prev_pair = pairGroups[0] 355 | node_height -= 1500 356 | prev_idx = 0 357 | 358 | for i, pair in enumerate(pairGroups): 359 | if i == 0: 360 | continue 361 | pairMixer = material.nodes.new('ShaderNodeGroup') 362 | pairMixer.node_tree = bpy.data.node_groups['meddle colortablepair_mixer'] 363 | horizontal_pos = pairPositions[i] 364 | pairMixer.location = (horizontal_pos + 200, node_height) 365 | #material.links.new(textureSeparate.outputs['Red'], pairMixer.inputs['id_mix']) 366 | linkInputSafe(material, textureSeparate.outputs['Red'], pairMixer, 'id_mix') 367 | #pairMixer.inputs['idx_0'].default_value = prev_idx 368 | #pairMixer.inputs['idx_1'].default_value = i 369 | setInputSafe(pairMixer, 'idx_0', prev_idx) 370 | setInputSafe(pairMixer, 'idx_1', i) 371 | self.mapPairMixer(material, pairMixer, pair, prev_pair) 372 | prev_pair = pairMixer 373 | prev_idx = i 374 | 375 | # connect final mixer to 'meddle character.shpk' inputs 376 | for output in prev_pair.outputs: 377 | if output.name in groupNode.inputs: 378 | material.links.new(output, groupNode.inputs[output.name]) 379 | 380 | return node_height - 300 381 | 382 | def mapPairMixer(self, material, pairMixer, pair, prev_pair): 383 | for output in prev_pair.outputs: 384 | mappedName = f'{output.name}_0' 385 | if mappedName in pairMixer.inputs: 386 | #material.links.new(output, pairMixer.inputs[mappedName]) 387 | linkInputSafe(material, output, pairMixer, mappedName) 388 | for output in pair.outputs: 389 | mappedName = f'{output.name}_1' 390 | if mappedName in pairMixer.inputs: 391 | #material.links.new(output, pairMixer.inputs[mappedName]) 392 | linkInputSafe(material, output, pairMixer, mappedName) 393 | 394 | 395 | def fixColorArray(self, color): 396 | return (color['X'], color['Y'], color['Z'], 1.0) 397 | 398 | def getRowInputs(self, row, suffix): 399 | diffuse = self.fixColorArray(row['Diffuse']) 400 | specular = self.fixColorArray(row['Specular']) 401 | emissive = self.fixColorArray(row['Emissive']) 402 | sheenRate = row['SheenRate'] 403 | sheenTint = row['SheenTint'] 404 | sheenAptitude = row['SheenAptitude'] 405 | roughness = row['Roughness'] 406 | metalness = row['Metalness'] 407 | anisotropy = row['Anisotropy'] 408 | sphereMask = row['SphereMask'] 409 | shaderId = row['ShaderId'] 410 | tileIndex = row['TileIndex'] 411 | tileAlpha = row['TileAlpha'] 412 | sphereIndex = row['SphereIndex'] 413 | tileMatrix = row['TileMatrix'] 414 | 415 | return { 416 | f'diffuse_color{suffix}': diffuse, 417 | f'specular_color{suffix}': specular, 418 | f'emissive_color{suffix}': emissive, 419 | f'sheen_rate{suffix}': sheenRate, 420 | f'sheen_tint{suffix}': sheenTint, 421 | f'sheen_aptitude{suffix}': sheenAptitude, 422 | f'roughness{suffix}': roughness, 423 | f'metallic{suffix}': metalness, 424 | f'anisotropy{suffix}': anisotropy, 425 | f'sphere_mask{suffix}': sphereMask, 426 | f'shader_id{suffix}': shaderId, 427 | f'tile_index{suffix}': tileIndex, 428 | f'tile_alpha{suffix}': tileAlpha, 429 | f'sphere_index{suffix}': sphereIndex, 430 | f'tile_matrix{suffix}': tileMatrix 431 | } 432 | 433 | class BoolToFloatMapping: 434 | def __init__(self, property_name: str, float_dest: str): 435 | self.property_name = property_name 436 | self.float_dest = float_dest 437 | 438 | def __repr__(self): 439 | return f"BoolToFloatMapping({self.property_name}, {self.float_dest})" 440 | 441 | def apply(self, groupNode, properties): 442 | if properties[self.property_name]: 443 | setInputSafe(groupNode, self.float_dest, 1.0) 444 | else: 445 | setInputSafe(groupNode, self.float_dest, 0.0) 446 | 447 | class FloatMapping: 448 | def __init__(self, property_name: str, float_dest: str): 449 | self.property_name = property_name 450 | self.float_dest = float_dest 451 | 452 | def __repr__(self): 453 | return f"FloatMapping({self.property_name}, {self.float_dest})" 454 | 455 | def apply(self, groupNode, properties): 456 | if self.property_name not in properties: 457 | print(f"Property {self.property_name} not found in material") 458 | return 459 | 460 | def getFixedValueFloat(properties, property_name): 461 | val_arr = properties[property_name].to_list() 462 | return val_arr[0] 463 | 464 | #groupNode.inputs[self.float_dest].default_value = getFixedValueFloat(properties, self.property_name) 465 | setInputSafe(groupNode, self.float_dest, getFixedValueFloat(properties, self.property_name)) 466 | 467 | class FloatArrayIndexedValueMapping: 468 | def __init__(self, property_name: str, float_dest: str, index: int): 469 | self.property_name = property_name 470 | self.float_dest = float_dest 471 | self.index = index 472 | 473 | def __repr__(self): 474 | return f"FloatArrayIndexedValueMapping({self.property_name}, {self.float_dest}, {self.index})" 475 | 476 | def apply(self, groupNode, properties): 477 | if self.property_name not in properties: 478 | print(f"Property {self.property_name} not found in material") 479 | return 480 | 481 | def getFixedValueFloat(properties, property_name, index): 482 | val_arr = properties[property_name].to_list() 483 | return val_arr[index] 484 | 485 | #groupNode.inputs[self.float_dest].default_value = getFixedValueFloat(properties, self.property_name, self.index) 486 | setInputSafe(groupNode, self.float_dest, getFixedValueFloat(properties, self.property_name, self.index)) 487 | 488 | class UVMapping: 489 | def __init__(self, uv_map_name: str, uv_dest: str): 490 | self.uv_map_name = uv_map_name 491 | self.uv_dest = uv_dest 492 | 493 | def __repr__(self): 494 | return f"UVMapping({self.uv_map_name}, {self.uv_dest})" 495 | 496 | def apply(self, material, mesh, groupNode, node_height): 497 | if mesh is None: 498 | return node_height - 300 499 | 500 | if not isinstance(mesh, bpy.types.Mesh): 501 | print(f"Object {mesh.name} is not a Mesh") 502 | return node_height - 300 503 | 504 | if self.uv_map_name not in mesh.uv_layers: 505 | print(f"UV Map {self.uv_map_name} not found in mesh") 506 | return node_height - 300 507 | 508 | uvMap = mesh.uv_layers[self.uv_map_name] 509 | uvMapNode = material.nodes.new('ShaderNodeUVMap') 510 | uvMapNode.uv_map = self.uv_map_name 511 | uvMapNode.location = (-500, node_height) 512 | #material.links.new(uvMapNode.outputs['UV'], groupNode.inputs[self.uv_dest]) 513 | linkInputSafe(material, uvMapNode.outputs['UV'], groupNode, self.uv_dest) 514 | 515 | return node_height - 300 516 | 517 | 518 | class BgMapping: 519 | def __init__(self): 520 | pass 521 | 522 | def __repr__(self): 523 | return f"BgMapping" 524 | 525 | def apply(self, material, mesh, groupNode, properties, directory, node_height): 526 | 527 | # UVMAP -> Vector Mapping Vector 528 | # UVMAP -> Vornoi Texture Vector 529 | # Vornoi Texture Color -> Vector Mapping Rotation 530 | # Vector Mapping Vector -> Texture Vector 531 | 532 | vectorMapping = None 533 | if '0x36F72D5F' in properties and properties['0x36F72D5F'] == '0x9807BAC4': 534 | uvMapNode = material.nodes.new('ShaderNodeUVMap') 535 | uvMapNode.uv_map = 'UVMap' 536 | uvMapNode.location = (-500, node_height) 537 | 538 | voronoiTexture = material.nodes.new('ShaderNodeTexVoronoi') 539 | voronoiTexture.location = (-300, node_height) 540 | 541 | vectorMapping = material.nodes.new('ShaderNodeMapping') 542 | vectorMapping.location = (0, node_height) 543 | 544 | # material.links.new(uvMapNode.outputs['UV'], vectorMapping.inputs['Vector']) 545 | # material.links.new(uvMapNode.outputs['UV'], voronoiTexture.inputs['Vector']) 546 | # material.links.new(voronoiTexture.outputs['Color'], vectorMapping.inputs['Rotation']) 547 | linkInputSafe(material, uvMapNode.outputs['UV'], vectorMapping, 'Vector') 548 | linkInputSafe(material, uvMapNode.outputs['UV'], voronoiTexture, 'Vector') 549 | linkInputSafe(material, voronoiTexture.outputs['Color'], vectorMapping, 'Rotation') 550 | 551 | # connect 0 maps. 552 | # only connect vertex property mapping IF 1 maps exist 553 | def mapTextureIfExists(texture_name, dest_name, alpha_dest_name, colorSpace): # returns node height if exists, otherwise none 554 | if texture_name not in properties: 555 | return None 556 | 557 | pathStr = bpy.path.native_pathsep(properties[texture_name]) 558 | 559 | if properties[texture_name] is None: 560 | return None 561 | 562 | # if path contains dummy_ string, skip 563 | if 'dummy_' in properties[texture_name]: 564 | return None 565 | 566 | # if image loaded already, use that 567 | img = None 568 | for image in bpy.data.images: 569 | if image.filepath == path.join(directory, pathStr): 570 | img = image 571 | break 572 | else: 573 | img = bpy.data.images.load(path.join(directory, pathStr)) 574 | 575 | texture = material.nodes.new('ShaderNodeTexImage') 576 | texture.image = img 577 | texture.location = (-500, node_height) 578 | texture.image.colorspace_settings.name = colorSpace 579 | 580 | if alpha_dest_name is not None: 581 | material.links.new(texture.outputs['Alpha'], groupNode.inputs[alpha_dest_name]) 582 | 583 | if dest_name is not None: 584 | material.links.new(texture.outputs['Color'], groupNode.inputs[dest_name]) 585 | 586 | if vectorMapping is not None: 587 | material.links.new(vectorMapping.outputs['Vector'], texture.inputs['Vector']) 588 | 589 | return node_height - 300 590 | 591 | should_connect_vertex = False 592 | new_height = mapTextureIfExists('g_SamplerColorMap0_PngCachePath', 'g_SamplerColorMap0', 'g_SamplerColorMap0_alpha', 'sRGB') 593 | if new_height is not None: 594 | node_height = new_height 595 | 596 | new_height = mapTextureIfExists('g_SamplerNormalMap0_PngCachePath', 'g_SamplerNormalMap0', None, 'Non-Color') 597 | if new_height is not None: 598 | node_height = new_height 599 | 600 | new_height = mapTextureIfExists('g_SamplerSpecularMap0_PngCachePath', 'g_SamplerSpecularMap0', None, 'Non-Color') 601 | if new_height is not None: 602 | node_height = new_height 603 | 604 | new_height = mapTextureIfExists('g_SamplerColorMap1_PngCachePath', 'g_SamplerColorMap1', 'g_SamplerColorMap1_alpha', 'sRGB') 605 | if new_height is not None: 606 | node_height = new_height 607 | should_connect_vertex = True 608 | 609 | new_height = mapTextureIfExists('g_SamplerNormalMap1_PngCachePath', 'g_SamplerNormalMap1', None, 'Non-Color') 610 | if new_height is not None: 611 | node_height = new_height 612 | should_connect_vertex = True 613 | 614 | new_height = mapTextureIfExists('g_SamplerSpecularMap1_PngCachePath', 'g_SamplerSpecularMap1', None, 'Non-Color') 615 | if new_height is not None: 616 | node_height = new_height 617 | should_connect_vertex = True 618 | 619 | if should_connect_vertex: 620 | vertexProperty = VertexPropertyMapping('Color', None, 'vertex_alpha', (0.5, 0.5, 0.5, 0)) 621 | new_height = vertexProperty.apply(material, mesh, groupNode, node_height) 622 | if new_height is not None: 623 | node_height = new_height 624 | 625 | return node_height - 300 626 | 627 | 628 | def clearMaterialNodes(node_tree: bpy.types.ShaderNodeTree): 629 | for node in node_tree.nodes: 630 | node_tree.nodes.remove(node) 631 | 632 | def createBsdfNode(node_tree: bpy.types.ShaderNodeTree): 633 | bsdf_node: bpy.types.ShaderNodeBsdfPrincipled = node_tree.nodes.new('ShaderNodeBsdfPrincipled') # type: ignore 634 | bsdf_node.width = 300 635 | try: 636 | bsdf_node.subsurface_method = 'BURLEY' 637 | except: 638 | print("Subsurface method not found") 639 | return bsdf_node 640 | 641 | def mapBsdfOutput(mat: bpy.types.Material, material_output: bpy.types.ShaderNodeOutputMaterial, bsdf_node: bpy.types.ShaderNodeBsdfPrincipled, targetIdentifier: str): 642 | source = None 643 | for output in bsdf_node.outputs: 644 | if output.identifier == 'BSDF': 645 | source = output 646 | break 647 | 648 | if source is None: 649 | print("BSDF output not found") 650 | return 651 | 652 | target = None 653 | for input in material_output.inputs: 654 | if input.identifier == targetIdentifier: 655 | target = input 656 | break 657 | 658 | if target is None: 659 | print("Surface input not found") 660 | return 661 | 662 | if mat.node_tree is None: 663 | print("Material has no node tree") 664 | return 665 | 666 | mat.node_tree.links.new(source, target) 667 | 668 | def mapGroupOutputs(mat: bpy.types.Material, group_target: bpy.types.ShaderNode, group_node: bpy.types.ShaderNodeGroup): 669 | for output in group_node.outputs: 670 | inputMatch = None 671 | for input in group_target.inputs: 672 | if input.identifier == output.name: 673 | inputMatch = input 674 | break 675 | 676 | if inputMatch is None: 677 | for input in group_target.inputs: 678 | if input.name == output.name: 679 | inputMatch = input 680 | break 681 | 682 | if inputMatch is None: 683 | print(f"Input {output.name} not found in target node") 684 | continue 685 | 686 | if mat.node_tree is None: 687 | print("Material has no node tree") 688 | return 689 | 690 | mat.node_tree.links.new(output, inputMatch) 691 | 692 | def mapMappings(mat: bpy.types.Material, mesh, targetNode: bpy.types.ShaderNode, directory, mappings: list): 693 | node_tree = mat.node_tree 694 | if node_tree is None: 695 | print(f"Material {mat.name} has no node tree") 696 | return {'CANCELLED'} 697 | 698 | node_height = 0 699 | 700 | for mapping in mappings: 701 | if isinstance(mapping, PngMapping): 702 | node_height = mapping.apply(node_tree, targetNode, mat, directory, node_height) 703 | elif isinstance(mapping, FloatRgbMapping): 704 | mapping.apply(targetNode, mat) 705 | elif isinstance(mapping, BoolToFloatMapping): 706 | mapping.apply(targetNode, mat) 707 | elif isinstance(mapping, VertexPropertyMapping): 708 | node_height = mapping.apply(node_tree, mesh, targetNode, node_height) 709 | elif isinstance(mapping, FloatValueMapping): 710 | mapping.apply(targetNode) 711 | elif isinstance(mapping, FloatRgbaAlphaMapping): 712 | mapping.apply(targetNode, mat) 713 | elif isinstance(mapping, ColorSetMapping2): 714 | node_height = mapping.apply(node_tree, targetNode, mat, directory, node_height) 715 | elif isinstance(mapping, BgMapping): 716 | node_height = mapping.apply(node_tree, mesh, targetNode, mat, directory, node_height) 717 | elif isinstance(mapping, FloatMapping): 718 | mapping.apply(targetNode, mat) 719 | elif isinstance(mapping, UVMapping): 720 | node_height = mapping.apply(node_tree, mesh, targetNode, node_height) 721 | elif isinstance(mapping, FloatArrayIndexedValueMapping): 722 | mapping.apply(targetNode, mat) 723 | elif isinstance(mapping, FloatHdrMapping): 724 | mapping.apply(targetNode, mat) 725 | elif isinstance(mapping, FloatArrayMapping): 726 | mapping.apply(targetNode, mat) 727 | else: 728 | print(f"Unknown mapping type {type(mapping)}") 729 | 730 | def getEastModePosition(node_tree: bpy.types.ShaderNodeTree): 731 | east = 0 732 | for node in node_tree.nodes: 733 | if node.location[0] > east: 734 | east = node.location[0] 735 | 736 | return east 737 | 738 | def handleSkin(mat: bpy.types.Material, mesh, directory): 739 | group_name = "meddle skin2.shpk" 740 | base_mappings = [ 741 | PngMapping('g_SamplerDiffuse_PngCachePath', 'g_SamplerDiffuse', 'g_SamplerDiffuse_alpha', 'sRGB'), 742 | PngMapping('g_SamplerNormal_PngCachePath', 'g_SamplerNormal', 'g_SamplerNormal_alpha', 'Non-Color'), 743 | PngMapping('g_SamplerMask_PngCachePath', 'g_SamplerMask', 'g_SamplerMask_alpha', 'Non-Color'), 744 | FloatRgbMapping('SkinColor', 'Skin Color'), 745 | FloatRgbMapping('LipColor', 'Lip Color'), 746 | FloatRgbaAlphaMapping('LipColor', 'Lip Color Strength'), 747 | FloatRgbMapping('MainColor', 'Hair Color'), 748 | FloatRgbMapping('MeshColor', 'Highlights Color'), 749 | ] 750 | 751 | node_tree = mat.node_tree 752 | if node_tree is None: 753 | print(f"Material {mat.name} has no node tree") 754 | return {'CANCELLED'} 755 | 756 | if group_name not in bpy.data.node_groups: 757 | print(f"Node group {group_name} not found") 758 | return {'CANCELLED'} 759 | 760 | mappings = [FloatValueMapping(1.0, 'IS_FACE')] 761 | if 'GetMaterialValue' in mat: 762 | if mat["GetMaterialValue"] == 'GetMaterialValueBody': 763 | mappings = [] 764 | elif mat["GetMaterialValue"] == 'GetMaterialValueFace': 765 | mappings = [FloatValueMapping(1.0, 'IS_FACE')] 766 | elif mat["GetMaterialValue"] == 'GetMaterialValueBodyJJM': 767 | mappings = [FloatValueMapping(1.0, 'IS_HROTHGAR')] 768 | elif mat["GetMaterialValue"] == 'GetMaterialValueFaceEmissive': 769 | mappings = [FloatValueMapping(1.0, 'IS_EMISSIVE')] 770 | 771 | if 'CategorySkinType' in mat: 772 | if mat["CategorySkinType"] == 'Body': 773 | mappings = [] 774 | elif mat["CategorySkinType"] == 'Face': 775 | mappings = [FloatValueMapping(1.0, 'IS_FACE')] 776 | elif mat["CategorySkinType"] == 'Hrothgar': 777 | mappings = [FloatValueMapping(1.0, 'IS_HROTHGAR')] 778 | 779 | clearMaterialNodes(node_tree) 780 | 781 | material_output: bpy.types.ShaderNodeOutputMaterial = node_tree.nodes.new('ShaderNodeOutputMaterial') # type: ignore 782 | 783 | group_node: bpy.types.ShaderNodeGroup = node_tree.nodes.new('ShaderNodeGroup') # type: ignore 784 | group_node.node_tree = bpy.data.node_groups[group_name] # type: ignore 785 | group_node.width = 300 786 | 787 | bsdf_node = createBsdfNode(node_tree) 788 | mapBsdfOutput(mat, material_output, bsdf_node, 'Surface') 789 | mapGroupOutputs(mat, bsdf_node, group_node) 790 | mapMappings(mat, mesh, group_node, directory, base_mappings + mappings) 791 | east = getEastModePosition(node_tree) 792 | group_node.location = (east + 300, 300) 793 | bsdf_node.location = (east + 600, 300) 794 | material_output.location = (east + 1000, 300) 795 | return {'FINISHED'} 796 | 797 | def handleHair(mat: bpy.types.Material, mesh, directory): 798 | group_name = "meddle hair2.shpk" 799 | base_mappings = [ 800 | PngMapping('g_SamplerNormal_PngCachePath', 'g_SamplerNormal', 'g_SamplerNormal_alpha', 'Non-Color'), 801 | PngMapping('g_SamplerMask_PngCachePath', 'g_SamplerMask', 'g_SamplerMask_alpha', 'Non-Color'), 802 | FloatRgbMapping('MainColor', 'Hair Color'), 803 | FloatRgbMapping('MeshColor', 'Highlights Color'), 804 | ] 805 | 806 | node_tree = mat.node_tree 807 | if node_tree is None: 808 | print(f"Material {mat.name} has no node tree") 809 | return {'CANCELLED'} 810 | 811 | if group_name not in bpy.data.node_groups: 812 | print(f"Node group {group_name} not found") 813 | return {'CANCELLED'} 814 | 815 | mappings = [FloatValueMapping(1.0, 'IS_FACE')] 816 | if 'GetSubColor' in mat: 817 | if mat["GetSubColor"] == 'GetSubColorFace': 818 | mappings = [FloatValueMapping(1.0, 'IS_FACE')] 819 | if mat["GetSubColor"] == 'GetSubColorHair': 820 | mappings = [] 821 | 822 | if 'CategoryHairType' in mat: 823 | if mat["CategoryHairType"] == 'Face': 824 | mappings = [FloatValueMapping(1.0, 'IS_FACE')] 825 | if mat["CategoryHairType"] == 'Hair': 826 | mappings = [] 827 | 828 | clearMaterialNodes(node_tree) 829 | 830 | material_output: bpy.types.ShaderNodeOutputMaterial = node_tree.nodes.new('ShaderNodeOutputMaterial') # type: ignore 831 | 832 | group_node: bpy.types.ShaderNodeGroup = node_tree.nodes.new('ShaderNodeGroup') # type: ignore 833 | group_node.node_tree = bpy.data.node_groups[group_name] # type: ignore 834 | group_node.width = 300 835 | 836 | bsdf_node = createBsdfNode(node_tree) 837 | mapBsdfOutput(mat, material_output, bsdf_node, 'Surface') 838 | mapGroupOutputs(mat, bsdf_node, group_node) 839 | mapMappings(mat, mesh, group_node, directory, base_mappings + mappings) 840 | east = getEastModePosition(node_tree) 841 | group_node.location = (east + 300, 300) 842 | bsdf_node.location = (east + 600, 300) 843 | material_output.location = (east + 1000, 300) 844 | return {'FINISHED'} 845 | 846 | def handleIris(mat: bpy.types.Material, mesh, directory): 847 | group_name = "meddle iris2.shpk" 848 | base_mappings = [ 849 | PngMapping('g_SamplerDiffuse_PngCachePath', 'g_SamplerDiffuse', None, 'sRGB'), 850 | PngMapping('g_SamplerNormal_PngCachePath', 'g_SamplerNormal', None, 'Non-Color'), 851 | PngMapping('g_SamplerMask_PngCachePath', 'g_SamplerMask', None, 'Non-Color'), 852 | VertexPropertyMapping('Color', 'vertex_color', None, (1.0, 0, 0, 1)), 853 | FloatRgbMapping('g_WhiteEyeColor', 'g_WhiteEyeColor'), 854 | FloatRgbMapping('LeftIrisColor', 'left_iris_color'), 855 | FloatRgbMapping('RightIrisColor', 'right_iris_color'), 856 | FloatRgbaAlphaMapping('LeftIrisColor', 'left_iris_limbal_ring_intensity'), 857 | FloatRgbaAlphaMapping('RightIrisColor', 'right_iris_limbal_ring_intensity'), 858 | FloatRgbMapping('g_IrisRingColor', 'g_IrisRingColor'), 859 | FloatMapping('g_IrisRingEmissiveIntensity', 'g_IrisRingEmissiveIntensity'), 860 | UVMapping('UVMap', 'UVMap'), 861 | FloatArrayIndexedValueMapping('unk_LimbalRingRange', 'unk_LimbalRingRange_start', 0), 862 | FloatArrayIndexedValueMapping('unk_LimbalRingRange', 'unk_LimbalRingRange_end', 1), 863 | FloatArrayIndexedValueMapping('unk_LimbalRingFade', 'unk_LimbalRingFade_start', 0), 864 | FloatArrayIndexedValueMapping('unk_LimbalRingFade', 'unk_LimbalRingFade_end', 1), 865 | ] 866 | 867 | node_tree = mat.node_tree 868 | if node_tree is None: 869 | print(f"Material {mat.name} has no node tree") 870 | return {'CANCELLED'} 871 | 872 | if group_name not in bpy.data.node_groups: 873 | print(f"Node group {group_name} not found") 874 | return {'CANCELLED'} 875 | 876 | mappings = [] 877 | 878 | clearMaterialNodes(node_tree) 879 | 880 | material_output: bpy.types.ShaderNodeOutputMaterial = node_tree.nodes.new('ShaderNodeOutputMaterial') # type: ignore 881 | 882 | group_node: bpy.types.ShaderNodeGroup = node_tree.nodes.new('ShaderNodeGroup') # type: ignore 883 | 884 | group_node.node_tree = bpy.data.node_groups[group_name] # type: ignore 885 | group_node.width = 300 886 | 887 | bsdf_node = createBsdfNode(node_tree) 888 | mapBsdfOutput(mat, material_output, bsdf_node, 'Surface') 889 | mapGroupOutputs(mat, bsdf_node, group_node) 890 | mapMappings(mat, mesh, group_node, directory, base_mappings + mappings) 891 | east = getEastModePosition(node_tree) 892 | group_node.location = (east + 300, 300) 893 | bsdf_node.location = (east + 600, 300) 894 | material_output.location = (east + 1000, 300) 895 | return {'FINISHED'} 896 | 897 | def handleCharacter(mat: bpy.types.Material, mesh, directory): 898 | group_name = "meddle character.shpk" 899 | base_mappings = [ 900 | ColorSetMapping2(), 901 | PngMapping('g_SamplerDiffuse_PngCachePath', 'g_SamplerDiffuse', 'g_SamplerDiffuse_alpha', 'sRGB'), 902 | PngMapping('g_SamplerNormal_PngCachePath', 'g_SamplerNormal', None, 'Non-Color'), 903 | PngMapping('g_SamplerMask_PngCachePath', 'g_SamplerMask', None, 'Non-Color'), 904 | ] 905 | 906 | node_tree = mat.node_tree 907 | if node_tree is None: 908 | print(f"Material {mat.name} has no node tree") 909 | return {'CANCELLED'} 910 | 911 | if group_name not in bpy.data.node_groups: 912 | print(f"Node group {group_name} not found") 913 | return {'CANCELLED'} 914 | 915 | mappings = [] 916 | if 'GetValues' in mat: 917 | if mat["GetValues"] == 'GetValuesCompatibility': 918 | mappings = [FloatValueMapping(1.0, 'IS_COMPATIBILITY')] 919 | 920 | if 'GetValuesTextureType' in mat: 921 | if mat["GetValuesTextureType"] == 'Compatibility': 922 | mappings = [FloatValueMapping(1.0, 'IS_COMPATIBILITY')] 923 | 924 | clearMaterialNodes(node_tree) 925 | 926 | material_output: bpy.types.ShaderNodeOutputMaterial = node_tree.nodes.new('ShaderNodeOutputMaterial') # type: ignore 927 | 928 | group_node: bpy.types.ShaderNodeGroup = node_tree.nodes.new('ShaderNodeGroup') # type: ignore 929 | 930 | group_node.node_tree = bpy.data.node_groups[group_name] # type: ignore 931 | group_node.width = 300 932 | 933 | bsdf_node = createBsdfNode(node_tree) 934 | mapBsdfOutput(mat, material_output, bsdf_node, 'Surface') 935 | mapGroupOutputs(mat, bsdf_node, group_node) 936 | mapMappings(mat, mesh, group_node, directory, base_mappings + mappings) 937 | east = getEastModePosition(node_tree) 938 | group_node.location = (east + 300, 300) 939 | bsdf_node.location = (east + 600, 300) 940 | material_output.location = (east + 1000, 300) 941 | return {'FINISHED'} 942 | 943 | def handleCharacterSimple(mat: bpy.types.Material, mesh, directory, shader_package: str): 944 | group_name = "meddle character.shpk" 945 | is_legacy = shader_package == 'characterlegacy.shpk' 946 | is_legacy_value = 1.0 if is_legacy else 0.0 947 | is_stocking = shader_package == 'characterstockings.shpk' 948 | is_stocking_value = 1.0 if is_stocking else 0.0 949 | base_mappings = [ 950 | PngMapping('g_SamplerDiffuse_PngCachePath', 'g_SamplerDiffuse', 'g_SamplerDiffuse_alpha', 'sRGB', optional=True), 951 | PngMapping('g_SamplerNormal_PngCachePath', 'g_SamplerNormal', None, 'Non-Color'), 952 | PngMapping('g_SamplerMask_PngCachePath', 'g_SamplerMask', None, 'Non-Color'), 953 | FloatValueMapping(is_legacy_value, 'IS_LEGACY'), 954 | FloatValueMapping(is_stocking_value, 'IS_STOCKING'), 955 | ] 956 | 957 | node_tree = mat.node_tree 958 | if node_tree is None: 959 | print(f"Material {mat.name} has no node tree") 960 | return {'CANCELLED'} 961 | 962 | if group_name not in bpy.data.node_groups: 963 | print(f"Node group {group_name} not found") 964 | return {'CANCELLED'} 965 | 966 | mappings = [] 967 | if 'GetValues' in mat: 968 | if mat["GetValues"] == 'GetValuesCompatibility': 969 | mappings.extend([FloatValueMapping(1.0, 'IS_COMPATIBILITY')]) 970 | 971 | if 'GetValuesTextureType' in mat: 972 | if mat["GetValuesTextureType"] == 'Compatibility': 973 | mappings.extend([FloatValueMapping(1.0, 'IS_COMPATIBILITY')]) 974 | 975 | if 'SkinColor' in mat: 976 | mappings.extend([FloatRgbMapping('SkinColor', 'SkinColor')]) 977 | 978 | def setupRamp(node_height, material, name): 979 | ramp = None 980 | for node in material.nodes: 981 | if node.name == name: 982 | ramp = node 983 | break 984 | 985 | if ramp is None: 986 | ramp = material.nodes.new('ShaderNodeValToRGB') 987 | 988 | ramp.location = (0, node_height) 989 | ramp.name = name 990 | ramp.label = name 991 | ramp.color_ramp.interpolation = 'CONSTANT' 992 | 993 | while len(ramp.color_ramp.elements) > 1: 994 | ramp.color_ramp.elements.remove(ramp.color_ramp.elements[0]) 995 | 996 | return ramp 997 | 998 | def mapRamp(rampA, rampB, rows, rowProp, type): 999 | def getValueForType(row, type): 1000 | if type == 'XYZ': 1001 | return (row[rowProp]['X'], row[rowProp]['Y'], row[rowProp]['Z'], 1.0) 1002 | elif type == 'Float': 1003 | return (row[rowProp], row[rowProp], row[rowProp], 1.0) 1004 | elif type == 'FloatPct': 1005 | return (row[rowProp] / 100, row[rowProp] / 100, row[rowProp] / 100, 1.0) 1006 | 1007 | odds = [] 1008 | evens = [] 1009 | 1010 | for i, row in enumerate(rows): 1011 | if i % 2 == 0: 1012 | evens.append(row) 1013 | else: 1014 | odds.append(row) 1015 | 1016 | for i, row in enumerate(evens): 1017 | if rowProp not in row: 1018 | print(f"Row {i} does not have property {rowProp}") 1019 | continue 1020 | pos = i / len(evens) 1021 | if i == 0: 1022 | rampA.color_ramp.elements[0].position = pos 1023 | rampA.color_ramp.elements[0].color = getValueForType(row, type) 1024 | else: 1025 | elementA = rampA.color_ramp.elements.new(pos) 1026 | elementA.color = getValueForType(row, type) 1027 | 1028 | for i, row in enumerate(odds): 1029 | if rowProp not in row: 1030 | print(f"Row {i} does not have property {rowProp}") 1031 | continue 1032 | pos = i / len(odds) 1033 | if i == 0: 1034 | rampB.color_ramp.elements[0].position = pos 1035 | rampB.color_ramp.elements[0].color = getValueForType(row, type) 1036 | else: 1037 | element = rampB.color_ramp.elements.new(pos) 1038 | element.color = getValueForType(row, type) 1039 | 1040 | if 'ColorTable' not in mat: 1041 | print("ColorTable prop not found") 1042 | return {'CANCELLED'} 1043 | 1044 | colorSet = mat['ColorTable'] 1045 | if 'ColorTable' not in colorSet: 1046 | print("ColorTable not found in colorset") 1047 | return {'CANCELLED'} 1048 | 1049 | colorTable = colorSet['ColorTable'] 1050 | 1051 | if 'Rows' not in colorTable: 1052 | print("Rows not found in colorTable") 1053 | return {'CANCELLED'} 1054 | 1055 | rows = colorTable['Rows'] 1056 | 1057 | if len(rows) == 0: 1058 | print("No rows found in colorTable") 1059 | return {'CANCELLED'} 1060 | 1061 | clearMaterialNodes(node_tree) 1062 | indexMapping = PngMapping('g_SamplerIndex_PngCachePath', None, None, 'Non-Color', 'Closest') 1063 | indexMapping.apply(node_tree, None, mat, directory, 300) 1064 | 1065 | indexTexture = None 1066 | for node in node_tree.nodes: 1067 | if node.name == 'g_SamplerIndex_PngCachePath': 1068 | indexTexture = node 1069 | break 1070 | 1071 | if indexTexture is None: 1072 | print("Index texture not found") 1073 | return {'CANCELLED'} 1074 | 1075 | material_output: bpy.types.ShaderNodeOutputMaterial = node_tree.nodes.new('ShaderNodeOutputMaterial') # type: ignore 1076 | group_node: bpy.types.ShaderNodeGroup = node_tree.nodes.new('ShaderNodeGroup') # type: ignore 1077 | group_node.node_tree = bpy.data.node_groups[group_name] # type: ignore 1078 | group_node.width = 300 1079 | bsdf_node = createBsdfNode(node_tree) 1080 | mapBsdfOutput(mat, material_output, bsdf_node, 'Surface') 1081 | mapGroupOutputs(mat, bsdf_node, group_node) 1082 | mapMappings(mat, mesh, group_node, directory, base_mappings + mappings) 1083 | 1084 | colorRampA = setupRamp(0, node_tree, 'ColorRampA') 1085 | colorRampB = setupRamp(-300, node_tree, 'ColorRampB') 1086 | specularRampA = setupRamp(-600, node_tree, 'SpecularRampA') 1087 | specularRampB = setupRamp(-900, node_tree, 'SpecularRampB') 1088 | emissionRampA = setupRamp(-1200, node_tree, 'EmissionRampA') 1089 | emissionRampB = setupRamp(-1500, node_tree, 'EmissionRampB') 1090 | metalnessRampA = setupRamp(-1800, node_tree, 'MetalnessRampA') 1091 | metalnessRampB = setupRamp(-2100, node_tree, 'MetalnessRampB') 1092 | roughnessRampA = setupRamp(-2400, node_tree, 'RoughnessRampA') 1093 | roughnessRampB = setupRamp(-2700, node_tree, 'RoughnessRampB') 1094 | glossRampA = setupRamp(-3000, node_tree, 'GlossRampA') 1095 | glossRampB = setupRamp(-3300, node_tree, 'GlossRampB') 1096 | specStrengthRampA = setupRamp(-3600, node_tree, 'SpecStrengthRampA') 1097 | specStrengthRampB = setupRamp(-3900, node_tree, 'SpecStrengthRampB') 1098 | sheenRateRampA = setupRamp(-4200, node_tree, 'SheenRateRampA') 1099 | sheenRateRampB = setupRamp(-4500, node_tree, 'SheenRateRampB') 1100 | sheenTintRampA = setupRamp(-4800, node_tree, 'SheenTintRampA') 1101 | sheenTintRampB = setupRamp(-5100, node_tree, 'SheenTintRampB') 1102 | sheenAptitudeRampA = setupRamp(-5400, node_tree, 'SheenAptitudeRampA') 1103 | sheenAptitudeRampB = setupRamp(-5700, node_tree, 'SheenAptitudeRampB') 1104 | anisotropyRampA = setupRamp(-6000, node_tree, 'AnisotropyRampA') 1105 | anisotropyRampB = setupRamp(-6300, node_tree, 'AnisotropyRampB') 1106 | 1107 | mapRamp(colorRampA, colorRampB, rows, 'Diffuse', 'XYZ') 1108 | mapRamp(specularRampA, specularRampB, rows, 'Specular', 'XYZ') 1109 | mapRamp(emissionRampA, emissionRampB, rows, 'Emissive', 'XYZ') 1110 | mapRamp(metalnessRampA, metalnessRampB, rows, 'Metalness', 'Float') 1111 | mapRamp(roughnessRampA, roughnessRampB, rows, 'Roughness', 'Float') 1112 | mapRamp(glossRampA, glossRampB, rows, 'GlossStrength', 'FloatPct') 1113 | mapRamp(specStrengthRampA, specStrengthRampB, rows, 'SpecularStrength', 'Float') 1114 | mapRamp(sheenRateRampA, sheenRateRampB, rows, 'SheenRate', 'Float') 1115 | mapRamp(sheenTintRampA, sheenTintRampB, rows, 'SheenTint', 'Float') 1116 | mapRamp(sheenAptitudeRampA, sheenAptitudeRampB, rows, 'SheenAptitude', 'Float') 1117 | mapRamp(anisotropyRampA, anisotropyRampB, rows, 'Anisotropy', 'Float') 1118 | 1119 | textureSeparate: bpy.types.ShaderNodeSeparateColor = node_tree.nodes.new('ShaderNodeSeparateColor') # type: ignore 1120 | textureSeparate.location = (-200, -300) 1121 | node_tree.links.new(indexTexture.outputs['Color'], textureSeparate.inputs['Color']) 1122 | 1123 | allRamps = [ 1124 | colorRampA, colorRampB, 1125 | specularRampA, specularRampB, 1126 | emissionRampA, emissionRampB, 1127 | metalnessRampA, metalnessRampB, 1128 | roughnessRampA, roughnessRampB, 1129 | glossRampA, glossRampB, 1130 | specStrengthRampA, specStrengthRampB, 1131 | sheenRateRampA, sheenRateRampB, 1132 | sheenTintRampA, sheenTintRampB, 1133 | sheenAptitudeRampA, sheenAptitudeRampB, 1134 | anisotropyRampA, anisotropyRampB 1135 | ] 1136 | 1137 | for ramp in allRamps: 1138 | node_tree.links.new(textureSeparate.outputs['Red'], ramp.inputs['Fac']) 1139 | 1140 | pair_node: bpy.types.ShaderNodeGroup = node_tree.nodes.new('ShaderNodeGroup') # type: ignore 1141 | pair_node.node_tree = bpy.data.node_groups["meddle colortablepair"] # type: ignore 1142 | pair_node.width = 300 1143 | 1144 | node_tree.links.new(textureSeparate.outputs['Green'], pair_node.inputs['id_mix']) 1145 | node_tree.links.new(colorRampA.outputs['Color'], pair_node.inputs['diffuse_color_0']) 1146 | node_tree.links.new(colorRampB.outputs['Color'], pair_node.inputs['diffuse_color_1']) 1147 | node_tree.links.new(specularRampA.outputs['Color'], pair_node.inputs['specular_color_0']) 1148 | node_tree.links.new(specularRampB.outputs['Color'], pair_node.inputs['specular_color_1']) 1149 | node_tree.links.new(emissionRampA.outputs['Color'], pair_node.inputs['emissive_color_0']) 1150 | node_tree.links.new(emissionRampB.outputs['Color'], pair_node.inputs['emissive_color_1']) 1151 | node_tree.links.new(glossRampA.outputs['Color'], pair_node.inputs['gloss_strength_0']) 1152 | node_tree.links.new(glossRampB.outputs['Color'], pair_node.inputs['gloss_strength_1']) 1153 | node_tree.links.new(specStrengthRampA.outputs['Color'], pair_node.inputs['specular_strength_0']) 1154 | node_tree.links.new(specStrengthRampB.outputs['Color'], pair_node.inputs['specular_strength_1']) 1155 | node_tree.links.new(metalnessRampA.outputs['Color'], pair_node.inputs['metallic_0']) 1156 | node_tree.links.new(metalnessRampB.outputs['Color'], pair_node.inputs['metallic_1']) 1157 | node_tree.links.new(roughnessRampA.outputs['Color'], pair_node.inputs['roughness_0']) 1158 | node_tree.links.new(roughnessRampB.outputs['Color'], pair_node.inputs['roughness_1']) 1159 | node_tree.links.new(sheenRateRampA.outputs['Color'], pair_node.inputs['sheen_rate_0']) 1160 | node_tree.links.new(sheenRateRampB.outputs['Color'], pair_node.inputs['sheen_rate_1']) 1161 | node_tree.links.new(sheenTintRampA.outputs['Color'], pair_node.inputs['sheen_tint_0']) 1162 | node_tree.links.new(sheenTintRampB.outputs['Color'], pair_node.inputs['sheen_tint_1']) 1163 | node_tree.links.new(sheenAptitudeRampA.outputs['Color'], pair_node.inputs['sheen_apt_0']) 1164 | node_tree.links.new(sheenAptitudeRampB.outputs['Color'], pair_node.inputs['sheen_apt_1']) 1165 | node_tree.links.new(anisotropyRampA.outputs['Color'], pair_node.inputs['anisotropy_0']) 1166 | node_tree.links.new(anisotropyRampB.outputs['Color'], pair_node.inputs['anisotropy_1']) 1167 | mapGroupOutputs(mat, group_node, pair_node) 1168 | 1169 | east = getEastModePosition(node_tree) 1170 | pair_node.location = (east + 300, 300) 1171 | group_node.location = (east + 700, 300) 1172 | bsdf_node.location = (east + 1000, 300) 1173 | material_output.location = (east + 1300, 300) 1174 | 1175 | return {'FINISHED'} 1176 | 1177 | 1178 | 1179 | class FloatHdrMapping: 1180 | def __init__(self, identifier: str, destRgb: str, destMagnitude: str): 1181 | self.identifier = identifier 1182 | self.destRgb = destRgb 1183 | self.destMagnitude = destMagnitude 1184 | 1185 | def apply(self, targetNode: bpy.types.ShaderNode, mat: bpy.types.Material): 1186 | if self.identifier not in mat: 1187 | return 1188 | 1189 | if targetNode is None: 1190 | return 1191 | 1192 | value = mat[self.identifier] 1193 | magnitude = 0 1194 | for val in value: 1195 | if val > magnitude: 1196 | magnitude = val 1197 | 1198 | if magnitude == 0: 1199 | return 1200 | 1201 | adjustedValue = [val / magnitude for val in value] 1202 | 1203 | if len(adjustedValue) == 3: 1204 | adjustedValue.append(1.0) 1205 | 1206 | #targetNode.inputs[self.destRgb].default_value = adjustedValue 1207 | #targetNode.inputs[self.destMagnitude].default_value = magnitude 1208 | setInputSafe(targetNode, self.destRgb, adjustedValue) 1209 | setInputSafe(targetNode, self.destMagnitude, magnitude) 1210 | 1211 | def handleBg(mat: bpy.types.Material, mesh, directory): 1212 | group_name = "meddle bg.shpk" 1213 | base_mappings = [ 1214 | BgMapping(), 1215 | FloatRgbMapping('g_DiffuseColor', 'g_DiffuseColor'), 1216 | FloatHdrMapping('g_EmissiveColor', 'g_EmissiveColor', 'g_EmissiveColor_magnitude'), 1217 | ] 1218 | 1219 | node_tree = mat.node_tree 1220 | if node_tree is None: 1221 | print(f"Material {mat.name} has no node tree") 1222 | return {'CANCELLED'} 1223 | 1224 | if group_name not in bpy.data.node_groups: 1225 | print(f"Node group {group_name} not found") 1226 | return {'CANCELLED'} 1227 | 1228 | mappings = [] 1229 | 1230 | clearMaterialNodes(node_tree) 1231 | 1232 | material_output: bpy.types.ShaderNodeOutputMaterial = node_tree.nodes.new('ShaderNodeOutputMaterial') # type: ignore 1233 | 1234 | group_node: bpy.types.ShaderNodeGroup = node_tree.nodes.new('ShaderNodeGroup') # type: ignore 1235 | 1236 | group_node.node_tree = bpy.data.node_groups[group_name] # type: ignore 1237 | group_node.width = 300 1238 | 1239 | bsdf_node = createBsdfNode(node_tree) 1240 | mapBsdfOutput(mat, material_output, bsdf_node, 'Surface') 1241 | mapGroupOutputs(mat, bsdf_node, group_node) 1242 | mapMappings(mat, mesh, group_node, directory, base_mappings + mappings) 1243 | east = getEastModePosition(node_tree) 1244 | group_node.location = (east + 300, 300) 1245 | bsdf_node.location = (east + 600, 300) 1246 | material_output.location = (east + 1000, 300) 1247 | return {'FINISHED'} 1248 | 1249 | def handleCharacterTattoo(mat: bpy.types.Material, mesh, directory): 1250 | group_name = "meddle charactertattoo.shpk" 1251 | base_mappings = [ 1252 | PngMapping('g_SamplerNormal_PngCachePath', 'g_SamplerNormal', 'g_SamplerNormal_alpha', 'Non-Color'), 1253 | FloatRgbMapping('OptionColor', 'OptionColor'), 1254 | # DecalColor mapping to g_DecalColor <- not implemented 1255 | ] 1256 | 1257 | node_tree = mat.node_tree 1258 | if node_tree is None: 1259 | print(f"Material {mat.name} has no node tree") 1260 | return {'CANCELLED'} 1261 | 1262 | if group_name not in bpy.data.node_groups: 1263 | print(f"Node group {group_name} not found") 1264 | return {'CANCELLED'} 1265 | 1266 | mappings = [] 1267 | 1268 | clearMaterialNodes(node_tree) 1269 | 1270 | material_output: bpy.types.ShaderNodeOutputMaterial = node_tree.nodes.new('ShaderNodeOutputMaterial') # type: ignore 1271 | 1272 | group_node: bpy.types.ShaderNodeGroup = node_tree.nodes.new('ShaderNodeGroup') # type: ignore 1273 | 1274 | group_node.node_tree = bpy.data.node_groups[group_name] # type: ignore 1275 | group_node.width = 300 1276 | 1277 | bsdf_node = createBsdfNode(node_tree) 1278 | mapBsdfOutput(mat, material_output, bsdf_node, 'Surface') 1279 | mapGroupOutputs(mat, bsdf_node, group_node) 1280 | mapMappings(mat, mesh, group_node, directory, base_mappings + mappings) 1281 | east = getEastModePosition(node_tree) 1282 | group_node.location = (east + 300, 300) 1283 | bsdf_node.location = (east + 600, 300) 1284 | material_output.location = (east + 1000, 300) 1285 | return {'FINISHED'} 1286 | 1287 | def handleCharacterOcclusion(mat: bpy.types.Material, mesh, directory): 1288 | group_name = "meddle characterocclusion.shpk" 1289 | base_mappings = [ 1290 | PngMapping('g_SamplerNormal_PngCachePath', 'g_SamplerNormal', 'g_SamplerNormal_alpha', 'Non-Color'), 1291 | ] 1292 | 1293 | node_tree = mat.node_tree 1294 | if node_tree is None: 1295 | print(f"Material {mat.name} has no node tree") 1296 | return {'CANCELLED'} 1297 | 1298 | if group_name not in bpy.data.node_groups: 1299 | print(f"Node group {group_name} not found") 1300 | return {'CANCELLED'} 1301 | 1302 | mappings = [] 1303 | 1304 | clearMaterialNodes(node_tree) 1305 | 1306 | material_output: bpy.types.ShaderNodeOutputMaterial = node_tree.nodes.new('ShaderNodeOutputMaterial') # type: ignore 1307 | 1308 | group_node: bpy.types.ShaderNodeGroup = node_tree.nodes.new('ShaderNodeGroup') # type: ignore 1309 | 1310 | group_node.node_tree = bpy.data.node_groups[group_name] # type: ignore 1311 | group_node.width = 300 1312 | 1313 | bsdf_node = createBsdfNode(node_tree) 1314 | mapBsdfOutput(mat, material_output, bsdf_node, 'Surface') 1315 | mapGroupOutputs(mat, bsdf_node, group_node) 1316 | mapMappings(mat, mesh, group_node, directory, base_mappings + mappings) 1317 | east = getEastModePosition(node_tree) 1318 | group_node.location = (east + 300, 300) 1319 | bsdf_node.location = (east + 600, 300) 1320 | material_output.location = (east + 1000, 300) 1321 | return {'FINISHED'} 1322 | 1323 | def handleBgProp(mat: bpy.types.Material, mesh, directory): 1324 | group_name = "meddle bgprop.shpk" 1325 | base_mappings = [ 1326 | PngMapping('g_SamplerColorMap0', 'g_SamplerColorMap0', 'g_SamplerColorMap0_alpha', 'sRGB'), 1327 | PngMapping('g_SamplerNormalMap0', 'g_SamplerNormalMap0', None, 'Non-Color'), 1328 | PngMapping('g_SamplerSpecularMap0', 'g_SamplerSpecularMap0', None, 'Non-Color'), 1329 | ] 1330 | 1331 | node_tree = mat.node_tree 1332 | if node_tree is None: 1333 | print(f"Material {mat.name} has no node tree") 1334 | return {'CANCELLED'} 1335 | 1336 | if group_name not in bpy.data.node_groups: 1337 | print(f"Node group {group_name} not found") 1338 | return {'CANCELLED'} 1339 | 1340 | mappings = [] 1341 | 1342 | clearMaterialNodes(node_tree) 1343 | 1344 | material_output: bpy.types.ShaderNodeOutputMaterial = node_tree.nodes.new('ShaderNodeOutputMaterial') # type: ignore 1345 | 1346 | group_node: bpy.types.ShaderNodeGroup = node_tree.nodes.new('ShaderNodeGroup') # type: ignore 1347 | 1348 | group_node.node_tree = bpy.data.node_groups[group_name] # type: ignore 1349 | group_node.width = 300 1350 | 1351 | bsdf_node = createBsdfNode(node_tree) 1352 | mapBsdfOutput(mat, material_output, bsdf_node, 'Surface') 1353 | mapGroupOutputs(mat, bsdf_node, group_node) 1354 | mapMappings(mat, mesh, group_node, directory, base_mappings + mappings) 1355 | east = getEastModePosition(node_tree) 1356 | group_node.location = (east + 300, 300) 1357 | bsdf_node.location = (east + 600, 300) 1358 | material_output.location = (east + 1000, 300) 1359 | return {'FINISHED'} 1360 | 1361 | def handleBgColorChange(mat: bpy.types.Material, mesh, directory): 1362 | group_name = "meddle bgcolorchange.shpk" 1363 | base_mappings = [ 1364 | PngMapping('g_SamplerColorMap0', 'g_SamplerColorMap0', 'g_SamplerColorMap0_alpha', 'sRGB'), 1365 | PngMapping('g_SamplerNormalMap0', 'g_SamplerNormalMap0', 'g_SamplerNormalMap0_alpha', 'Non-Color'), 1366 | PngMapping('g_SamplerSpecularMap0', 'g_SamplerSpecularMap0', None, 'Non-Color'), 1367 | FloatRgbMapping('StainColor', 'StainColor'), 1368 | FloatRgbMapping('g_DiffuseColor', 'g_DiffuseColor'), 1369 | ] 1370 | 1371 | node_tree = mat.node_tree 1372 | if node_tree is None: 1373 | print(f"Material {mat.name} has no node tree") 1374 | return {'CANCELLED'} 1375 | 1376 | if group_name not in bpy.data.node_groups: 1377 | print(f"Node group {group_name} not found") 1378 | return {'CANCELLED'} 1379 | 1380 | mappings = [] 1381 | 1382 | clearMaterialNodes(node_tree) 1383 | 1384 | material_output: bpy.types.ShaderNodeOutputMaterial = node_tree.nodes.new('ShaderNodeOutputMaterial') # type: ignore 1385 | 1386 | group_node: bpy.types.ShaderNodeGroup = node_tree.nodes.new('ShaderNodeGroup') # type: ignore 1387 | 1388 | group_node.node_tree = bpy.data.node_groups[group_name] # type: ignore 1389 | group_node.width = 300 1390 | 1391 | bsdf_node = createBsdfNode(node_tree) 1392 | mapBsdfOutput(mat, material_output, bsdf_node, 'Surface') 1393 | mapGroupOutputs(mat, bsdf_node, group_node) 1394 | mapMappings(mat, mesh, group_node, directory, base_mappings + mappings) 1395 | east = getEastModePosition(node_tree) 1396 | group_node.location = (east + 300, 300) 1397 | bsdf_node.location = (east + 600, 300) 1398 | material_output.location = (east + 1000, 300) 1399 | return {'FINISHED'} 1400 | 1401 | def handleLightShaft(mat: bpy.types.Material, mesh, directory): 1402 | group_name = "meddle lightshaft.shpk" 1403 | base_mappings = [ 1404 | PngMapping('g_Sampler0_PngCachePath', 'g_Sampler0', 'g_Sampler0_alpha', 'sRGB'), 1405 | PngMapping('g_Sampler1_PngCachePath', 'g_Sampler1', 'g_Sampler1_alpha', 'sRGB'), 1406 | FloatRgbMapping('g_Color', 'g_Color'), 1407 | VertexPropertyMapping('Color', 'vertex_color', 'vertex_alpha'), 1408 | FloatArrayMapping('g_TexAnim', 'g_TexAnim', 3), 1409 | FloatArrayMapping('g_TexU', 'g_TexU', 3), 1410 | FloatArrayMapping('g_TexV', 'g_TexV', 3), 1411 | FloatArrayMapping('g_Ray', 'g_Ray', 3), 1412 | ] 1413 | 1414 | node_tree = mat.node_tree 1415 | if node_tree is None: 1416 | print(f"Material {mat.name} has no node tree") 1417 | return {'CANCELLED'} 1418 | 1419 | if group_name not in bpy.data.node_groups: 1420 | print(f"Node group {group_name} not found") 1421 | return {'CANCELLED'} 1422 | 1423 | mappings = [] 1424 | 1425 | clearMaterialNodes(node_tree) 1426 | 1427 | material_output: bpy.types.ShaderNodeOutputMaterial = node_tree.nodes.new('ShaderNodeOutputMaterial') # type: ignore 1428 | 1429 | group_node: bpy.types.ShaderNodeGroup = node_tree.nodes.new('ShaderNodeGroup') # type: ignore 1430 | 1431 | group_node.node_tree = bpy.data.node_groups[group_name] # type: ignore 1432 | group_node.width = 300 1433 | 1434 | bsdf_node = createBsdfNode(node_tree) 1435 | mapBsdfOutput(mat, material_output, bsdf_node, 'Surface') 1436 | mapGroupOutputs(mat, bsdf_node, group_node) 1437 | mapMappings(mat, mesh, group_node, directory, base_mappings + mappings) 1438 | east = getEastModePosition(node_tree) 1439 | group_node.location = (east + 300, 300) 1440 | bsdf_node.location = (east + 600, 300) 1441 | material_output.location = (east + 1000, 300) 1442 | return {'FINISHED'} 1443 | 1444 | def handleCrystal(mat: bpy.types.Material, mesh, directory): 1445 | group_name = "meddle crystal.shpk" 1446 | base_mappings = [ 1447 | PngMapping('g_SamplerColorMap0', 'g_SamplerColorMap0', None, 'sRGB'), 1448 | PngMapping('g_SamplerEnvMap', 'g_SamplerEnvMap', None, 'Non-Color'), 1449 | PngMapping('g_SamplerNormalMap0', 'g_SamplerNormalMap0', None, 'Non-Color'), 1450 | PngMapping('g_SamplerSpecularMap0', 'g_SamplerSpecularMap0', None, 'Non-Color'), 1451 | ] 1452 | 1453 | node_tree = mat.node_tree 1454 | if node_tree is None: 1455 | print(f"Material {mat.name} has no node tree") 1456 | return {'CANCELLED'} 1457 | 1458 | if group_name not in bpy.data.node_groups: 1459 | print(f"Node group {group_name} not found") 1460 | return {'CANCELLED'} 1461 | 1462 | mappings = [] 1463 | 1464 | clearMaterialNodes(node_tree) 1465 | 1466 | material_output: bpy.types.ShaderNodeOutputMaterial = node_tree.nodes.new('ShaderNodeOutputMaterial') # type: ignore 1467 | 1468 | group_node: bpy.types.ShaderNodeGroup = node_tree.nodes.new('ShaderNodeGroup') # type: ignore 1469 | 1470 | group_node.node_tree = bpy.data.node_groups[group_name] # type: ignore 1471 | group_node.width = 300 1472 | 1473 | bsdf_node = createBsdfNode(node_tree) 1474 | mapBsdfOutput(mat, material_output, bsdf_node, 'Surface') 1475 | mapGroupOutputs(mat, bsdf_node, group_node) 1476 | mapMappings(mat, mesh, group_node, directory, base_mappings + mappings) 1477 | east = getEastModePosition(node_tree) 1478 | group_node.location = (east + 300, 300) 1479 | bsdf_node.location = (east + 600, 300) 1480 | material_output.location = (east + 1000, 300) 1481 | return {'FINISHED'} 1482 | 1483 | def handleWater(mat: bpy.types.Material, mesh, directory): 1484 | group_name = "meddle water.shpk" 1485 | base_mappings = [ 1486 | FloatRgbMapping('0xD315E728', 'unk_WaterColor'), 1487 | FloatRgbMapping('unk_WaterColor', 'unk_WaterColor'), 1488 | 1489 | FloatRgbMapping('g_RefractionColor', 'g_RefractionColor'), 1490 | FloatRgbMapping('g_WhitecapColor', 'g_WhitecapColor'), 1491 | FloatMapping('g_Transparency', 'g_Transparency'), 1492 | PngMapping('g_SamplerWaveMap_PngCachePath', 'g_SamplerWaveMap', 'g_SamplerWaveMap_alpha', 'Non-Color'), # water river 1493 | PngMapping('g_SamplerWaveMap1_PngCachePath', 'g_SamplerWaveMap1', 'g_SamplerWaveMap1_alpha', 'Non-Color'), # water only 1494 | PngMapping('g_SamplerWhitecapMap_PngCachePath', 'g_SamplerWhitecapMap', 'g_SamplerWhitecapMap_alpha', 'Non-Color'), # water river 1495 | ] 1496 | 1497 | node_tree = mat.node_tree 1498 | if node_tree is None: 1499 | print(f"Material {mat.name} has no node tree") 1500 | return {'CANCELLED'} 1501 | 1502 | if group_name not in bpy.data.node_groups: 1503 | print(f"Node group {group_name} not found") 1504 | return {'CANCELLED'} 1505 | 1506 | mappings = [] 1507 | 1508 | clearMaterialNodes(node_tree) 1509 | 1510 | material_output: bpy.types.ShaderNodeOutputMaterial = node_tree.nodes.new('ShaderNodeOutputMaterial') # type: ignore 1511 | 1512 | group_node: bpy.types.ShaderNodeGroup = node_tree.nodes.new('ShaderNodeGroup') # type: ignore 1513 | 1514 | group_node.node_tree = bpy.data.node_groups[group_name] # type: ignore 1515 | group_node.width = 300 1516 | 1517 | bsdf_node = createBsdfNode(node_tree) 1518 | mapBsdfOutput(mat, material_output, bsdf_node, 'Surface') 1519 | mapGroupOutputs(mat, bsdf_node, group_node) 1520 | mapMappings(mat, mesh, group_node, directory, base_mappings + mappings) 1521 | east = getEastModePosition(node_tree) 1522 | group_node.location = (east + 300, 300) 1523 | bsdf_node.location = (east + 600, 300) 1524 | material_output.location = (east + 1000, 300) 1525 | 1526 | return {'FINISHED'} 1527 | 1528 | def spawnFallbackTextures(mat: bpy.types.Material, directory): 1529 | # check props for _PngCachePath, spawn image texture nodes for each 1530 | node_tree = mat.node_tree 1531 | if node_tree is None: 1532 | print(f"Material {mat.name} has no node tree") 1533 | return {'CANCELLED'} 1534 | 1535 | clearMaterialNodes(node_tree) 1536 | node_height = 0 1537 | 1538 | try: 1539 | for prop in mat.keys(): 1540 | if prop.endswith('_PngCachePath'): 1541 | print(f"Spawning texture node for {prop}") 1542 | mapping = PngMapping(prop, None, None, 'sRGB', optional=True) 1543 | node_height = mapping.apply(node_tree, None, mat, directory, node_height) 1544 | 1545 | except Exception as e: 1546 | print(f"Error spawning texture nodes: {e}") 1547 | return {'CANCELLED'} 1548 | 1549 | return {'FINISHED'} 1550 | 1551 | def handleShader(mat: bpy.types.Material, mesh, object, deduplicate: bool, directory): 1552 | if mat is None: 1553 | return {'CANCELLED'} 1554 | 1555 | shader_package = mat["ShaderPackage"] 1556 | if shader_package is None: 1557 | return {'CANCELLED'} 1558 | 1559 | print(f"Handling shader package {shader_package} on material {mat.name}") 1560 | 1561 | if shader_package == 'skin.shpk': 1562 | handleSkin(mat, mesh, directory) 1563 | return {'FINISHED'} 1564 | 1565 | if shader_package == 'hair.shpk': 1566 | handleHair(mat, mesh, directory) 1567 | return {'FINISHED'} 1568 | 1569 | if shader_package == 'iris.shpk': 1570 | handleIris(mat, mesh, directory) 1571 | return {'FINISHED'} 1572 | 1573 | if shader_package == 'charactertattoo.shpk': 1574 | handleCharacterTattoo(mat, mesh, directory) 1575 | return {'FINISHED'} 1576 | 1577 | if shader_package == 'characterocclusion.shpk': 1578 | handleCharacterOcclusion(mat, mesh, directory) 1579 | return {'FINISHED'} 1580 | 1581 | if shader_package in ('character.shpk', 'characterlegacy.shpk', 'characterscroll.shpk', 1582 | 'characterglass.shpk', 'characterinc.shpk', 'characterstockings.shpk'): 1583 | handleCharacterSimple(mat, mesh, directory, shader_package) 1584 | return {'FINISHED'} 1585 | 1586 | if shader_package == 'bgcolorchange.shpk': 1587 | handleBgColorChange(mat, mesh, directory) 1588 | return {'FINISHED'} 1589 | 1590 | if shader_package in ('water.shpk', 'river.shpk'): 1591 | handleWater(mat, mesh, directory) 1592 | return {'FINISHED'} 1593 | 1594 | # check if material exists already in scene by same name 1595 | # note: any materials with additional inputs outside the .mtrl values, should not be deduplicated as they should be unique to the object 1596 | if 'Material' in mat and deduplicate: 1597 | for obj in (o for o in bpy.data.objects if o.type == 'MESH'): 1598 | for slot in obj.material_slots: 1599 | if slot.material is None: 1600 | continue 1601 | if 'Material' in slot.material and slot.material['Material'] == mat['Material'] and 'MeddleApplied' in slot.material and slot.material['MeddleApplied'] == True: 1602 | # there is another object in the scene with the same material as this. Replace object material with the one in the scene 1603 | for objSlot in object.material_slots: 1604 | if objSlot.material.name == mat.name: 1605 | objSlot.material = slot.material 1606 | print(f"Material {mat.name} already exists in scene, using existing material") 1607 | return {'FINISHED'} 1608 | 1609 | 1610 | if shader_package == 'bg.shpk' or shader_package == 'bguvscroll.shpk' or shader_package == 'bgcrestchange.shpk': 1611 | handleBg(mat, mesh, directory) 1612 | mat['MeddleApplied'] = True 1613 | return {'FINISHED'} 1614 | 1615 | if shader_package == 'lightshaft.shpk': 1616 | handleLightShaft(mat, mesh, directory) 1617 | mat['MeddleApplied'] = True 1618 | return {'FINISHED'} 1619 | 1620 | if shader_package == 'bgprop.shpk': 1621 | handleBgProp(mat, mesh, directory) 1622 | mat['MeddleApplied'] = True 1623 | return {'FINISHED'} 1624 | 1625 | if shader_package == 'crystal.shpk': 1626 | handleCrystal(mat, mesh, directory) 1627 | mat['MeddleApplied'] = True 1628 | return {'FINISHED'} 1629 | 1630 | spawnFallbackTextures(mat, directory) 1631 | print(f"No suitable shader found for {shader_package} on material {mat.name}") 1632 | return {'CANCELLED'} 1633 | -------------------------------------------------------------------------------- /MeddleTools/panel.py: -------------------------------------------------------------------------------- 1 | import glob 2 | import bpy 3 | from . import blend_import 4 | from . import shader_fix 5 | from . import gltf_import 6 | import requests 7 | import addon_utils 8 | 9 | repo_url = "https://github.com/PassiveModding/MeddleTools" 10 | repo_release_download_url = "https://github.com/PassiveModding/MeddleTools/releases" 11 | repo_release_url = "https://api.github.com/repos/PassiveModding/MeddleTools/releases/latest" 12 | repo_issues_url = "https://github.com/PassiveModding/MeddleTools/issues" 13 | sponsor_url = "https://github.com/sponsors/PassiveModding" 14 | current_version = "Unknown" 15 | latest_version = "Unknown" 16 | latest_version_blob = None 17 | 18 | 19 | def getLatestVersion(): 20 | response = requests.get(repo_release_url) 21 | if response.status_code != 200: 22 | raise Exception(f"Failed to get latest version: {response.status_code}") 23 | data = response.json() 24 | return data 25 | 26 | class MeddleImportPanel(bpy.types.Panel): 27 | bl_idname = "OBJECT_PT_MeddlePanel" 28 | bl_label = "Meddle Import" 29 | bl_space_type = 'VIEW_3D' 30 | bl_region_type = 'UI' 31 | bl_context = "objectmode" 32 | bl_category = "Meddle Tools" 33 | 34 | blender_import: bpy.props.BoolProperty(name="Blender Import", default=True) 35 | 36 | 37 | def draw(self, context): 38 | if context is None: 39 | return {'CANCELLED'} 40 | 41 | layout = self.layout 42 | 43 | layout.prop(context.scene.model_import_settings, 'gltfImportMode', text='Import Mode', expand=True) 44 | layout.prop(context.scene.model_import_settings, 'deduplicateMaterials', text='Deduplicate Materials') 45 | row = layout.row() 46 | row.operator(gltf_import.ModelImport.bl_idname, text='Import .gltf/.glb', icon='IMPORT') 47 | row.operator(gltf_import.ModelImportHelpHover.bl_idname, text='', icon='QUESTION') 48 | 49 | if context.scene.model_import_settings.displayImportHelp: 50 | gltf_import.drawModelImportHelp(layout) 51 | 52 | 53 | class MeddleShaderImportPanel(bpy.types.Panel): 54 | bl_idname = "OBJECT_PT_MeddleShaderImportPanel" 55 | bl_label = "Meddle Shaders" 56 | bl_space_type = 'VIEW_3D' 57 | bl_region_type = 'UI' 58 | bl_context = "objectmode" 59 | bl_category = "Meddle Tools" 60 | bl_options = {'DEFAULT_CLOSED'} 61 | 62 | def draw(self, context): 63 | layout = self.layout 64 | 65 | row = layout.row() 66 | section = layout.box() 67 | col = section.column() 68 | 69 | row = col.row() 70 | row.operator(shader_fix.ShaderFixSelected.bl_idname, text='Apply Shaders to Selected Objects') 71 | 72 | row = col.row() 73 | row.operator(shader_fix.ShaderFixActive.bl_idname, text='Apply Shaders to Current Material') 74 | 75 | row = col.row() 76 | row.label(text="Navigate to the 'cache' folder") 77 | row = col.row() 78 | row.label(text="in the same folder as your model") 79 | 80 | row = layout.row() 81 | row.operator(blend_import.ImportShaders.bl_idname, text='Import Shaders') 82 | 83 | row = layout.row() 84 | row.operator(blend_import.ReplaceShaders.bl_idname, text='Replace Shaders') 85 | 86 | box = layout.box() 87 | col = box.column() 88 | 89 | row = col.row() 90 | row.label(text="Imports the Meddle shader node groups") 91 | 92 | row = layout.row() 93 | row.operator(shader_fix.LightingBoost.bl_idname, text='Reparse Lights') 94 | 95 | row = layout.row() 96 | row.operator(shader_fix.MeddleClear.bl_idname, text='Clear Applied Status') 97 | 98 | class MeddleCreditPanel(bpy.types.Panel): 99 | bl_idname = "OBJECT_PT_MeddleVersionPanel" 100 | bl_label = "Credits" 101 | bl_space_type = 'VIEW_3D' 102 | bl_region_type = 'UI' 103 | bl_context = "objectmode" 104 | bl_category = "Meddle Tools" 105 | 106 | def draw(self, context): 107 | layout = self.layout 108 | 109 | if latest_version != "Unknown" and current_version != "Unknown": 110 | if latest_version != current_version: 111 | box = layout.box() 112 | col = box.column() 113 | row = col.row() 114 | row.label(text=f"New version available: {latest_version}") 115 | row = col.row() 116 | row.operator("wm.url_open", text="Download").url = repo_release_download_url 117 | else: 118 | row = layout.row() 119 | row.label(text="Failed to check for updates") 120 | 121 | section = layout.box() 122 | col = section.column() 123 | row = col.row() 124 | row.label(text=f"Version: {current_version}") 125 | row = col.row() 126 | row.label(text=f"Latest Release ({latest_version})") 127 | row = col.row() 128 | if latest_version_blob is not None: 129 | latest_version_name = latest_version_blob["name"] 130 | row.label(text=f"{latest_version_name}") 131 | else: 132 | row.label(text="Unknown") 133 | 134 | layout.separator() 135 | 136 | # credits 137 | box = layout.box() 138 | col = box.column() 139 | 140 | row = col.row() 141 | row.label(text="Developed by:") 142 | row = col.row() 143 | row.label(text=" - PassiveModding/Ramen") 144 | row = col.row() 145 | row.label(text="Special thanks to:") 146 | row = col.row() 147 | row.label(text=" - SkulblakaDrotningu for Lizzer Tools Meddle") 148 | 149 | layout.separator() 150 | 151 | row = layout.row() 152 | row.operator("wm.url_open", text="MeddleTools Github").url = repo_url 153 | row.operator("wm.url_open", text="Report Issues").url = repo_issues_url 154 | 155 | row = layout.row() 156 | row.operator("wm.url_open", text="Support Meddle").url = sponsor_url 157 | 158 | classes = [ 159 | blend_import.ImportShaders, 160 | blend_import.ReplaceShaders, 161 | blend_import.ShaderHelper, 162 | shader_fix.ShaderFixActive, 163 | shader_fix.ShaderFixSelected, 164 | shader_fix.LightingBoost, 165 | shader_fix.MeddleClear, 166 | gltf_import.ModelImport, 167 | MeddleImportPanel, 168 | MeddleShaderImportPanel, 169 | MeddleCreditPanel 170 | ] 171 | 172 | def register(): 173 | try: 174 | latest_version_info = getLatestVersion() 175 | global latest_version 176 | latest_version = latest_version_info["tag_name"] 177 | global latest_version_blob 178 | latest_version_blob = latest_version_info 179 | print(f"Latest version: {latest_version}") 180 | except Exception as e: 181 | print(f"Failed to get latest version: {e}") 182 | 183 | try: 184 | global current_version 185 | version_set = False 186 | for mod in addon_utils.modules(): 187 | if mod.bl_info.get("name") == "Meddle Tools": 188 | print(f"Found MeddleTools: {mod.bl_info.get('version')}") 189 | current_version = ".".join([str(v) for v in mod.bl_info.get("version")]) 190 | version_set = True 191 | if not version_set: 192 | current_version = "Unknown" 193 | print(f"Current version: {current_version}") 194 | except Exception as e: 195 | print(f"Failed to read current version: {e}") 196 | 197 | for cls in classes: 198 | bpy.utils.register_class(cls) 199 | 200 | gltf_import.registerModelImportSettings() 201 | 202 | 203 | def unregister(): 204 | for cls in classes: 205 | bpy.utils.unregister_class(cls) 206 | 207 | gltf_import.unregisterModelImportSettings() 208 | 209 | -------------------------------------------------------------------------------- /MeddleTools/shader_fix.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | from os import path 3 | 4 | from numpy import isin 5 | from . import blend_import 6 | from . import node_groups 7 | 8 | class ShaderFixActive(bpy.types.Operator): 9 | bl_idname = "meddle.use_shaders_active_material" 10 | bl_label = "Use Shaders" 11 | 12 | directory: bpy.props.StringProperty(subtype='DIR_PATH') 13 | 14 | def invoke(self, context, event): 15 | if context is None: 16 | return {'CANCELLED'} 17 | 18 | context.window_manager.fileselect_add(self) 19 | return {'RUNNING_MODAL'} 20 | 21 | def execute(self, context): 22 | if context is None: 23 | return {'CANCELLED'} 24 | 25 | active = context.active_object 26 | 27 | blend_import.import_shaders() 28 | 29 | print(f"Folder selected: {self.directory}") 30 | 31 | if active is None: 32 | return {'CANCELLED'} 33 | 34 | if active.active_material is None: 35 | return {'CANCELLED'} 36 | 37 | return handleShaderFix(active, active.active_material, False, self.directory) 38 | 39 | class ShaderFixSelected(bpy.types.Operator): 40 | bl_idname = "meddle.use_shaders_selected_objects" 41 | bl_label = "Use Shaders on Selected" 42 | 43 | directory: bpy.props.StringProperty(subtype='DIR_PATH') 44 | 45 | def invoke(self, context, event): 46 | if context is None: 47 | return {'CANCELLED'} 48 | 49 | context.window_manager.fileselect_add(self) 50 | return {'RUNNING_MODAL'} 51 | 52 | def execute(self, context): 53 | if context is None: 54 | return {'CANCELLED'} 55 | 56 | # copy of selected objects 57 | selected = context.selected_objects.copy() 58 | 59 | blend_import.import_shaders() 60 | 61 | print(f"Folder selected: {self.directory}") 62 | deduplicate: bool = context.scene.model_import_settings.deduplicateMaterials 63 | 64 | for obj in selected: 65 | if obj is None: 66 | continue 67 | 68 | for slot in obj.material_slots: 69 | if slot.material is not None: 70 | try: 71 | handleShaderFix(obj, slot.material, deduplicate, self.directory) 72 | #shpkMtrlFixer(obj, slot.material, self.directory) 73 | except Exception as e: 74 | print(f"Error on {slot.material.name}: {e}") 75 | 76 | return {'FINISHED'} 77 | 78 | def handleShaderFix(object: bpy.types.Object, mat: bpy.types.Material, deduplicate: bool, directory: str): 79 | if mat is None: 80 | return {'CANCELLED'} 81 | 82 | mesh = object.data 83 | if mesh is None: 84 | return {'CANCELLED'} 85 | 86 | if not isinstance(mesh, bpy.types.Mesh): 87 | return {'CANCELLED'} 88 | 89 | return node_groups.handleShader(mat, mesh, object, deduplicate, directory) 90 | 91 | class MeddleClear(bpy.types.Operator): 92 | bl_idname = "meddle.clear_applied" 93 | bl_label = "Clear" 94 | 95 | def execute(self, context): 96 | # removes the 'MeddleApplied' custom property from all objects 97 | for obj in bpy.data.objects: 98 | if obj.type == 'MESH': 99 | # get materials 100 | for slot in obj.material_slots: 101 | if slot.material is not None: 102 | if 'MeddleApplied' in slot.material: 103 | print(f"Removing MeddleApplied from {slot.material.name}") 104 | del slot.material['MeddleApplied'] 105 | 106 | return {'FINISHED'} 107 | 108 | class LightingBoost(bpy.types.Operator): 109 | bl_idname = "meddle.lighting_boost" 110 | bl_label = "Lighting Boost" 111 | 112 | def execute(self, context): 113 | if context is None: 114 | return {'CANCELLED'} 115 | 116 | for obj in context.selected_objects: 117 | if obj is None: 118 | continue 119 | 120 | if obj.type == 'LIGHT': 121 | handleLightFix(obj) 122 | 123 | return {'FINISHED'} 124 | 125 | def handleLightFix(light: bpy.types.Object): 126 | if light is None: 127 | return {'CANCELLED'} 128 | 129 | lightData: bpy.types.Light = light.data # type: ignore 130 | if lightData is None: 131 | return {'CANCELLED'} 132 | 133 | if "LightType" in light: 134 | if light["LightType"] == "AreaLight": 135 | newLight = bpy.data.lights.new(name=light.name, type='AREA') 136 | newLight.size = light["ShadowNear"] 137 | newLight.energy = light["HDRIntensity"] 138 | rgbCol = light["ColorRGB"] 139 | newLight.color = [rgbCol["X"], rgbCol["Y"], rgbCol["Z"]] 140 | newLight.use_custom_distance = True 141 | newLight.cutoff_distance = light["Range"] 142 | lightData.use_shadow = False 143 | 144 | # parent new lightData to the object 145 | light.data = newLight 146 | # remove old light 147 | bpy.data.lights.remove(lightData) 148 | if light["LightType"] == "PointLight": 149 | lightData.use_custom_distance = True 150 | lightData.cutoff_distance = light["Range"] 151 | lightData.shadow_soft_size = light["ShadowNear"] 152 | lightData.use_soft_falloff = False 153 | lightData.use_shadow = False 154 | lightData.energy = light["HDRIntensity"] 155 | if light["LightType"] == "SpotLight": 156 | lightData.use_custom_distance = True 157 | lightData.cutoff_distance = light["Range"] 158 | lightData.shadow_soft_size = light["ShadowNear"] 159 | lightData.use_soft_falloff = False 160 | lightData.use_shadow = False 161 | lightData.energy = light["HDRIntensity"] 162 | if light["LightType"] == "CapsuleLight": 163 | newLight = bpy.data.lights.new(name=light.name, type='AREA') 164 | newLight.shape = 'RECTANGLE' 165 | newLight.energy = light["HDRIntensity"] 166 | newLight.size = (light["BoundsMax"]["X"] / 10) 167 | newLight.size_y = (light["BoundsMax"]["X"] / 10) 168 | rgbCol = light["ColorRGB"] 169 | newLight.color = [rgbCol["X"], rgbCol["Y"], rgbCol["Z"]] 170 | newLight.use_custom_distance = True 171 | newLight.cutoff_distance = light["Range"] 172 | lightData.use_shadow = False 173 | 174 | # parent new lightData to the object 175 | light.data = newLight 176 | # remove old light 177 | bpy.data.lights.remove(lightData) -------------------------------------------------------------------------------- /MeddleTools/shaders.blend: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PassiveModding/MeddleTools/55d10fb8c188b1ad12e9dc7d983fab2a8b3bb17f/MeddleTools/shaders.blend -------------------------------------------------------------------------------- /MeddleTools/shaders.blend1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PassiveModding/MeddleTools/55d10fb8c188b1ad12e9dc7d983fab2a8b3bb17f/MeddleTools/shaders.blend1 -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Meddle Tools 2 | Sponsor Badge 3 | MeddleTools 4 | Meddle 5 | 6 | This project is a Blender addon that provides various helper functions to assist working with [Meddle](https://github.com/PassiveModding/Meddle) exports. 7 | 8 | ## Installation 9 | - Head to [Releases](https://github.com/PassiveModding/MeddleTools/releases) 10 | - Download the latest MeddleTools.zip 11 | - Install the zip in blender 4.2+ via `Edit > Preferences > Add-Ons > Install From Disk...` 12 | 13 | ## Usage 14 | 15 | Simply click `Import .gltf/.glb` and navigate to the same folder you exported from meddle and select the `.gltf` or `.glb` file, you can select multiple files from the same folder if you need. 16 | 17 | ![Usage](Assets/panel.png) 18 | 19 | If you need to re-apply the shaders, you can use the shaders panel. If applying to multiple meshes, select them in the Layout view and click the 'Apply Shaders to Selected Objects' button. If you are in the shader view and have a material already open, select the 'Apply Shaders to Current Material' button to update only the active material. The import shaders and re-import shaders aren't typically needed as it is performed automatically. 20 | 21 | ![Shaders Panel](Assets/shaderspanel.png) 22 | 23 | > NOTE: Make sure you export with Character Texture Mode set to 'raw' from the Meddle plugin 24 | 25 | ![Meddle Setup](Assets/raw-mode.png) 26 | 27 | # How does MeddleTools work? 28 | Any models/meshes exported by the Meddle XIV plugin will have the relevant keys and values supplied by the in-game shaders attached under Custom Properties of the material once imported into Blender. 29 | 30 | In general, Meddle will spawn textures for all cached textures by referencing the `/cache` folder in your export directory. It will then make use of the other properties and hand crafted node groups imported from [MeddleTools/shaders.blend](MeddleTools/shaders.blend) to set up each material. 31 | 32 | ![Custom Properties Example](Assets/custom_properties_example.png) 33 | 34 | # Limitations 35 | 36 | ## Array textures 37 | Certain materials have properties (or color tables) which include indexes into array textures. Blender does not support indexed texture arrays so MeddleTools will spawn an individual texture for each referenced array index. Currently MeddleTools does not make use of these outside spawning the textures due to difficulties in testing and validating accuracy. 38 | 39 | ## Lights 40 | A lot of properties of in-game lights do not translate well to blender, I have listed them below 41 | 42 | ### Shadows 43 | In-game Lights have properties such as ShadowNear and ShadowFar, some lights are placed within meshes which would typically occlude them, but if the ShadowNear value exceeds the distance from the source of the light to the mesh, it would not be occluded (this is an assumption but from testing appears true). There does not appear to be a blender supported method of handling this. 44 | 45 | These lights can affect characters and objects differently, and have toggles which indicate whether or not to cast shadows for Characters/Objects independently. This doesn't appear achievable in blender without significantly more complex setup and light linking. 46 | 47 | ### Light types 48 | - Area: Supported in blender but does not translate to KHR_lights_punctual (glTF) 49 | - Capsule: Generally equivalent to Area light but with an ellipse shape, does not translate to KHR_lights_punctual (glTF) 50 | - Point: Supported 51 | - Spotlight: Supported 52 | - Directional: Supported 53 | 54 | ### Light intensity 55 | Light color/intensity is represented as a HDR, i.e. values could be RGB (0.5, 1.0, 23.5), this does not translate well to Blender despite it supporting HDR under the hood. Current approximations use reinhardt tone mapping (L / (1+L)) to convert the HDR light to RGB. This works to a degree but is far from accurate to in-game. 56 | 57 | ## LODs and Mips 58 | Lower lods are not exported by Meddle and as such filling a scene with lower poly models is not achievable. 59 | Meddle exported PNG files are exported using the Highest Mip level for the texture, therefore dynamic mip levels are not achievable 60 | 61 | ## Animated materials 62 | Lightshaft and bguvscroll materials can be animated in-game. This is not currently supported as it is rather difficult to animate these for rendering. It is technically feasable but would require significantly more reverse engineering of these shaders to get something accurate which can be translated to frame-based instead of time-based in blender. 63 | 64 | ## Unsupported shaders 65 | Some shaders are not yet supported. If you wish to get support them, please attempt to recreate them yourself and make a pull request or submit an issue with your research. It is extremely time consuming to reverse engineer in-game shaders and any support is welcome. 66 | 67 | ## Attributions 68 | ### [Lizzer_Tools_Meddle](https://github.com/SkulblakaDrotningu/Lizzer_Tools_Meddle) - [GNU GPL v3.0](https://github.com/SkulblakaDrotningu/Lizzer_Tools_Meddle/blob/main/LICENSE.txt) 69 | Initial [Character Shaders](./MeddleTools/shaders.blend) and logic for character shaders + starting point for embedded blender file, shader node setups for skin, face, hair and variants. 70 | --------------------------------------------------------------------------------