├── .gitignore ├── LICENSE ├── README.md ├── io_scene_usdz.zip ├── io_scene_usdz ├── __init__.py ├── compression_utils.py ├── crate_file.py ├── export_usdz.py ├── import_usdz.py ├── material_utils.py ├── object_utils.py ├── scene_data.py └── value_types.py └── testing ├── TestGrid.png ├── TestNormals.png ├── TestUSDZ_280.blend ├── TestUSDZ_300_Import.blend ├── TestUSDZ_Import.blend ├── Test_Export_280.py ├── Test_Import_280.py ├── Test_Import_300.py ├── Test_LZ4_Compression.py └── Test_Zip.py /.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 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | *.blend1 106 | exports/ 107 | testing/.DS_Store 108 | .DS_Store 109 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 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 General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Blender UDSZ file import/export add-on 2 | 3 | USDZ file import and export plugin for [Blender](https://www.blender.org), that provides a simple method of importing and exporting models used with Augmented Reality applications. 4 | 5 | 6 | ## Installation 7 | 8 | 1. Download io_export_usdz.zip file from the root of this repository. 9 | 2. Open Blender 2.8 and Go to edit -> User Preferences... 10 | 3. In User Preferences select Add-ons on the left hand menu and then select the Install button on the top right side of the window. 11 | 4. Navigate to and select the downloaded zip file from step 1. 12 | 5. Select the check mark next to Import-Export: UDSZ format to activate the plugin. 13 | 14 | 15 | ## Usage 16 | 17 | Always be sure to save your work before using this tool. 18 | This tool will attempt to export the currently selected objects in the blender scene. 19 | The tool can be found in blender under File -> Export -> USDZ (.usdz) 20 | When selected the add-on will present the usual file export window for where to export the usdz file along with some options on the left side tool bar. 21 | Depending on which options are selected and the size and complexity of the selected objects could affect the amount of time it takes to export a usdz file. 22 | 23 | 24 | ## Add-on Options 25 | 26 | ### Import Options 27 | 28 | Import Materials - By selecting this option, the add-on will attempt to import materials associated with objects. 29 | 30 | ### Export Options 31 | 32 | Export Materials - The exporter will export object materials as USD Principled shader materials which share many of the same properties as the Principled BSDF shader for Eevee and Cycles in Blender. Mix and Add shader nodes are not supported yet in this add-on. 33 | 34 | Export Animations - When selected, the active object/bone animation will be exported to the usdz file. Currently any animations are baked per-frame. 35 | 36 | Bake Textures - When enabled, any textures associated with materials will be baked out to image files that will be bundled into the usdz file. Currently the add-on will automatically switch to Cycles to bake images which could take a significant amount of time. This option is ignored if Export Materials is unchecked. 37 | 38 | Bake AO - This options bakes ambient occlusion textures that are applied to the USD Principled shader materials in the usdz file. Activating this option can add a significant amount of time to export. This option is ignored if Export Materials is unchecked. 39 | 40 | Samples - The number of samples used in baking the ambient occlusion textures. A higher number generates higher quality occlusion textures with added time to export. This option is ignored if either Export Materials or Bake AO options are unchecked. 41 | 42 | Scale - This value is used to scale the objects exported to the usdz file. 43 | 44 | Use Usdz Converter Tool - By selecting this option, the add-on will export a usda file that will be converted to usdz by the external Usdz Converter Tool bundled with Xcode. Note that the Usdz Converter has been deprecated from the current version of Xcode and this option will no longer work. 45 | 46 | ## Notes 47 | 48 | This add-on has only been tested to work on Mac-OS and there are no guarantees that it will work on Windows or Linux. 49 | 50 | The generated binary usd file used in the exported usdz file could potentially be incompatible to some augmented reality applications, in these cases it is recommend to export the text version of a usd file by adding the ".usda" extension to the exported file name. Then use the usdconvert tool in usdpython to generate the final usdz file. 51 | 52 | The import functionality is currently limited to simple static models with no animations. 53 | 54 | -------------------------------------------------------------------------------- /io_scene_usdz.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/robmcrosby/BlenderUSDZ/c78edfeeef62d19ce9b04b911492e975be935415/io_scene_usdz.zip -------------------------------------------------------------------------------- /io_scene_usdz/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | bl_info = { 3 | "name": "USDZ Export", 4 | "author": "Robert Crosby", 5 | "version": (0, 0, 6), 6 | "blender": (3, 0, 0), 7 | "location": "File > Import-Export", 8 | "description": "Import/Export USDZ Files", 9 | "category": "Import-Export" 10 | } 11 | 12 | if "bpy" in locals(): 13 | import importlib 14 | if "import_usdz" in locals(): 15 | importlib.reload(import_usdz) 16 | if "export_usdz" in locals(): 17 | importlib.reload(export_usdz) 18 | 19 | import bpy 20 | from bpy.props import ( 21 | BoolProperty, 22 | FloatProperty, 23 | IntProperty, 24 | StringProperty, 25 | EnumProperty, 26 | ) 27 | from bpy_extras.io_utils import ( 28 | ImportHelper, 29 | ExportHelper, 30 | path_reference_mode, 31 | axis_conversion, 32 | ) 33 | from bpy.types import ( 34 | Operator, 35 | OperatorFileListElement, 36 | ) 37 | 38 | 39 | class ImportUSDZ(bpy.types.Operator, ImportHelper): 40 | """Import a USDZ File""" 41 | 42 | bl_idname = "import.usdz" 43 | bl_label = "Import USDZ File" 44 | bl_options = {'PRESET', 'UNDO'} 45 | 46 | filename_ext = "" 47 | filter_glob: StringProperty( 48 | default="*.usdz;*.usda;*.usdc", 49 | options={'HIDDEN'}, 50 | ) 51 | 52 | materials: BoolProperty( 53 | name="Materials", 54 | description="Import Materials and textures", 55 | default=True, 56 | ) 57 | animations: BoolProperty( 58 | name="Animations", 59 | description="Import Animations", 60 | default=True, 61 | ) 62 | 63 | def execute(self, context): 64 | from . import import_usdz 65 | keywords = self.as_keywords(ignore=("filter_glob",)) 66 | return import_usdz.import_usdz(context, **keywords) 67 | 68 | def draw(self, context): 69 | pass 70 | 71 | 72 | class USDZ_PT_import_include(bpy.types.Panel): 73 | bl_space_type = 'FILE_BROWSER' 74 | bl_region_type = 'TOOL_PROPS' 75 | bl_label = "Include" 76 | bl_parent_id = "FILE_PT_operator" 77 | 78 | @classmethod 79 | def poll(cls, context): 80 | sfile = context.space_data 81 | operator = sfile.active_operator 82 | return operator.bl_idname == "IMPORT_OT_usdz" 83 | 84 | def draw(self, context): 85 | layout = self.layout 86 | layout.use_property_split = True 87 | layout.use_property_decorate = False 88 | 89 | sfile = context.space_data 90 | operator = sfile.active_operator 91 | 92 | col = layout.column(heading="Import") 93 | 94 | col.prop(operator, 'materials') 95 | col.prop(operator, 'animations') 96 | 97 | 98 | class ExportUSDZ(bpy.types.Operator, ExportHelper): 99 | """Save a USDZ File""" 100 | 101 | bl_idname = "export.usdz" 102 | bl_label = "Export USDZ File" 103 | bl_options = {'PRESET'} 104 | 105 | filename_ext = ".usdz" 106 | filter_glob: StringProperty( 107 | default="*.usdz;*.usda;*.usdc", 108 | options={'HIDDEN'}, 109 | ) 110 | exportMaterials: BoolProperty( 111 | name="Materials", 112 | description="Export Materials from Objects", 113 | default=True, 114 | ) 115 | exportAnimations: BoolProperty( 116 | name="Animations", 117 | description="Export Animations", 118 | default=False, 119 | ) 120 | bakeTextures: BoolProperty( 121 | name="Textures", 122 | description="Bake Diffuse, Roughness, Normal, etc", 123 | default=False, 124 | ) 125 | bakeAO: BoolProperty( 126 | name="Ambiant Occlusion", 127 | description="Bake Ambiant Occlusion Texture", 128 | default=False, 129 | ) 130 | bakeAOSamples: IntProperty( 131 | name="AO Samples", 132 | description="Number of Samples for Ambiant Occlusion", 133 | min=1, 134 | max=1000, 135 | default= 64, 136 | ) 137 | bakeTextureSize: IntProperty( 138 | name="Image Size", 139 | description="Default Size of any Baked Images", 140 | min=16, 141 | max=4096, 142 | default= 1024, 143 | ) 144 | globalScale: FloatProperty( 145 | name="Scale", 146 | min=0.01, 147 | max=1000.0, 148 | default=1.0, 149 | ) 150 | useConverter: BoolProperty( 151 | name="Use Usdz Converter Tool", 152 | description="Use Apple's Converter Tool to create the Usdz file", 153 | default=False, 154 | ) 155 | 156 | def execute(self, context): 157 | from . import export_usdz 158 | keywords = self.as_keywords(ignore=("axis_forward", 159 | "axis_up", 160 | "global_scale", 161 | "check_existing", 162 | "filter_glob", 163 | )) 164 | return export_usdz.export_usdz(context, **keywords) 165 | 166 | def draw(self, context): 167 | pass 168 | 169 | 170 | class USDZ_PT_export_include(bpy.types.Panel): 171 | bl_space_type = 'FILE_BROWSER' 172 | bl_region_type = 'TOOL_PROPS' 173 | bl_label = "Include" 174 | bl_parent_id = "FILE_PT_operator" 175 | 176 | @classmethod 177 | def poll(cls, context): 178 | sfile = context.space_data 179 | operator = sfile.active_operator 180 | return operator.bl_idname == "EXPORT_OT_usdz" 181 | 182 | def draw(self, context): 183 | layout = self.layout 184 | layout.use_property_split = True 185 | layout.use_property_decorate = False 186 | 187 | sfile = context.space_data 188 | operator = sfile.active_operator 189 | 190 | col = layout.column(heading="Export") 191 | col.prop(operator, 'exportMaterials') 192 | col.prop(operator, 'exportAnimations') 193 | layout.prop(operator, 'globalScale') 194 | 195 | 196 | class USDZ_PT_export_textures(bpy.types.Panel): 197 | bl_space_type = 'FILE_BROWSER' 198 | bl_region_type = 'TOOL_PROPS' 199 | bl_label = "Textures" 200 | bl_parent_id = "FILE_PT_operator" 201 | 202 | @classmethod 203 | def poll(cls, context): 204 | sfile = context.space_data 205 | operator = sfile.active_operator 206 | return operator.bl_idname == "EXPORT_OT_usdz" 207 | 208 | def draw(self, context): 209 | layout = self.layout 210 | layout.use_property_split = True 211 | layout.use_property_decorate = False 212 | 213 | sfile = context.space_data 214 | operator = sfile.active_operator 215 | 216 | col = layout.column(heading="Bake") 217 | col.prop(operator, 'bakeTextures') 218 | col.prop(operator, 'bakeAO') 219 | 220 | layout.separator() 221 | 222 | layout.prop(operator, 'bakeTextureSize') 223 | layout.prop(operator, 'bakeAOSamples') 224 | 225 | 226 | def menu_func_usdz_import(self, context): 227 | self.layout.operator(ImportUSDZ.bl_idname, text="USDZ (.usdz)") 228 | 229 | 230 | def menu_func_usdz_export(self, context): 231 | self.layout.operator(ExportUSDZ.bl_idname, text="USDZ (.usdz)") 232 | 233 | 234 | classes = ( 235 | ImportUSDZ, 236 | USDZ_PT_import_include, 237 | ExportUSDZ, 238 | USDZ_PT_export_include, 239 | USDZ_PT_export_textures, 240 | ) 241 | 242 | 243 | def register(): 244 | for cls in classes: 245 | bpy.utils.register_class(cls) 246 | 247 | bpy.types.TOPBAR_MT_file_import.append(menu_func_usdz_import) 248 | bpy.types.TOPBAR_MT_file_export.append(menu_func_usdz_export) 249 | 250 | 251 | def unregister(): 252 | bpy.types.TOPBAR_MT_file_import.remove(menu_func_usdz_import) 253 | bpy.types.TOPBAR_MT_file_export.remove(menu_func_usdz_export) 254 | 255 | for cls in classes: 256 | bpy.utils.unregister_class(cls) 257 | 258 | 259 | if __name__ == "__main__": 260 | register() 261 | -------------------------------------------------------------------------------- /io_scene_usdz/compression_utils.py: -------------------------------------------------------------------------------- 1 | 2 | from collections import Counter 3 | 4 | MAX_BLOCK_INPUT_SIZE = 0x7E000000 5 | 6 | MAX_OFFSET = 65535 7 | MIN_MATCH = 4 8 | MFLIMIT = 12 9 | 10 | 11 | def decodeStrings(data, count, encoding='utf-8'): 12 | strings = [] 13 | while count > 0: 14 | p = data.find(0) 15 | if p < 0: 16 | break 17 | strings.append(data[:p].decode(encoding)) 18 | data = data[p+1:] 19 | count -= 1 20 | return strings 21 | 22 | def encodeStrings(strings, encoding='utf-8'): 23 | data = bytearray() 24 | for str in strings: 25 | data += str.encode(encoding) + b'\x00' 26 | return data 27 | 28 | 29 | def decodeInts(data, count, size, byteorder='little', signed=False): 30 | ints = [] 31 | for i in range(count): 32 | if i * size > len(data): 33 | print('Over Run Data') 34 | break 35 | value = int.from_bytes(data[i*size:i*size + size], byteorder, signed=signed) 36 | ints.append(value) 37 | return ints 38 | 39 | def encodeInts(ints, size, byteorder='little', signed=False): 40 | data = bytearray() 41 | for i in ints: 42 | data += i.to_bytes(size, byteorder, signed=signed) 43 | return data 44 | 45 | 46 | class PositionTable: 47 | TABLE_SIZE = 4096 48 | 49 | def __init__(self): 50 | self.table = [None] * self.TABLE_SIZE 51 | 52 | @staticmethod 53 | def _hash(val): 54 | val = val & 0x0FFFFFFFF # prune to 32 bit 55 | return (val * 2654435761) & 0x0FFF # max = 4095 56 | 57 | def getPosition(self, val): 58 | index = self._hash(val) 59 | return self.table[index] 60 | 61 | def setPosition(self, val, pos): 62 | index = self._hash(val) 63 | self.table[index] = pos 64 | 65 | 66 | def worstCaseBlockLength(srcLen): 67 | return srcLen + (srcLen // 255) + 16 68 | 69 | def readLeUint32(buf, pos): 70 | return int.from_bytes(buf[pos:pos+4], 'little') 71 | 72 | def writeLeUint16(buf, i, val): 73 | buf[i] = val & 0x00FF 74 | buf[i + 1] = (val >> 8) & 0x00FF 75 | 76 | def writeLeUint32(buf, i, val): 77 | buf[i] = val & 0x000000FF 78 | buf[i + 1] = (val >> 8) & 0x000000FF 79 | buf[i + 2] = (val >> 16) & 0x000000FF 80 | buf[i + 3] = (val >> 24) & 0x000000FF 81 | 82 | def findMatch(table, val, src, srcPtr): 83 | pos = table.getPosition(val) 84 | if pos is not None and val == readLeUint32(src, pos): 85 | # Check if the match is too far away 86 | if srcPtr - pos > MAX_OFFSET: 87 | return None 88 | else: 89 | return pos 90 | else: 91 | return None 92 | 93 | 94 | def countMatch(buf, front, back, max): 95 | count = 0 96 | while back <= max: 97 | if buf[front] == buf[back]: 98 | count += 1 99 | else: 100 | break 101 | front += 1 102 | back += 1 103 | return count 104 | 105 | 106 | def copySequence(dst, dstHead, literal, match): 107 | litLen = len(literal) 108 | dstPtr = dstHead 109 | 110 | # Write the length of the literal 111 | token = memoryview(dst)[dstPtr:dstPtr + 1] 112 | dstPtr += 1 113 | if litLen >= 15: 114 | token[0] = (15 << 4) 115 | remLen = litLen - 15 116 | while remLen >= 255: 117 | dst[dstPtr] = 255 118 | dstPtr += 1 119 | remLen -= 255 120 | dst[dstPtr] = remLen 121 | dstPtr += 1 122 | else: 123 | token[0] = (litLen << 4) 124 | 125 | # Write the literal 126 | dst[dstPtr:dstPtr + litLen] = literal 127 | dstPtr += litLen 128 | 129 | offset, matchLen = match 130 | if matchLen > 0: 131 | # Write the Match offset 132 | writeLeUint16(dst, dstPtr, offset) 133 | dstPtr += 2 134 | 135 | # Write the Match length 136 | matchLen -= MIN_MATCH 137 | if matchLen >= 15: 138 | token[0] = token[0] | 15 139 | matchLen -= 15 140 | while matchLen >= 255: 141 | dst[dstPtr] = 255 142 | dstPtr += 1 143 | matchLen -= 255 144 | dst[dstPtr] = matchLen 145 | dstPtr += 1 146 | else: 147 | token[0] = token[0] | matchLen 148 | return dstPtr - dstHead 149 | 150 | 151 | def lz4CompressDefault(src): 152 | srcLen = len(src) 153 | if srcLen > MAX_BLOCK_INPUT_SIZE: 154 | return b'' 155 | dst = bytearray(worstCaseBlockLength(srcLen)) 156 | posTable = PositionTable() 157 | srcPtr = 0 158 | literalHead = 0 159 | dstPtr = 0 160 | MAX_INDEX = srcLen - MFLIMIT 161 | 162 | while srcPtr < MAX_INDEX: 163 | curValue = readLeUint32(src, srcPtr) 164 | matchPos = findMatch(posTable, curValue, src, srcPtr) 165 | if matchPos is not None: 166 | length = countMatch(src, matchPos, srcPtr, MAX_INDEX) 167 | if length < MIN_MATCH: 168 | break 169 | dstPtr += copySequence(dst, dstPtr, 170 | memoryview(src)[literalHead:srcPtr], 171 | (srcPtr - matchPos, length)) 172 | srcPtr += length 173 | literalHead = srcPtr 174 | else: 175 | posTable.setPosition(curValue, srcPtr) 176 | srcPtr += 1 177 | # Write the last literal 178 | dstPtr += copySequence(dst, dstPtr, 179 | memoryview(src)[literalHead:srcLen], 180 | (0, 0)) 181 | return dst[:dstPtr] 182 | 183 | def lz4Compress(src): 184 | dst = bytearray() 185 | inputSize = len(src) 186 | if inputSize == 0: 187 | return dst 188 | if inputSize > 127 * MAX_BLOCK_INPUT_SIZE: 189 | print('Buffer Too Large for LZ4 Compression') 190 | elif inputSize <= MAX_BLOCK_INPUT_SIZE: 191 | dst.append(0) 192 | dst += lz4CompressDefault(src) 193 | else: 194 | wholeChunks = inputSize // MAX_BLOCK_INPUT_SIZE 195 | partChunkSize = inputSize % MAX_BLOCK_INPUT_SIZE 196 | partChunk = 1 if partChunkSize > 0 else 0 197 | dst = (wholeChunks+partChunk).to_bytes(1, byteorder='little') 198 | for i in range(wholeChunks): 199 | offset = i * MAX_BLOCK_INPUT_SIZE 200 | chunk = src[offset:offset+MAX_BLOCK_INPUT_SIZE] 201 | chunk = lz4CompressDefault(chunk) 202 | dst += (len(chunk)).to_bytes(4, byteorder='little') 203 | dst += chunk 204 | if partChunk == 1: 205 | offset = wholeChunks * MAX_BLOCK_INPUT_SIZE 206 | chunk = src[offset:] 207 | chunk = lz4CompressDefault(chunk) 208 | dst += (len(chunk)).to_bytes(4, byteorder='little') 209 | dst += chunk 210 | return dst 211 | 212 | 213 | def lz4DecompressChunk(src): 214 | dst = bytearray() 215 | srcLen = len(src) 216 | srcPtr = 0 217 | while srcPtr < srcLen: 218 | token = memoryview(src)[srcPtr:srcPtr + 1] 219 | srcPtr += 1 220 | # Get Literal Length 221 | litLen = (token[0] >> 4) & 0x0F 222 | if litLen == 15: 223 | while src[srcPtr] == 255: 224 | litLen += 255 225 | srcPtr += 1 226 | litLen += src[srcPtr] 227 | srcPtr += 1 228 | # Copy Literal 229 | dst += src[srcPtr:srcPtr + litLen] 230 | srcPtr += litLen 231 | # Reached Last Literal 232 | if srcPtr >= srcLen: 233 | break 234 | # Get match offset 235 | offset = int.from_bytes(src[srcPtr:srcPtr + 2], 'little') 236 | srcPtr += 2 237 | # Get match length 238 | matchLen = token[0] & 0x0F 239 | if matchLen == 15: 240 | while src[srcPtr] == 255: 241 | matchLen += 255 242 | srcPtr += 1 243 | matchLen += src[srcPtr] 244 | srcPtr += 1 245 | matchLen += MIN_MATCH 246 | # Copy Match 247 | for i in range(matchLen): 248 | dst.append(dst[len(dst) - offset]) 249 | return dst 250 | 251 | 252 | def lz4Decompress(src): 253 | dst = bytearray() 254 | if len(src) > 0: 255 | if src[0] == 0: 256 | dst = lz4DecompressChunk(memoryview(src)[1:]) 257 | else: 258 | chunkSize = int.from_bytes(src[:4], 'little') - 1 259 | #print('chunkSize', chunkSize) 260 | srcPtr = 9 261 | while chunkSize > 0: 262 | dst += lz4DecompressChunk(memoryview(src)[srcPtr:srcPtr+chunkSize]) 263 | srcPtr += chunkSize 264 | if srcPtr + 8 < len(src): 265 | srcPtr += 1 266 | chunkSize = int.from_bytes(src[srcPtr:srcPtr + 4], 'little') 267 | #print('chunkSize', chunkSize) 268 | srcPtr += 8 269 | else: 270 | chunkSize = 0 271 | return dst 272 | 273 | 274 | def usdInt32Compress(values): 275 | values = values.copy() 276 | data = bytearray() 277 | if len(values) == 0: 278 | return data 279 | preValue = 0 280 | for i in range(len(values)): 281 | value = values[i] 282 | values[i] = value - preValue 283 | preValue = value 284 | commonValue = Counter(values).most_common()[0][0] 285 | data += commonValue.to_bytes(4, 'little', signed=True) + data 286 | data += bytes((len(values) * 2 + 7) // 8) 287 | for v in range(len(values)): 288 | value = values[v] 289 | i = v + 16 290 | if value != commonValue: 291 | if value.bit_length() < 8: 292 | data[i//4] |= 1 << ((i%4)*2) 293 | data += value.to_bytes(1, 'little', signed=True) 294 | elif value.bit_length() < 16: 295 | data[i//4] |= 2 << ((i%4)*2) 296 | data += value.to_bytes(2, 'little', signed=True) 297 | else: 298 | data[i//4] |= 3 << ((i%4)*2) 299 | data += value.to_bytes(4, 'little', signed=True) 300 | return data 301 | 302 | 303 | def usdInt32Decompress(data, numInts): 304 | values = [] 305 | numCodes = (numInts * 2 + 7) // 8 306 | commonValue = int.from_bytes(data[:4], 'little', signed=True) 307 | data = data[4:] 308 | codes = memoryview(data)[:numCodes] 309 | vints = memoryview(data)[numCodes:] 310 | preValue = 0 311 | cp = 0 312 | vp = 0 313 | while cp < numInts: 314 | code = (codes[cp//4] >> (cp%4)*2) & 0x3 315 | if code == 0: 316 | preValue += commonValue 317 | elif code == 1: 318 | preValue += int.from_bytes(vints[vp:vp+1], 'little', signed=True) 319 | vp += 1 320 | elif code == 2: 321 | preValue += int.from_bytes(vints[vp:vp+2], 'little', signed=True) 322 | vp += 2 323 | else: 324 | preValue += int.from_bytes(vints[vp:vp+4], 'little', signed=True) 325 | vp += 4 326 | values.append(preValue) 327 | cp += 1 328 | return values 329 | 330 | 331 | def usdInt64Decompress(data, numInts): 332 | values = [] 333 | numCodes = (numInts * 2 + 7) // 8 334 | commonValue = int.from_bytes(data[:8], 'little', signed=True) 335 | data = data[8:] 336 | codes = memoryview(data)[:numCodes] 337 | vints = memoryview(data)[numCodes:] 338 | preValue = 0 339 | cp = 0 340 | vp = 0 341 | while cp < numInts: 342 | code = (codes[cp//4] >> (cp%4)*2) & 0x3 343 | if code == 0: 344 | preValue += commonValue 345 | elif code == 1: 346 | preValue += int.from_bytes(vints[vp:vp+2], 'little', signed=True) 347 | vp += 2 348 | elif code == 2: 349 | preValue += int.from_bytes(vints[vp:vp+4], 'little', signed=True) 350 | vp += 4 351 | else: 352 | preValue += int.from_bytes(vints[vp:vp+8], 'little', signed=True) 353 | vp += 8 354 | values.append(preValue) 355 | cp += 1 356 | return values 357 | -------------------------------------------------------------------------------- /io_scene_usdz/export_usdz.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import os 3 | import subprocess 4 | import tempfile 5 | import shutil 6 | import time 7 | 8 | try: 9 | import zlib 10 | crc32 = zlib.crc32 11 | except ImportError: 12 | crc32 = binascii.crc32 13 | 14 | from io_scene_usdz.scene_data import * 15 | from io_scene_usdz.value_types import * 16 | from io_scene_usdz.crate_file import * 17 | 18 | def export_usdz(context, filepath = '', exportMaterials = True, 19 | bakeTextures = False, bakeTextureSize = 1024, bakeAO = False, 20 | bakeAOSamples = 64, exportAnimations = False, 21 | globalScale = 1.0, useConverter = False, 22 | ): 23 | exportDir, fileName = os.path.split(filepath) 24 | fileParts = fileName.split('.') 25 | fileName = fileParts[0] if len(fileParts) > 0 else 'file' 26 | fileType = fileParts[1] if len(fileParts) > 1 else 'usdz' 27 | filePath = exportDir + '/' + fileName + '.' + fileType 28 | tempDir = None 29 | if not fileType in ('usda', 'usdc'): 30 | tempDir = tempfile.mkdtemp() 31 | exportDir = tempDir 32 | usdData, texturePaths = exportUsdData(context = context, 33 | exportMaterials = exportMaterials, 34 | exportDir = exportDir, 35 | bakeTextures = bakeTextures, 36 | bakeTextureSize = bakeTextureSize, 37 | bakeAO = bakeAO, 38 | bakeAOSamples = bakeAOSamples, 39 | exportAnimations = exportAnimations, 40 | globalScale = globalScale) 41 | if fileType == 'usda': 42 | usdData.writeUsda(filePath) 43 | elif fileType == 'usdc': 44 | writeCrateFile(filePath, usdData) 45 | else: 46 | if useConverter: 47 | # Crate text usda file and run the USDZ Converter Tool 48 | usdaPath = tempDir + '/' + fileName + '.usda' 49 | usdData.writeUsda(usdaPath) 50 | convertToUsdz(filePath, usdaPath) 51 | else: 52 | # Create Binary and Manually zip to a usdz file 53 | usdcPath = tempDir + '/' + fileName + '.usdc' 54 | writeCrateFile(usdcPath, usdData) 55 | writeUsdzFile(filePath, usdcPath, texturePaths) 56 | if tempDir != None: 57 | # Cleanup the Temp Directory 58 | shutil.rmtree(tempDir) 59 | return {'FINISHED'} 60 | 61 | 62 | def exportUsdData(context, exportMaterials, exportDir, bakeTextures, 63 | bakeTextureSize, bakeAO, bakeAOSamples, exportAnimations, 64 | globalScale): 65 | scene = Scene() 66 | scene.exportMaterials = exportMaterials 67 | scene.exportPath = exportDir 68 | scene.bakeTextures = bakeTextures 69 | scene.bakeSize = bakeTextureSize 70 | scene.bakeAO = bakeAO 71 | scene.bakeSamples = bakeAOSamples 72 | scene.animated = exportAnimations 73 | scene.scale = globalScale 74 | scene.loadContext(context) 75 | # Export image files 76 | if scene.bakeTextures: 77 | scene.exportBakedTextures() 78 | # Export the USD Data 79 | usdData = scene.exportUsd() 80 | texturePaths = scene.textureFilePaths 81 | # Cleanup the scene 82 | scene.cleanup() 83 | return usdData, texturePaths 84 | 85 | 86 | def convertToUsdz(filePath, usdaPath): 87 | args = ['xcrun', 'usdz_converter', usdaPath, filePath] 88 | args += ['-v'] 89 | subprocess.run(args) 90 | 91 | 92 | def writeUsdzFile(filePath, usdcPath, texturePaths): 93 | usdz = UsdzFile(filePath) 94 | usdz.addFile(usdcPath) 95 | for texturePath in texturePaths: 96 | usdz.addFile(texturePath) 97 | usdz.close() 98 | 99 | 100 | def writeCrateFile(filePath, usdData): 101 | crateFile = open(filePath, 'wb') 102 | crate = CrateFile(crateFile) 103 | crate.writeUsd(usdData) 104 | crateFile.close() 105 | 106 | 107 | def readFileContents(filePath): 108 | file = open(filePath, 'rb') 109 | contents = file.read() 110 | file.close() 111 | return contents 112 | 113 | 114 | class UsdzFile: 115 | def __init__(self, filePath): 116 | self.file = open(filePath, 'wb') 117 | self.entries = [] 118 | self.cdOffset = 0 119 | self.cdLength = 0 120 | 121 | def getExtraAlignmentSize(self, name): 122 | return 64 - ((self.file.tell() + 30 + len(name) + 4) % 64) 123 | 124 | def addFile(self, filePath): 125 | contents = readFileContents(filePath) 126 | entry = {} 127 | entry['name'] = os.path.basename(filePath) 128 | # File offset and crc32 hash 129 | entry['offset'] = self.file.tell() 130 | entry['crc'] = crc32(contents) & 0xffffffff 131 | # Write the Current Date and Time 132 | dt = time.localtime(time.time()) 133 | dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2] 134 | dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2) 135 | entry['time'] = dosdate.to_bytes(2, byteorder = 'little') 136 | entry['date'] = dostime.to_bytes(2, byteorder = 'little') 137 | extraSize = self.getExtraAlignmentSize(entry['name']) 138 | # Local Entry Signature 139 | self.file.write(b'\x50\x4b\x03\x04') 140 | # Version for Extract, Bits, Compression Method 141 | writeInt(self.file, 20, 2) 142 | writeInt(self.file, 0, 2) 143 | writeInt(self.file, 0, 2) 144 | # Mod Time/Date 145 | self.file.write(entry['time']) 146 | self.file.write(entry['date']) 147 | # CRC Hash 148 | writeInt(self.file, entry['crc'], 4) 149 | # Size Uncompressed/Compressed 150 | writeInt(self.file, len(contents), 4) 151 | writeInt(self.file, len(contents), 4) 152 | # Filename/Extra Length 153 | writeInt(self.file, len(entry['name']), 2) 154 | writeInt(self.file, extraSize+4, 2) 155 | # Filename 156 | self.file.write(entry['name'].encode()) 157 | # Extra Header Id/Size 158 | writeInt(self.file, 1, 2) 159 | writeInt(self.file, extraSize, 2) 160 | # Padding Bytes and File Contents 161 | self.file.write(bytes(extraSize)) 162 | self.file.write(contents) 163 | entry['size'] = len(contents) 164 | self.entries.append(entry) 165 | 166 | def writeCentralDir(self): 167 | self.cdOffset = self.file.tell() 168 | for entry in self.entries: 169 | # Central Directory Signature 170 | self.file.write(b'\x50\x4B\x01\x02') 171 | # Version Made By 172 | writeInt(self.file, 62, 2) 173 | # Version For Extract 174 | writeInt(self.file, 20, 2) 175 | # Bits 176 | writeInt(self.file, 0, 2) 177 | # Compression Method 178 | writeInt(self.file, 0, 2) 179 | self.file.write(entry['time']) 180 | self.file.write(entry['date']) 181 | # CRC Hash 182 | writeInt(self.file, entry['crc'], 4) 183 | # Size Compressed/Uncompressed 184 | writeInt(self.file, entry['size'], 4) 185 | writeInt(self.file, entry['size'], 4) 186 | # Filename Length, Extra Field Length, Comment Length 187 | writeInt(self.file, len(entry['name']), 2) 188 | writeInt(self.file, 0, 2) 189 | writeInt(self.file, 0, 2) 190 | # Disk Number Start, Internal Attrs, External Attrs 191 | writeInt(self.file, 0, 2) 192 | writeInt(self.file, 0, 2) 193 | writeInt(self.file, 0, 4) 194 | # Local Header Offset 195 | writeInt(self.file, entry['offset'], 4) 196 | # Add the file name again 197 | self.file.write(entry['name'].encode()) 198 | # Get Central Dir Length 199 | self.cdLength = self.file.tell() - self.cdOffset 200 | 201 | def writeEndCentralDir(self): 202 | # End Central Directory Signature 203 | self.file.write(b'\x50\x4B\x05\x06') 204 | # Disk Number and Disk Number for Central Dir 205 | writeInt(self.file, 0, 2) 206 | writeInt(self.file, 0, 2) 207 | # Num Central Dir Entries on Disk and Num Central Dir Entries 208 | writeInt(self.file, len(self.entries), 2) 209 | writeInt(self.file, len(self.entries), 2) 210 | # Central Dir Length/Offset 211 | writeInt(self.file, self.cdLength, 4) 212 | writeInt(self.file, self.cdOffset, 4) 213 | # Comment Length 214 | writeInt(self.file, 0, 2) 215 | 216 | def close(self): 217 | self.writeCentralDir() 218 | self.writeEndCentralDir() 219 | self.file.close() 220 | -------------------------------------------------------------------------------- /io_scene_usdz/import_usdz.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import os 3 | import subprocess 4 | import tempfile 5 | import shutil 6 | import zipfile 7 | import bmesh 8 | import mathutils 9 | import math 10 | 11 | from io_scene_usdz.scene_data import * 12 | from io_scene_usdz.object_utils import * 13 | from io_scene_usdz.material_utils import * 14 | from io_scene_usdz.crate_file import * 15 | 16 | 17 | def import_usdz(context, filepath = '', materials = True, animations = True): 18 | filePath, fileName = os.path.split(filepath) 19 | fileName, fileType = fileName.split('.') 20 | if fileType == 'usdz': 21 | with zipfile.ZipFile(filepath, 'r') as zf: 22 | # Create a temp directory to extract to 23 | tempPath = tempfile.mkdtemp() 24 | try: 25 | zf.extractall(tempPath) 26 | except Exception as e: 27 | print(e) 28 | zf.close() 29 | # Find the usdc file 30 | usdcFile = findUsdz(tempPath) 31 | if usdcFile != '': 32 | file = open(usdcFile, 'rb') 33 | crate = CrateFile(file) 34 | usdData = crate.readUsd() 35 | file.close() 36 | print(usdData.toString(debug = True)) 37 | tempDir = usdcFile[:usdcFile.rfind('/')+1] 38 | importData(context, usdData, tempDir, materials, animations) 39 | else: 40 | print('No usdc file found') 41 | # Cleanup Temp Files 42 | if tempPath != None: 43 | shutil.rmtree(tempPath) 44 | elif fileType == 'usdc': 45 | usdcFile = filepath 46 | file = open(usdcFile, 'rb') 47 | crate = CrateFile(file) 48 | usdData = crate.readUsd() 49 | file.close() 50 | print(usdData.toString(debug = True)) 51 | tempDir = usdcFile[:usdcFile.rfind('/')+1] 52 | importData(context, usdData, tempDir, materials, animations) 53 | return {'FINISHED'} 54 | 55 | 56 | def findUsdz(dirpath): 57 | files = os.listdir(dirpath) 58 | dirs = [] 59 | for file in files: 60 | parts = file.split('.') 61 | filepath = dirpath + '/' + file 62 | if os.path.isdir(filepath): 63 | dirs.append(filepath) 64 | elif len(parts) > 0 and parts[-1] == 'usdc': 65 | return filepath 66 | for dir in dirs: 67 | file = findUsdz(dir) 68 | if file != '': 69 | return file 70 | return '' 71 | 72 | 73 | def importData(context, usdData, tempDir, materials, animated): 74 | if animated: 75 | if 'startTimeCode' in usdData.metadata: 76 | context.scene.frame_start = usdData['startTimeCode'] 77 | if 'endTimeCode' in usdData.metadata: 78 | context.scene.frame_end = usdData['endTimeCode'] 79 | if 'timeCodesPerSecond' in usdData.metadata: 80 | context.scene.render.fps = usdData['timeCodesPerSecond'] 81 | materials = importMaterials(usdData, tempDir) if materials else {} 82 | objects = getObjects(usdData) 83 | for object in objects: 84 | addObject(context, object, materials, animated = animated) 85 | 86 | 87 | def getOpMatrix(data, opName): 88 | invert = '!invert!' in opName 89 | opName = opName.replace('!invert!', '') 90 | data = data[opName] 91 | matrix = mathutils.Matrix() 92 | if data != None: 93 | value = data.value if data.value != None else data.frames[0][1] 94 | #print(opName, value) 95 | if opName in ('xformOp:transform', 'xformOp:transform:transforms'): 96 | matrix = mathutils.Matrix(value) 97 | matrix.transpose() 98 | elif opName == 'xformOp:rotateXYZ': 99 | rotX = mathutils.Matrix.Rotation(math.radians(value[0]), 4, 'X') 100 | rotY = mathutils.Matrix.Rotation(math.radians(value[1]), 4, 'Y') 101 | rotZ = mathutils.Matrix.Rotation(math.radians(value[2]), 4, 'Z') 102 | matrix = rotZ @ rotY @ rotX 103 | elif opName in ('xformOp:translate', 'xformOp:translate:pivot'): 104 | matrix = mathutils.Matrix.Translation(value) 105 | elif opName == 'xformOp:scale': 106 | mathutils.Matrix.Diagonal(value + (1.0,)) 107 | else: 108 | print('Unused Op:', opName) 109 | if invert: 110 | print('Invert') 111 | matrix.invert() 112 | return matrix 113 | 114 | 115 | def getFrameMatrix(opName, values, frame): 116 | invert = '!invert!' in opName 117 | opName = opName.replace('!invert!', '') 118 | matrix = mathutils.Matrix() 119 | if opName in ('xformOp:transform', 'xformOp:transform:transforms'): 120 | if type(values) is dict: 121 | if frame in values: 122 | matrix = mathutils.Matrix(values[frame]) 123 | matrix.transpose() 124 | else: 125 | matrix = mathutils.Matrix(values) 126 | matrix.transpose() 127 | return matrix 128 | 129 | 130 | def applyRidgidTransforms(data, obj): 131 | matrix = mathutils.Matrix() 132 | if 'xformOpOrder' in data: 133 | for opName in reversed(data['xformOpOrder'].value): 134 | matrix = getOpMatrix(data, opName) @ matrix 135 | if obj.parent == None: 136 | matrix = matrix @ mathutils.Matrix.Rotation(math.pi/2.0, 4, 'X') 137 | obj.matrix_local = matrix 138 | 139 | 140 | def applyRidgidAnimation(context, data, obj): 141 | keyFrames = set() 142 | keyValues = [] 143 | if 'xformOpOrder' in data: 144 | for opName in reversed(data['xformOpOrder'].value): 145 | keyData = data[opName] 146 | if keyData != None: 147 | if keyData.frames != None: 148 | values = {} 149 | for frame, value in keyData.frames: 150 | keyFrames.add(frame) 151 | values[frame] = value 152 | keyValues.append((opName, values)) 153 | elif keyData.value != None: 154 | keyValues.append((opName, keyData.value)) 155 | if len(keyFrames) > 0: 156 | selectBpyObject(obj) 157 | for frame in keyFrames: 158 | context.scene.frame_set(frame) 159 | matrix = mathutils.Matrix() 160 | for opName, values in keyValues: 161 | matrix = getFrameMatrix(opName, values, frame) @ matrix 162 | if obj.parent == None: 163 | matrix = matrix @ mathutils.Matrix.Rotation(math.pi/2.0, 4, 'X') 164 | obj.matrix_local = matrix 165 | bpy.ops.anim.keyframe_insert_menu(type='LocRotScale') 166 | deselectBpyObjects() 167 | else: 168 | applyRidgidTransforms(data, obj) 169 | """ 170 | selectBpyObject(obj) 171 | for frame in range(context.scene.frame_start, context.scene.frame_end+1): 172 | context.scene.frame_set(frame) 173 | matrix = mathutils.Matrix() 174 | if 'xformOpOrder' in data: 175 | for opName in reversed(data['xformOpOrder'].value): 176 | matrix = getOpMatrixFrame(data, opName, frame) @ matrix 177 | if obj.parent == None: 178 | matrix = matrix @ mathutils.Matrix.Rotation(math.pi/2.0, 4, 'X') 179 | obj.matrix_local = matrix 180 | bpy.ops.anim.keyframe_insert_menu(type='LocRotScale') 181 | deselectBpyObjects() 182 | """ 183 | 184 | """ 185 | transforms = data['xformOp:transform:transforms'] 186 | if transforms != None: 187 | selectBpyObject(obj) 188 | for frame, matrix in transforms.frames: 189 | context.scene.frame_set(frame) 190 | matrix = mathutils.Matrix(matrix) 191 | matrix.transpose() 192 | if obj.parent == None: 193 | matrix = matrix @ mathutils.Matrix.Rotation(math.pi/2.0, 4, 'X') 194 | obj.matrix_local = matrix 195 | bpy.ops.anim.keyframe_insert_menu(type='LocRotScale') 196 | context.scene.frame_set(context.scene.frame_start) 197 | deselectBpyObjects() 198 | else: 199 | applyRidgidTransforms(data, obj) 200 | """ 201 | 202 | 203 | def addBone(arm, joint, pose): 204 | stack = joint.split('/') 205 | bone = arm.data.edit_bones.new(stack[-1]) 206 | bone.head = (0.0, 0.0, 0.0) 207 | bone.tail = (0.0, 1.0, 0.0) 208 | matrix = mathutils.Matrix(pose) 209 | matrix.transpose() 210 | bone.transform(matrix) 211 | if len(stack) > 1: 212 | bone.parent = arm.data.edit_bones[stack[-2]] 213 | 214 | 215 | def addBones(arm, skeleton): 216 | joints = skeleton['joints'].value 217 | restPose = skeleton['restTransforms'].value 218 | selectBpyObject(arm) 219 | bpy.ops.object.mode_set(mode='EDIT',toggle=True) 220 | for joint, pose in zip(joints, restPose): 221 | addBone(arm, joint, pose) 222 | bpy.ops.object.mode_set(mode='OBJECT',toggle=True) 223 | deselectBpyObjects() 224 | 225 | 226 | def addArmatureAnimation(arm, animation): 227 | joints = animation['joints'].value 228 | locations = animation['translations'].frames 229 | rotations = animation['rotations'].frames 230 | scales = animation['scales'].frames 231 | selectBpyObject(arm) 232 | bpy.ops.object.mode_set(mode='POSE',toggle=True) 233 | for i, joint in enumerate(joints): 234 | joint = joint.split('/')[-1] 235 | bone = arm.pose.bones[joint] 236 | head = arm.data.bones[joint].head 237 | for frame, location in locations: 238 | #bone.location = mathutils.Vector(location[i]) - head 239 | bone.keyframe_insert(data_path = 'location', frame = frame, group = animation.name) 240 | for frame, rotation in rotations: 241 | bone.rotation_quaternion = rotation[i][3:] + rotation[i][:3] 242 | bone.keyframe_insert(data_path = 'rotation_quaternion', frame = frame, group = animation.name) 243 | for frame, scale in scales: 244 | bone.scale = scale[i] 245 | bone.keyframe_insert(data_path = 'scale', frame = frame, group = animation.name) 246 | bpy.ops.object.mode_set(mode='OBJECT',toggle=True) 247 | deselectBpyObjects() 248 | 249 | 250 | def addArmature(context, obj, data): 251 | skeleton = data.getChildOfType(ClassType.Skeleton) 252 | if skeleton != None: 253 | arm = createBpyArmatureObject(skeleton.name, skeleton.name) 254 | addToBpyCollection(arm, context.scene.collection) 255 | addBones(arm, skeleton) 256 | parentToBpyArmature(obj, arm) 257 | return arm 258 | return None 259 | 260 | 261 | def addObject(context, data, materials = {}, parent = None, animated = False): 262 | obj = None 263 | arm = None 264 | meshes = getMeshes(data) 265 | if len(meshes) == 0: 266 | # Create An Empty Object 267 | obj = createBpyEmptyObject(data.name) 268 | # Add to the Default Collection 269 | addToBpyCollection(obj, context.scene.collection) 270 | else: 271 | # Create A Mesh Object 272 | obj = createBpyMeshObject(meshes[0].name, data.name) 273 | # Add to the Default Collection 274 | addToBpyCollection(obj, context.scene.collection) 275 | # Create the Armature if in data 276 | arm = addArmature(context, obj, data) 277 | # Create any UV maps 278 | uvs = meshes[0].getAttributesOfTypeStr('texCoord2f[]') 279 | uvs += meshes[0].getAttributesOfTypeStr('float2[]') 280 | uvs = [uv.name[9:] for uv in uvs] 281 | for uv in uvs: 282 | obj.data.uv_layers.new(name = uv) 283 | # Add the Geometry 284 | for mesh in meshes: 285 | addMesh(obj, mesh, uvs, materials) 286 | applyBoneWeights(obj, mesh) 287 | obj.data.update() 288 | # Set the Parent 289 | if parent != None: 290 | obj.parent = parent 291 | if arm == None: 292 | # Apply Object Transforms 293 | if animated: 294 | applyRidgidAnimation(context, data, obj) 295 | else: 296 | applyRidgidTransforms(data, obj) 297 | elif animated: 298 | # Apply Armature Animation 299 | animation = data.getChildOfType(ClassType.SkelAnimation) 300 | if animation != None: 301 | addArmatureAnimation(arm, animation) 302 | # Add the Children 303 | children = getObjects(data) 304 | for child in children: 305 | addObject(context, child, materials, obj, animated) 306 | 307 | 308 | def addMaterial(obj, rel, materials): 309 | matName = rel.value.name 310 | if matName in materials: 311 | mat = materials[matName] 312 | if not mat.name in obj.data.materials: 313 | obj.data.materials.append(mat) 314 | return obj.data.materials.find(mat.name) 315 | return 0 316 | 317 | 318 | def addMesh(obj, data, uvs, materials): 319 | # Get Geometry From Data 320 | counts = data['faceVertexCounts'].value 321 | indices = data['faceVertexIndices'].value 322 | verts = data['points'].value 323 | normals = None 324 | if 'primvars:normals:indices' in data: 325 | normals = data['primvars:normals:indices'].value 326 | uvMaps = {} 327 | for uv in uvs: 328 | uvPrim = 'primvars:'+uv 329 | if uvPrim in data and uvPrim+':indices' in data: 330 | uvCoords = data[uvPrim].value 331 | uvIndices = data[uvPrim+':indices'].value 332 | uvMaps[uv] = [uvCoords[i] for i in uvIndices] 333 | # Compile Faces 334 | faces = [] 335 | smooth = [] 336 | index = 0 337 | for count in counts: 338 | faces.append(tuple([indices[index + i] for i in range(count)])) 339 | if normals != None: 340 | smooth.append(len(set(normals[index + i] for i in range(count))) > 1) 341 | else: 342 | smooth.append(True) 343 | index += count 344 | # Assign the Material 345 | matIndex = 0 346 | if 'material:binding' in data: 347 | matIndex = addMaterial(obj, data['material:binding'], materials) 348 | # Get Material Sub Sets 349 | matSubsets = [] 350 | for geomSubset in data.getChildrenOfType(ClassType.GeomSubset): 351 | type = geomSubset['familyName'] 352 | if type != None and type.value == 'materialBind': 353 | rel = geomSubset['material:binding'] 354 | indices = geomSubset['indices'] 355 | if rel != None and indices != None: 356 | index = addMaterial(obj, rel, materials) 357 | matSubsets.append((index, indices.value)) 358 | # Create BMesh from Mesh Object 359 | bm = bmesh.new() 360 | bm.from_mesh(obj.data) 361 | # Add the Vertices 362 | vBase = len(bm.verts) 363 | fBase = len(bm.faces) 364 | for vert in verts: 365 | bm.verts.new(vert) 366 | bm.verts.ensure_lookup_table() 367 | # Add the Faces 368 | ordered = set() 369 | for i, face in enumerate(faces): 370 | o = tuple(sorted(face)) 371 | if not o in ordered: 372 | ordered.add(o) 373 | f = bm.faces.new((bm.verts[i + vBase] for i in face)) 374 | f.smooth = smooth[i] 375 | f.material_index = matIndex 376 | # Assign Aditional Materials 377 | bm.faces.ensure_lookup_table() 378 | for matIndex, indices in matSubsets: 379 | for i in indices: 380 | fIndex = i + fBase 381 | if fIndex < len(bm.faces): 382 | bm.faces[fIndex].material_index = matIndex 383 | # Add the UVs 384 | for uvName, uvs in uvMaps.items(): 385 | uvIndex = bm.loops.layers.uv[uvName] 386 | index = 0 387 | for f in bm.faces[-len(faces):]: 388 | for i, l in enumerate(f.loops): 389 | if index+i < len(uvs): 390 | l[uvIndex].uv = uvs[index + i] 391 | else: 392 | l[uvIndex].uv = (0.0, 0.0) 393 | index += len(f.loops) 394 | # Apply BMesh back to Mesh Object 395 | bm.to_mesh(obj.data) 396 | bm.free() 397 | 398 | 399 | def applyBoneWeights(obj, data): 400 | indices = data['primvars:skel:jointIndices'] 401 | weights = data['primvars:skel:jointWeights'] 402 | if indices != None and weights != None: 403 | elementSize = weights['elementSize'] 404 | base = len(obj.data.vertices) - int(len(indices.value)/elementSize) 405 | for i, weight in enumerate(zip(indices.value, weights.value)): 406 | bone, weight = weight 407 | if weight > 0.0: 408 | index = base + i//elementSize 409 | obj.vertex_groups[bone].add([index], weight, 'REPLACE') 410 | 411 | 412 | def getObjects(data): 413 | objects = [] 414 | for child in data.children: 415 | if child.classType == ClassType.Scope: 416 | objects += getObjects(child) 417 | elif child.classType in (ClassType.Xform, ClassType.SkelRoot): 418 | objects.append(child) 419 | elif child.classType == ClassType.Mesh and 'xformOpOrder' in child: 420 | objects.append(child) 421 | return objects 422 | 423 | 424 | def getMeshes(data): 425 | if data.classType == ClassType.Mesh: 426 | return [data] 427 | meshes = [] 428 | for child in data.children: 429 | if child.classType == ClassType.Mesh and not 'xformOpOrder' in child: 430 | meshes.append(child) 431 | elif child.classType == ClassType.Scope: 432 | meshes += getMeshes(child) 433 | return meshes 434 | 435 | 436 | def importMaterials(data, tempDir): 437 | materialMap = {} 438 | materials = data.getAllMaterials() 439 | for matData in materials: 440 | mat = createMaterial(matData, tempDir) 441 | materialMap[matData.name] = mat 442 | return materialMap 443 | 444 | 445 | def createMaterial(usdMat, tempDir): 446 | mat = bpy.data.materials.new(usdMat.name) 447 | mat.use_nodes = True 448 | data = {'usdMat':usdMat, 'tempDir':tempDir, 'material':mat} 449 | data['textureNodes'] = {} 450 | data['uvMapNodes'] = {} 451 | data['outputNode'] = getBpyOutputNode(mat) 452 | data['shaderNode'] = getBpyShaderNode(data['outputNode']) 453 | setMaterialInput(data, 'diffuseColor', 'Base Color') 454 | setMaterialInput(data, 'metallic', 'Metallic') 455 | setMaterialInput(data, 'specularColor', 'Specular') 456 | setMaterialInput(data, 'roughness', 'Roughness') 457 | setMaterialInput(data, 'clearcoat', 'Clearcoat') 458 | setMaterialInput(data, 'clearcoatRoughness', 'Clearcoat Roughness') 459 | setMaterialInput(data, 'emissiveColor', 'Emission') 460 | setMaterialInput(data, 'ior', 'IOR') 461 | setMaterialInput(data, 'opacity', 'Alpha') 462 | setMaterialInput(data, 'normal', 'Normal') 463 | #setMaterialInput(data, 'occlusion', 'Occlusion') 464 | # Setup Transparent Materials 465 | if 'Alpha' in data['shaderNode'].inputs: 466 | input = data['shaderNode'].inputs['Alpha'] 467 | if input.is_linked or input.default_value < 1.0: 468 | mat.blend_method = 'CLIP' 469 | usdShader = getUsdSurfaceShader(usdMat) 470 | if 'inputs:opacityThreshold' in usdShader: 471 | alphaThreshold = usdShader['inputs:opacityThreshold'].value 472 | mat.alpha_threshold = alphaThreshold 473 | return mat 474 | 475 | 476 | def getUsdSurfaceShader(usdMat): 477 | if not 'outputs:surface' in usdMat: 478 | print('outputs:surface not found in shader', usdMat.name) 479 | return None 480 | return usdMat['outputs:surface'].value.parent 481 | 482 | 483 | def getInputData(usdMat, inputName): 484 | usdShader = getUsdSurfaceShader(usdMat) 485 | inputName = 'inputs:' + inputName 486 | if inputName in usdShader: 487 | return usdShader[inputName] 488 | return None 489 | 490 | 491 | def setMaterialInput(data, valName, inputName): 492 | inputData = getInputData(data['usdMat'], valName) 493 | if inputData != None: 494 | if inputData.isConnection(): 495 | setShaderInputTexture(data, inputData, inputName) 496 | else: 497 | setShaderInputValue(data, inputData, inputName) 498 | 499 | 500 | def setShaderInputValue(data, inputData, inputName): 501 | input = getBpyNodeInput(data['shaderNode'], inputName) 502 | if input != None: 503 | valueType = inputData.valueTypeToString() 504 | if valueType == 'float': 505 | input.default_value = inputData.value 506 | elif valueType == 'color3f': 507 | if type(input.default_value) == float: 508 | input.default_value = inputData.value[0] 509 | else: 510 | input.default_value = inputData.value + (1,) 511 | elif valueType == 'normal3f': 512 | input.default_value = (0.0, 0.0, 1.0) 513 | else: 514 | print('Value Not Set:', inputData) 515 | 516 | 517 | def getTextureMappingNode(data, usdTexture): 518 | stData = usdTexture['inputs:st'].value.parent 519 | uvMap = stData['inputs:varname'].value 520 | if not type(uvMap) is str: 521 | uvMap = uvMap.value 522 | if uvMap in data['uvMapNodes']: 523 | return data['uvMapNodes'][uvMap] 524 | posY = data['shaderNode'].location.y - len(data['uvMapNodes']) * 200.0 525 | mapNode = data['material'].node_tree.nodes.new('ShaderNodeUVMap') 526 | mapNode.location.x = -850.0 527 | mapNode.location.y = posY 528 | mapNode.uv_map = uvMap 529 | data['uvMapNodes'][uvMap] = mapNode 530 | return mapNode 531 | 532 | 533 | def getImageTextureNode(data, usdTexture): 534 | if usdTexture.name in data['textureNodes']: 535 | return data['textureNodes'][usdTexture.name] 536 | # Get the Image File Path 537 | filePath = data['tempDir'] + usdTexture['inputs:file'].value 538 | posY = data['shaderNode'].location.y - len(data['textureNodes']) * 300.0 539 | # Add an Image Texture Node 540 | texNode = data['material'].node_tree.nodes.new('ShaderNodeTexImage') 541 | texNode.location.x = -600.0 542 | texNode.location.y = posY 543 | texNode.image = bpy.data.images.load(filePath) 544 | texNode.image.pack() 545 | mapNode = getTextureMappingNode(data, usdTexture) 546 | data['material'].node_tree.links.new(texNode.inputs[0], mapNode.outputs[0]) 547 | data['textureNodes'][usdTexture.name] = texNode 548 | return texNode 549 | 550 | 551 | def connectTextureToValueInput(data, texNode, input): 552 | texNode.image.colorspace_settings.name = 'Non-Color' 553 | # Add a Seperate Color Node 554 | sepNode = data['material'].node_tree.nodes.new('ShaderNodeSeparateRGB') 555 | sepNode.location.y = texNode.location.y 556 | sepNode.location.x = -250.0 557 | # Link in new Node 558 | data['material'].node_tree.links.new(sepNode.inputs[0], texNode.outputs[0]) 559 | data['material'].node_tree.links.new(input, sepNode.outputs[0]) 560 | 561 | 562 | def connectTextureToNormalInput(data, texNode, input): 563 | texNode.image.colorspace_settings.name = 'Non-Color' 564 | # Add a Normal Map Node 565 | mapNode = data['material'].node_tree.nodes.new('ShaderNodeNormalMap') 566 | mapNode.location.y = texNode.location.y 567 | mapNode.location.x = -250.0 568 | # Link in new Node 569 | data['material'].node_tree.links.new(mapNode.inputs[1], texNode.outputs[0]) 570 | data['material'].node_tree.links.new(input, mapNode.outputs[0]) 571 | 572 | 573 | def setShaderInputTexture(data, inputData, inputName): 574 | input = getBpyNodeInput(data['shaderNode'], inputName) 575 | if input != None: 576 | texNode = getImageTextureNode(data, inputData.value.parent) 577 | mat = data['material'] 578 | if input.type == 'RGBA': 579 | # Connect to the Color Input 580 | mat.node_tree.links.new(input, texNode.outputs['Color']) 581 | elif input.type == 'VALUE': 582 | connectTextureToValueInput(data, texNode, input) 583 | elif input.type == 'VECTOR': 584 | connectTextureToNormalInput(data, texNode, input) 585 | -------------------------------------------------------------------------------- /io_scene_usdz/material_utils.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | 3 | 4 | def getBpyMaterialName(material): 5 | return material.name.replace('.', '_') 6 | 7 | def getBpyOutputNode(material): 8 | if material.use_nodes: 9 | for node in material.node_tree.nodes: 10 | if node.type == 'OUTPUT_MATERIAL' and node.is_active_output: 11 | return node 12 | return None 13 | 14 | def getBpyShaderNode(node): 15 | if node != None and len(node.inputs[0].links) > 0: 16 | return node.inputs[0].links[0].from_node 17 | return None 18 | 19 | def getBpyNodeInput(node, name): 20 | if node != None and name in node.inputs: 21 | return node.inputs[name] 22 | return None 23 | 24 | def getBpyDiffuseInput(node): 25 | input = getBpyNodeInput(node, 'Base Color') 26 | if input == None: 27 | input = getBpyNodeInput(node, 'Color') 28 | return input 29 | 30 | def getBpyEmissiveInput(node): 31 | return getBpyNodeInput(node, 'Emission') 32 | 33 | def getBpySpecularInput(node): 34 | return getBpyNodeInput(node, 'Specular') 35 | 36 | def getBpySpecularTintInput(node): 37 | return getBpyNodeInput(node, 'Sheen Tint') 38 | 39 | def getBpyMetallicInput(node): 40 | return getBpyNodeInput(node, 'Metallic') 41 | 42 | def getBpyRoughnessInput(node): 43 | return getBpyNodeInput(node, 'Roughness') 44 | 45 | def getBpyClearcoatInput(node): 46 | return getBpyNodeInput(node, 'Clearcoat') 47 | 48 | def getBpyClearcoatRoughnessInput(node): 49 | return getBpyNodeInput(node, 'Clearcoat Roughness') 50 | 51 | def getBpyIorInput(node): 52 | return getBpyNodeInput(node, 'IOR') 53 | 54 | def getBpyTransmissionInput(node): 55 | return getBpyNodeInput(node, 'Transmission') 56 | 57 | def getBpyAlphaInput(node): 58 | return getBpyNodeInput(node, 'Alpha') 59 | 60 | def getBpyNormalInput(node): 61 | return getBpyNodeInput(node, 'Normal') 62 | 63 | def getBpyDiffuseColor(node, default = (0.6, 0.6, 0.6)): 64 | input = getBpyDiffuseInput(node) 65 | if input == None: 66 | return default 67 | return input.default_value[:3] 68 | 69 | def getBpySpecularValue(node, default = 0.5): 70 | input = getBpySpecularInput(node) 71 | if input == None: 72 | return default 73 | return input.default_value 74 | 75 | def getBpySpecularTintValue(node, default = 0.0): 76 | input = getBpySpecularTintInput(node) 77 | if input == None: 78 | return default 79 | return input.default_value 80 | 81 | def getBpySpecularColor(node): 82 | specular = (getBpySpecularValue(node),)*3 83 | return specular 84 | 85 | def getBpyEmissiveColor(node, default = (0.0, 0.0, 0.0)): 86 | input = getBpyEmissiveInput(node) # getBpyNodeInput(node, 'Emission') 87 | if input == None: 88 | return default 89 | return input.default_value[:3] 90 | 91 | def getBpyRoughnessValue(node, default = 0.0): 92 | input = getBpyRoughnessInput(node) 93 | if input == None: 94 | return default 95 | return input.default_value 96 | 97 | def getBpyMetallicValue(node, default = 0.0): 98 | input = getBpyMetallicInput(node) 99 | if input == None: 100 | return default 101 | return input.default_value 102 | 103 | def getBpyAlphaValue(node, default = 1.0): 104 | input = getBpyAlphaInput(node) 105 | if input == None: 106 | return default 107 | return input.default_value 108 | 109 | def getBpyIorValue(node, default = 1.5): 110 | input = getBpyIorInput(node) 111 | if input == None: 112 | return default 113 | return input.default_value 114 | 115 | def getBpyClearcoatValue(node, default = 0.0): 116 | input = getBpyClearcoatInput(node) 117 | if input == None: 118 | return default 119 | return input.default_value 120 | 121 | def getBpyClearcoatRoughnessValue(node, default = 0.0): 122 | input = getBpyClearcoatRoughnessInput(node) 123 | if input == None: 124 | return default 125 | return input.default_value 126 | 127 | def getBpyActiveUvMap(obj): 128 | if obj.data.uv_layers.active != None: 129 | return obj.data.uv_layers.active.name 130 | return 'UVMap' 131 | 132 | def getBpyInputUvMap(input, obj): 133 | if input != None and input.is_linked: 134 | node = input.links[0].from_node 135 | if node.type == 'TEX_IMAGE': 136 | return getBpyInputUvMap(node.inputs['Vector'], obj) 137 | elif node.type == 'UVMAP' and node.uv_map != None: 138 | return node.uv_map 139 | return getBpyActiveUvMap(obj) 140 | -------------------------------------------------------------------------------- /io_scene_usdz/object_utils.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import math 3 | import mathutils 4 | 5 | epslon = 0.000001 6 | 7 | 8 | def deselectBpyObjects(): 9 | bpy.ops.object.select_all(action='DESELECT') 10 | 11 | 12 | def selectBpyObject(object): 13 | deselectBpyObjects() 14 | object.select_set(True) 15 | setBpyActiveObject(object) 16 | 17 | 18 | def selectBpyObjects(objects): 19 | deselectBpyObjects() 20 | for obj in objects: 21 | obj.select_set(True) 22 | 23 | 24 | def setBpyActiveObject(object): 25 | bpy.context.view_layer.objects.active = object 26 | 27 | 28 | def duplicateBpyObject(object): 29 | selectBpyObject(object) 30 | bpy.ops.object.duplicate() 31 | return bpy.context.active_object 32 | 33 | 34 | def parentToBpyArmature(obj, arm): 35 | deselectBpyObjects() 36 | obj.select_set(True) 37 | arm.select_set(True) 38 | bpy.ops.object.parent_set(type='ARMATURE_NAME') 39 | deselectBpyObjects() 40 | 41 | 42 | def duplicateBpySkinnedObject(mesh, armature): 43 | selectBpyObjects([mesh, armature]) 44 | setBpyActiveObject(armature) 45 | bpy.ops.object.mode_set(mode='OBJECT') 46 | bpy.ops.object.duplicate() 47 | for obj in bpy.context.selected_objects: 48 | if obj.type == 'ARMATURE': 49 | armature = obj 50 | else: 51 | mesh = obj 52 | return (mesh, armature) 53 | 54 | 55 | def applyBpyArmatureAnimation(dstArmature, srcArmature, startFrame, endFrame): 56 | selectBpyObject(dstArmature) 57 | # Select all the pose bones 58 | for bone in dstArmature.pose.bones: 59 | bone.bone.select = True 60 | bpy.ops.object.mode_set(mode='POSE') 61 | # Remove all pose bone contraints 62 | for bone in dstArmature.pose.bones: 63 | for constraint in bone.constraints: 64 | bone.constraints.remove(constraint) 65 | bpy.ops.object.mode_set(mode='EDIT') 66 | # Remove all non-deforming bones 67 | for bone in bpy.data.armatures[dstArmature.data.name].edit_bones: 68 | if bone.use_deform == False: 69 | bpy.data.armatures[dstArmature.data.name].edit_bones.remove(bone) 70 | bpy.ops.object.mode_set(mode='POSE') 71 | # Create copy transform constraints to the ik rig 72 | for bone in bpy.context.selected_pose_bones: 73 | bone.rotation_mode = 'QUATERNION' 74 | copyTransforms = bone.constraints.new('COPY_TRANSFORMS') 75 | copyTransforms.target = srcArmature 76 | copyTransforms.subtarget = bone.name 77 | bpy.ops.object.mode_set(mode='OBJECT') 78 | bpy.ops.nla.bake( 79 | frame_start = startFrame, 80 | frame_end = endFrame, 81 | only_selected = True, 82 | visual_keying = True, 83 | clear_constraints = True, 84 | use_current_action = True, 85 | bake_types = {'POSE'} 86 | ) 87 | 88 | 89 | def applyBpyObjectModifers(object): 90 | if object != None: 91 | selectBpyObject(object) 92 | bpy.ops.object.make_single_user() 93 | bpy.ops.object.convert(target='MESH') 94 | 95 | 96 | def createBpyEmptyObject(emptyName): 97 | return bpy.data.objects.new(emptyName, None) 98 | 99 | 100 | def createBpyMeshObject(meshName, objName): 101 | mesh = bpy.data.meshes.new(meshName) 102 | obj = bpy.data.objects.new(objName, mesh) 103 | return obj 104 | 105 | 106 | def createBpyArmatureObject(armName, objName): 107 | arm = bpy.data.armatures.new(armName) 108 | obj = bpy.data.objects.new(objName, arm) 109 | return obj 110 | 111 | def deleteBpyObject(object): 112 | selectBpyObject(object) 113 | bpy.ops.object.delete() 114 | 115 | 116 | def convertBpyMatrix(matrix): 117 | matrix = mathutils.Matrix.transposed(matrix) 118 | return (matrix[0][:], matrix[1][:], matrix[2][:], matrix[3][:]) 119 | 120 | 121 | def convertBpyRootMatrix(matrix, scale): 122 | scale = mathutils.Matrix.Scale(scale, 4) 123 | rotation = mathutils.Matrix.Rotation(-math.pi/2.0, 4, 'X') 124 | return convertBpyMatrix(rotation @ scale @ matrix) 125 | 126 | 127 | def exportBpyExtents(object, scale = 1.0): 128 | low = object.bound_box[0][:] 129 | high = object.bound_box[0][:] 130 | for v in object.bound_box: 131 | low = min(low, v[:]) 132 | high = max(high, v[:]) 133 | low = tuple(i*scale for i in low) 134 | high = tuple(i*scale for i in high) 135 | return [low, high] 136 | 137 | 138 | def applyBpySmartProjection(mesh): 139 | selectBpyObject(mesh) 140 | bpy.ops.uv.smart_project() 141 | 142 | 143 | def exportBpyMeshVertexCounts(mesh, material = -1): 144 | counts = [] 145 | if material == -1: 146 | counts = [len(poly.vertices) for poly in mesh.polygons] 147 | else: 148 | for poly in mesh.polygons: 149 | if poly.material_index == material: 150 | counts.append(len(poly.vertices)) 151 | return counts 152 | 153 | 154 | def exportBpyFaceIndices(mesh, material = -1): 155 | indices = [] 156 | for poly in mesh.polygons: 157 | if poly.material_index == material or material == -1: 158 | indices.append(poly.index) 159 | return indices 160 | 161 | 162 | def exportBpyMeshVertices(mesh, material = -1): 163 | indices = [] 164 | vertices = [] 165 | if material == -1: 166 | for poly in mesh.polygons: 167 | indices += [i for i in poly.vertices] 168 | vertices = [v.co[:] for v in mesh.vertices] 169 | else: 170 | map = {} 171 | for poly in mesh.polygons: 172 | if poly.material_index == material: 173 | for i in poly.vertices: 174 | if not i in map: 175 | map[i] = len(vertices) 176 | vertices.append(mesh.vertices[i].co[:]) 177 | indices.append(map[i]) 178 | return (indices, vertices) 179 | 180 | 181 | def addValueIndex(valueMap, values, indices, value, repeats = 1): 182 | if value in valueMap: 183 | indices += [valueMap[value]] * repeats 184 | else: 185 | index = len(values) 186 | indices += [index] * repeats 187 | values.append(value) 188 | valueMap[value] = index 189 | 190 | 191 | def exportBpyMeshNormals(mesh, material = -1): 192 | indices = [] 193 | normals = [] 194 | normalMap = {} 195 | if mesh.has_custom_normals: 196 | # Calculate and Export Custom Normals 197 | mesh.calc_normals_split() 198 | for loop in mesh.loops: 199 | addValueIndex(normalMap, normals, indices, loop.normal[:]) 200 | mesh.free_normals_split() 201 | return (indices, normals) 202 | for poly in mesh.polygons: 203 | if material == -1 or poly.material_index == material: 204 | if poly.use_smooth: 205 | for i in poly.vertices: 206 | normal = mesh.vertices[i].normal[:] 207 | addValueIndex(normalMap, normals, indices, normal) 208 | else: 209 | normal = poly.normal[:] 210 | vertices = len(poly.vertices) 211 | addValueIndex(normalMap, normals, indices, normal, vertices) 212 | return (indices, normals) 213 | 214 | 215 | def exportBpyMeshUvs(mesh, layer, material = -1): 216 | indices = [] 217 | uvs = [] 218 | uvMap = {} 219 | index = 0 220 | for poly in mesh.polygons: 221 | if material == -1 or poly.material_index == material: 222 | for i in range(index, index + len(poly.vertices)): 223 | uv = layer.data[i].uv[:] 224 | addValueIndex(uvMap, uvs, indices, uv) 225 | index += len(poly.vertices) 226 | return (indices, uvs) 227 | 228 | 229 | def exportBpyVertexWeights(index, groups): 230 | indices = [] 231 | weights = [] 232 | for group in groups: 233 | try: 234 | weight = group.weight(index) 235 | if weight > epslon: 236 | indices.append(group.index) 237 | weights.append(weight) 238 | except RuntimeError: 239 | pass 240 | return (indices, weights) 241 | 242 | 243 | def exportBpyMeshIndices(obj, material = -1): 244 | if material == -1: 245 | return [i for i in range(0, len(obj.data.vertices))] 246 | indices = [] 247 | indexSet = set() 248 | for poly in obj.data.polygons: 249 | if poly.material_index == material: 250 | for i in poly.vertices: 251 | if not i in indexSet: 252 | indexSet.add(i) 253 | indices.append(i) 254 | return indices 255 | 256 | 257 | def exportBpyMeshWeights(obj, material = -1): 258 | groups = [] 259 | weights = [] 260 | size = 0 261 | indices = exportBpyMeshIndices(obj, material) 262 | items = [] 263 | for index in indices: 264 | item = exportBpyVertexWeights(index, obj.vertex_groups) 265 | size = max(size, len(item[0])) 266 | items.append(item) 267 | for g, w in items: 268 | groups += g + (size-len(g))*[0] 269 | weights += w + (size-len(w))*[0.0] 270 | return (groups, weights, size) 271 | 272 | 273 | def createBpyCollection(name): 274 | collection = bpy.data.collections.new(name) 275 | bpy.context.scene.collection.children.link(collection) 276 | return collection 277 | 278 | 279 | def deleteBpyCollection(collection): 280 | if collection != None: 281 | bpy.data.collections.remove(collection) 282 | 283 | 284 | def addToBpyCollection(object, collection = None): 285 | if object != None and collection != None: 286 | if collection == None: 287 | collection = bpy.context.scene.collection 288 | collection.objects.link(object) 289 | 290 | 291 | def getBpyOrderedCollections(): 292 | def fn(c, out, addme): 293 | if addme: 294 | out.append(c) 295 | for c1 in c.children: 296 | out.append(c1) 297 | for c1 in c.children: 298 | fn(c1, out, False) 299 | collections = [] 300 | fn(bpy.context.scene.collection, collections, True) 301 | return collections 302 | 303 | 304 | def getBpyAreaFromContext(context, areaType): 305 | area = None 306 | for a in context['screen'].areas: 307 | if a.type == areaType: 308 | area = a 309 | break 310 | return area 311 | 312 | 313 | def setBpyCollectionVisibility(collection, visible): 314 | if collection != None: 315 | collections = getBpyOrderedCollections() 316 | if collection in collections: 317 | index = collections.index(collection) 318 | hidden = not visible 319 | try: 320 | bpy.ops.object.hide_collection(bpy.context, collection_index=index, toggle=hidden) 321 | except: 322 | context = bpy.context.copy() 323 | context['area'] = getBpyAreaFromContext(context, 'VIEW_3D') 324 | bpy.ops.object.hide_collection(context, collection_index=index, toggle=hidden) 325 | 326 | 327 | def exportBpyBoneJoint(bone): 328 | name = bone.name.replace('.', '_') 329 | if bone.parent != None: 330 | return exportBpyBoneJoint(bone.parent) + '/' + name 331 | return name 332 | 333 | 334 | def exportBpyJoints(armature): 335 | return [exportBpyBoneJoint(bone) for bone in armature.data.bones] 336 | 337 | 338 | def exportBpyBindTransforms(armature): 339 | transforms = [] 340 | for bone in armature.data.bones: 341 | matrix = bone.matrix_local 342 | transforms.append(convertBpyMatrix(matrix)) 343 | return transforms 344 | 345 | 346 | def exportBpyRestTransforms(armature): 347 | transforms = [] 348 | for bone in armature.data.bones: 349 | matrix = bone.matrix_local 350 | transforms.append(convertBpyMatrix(matrix)) 351 | return transforms 352 | -------------------------------------------------------------------------------- /io_scene_usdz/scene_data.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import mathutils 3 | 4 | from io_scene_usdz.object_utils import * 5 | from io_scene_usdz.material_utils import * 6 | from io_scene_usdz.value_types import * 7 | 8 | 9 | class ShaderInput: 10 | """Shader Input Information""" 11 | 12 | def __init__(self, type, name, default): 13 | self.type = type 14 | self.name = name 15 | self.value = default 16 | self.image = None 17 | self.uvMap = None 18 | self.usdAtt = None 19 | 20 | 21 | def exportShaderInput(self, material, usdShader): 22 | if self.usdAtt != None: 23 | usdShader['inputs:'+self.name] = self.usdAtt 24 | else: 25 | usdShader['inputs:'+self.name] = self.value 26 | if usdShader['inputs:'+self.name].valueType.name != self.type: 27 | usdShader['inputs:'+self.name].valueTypeStr = self.type 28 | 29 | 30 | def exportShader(self, material, usdMaterial): 31 | if self.image != None and self.uvMap != None: 32 | v = self.value 33 | default = (v, v, v, 1.0) if self.type == 'float' else v+(1.0,) 34 | usdShader = usdMaterial.createChild(self.name+'_map', ClassType.Shader) 35 | usdShader['info:id'] = 'UsdUVTexture' 36 | usdShader['info:id'].addQualifier('uniform') 37 | usdShader['inputs:fallback'] = default 38 | usdShader['inputs:file'] = self.image 39 | usdShader['inputs:file'].valueType = ValueType.asset 40 | primUsdShader = usdMaterial.getChild('primvar_'+self.uvMap) 41 | if primUsdShader != None: 42 | usdShader['inputs:st'] = primUsdShader['outputs:result'] 43 | usdShader['inputs:wrapS'] = 'repeat' 44 | usdShader['inputs:wrapT'] = 'repeat' 45 | if self.type == 'float': 46 | usdShader['outputs:r'] = ValueType.float 47 | if usdShader['outputs:r'].valueType.name != self.type: 48 | usdShader['outputs:r'].valueTypeStr = self.type 49 | self.usdAtt = usdShader['outputs:r'] 50 | else: 51 | usdShader['outputs:rgb'] = ValueType.vec3f 52 | if usdShader['outputs:rgb'].valueType.name != self.type: 53 | usdShader['outputs:rgb'].valueTypeStr = self.type 54 | self.usdAtt = usdShader['outputs:rgb'] 55 | 56 | 57 | class Material: 58 | """Wraper for Blender Material""" 59 | def __init__(self, material): 60 | self.material = material 61 | self.usdMaterial = None 62 | self.name = getBpyMaterialName(material) 63 | self.outputNode = getBpyOutputNode(material) 64 | self.shaderNode = getBpyShaderNode(self.outputNode) 65 | self.inputs = {} 66 | self.bakeImageNode = None 67 | self.bakeUVMapNode = None 68 | self.activeNode = None 69 | self.bakeNodes = [] 70 | self.createInputs() 71 | 72 | 73 | def createInputs(self): 74 | defDiffuseColor = self.material.diffuse_color[:3] 75 | defRoughness = self.material.roughness 76 | diffuse = getBpyDiffuseColor(self.shaderNode, defDiffuseColor) 77 | specular = getBpySpecularColor(self.shaderNode) 78 | emissive = getBpyEmissiveColor(self.shaderNode) 79 | clearcoat = getBpyClearcoatValue(self.shaderNode) 80 | clearcoatRoughness = getBpyClearcoatRoughnessValue(self.shaderNode) 81 | metallic = getBpyMetallicValue(self.shaderNode) 82 | roughness = getBpyRoughnessValue(self.shaderNode, defRoughness) 83 | opacity = getBpyAlphaValue(self.shaderNode) 84 | opacityThreshold = self.material.alpha_threshold 85 | ior = getBpyIorValue(self.shaderNode) 86 | useSpecular = 0 if metallic > 0.0 else 1 87 | self.inputs = { 88 | 'clearcoat':ShaderInput('float', 'clearcoat', clearcoat), 89 | 'clearcoatRoughness':ShaderInput('float', 'clearcoatRoughness', clearcoatRoughness), 90 | 'diffuseColor':ShaderInput('color3f', 'diffuseColor', diffuse), 91 | 'displacement':ShaderInput('float', 'displacement', 0), 92 | 'emissiveColor':ShaderInput('color3f', 'emissiveColor', emissive), 93 | 'ior':ShaderInput('float', 'ior', ior), 94 | 'metallic':ShaderInput('float', 'metallic', metallic), 95 | 'normal':ShaderInput('normal3f', 'normal', (0.0, 0.0, 1.0)), 96 | 'occlusion':ShaderInput('float', 'occlusion', 0.0), 97 | 'opacity':ShaderInput('float', 'opacity', opacity), 98 | 'opacityThreshold':ShaderInput('float', 'opacityThreshold', opacityThreshold), 99 | 'roughness':ShaderInput('float', 'roughness', roughness), 100 | 'specularColor':ShaderInput('color3f', 'specularColor', specular), 101 | 'useSpecularWorkflow':ShaderInput('int', 'useSpecularWorkflow', useSpecular), 102 | } 103 | 104 | 105 | def setupBakeOutputNodes(self, object): 106 | nodes = self.material.node_tree.nodes 107 | self.activeNode = nodes.active 108 | if self.bakeImageNode == None: 109 | self.bakeImageNode = nodes.new('ShaderNodeTexImage') 110 | nodes.active = self.bakeImageNode 111 | if self.bakeUVMapNode == None: 112 | self.bakeUVMapNode = nodes.new('ShaderNodeUVMap') 113 | self.bakeUVMapNode.uv_map = object.bakeUVMap 114 | links = self.material.node_tree.links 115 | links.new(self.bakeImageNode.inputs[0], self.bakeUVMapNode.outputs[0]) 116 | 117 | 118 | def cleanupBakeOutputNodes(self): 119 | self.cleanupBakeNodes() 120 | nodes = self.material.node_tree.nodes 121 | nodes.active = self.activeNode 122 | if self.bakeImageNode != None: 123 | nodes.remove(self.bakeImageNode) 124 | self.bakeImageNode = None 125 | if self.bakeUVMapNode != None: 126 | nodes.remove(self.bakeUVMapNode) 127 | self.bakeUVMapNode = None 128 | 129 | 130 | def setupBakeColorOutput(self, output): 131 | if output != None: 132 | nodes = self.material.node_tree.nodes 133 | links = self.material.node_tree.links 134 | emitNode = nodes.new('ShaderNodeEmission') 135 | links.new(emitNode.inputs[0], output) 136 | links.new(self.outputNode.inputs[0], emitNode.outputs[0]) 137 | self.bakeNodes.append(emitNode) 138 | return True 139 | return False 140 | 141 | 142 | def setupBakeColorInput(self, input): 143 | if input != None and input.is_linked: 144 | return self.setupBakeColorOutput(input.links[0].from_socket) 145 | return False 146 | 147 | 148 | def setupBakeFloatOutput(self, output): 149 | if output != None: 150 | nodes = self.material.node_tree.nodes 151 | links = self.material.node_tree.links 152 | convertNode = nodes.new('ShaderNodeCombineRGB') 153 | links.new(convertNode.inputs[0], output) 154 | links.new(convertNode.inputs[1], output) 155 | links.new(convertNode.inputs[2], output) 156 | self.bakeNodes.append(convertNode) 157 | return self.setupBakeColorOutput(convertNode.outputs[0]) 158 | return False 159 | 160 | 161 | def setupBakeFloatInput(self, input): 162 | if input != None and input.is_linked: 163 | return self.setupBakeFloatOutput(input.links[0].from_socket) 164 | return False 165 | 166 | 167 | def setupBakeDiffuse(self, asset, object): 168 | input = getBpyDiffuseInput(self.shaderNode) 169 | if self.setupBakeColorInput(input): 170 | self.inputs['diffuseColor'].image = asset 171 | self.inputs['diffuseColor'].uvMap = object.bakeUVMap 172 | return True 173 | return False 174 | 175 | 176 | def setupBakeEmission(self, asset, object): 177 | input = getBpyEmissiveInput(self.shaderNode) 178 | if self.setupBakeColorInput(input): 179 | self.inputs['emissiveColor'].image = asset 180 | self.inputs['emissiveColor'].uvMap = object.bakeUVMap 181 | return True 182 | return False 183 | 184 | 185 | def setupBakeRoughness(self, asset, object): 186 | input = getBpyRoughnessInput(self.shaderNode) 187 | if self.setupBakeFloatInput(input): 188 | self.inputs['roughness'].image = asset 189 | self.inputs['roughness'].uvMap = object.bakeUVMap 190 | return True 191 | return False 192 | 193 | 194 | def setupBakeOpacity(self, asset, object): 195 | input = getBpyAlphaInput(self.shaderNode) 196 | if self.setupBakeFloatInput(input): 197 | self.inputs['opacity'].image = asset 198 | self.inputs['opacity'].uvMap = object.bakeUVMap 199 | return True 200 | return False 201 | 202 | 203 | def setupBakeMetallic(self, asset, object): 204 | input = getBpyMetallicInput(self.shaderNode) 205 | if self.setupBakeFloatInput(input): 206 | self.inputs['metallic'].image = asset 207 | self.inputs['metallic'].uvMap = object.bakeUVMap 208 | self.inputs['useSpecularWorkflow'].value = 0 209 | return True 210 | return False 211 | 212 | 213 | def setupBakeNormals(self, asset, object): 214 | input = getBpyNormalInput(self.shaderNode) 215 | if input != None and input.is_linked: 216 | self.inputs['normal'].image = asset 217 | self.inputs['normal'].uvMap = object.bakeUVMap 218 | return True 219 | return False 220 | 221 | 222 | def cleanupBakeNodes(self): 223 | if len(self.bakeNodes) > 0: 224 | nodes = self.material.node_tree.nodes 225 | for node in self.bakeNodes: 226 | nodes.remove(node) 227 | self.bakeNodes = [] 228 | links = self.material.node_tree.links 229 | links.new(self.outputNode.inputs[0], self.shaderNode.outputs[0]) 230 | 231 | 232 | def setBakeImage(self, image): 233 | if self.bakeImageNode != None: 234 | self.bakeImageNode.image = image 235 | 236 | 237 | def getUVMaps(self): 238 | uvMaps = set() 239 | for input in self.inputs.values(): 240 | if input.uvMap != None: 241 | uvMaps.add(input.uvMap) 242 | return list(uvMaps) 243 | 244 | 245 | def exportPrimvar(self, usdMaterial): 246 | uvMaps = self.getUVMaps() 247 | for map in uvMaps: 248 | usdMaterial['inputs:frame:stPrimvar_' + map] = map 249 | usdShader = usdMaterial.createChild('primvar_'+map, ClassType.Shader) 250 | usdShader['info:id'] = 'UsdPrimvarReader_float2' 251 | usdShader['info:id'].addQualifier('uniform') 252 | usdShader['inputs:fallback'] = (0.0, 0.0) 253 | usdShader['inputs:varname'] = usdMaterial['inputs:frame:stPrimvar_' + map] 254 | usdShader['outputs:result'] = ValueType.vec2f 255 | 256 | 257 | def exportInputs(self, usdMaterial): 258 | for input in self.inputs.values(): 259 | input.exportShader(self, usdMaterial) 260 | 261 | 262 | def exportPbrShader(self, usdMaterial): 263 | usdShader = usdMaterial.createChild('pbr', ClassType.Shader) 264 | usdShader['info:id'] = 'UsdPreviewSurface' 265 | for input in self.inputs.values(): 266 | input.exportShaderInput(self, usdShader) 267 | usdShader['outputs:displacement'] = ValueType.token 268 | usdShader['outputs:surface'] = ValueType.token 269 | return usdShader 270 | 271 | 272 | def exportUsd(self, parent): 273 | self.usdMaterial = parent.createChild(self.name, ClassType.Material) 274 | self.exportPrimvar(self.usdMaterial) 275 | self.exportInputs(self.usdMaterial) 276 | pbrShader = self.exportPbrShader(self.usdMaterial) 277 | self.usdMaterial['outputs:displacement'] = pbrShader['outputs:displacement'] 278 | self.usdMaterial['outputs:surface'] = pbrShader['outputs:surface'] 279 | 280 | 281 | class Mesh: 282 | """Wraper for Blender Mesh Data""" 283 | def __init__(self, object, scene): 284 | self.name = object.data.name.replace('.', '_') 285 | self.object = object 286 | self.scene = scene 287 | self.objectCopy = None 288 | self.armatueCopy = None 289 | self.shared = False 290 | self.usdMesh = None 291 | self.createCopies() 292 | 293 | 294 | def __del__(self): 295 | self.cleanup() 296 | 297 | 298 | def cleanup(self): 299 | self.clearCopies() 300 | 301 | 302 | def createCopies(self): 303 | self.clearCopies() 304 | self.armature = self.getArmature() 305 | if self.armature != None and self.scene.animated: 306 | obj, arm = duplicateBpySkinnedObject(self.object, self.armature) 307 | self.objectCopy = obj 308 | applyBpyArmatureAnimation( 309 | dstArmature = arm, 310 | srcArmature = self.armature, 311 | startFrame = self.scene.startFrame, 312 | endFrame = self.scene.endFrame 313 | ) 314 | self.armatueCopy = arm 315 | self.armatueCopy.data.pose_position = 'REST' 316 | addToBpyCollection(self.armatueCopy, self.scene.collection) 317 | addToBpyCollection(self.objectCopy, self.scene.collection) 318 | else: 319 | self.objectCopy = duplicateBpyObject(self.object) 320 | addToBpyCollection(self.objectCopy, self.scene.collection) 321 | applyBpyObjectModifers(self.objectCopy) 322 | self.objectCopy.hide_render = False 323 | if self.uvMapNeeded(self.objectCopy): 324 | applyBpySmartProjection(self.objectCopy) 325 | 326 | 327 | def clearCopies(self): 328 | if self.objectCopy != None: 329 | deleteBpyObject(self.objectCopy) 330 | self.objectCopy = None 331 | if self.armatueCopy != None: 332 | deleteBpyObject(self.armatueCopy) 333 | self.armatueCopy = None 334 | 335 | 336 | def getArmature(self): 337 | parent = self.object.parent 338 | if parent != None and parent.type == 'ARMATURE': 339 | return parent 340 | return None 341 | 342 | 343 | def exportMeshUvs(self, usdMesh): 344 | mesh = self.objectCopy.data 345 | for layer in mesh.uv_layers: 346 | indices, uvs = exportBpyMeshUvs(mesh, layer) 347 | name = layer.name.replace('.', '_') 348 | usdMesh['primvars:'+name] = uvs 349 | usdMesh['primvars:'+name].valueTypeStr = 'texCoord2f' 350 | usdMesh['primvars:'+name]['interpolation'] = 'faceVarying' 351 | usdMesh['primvars:'+name+':indices'] = indices 352 | 353 | 354 | def exportJoints(self, usdMesh): 355 | mesh = self.objectCopy.data 356 | if self.armatueCopy != None and self.scene.animated: 357 | indices, weights, size = exportBpyMeshWeights(self.objectCopy) 358 | usdMesh['primvars:skel:jointIndices'] = indices 359 | usdMesh['primvars:skel:jointIndices']['elementSize'] = size 360 | usdMesh['primvars:skel:jointIndices']['interpolation'] = 'vertex' 361 | usdMesh['primvars:skel:jointWeights'] = weights 362 | usdMesh['primvars:skel:jointWeights']['elementSize'] = size 363 | usdMesh['primvars:skel:jointWeights']['interpolation'] = 'vertex' 364 | 365 | 366 | def exportSkeleton(self, usdObj): 367 | usdSkeleton = None 368 | if self.armatueCopy != None and self.scene.animated: 369 | joints = exportBpyJoints(self.armatueCopy) 370 | bind = exportBpyBindTransforms(self.armatueCopy) 371 | rest = exportBpyRestTransforms(self.armatueCopy) 372 | name = self.armature.name.replace('.', '_') 373 | usdSkeleton = usdObj.createChild(name, ClassType.Skeleton) 374 | usdSkeleton['joints'] = joints 375 | usdSkeleton['joints'].addQualifier('uniform') 376 | usdSkeleton['bindTransforms'] = bind 377 | usdSkeleton['bindTransforms'].addQualifier('uniform') 378 | usdSkeleton['restTransforms'] = rest 379 | usdSkeleton['restTransforms'].addQualifier('uniform') 380 | return usdSkeleton 381 | 382 | 383 | def exportShared(self, usdMeshes): 384 | self.usdMesh = self.exportToObject(usdMeshes, ClassType.Mesh) 385 | self.usdMesh.specifierType = SpecifierType.Class 386 | return self.usdMesh 387 | 388 | 389 | def exportToObject(self, usdObj, classType = ClassType.Mesh): 390 | mesh = self.objectCopy.data 391 | name = self.object.data.name.replace('.', '_') 392 | usdMesh = usdObj.createChild(name, classType) 393 | usdMesh['extent'] = exportBpyExtents(self.objectCopy, self.scene.scale) 394 | usdMesh['faceVertexCounts'] = exportBpyMeshVertexCounts(mesh) 395 | indices, points = exportBpyMeshVertices(mesh) 396 | usdMesh['faceVertexIndices'] = indices 397 | usdMesh['points'] = points 398 | usdMesh['points'].valueTypeStr = 'point3f' 399 | self.exportMeshUvs(usdMesh) 400 | indices, normals = exportBpyMeshNormals(mesh) 401 | usdMesh['primvars:normals'] = normals 402 | usdMesh['primvars:normals'].valueTypeStr = 'normal3f' 403 | usdMesh['primvars:normals']['interpolation'] = 'faceVarying' 404 | usdMesh['primvars:normals:indices'] = indices 405 | usdMesh['subdivisionScheme'] = 'none' 406 | usdMesh['subdivisionScheme'].addQualifier('uniform') 407 | return usdMesh 408 | 409 | 410 | def uvMapNeeded(self, mesh): 411 | if self.scene.bakeTextures or self.scene.bakeAO: 412 | return len(mesh.data.uv_layers) == 0 413 | return False 414 | 415 | 416 | 417 | class Object: 418 | """Wraper for Blender Objects""" 419 | def __init__(self, object, scene, type = 'EMPTY'): 420 | self.name = object.name.replace('.', '_') 421 | self.object = object 422 | self.scene = scene 423 | self.type = type 424 | self.mesh = None 425 | self.parent = None 426 | self.children = [] 427 | self.materials = [] 428 | self.bakeUVMap = '' 429 | self.bakeWidth = scene.bakeSize 430 | self.bakeHeight = scene.bakeSize 431 | self.bakeImage = None 432 | self.hidden = object.hide_render 433 | self.collection = None 434 | 435 | 436 | def __del__(self): 437 | self.cleanup() 438 | 439 | 440 | def cleanup(self): 441 | if self.mesh != None: 442 | self.mesh.cleanup() 443 | self.mesn = None 444 | self.materials = [] 445 | self.object.hide_render = self.hidden 446 | 447 | 448 | def hasParent(self): 449 | parent = self.object.parent 450 | return parent != None and parent.type != 'ARMATURE' 451 | 452 | 453 | def createMaterials(self): 454 | self.materials = [] 455 | if self.scene.exportMaterials: 456 | for slot in self.object.material_slots: 457 | material = None 458 | if slot.material.name in self.scene.materials: 459 | material = self.scene.materials[slot.material.name] 460 | else: 461 | material = Material(slot.material) 462 | self.scene.materials[slot.material.name] = material 463 | self.materials.append(material) 464 | 465 | 466 | def createMesh(self): 467 | if self.mesh == None: 468 | if self.object.data.name in self.scene.meshObjs: 469 | self.mesh = self.scene.meshObjs[self.object.data.name].mesh 470 | self.mesh.shared = True 471 | else: 472 | self.mesh = Mesh(self.object, self.scene) 473 | self.scene.meshObjs[self.object.data.name] = self 474 | 475 | 476 | def setAsMesh(self): 477 | if self.type != 'MESH' and self.object.type == 'MESH': 478 | self.type = 'MESH' 479 | if not self.object.visible_get(): 480 | collection = self.object.users_collection[0] 481 | setBpyCollectionVisibility(collection, True) 482 | self.scene.hiddenCollections.add(collection) 483 | self.createMaterials() 484 | self.createMesh() 485 | self.object.hide_render = True 486 | 487 | 488 | def getPath(self): 489 | if self.parent == None: 490 | return '/'+self.name 491 | return self.parent.getPath()+'/'+self.name 492 | 493 | 494 | def setupBakeImage(self, file): 495 | self.cleanupBakeImage() 496 | images = bpy.data.images 497 | self.bakeImage = images.new('BakeImage', self.bakeWidth, self.bakeHeight) 498 | self.bakeImage.file_format = 'PNG' 499 | self.bakeImage.filepath = file 500 | for mat in self.materials: 501 | mat.setBakeImage(self.bakeImage) 502 | 503 | 504 | def cleanupBakeImage(self): 505 | if self.bakeImage != None: 506 | images = bpy.data.images 507 | images.remove(self.bakeImage) 508 | self.bakeImage = None 509 | for mat in self.materials: 510 | mat.setBakeImage(None) 511 | 512 | 513 | def setupBakeOutputNodes(self): 514 | self.bakeUVMap = getBpyActiveUvMap(self.object) 515 | for mat in self.materials: 516 | mat.setupBakeOutputNodes(self) 517 | 518 | 519 | def cleanupBakeOutputNodes(self): 520 | for mat in self.materials: 521 | mat.cleanupBakeOutputNodes() 522 | 523 | 524 | def cleanupBakeNodes(self): 525 | for mat in self.materials: 526 | mat.cleanupBakeNodes() 527 | 528 | 529 | def bakeToFile(self, type, file): 530 | self.setupBakeImage(file) 531 | bpy.ops.object.bake(type=type, use_clear=True) 532 | self.bakeImage.save() 533 | self.scene.textureFilePaths.append(file) 534 | self.cleanupBakeImage() 535 | 536 | 537 | def bakeDiffuseTexture(self): 538 | asset = self.name+'_diffuse.png' 539 | bake = False 540 | for mat in self.materials: 541 | bake = mat.setupBakeDiffuse(asset, self) or bake 542 | if bake: 543 | self.bakeToFile('EMIT', self.scene.exportPath+'/'+asset) 544 | self.cleanupBakeNodes() 545 | 546 | 547 | def bakeEmissionTexture(self): 548 | asset = self.name+'_emission.png' 549 | bake = False 550 | for mat in self.materials: 551 | bake = mat.setupBakeEmission(asset, self) or bake 552 | if bake: 553 | self.bakeToFile('EMIT', self.scene.exportPath+'/'+asset) 554 | self.cleanupBakeNodes() 555 | 556 | 557 | def bakeRoughnessTexture(self): 558 | asset = self.name+'_roughness.png' 559 | bake = False 560 | for mat in self.materials: 561 | bake = mat.setupBakeRoughness(asset, self) or bake 562 | if bake: 563 | self.bakeToFile('EMIT', self.scene.exportPath+'/'+asset) 564 | self.cleanupBakeNodes() 565 | 566 | 567 | def bakeOpacityTexture(self): 568 | asset = self.name+'_opacity.png' 569 | bake = False 570 | for mat in self.materials: 571 | bake = mat.setupBakeOpacity(asset, self) or bake 572 | if bake: 573 | self.bakeToFile('EMIT', self.scene.exportPath+'/'+asset) 574 | self.cleanupBakeNodes() 575 | 576 | 577 | def bakeMetallicTexture(self): 578 | asset = self.name+'_metallic.png' 579 | bake = False 580 | for mat in self.materials: 581 | bake = mat.setupBakeMetallic(asset, self) or bake 582 | if bake: 583 | self.bakeToFile('EMIT', self.scene.exportPath+'/'+asset) 584 | self.cleanupBakeNodes() 585 | 586 | 587 | def bakeNormalTexture(self): 588 | asset = self.name+'_normal.png' 589 | bake = False 590 | for mat in self.materials: 591 | bake = mat.setupBakeNormals(asset, self) or bake 592 | if bake: 593 | self.bakeToFile('NORMAL', self.scene.exportPath+'/'+asset) 594 | self.cleanupBakeNodes() 595 | 596 | 597 | def bakeOcclusionTexture(self): 598 | asset = self.name+'_occlusion.png' 599 | bake = False 600 | for mat in self.materials: 601 | mat.inputs['occlusion'].image = asset 602 | mat.inputs['occlusion'].uvMap = self.bakeUVMap 603 | bake = True 604 | if bake: 605 | self.bakeToFile('AO', self.scene.exportPath+'/'+asset) 606 | 607 | 608 | def bakeTextures(self): 609 | selectBpyObject(self.mesh.objectCopy) 610 | self.setupBakeOutputNodes() 611 | if self.scene.bakeTextures: 612 | self.bakeDiffuseTexture() 613 | self.bakeEmissionTexture() 614 | self.bakeRoughnessTexture() 615 | self.bakeOpacityTexture() 616 | self.bakeMetallicTexture() 617 | self.bakeNormalTexture() 618 | if self.scene.bakeAO: 619 | self.bakeOcclusionTexture() 620 | self.cleanupBakeOutputNodes() 621 | 622 | 623 | def getTransform(self): 624 | if self.parent == None: 625 | scale = self.scene.scale 626 | return convertBpyRootMatrix(self.object.matrix_world, scale) 627 | return convertBpyMatrix(self.object.matrix_local) 628 | 629 | 630 | def exportMaterialSubsets(self, usdMesh): 631 | if len(self.materials) == 1: 632 | usdMesh['material:binding'] = self.materials[0].usdMaterial 633 | elif len(self.materials) > 1: 634 | for i, mat in enumerate(self.materials): 635 | mesh = self.mesh.objectCopy.data 636 | subset = usdMesh.createChild(mat.name, ClassType.GeomSubset) 637 | subset['elementType'] = 'face' 638 | subset['elementType'].addQualifier('uniform') 639 | subset['familyName'] = 'materialBind' 640 | subset['familyName'].addQualifier('uniform') 641 | subset['indices'] = exportBpyFaceIndices(mesh, i) 642 | subset['material:binding'] = mat.usdMaterial 643 | #subset['material:binding'].addQualifier('uniform') 644 | 645 | 646 | def exportMesh(self, usdObj): 647 | if self.mesh != None: 648 | if self.mesh.usdMesh != None: 649 | usdMesh = usdObj.createChild(self.mesh.name, ClassType.Mesh) 650 | usdMesh.metadata['inherits'] = self.mesh.usdMesh 651 | usdMesh.metadata['instanceable'] = True 652 | #usdMesh.metadata['specifier'] = ValueType.Specifier 653 | #self.exportMaterialSubsets(usdMesh) 654 | else: 655 | usdMesh = self.mesh.exportToObject(usdObj) 656 | self.exportMaterialSubsets(usdMesh) 657 | usdSkeleton = self.mesh.exportSkeleton(usdObj) 658 | usdAnimation = self.exportAnimation(usdObj) 659 | if usdSkeleton != None and usdAnimation != None: 660 | self.mesh.exportJoints(usdMesh) 661 | usdMesh['skel:animationSource'] = usdAnimation 662 | usdMesh['skel:animationSource'].addQualifier('prepend') 663 | usdMesh['skel:skeleton'] = usdSkeleton 664 | usdMesh['skel:skeleton'].addQualifier('prepend') 665 | 666 | 667 | def exportArmatureAnimation(self, armature, usdAnimation): 668 | usdAnimation['rotations'] = ValueType.quatf 669 | usdRotations = usdAnimation['rotations'] 670 | usdAnimation['scales'] = ValueType.vec3f 671 | usdScales = usdAnimation['scales'] 672 | usdAnimation['translations'] = ValueType.vec3f 673 | usdTranslations = usdAnimation['translations'] 674 | start = self.scene.startFrame 675 | end = self.scene.endFrame 676 | selectBpyObject(armature) 677 | armature.data.pose_position = 'POSE' 678 | for frame in range(start, end+1): 679 | self.scene.context.scene.frame_set(frame) 680 | rotations = [] 681 | scales = [] 682 | locations = [] 683 | for bone in armature.data.bones: 684 | bone = armature.pose.bones[bone.name] 685 | scale = bone.scale.copy() 686 | location = bone.location.copy() 687 | rotation = bone.bone.matrix.to_quaternion() @ bone.rotation_quaternion 688 | if bone.parent != None: 689 | if bone.bone.use_connect: 690 | location = mathutils.Vector((0, bone.parent.length, 0)) 691 | else: 692 | location += mathutils.Vector((0, bone.parent.length, 0)) 693 | else: 694 | scale *= self.scene.scale 695 | location *= self.scene.scale 696 | rotation = bone.rotation_quaternion 697 | rotations.append(rotation[:]) 698 | scales.append(scale[:]) 699 | locations.append(location[:]) 700 | usdRotations.addTimeSample(frame, rotations) 701 | usdScales.addTimeSample(frame, scales) 702 | usdTranslations.addTimeSample(frame, locations) 703 | self.scene.context.scene.frame_set(self.scene.curFrame) 704 | bpy.ops.object.mode_set(mode='OBJECT') 705 | 706 | 707 | def exportAnimation(self, usdObj): 708 | usdAnimation = None 709 | if self.mesh.armatueCopy != None and self.scene.animated: 710 | self.mesh.armatueCopy.data.pose_position = 'POSE' 711 | usdAnimation = usdObj.createChild('Animation', ClassType.SkelAnimation) 712 | usdAnimation['joints'] = exportBpyJoints(self.mesh.armatueCopy) 713 | usdAnimation['joints'].addQualifier('uniform') 714 | self.exportArmatureAnimation(self.mesh.armatueCopy, usdAnimation) 715 | return usdAnimation 716 | 717 | 718 | def exportTimeSamples(self, item): 719 | item['xformOp:transform:transforms'] = ValueType.matrix4d 720 | item = item['xformOp:transform:transforms'] 721 | start = self.scene.startFrame 722 | end = self.scene.endFrame 723 | for frame in range(start, end+1): 724 | self.scene.context.scene.frame_set(frame) 725 | item.addTimeSample(frame, self.getTransform()) 726 | self.scene.context.scene.frame_set(self.scene.curFrame) 727 | 728 | 729 | def exportUsd(self, parent): 730 | usdObj = None 731 | if self.mesh != None and self.mesh.armatueCopy != None and self.scene.animated: 732 | # Export Skinned Object 733 | usdObj = parent.createChild(self.name, ClassType.SkelRoot) 734 | else: 735 | # Export Ridgid Object 736 | usdObj = parent.createChild(self.name, ClassType.Xform) 737 | if self.scene.animated and self.object.animation_data != None: 738 | self.exportTimeSamples(usdObj) 739 | usdObj['xformOpOrder'] = ['xformOp:transform:transforms'] 740 | usdObj['xformOpOrder'].addQualifier('uniform') 741 | else: 742 | usdObj['xformOp:transform'] = self.getTransform() 743 | usdObj['xformOp:transform'].addQualifier('custom') 744 | usdObj['xformOpOrder'] = ['xformOp:transform'] 745 | usdObj['xformOpOrder'].addQualifier('uniform') 746 | # Add Meshes if Mesh Object 747 | if self.type == 'MESH': 748 | self.exportMesh(usdObj) 749 | # Add Children 750 | for child in self.children: 751 | child.exportUsd(usdObj) 752 | if self.collection != None and self.collection in self.scene.usdCollections: 753 | usdObj.metadata['inherits'] = self.scene.usdCollections[self.collection] 754 | usdObj.metadata['instanceable'] = True 755 | 756 | 757 | def exportInstanced(self, parent): 758 | usdObj = None 759 | if self.mesh != None and self.mesh.armatueCopy != None and self.scene.animated: 760 | # Export Skinned Object 761 | usdObj = parent.createChild(self.name, ClassType.SkelRoot) 762 | else: 763 | # Export Ridgid Object 764 | usdObj = parent.createChild(self.name, ClassType.Xform) 765 | usdObj['xformOp:transform'] = convertBpyMatrix(self.object.matrix_local) 766 | usdObj['xformOp:transform'].addQualifier('custom') 767 | usdObj['xformOpOrder'] = ['xformOp:transform'] 768 | usdObj['xformOpOrder'].addQualifier('uniform') 769 | # Add Meshes if Mesh Object 770 | if self.type == 'MESH': 771 | self.exportMesh(usdObj) 772 | # Add Children 773 | for child in self.children: 774 | child.exportInstanced(usdObj) 775 | 776 | 777 | class Scene: 778 | """Container for Objects""" 779 | 780 | def __init__(self): 781 | self.context = None 782 | self.objects = [] 783 | self.objMap = {} 784 | self.meshObjs = {} 785 | self.collections = {} 786 | self.hiddenCollections = set() 787 | self.usdCollections = {} 788 | self.bpyObjects = [] 789 | self.bpyActive = None 790 | self.exportMaterials = False 791 | self.materials = {} 792 | self.exportPath = '' 793 | self.bakeAO = False 794 | self.bakeTextures = False 795 | self.textureFilePaths = [] 796 | self.bakeSamples = 8 797 | self.bakeSize = 1024 798 | self.sharedMeshes = True 799 | self.scale = 1.0 800 | self.animated = False 801 | self.startFrame = 0 802 | self.endFrame = 0 803 | self.curFrame = 0 804 | self.fps = 30 805 | self.customLayerData = {'creator':'Blender USDZ Plugin'} 806 | self.collection = None 807 | 808 | 809 | def cleanup(self): 810 | self.clearObjects() 811 | deselectBpyObjects() 812 | selectBpyObjects(self.bpyObjects) 813 | setBpyActiveObject(self.bpyActive) 814 | for collection in self.hiddenCollections: 815 | setBpyCollectionVisibility(collection, False) 816 | deleteBpyCollection(self.collection) 817 | self.collection = None 818 | 819 | 820 | def clearObjects(self): 821 | for obj in self.objMap.values(): 822 | obj.cleanup() 823 | self.objects = [] 824 | self.objMap = {} 825 | 826 | 827 | def loadContext(self, context): 828 | if context == None: 829 | context = bpy.context 830 | bpy.ops.object.mode_set(mode='OBJECT') 831 | self.context = context 832 | if len(context.selected_objects) > 0: 833 | self.bpyObjects = context.selected_objects.copy() 834 | else: 835 | self.bpyObjects = context.visible_objects.copy() 836 | self.bpyActive = context.view_layer.objects.active 837 | self.startFrame = context.scene.frame_start 838 | self.endFrame = context.scene.frame_end 839 | self.curFrame = context.scene.frame_current 840 | self.fps = context.scene.render.fps 841 | self.renderEngine = context.scene.render.engine 842 | self.scale *= self.getUnitScale() 843 | self.loadObjects() 844 | 845 | 846 | def loadObjects(self): 847 | deleteBpyCollection(self.collection) 848 | self.collection = createBpyCollection('TempCollection') 849 | for obj in self.bpyObjects: 850 | if (obj.type == 'MESH'): 851 | self.addBpyObject(obj, obj.type) 852 | elif (obj.type == 'EMPTY' and obj.instance_type == 'COLLECTION'): 853 | self.addBpyCollection(obj) 854 | 855 | 856 | def getUnitScale(self): 857 | settings = self.context.scene.unit_settings 858 | if settings.system == 'NONE': 859 | return 10.0 860 | return 100.0 * settings.scale_length 861 | 862 | 863 | def getSceneScale(self): 864 | settings = self.context.scene.unit_settings 865 | scale = 1.0 866 | if settings.system == 'METRIC': 867 | if settings.length_unit == 'KILOMETERS': 868 | scale = 100000.0 869 | elif settings.length_unit == 'METERS': 870 | scale = 100.0 871 | elif settings.length_unit == 'CENTIMETERS': 872 | scale = 1.0 873 | elif settings.length_unit == 'MILLIMETERS': 874 | scale = 0.1 875 | elif settings.length_unit == 'MILLIMETERS': 876 | scale = 0.0001 877 | elif settings.system == 'IMPERIAL': 878 | scale = 2.54 879 | if settings.length_unit == 'MILES': 880 | scale = 160934.0 881 | elif settings.length_unit == 'FEET': 882 | scale = 30.48 883 | elif settings.length_unit == 'INCHES': 884 | scale = 2.54 885 | elif settings.length_unit == 'THOU': 886 | scale = 0.00254 887 | else: 888 | scale = 10.0 889 | return scale * settings.scale_length 890 | 891 | 892 | def addBpyObject(self, object, type = 'EMPTY'): 893 | obj = Object(object, self) 894 | if obj.name in self.objMap: 895 | obj = self.objMap[obj.name] 896 | elif obj.hasParent(): 897 | obj.parent = self.addBpyObject(object.parent) 898 | obj.parent.children.append(obj) 899 | self.objMap[obj.name] = obj 900 | else: 901 | self.objects.append(obj) 902 | self.objMap[obj.name] = obj 903 | if type == 'MESH': 904 | obj.setAsMesh() 905 | return obj 906 | 907 | 908 | def addBpyCollection(self, collection): 909 | name = collection.instance_collection.name.replace('.', '_') 910 | obj = Object(collection, self) 911 | obj.collection = name 912 | if obj.name in self.objMap: 913 | obj = self.objMap[obj.name] 914 | elif obj.hasParent(): 915 | obj.parent = self.addBpyObject(collection.parent) 916 | obj.parent.children.append(obj) 917 | self.objMap[obj.name] = obj 918 | else: 919 | self.objects.append(obj) 920 | self.objMap[obj.name] = obj 921 | if not name in self.collections: 922 | bpyObjs = list(collection.instance_collection.objects) 923 | objs = [] 924 | for obj in bpyObjs: 925 | type = obj.type 926 | obj = Object(obj, self) 927 | if obj.name in self.objMap: 928 | obj = self.objMap[obj.name] 929 | else: 930 | self.objMap[obj.name] = obj 931 | objs.append(obj) 932 | if type == 'MESH': 933 | obj.setAsMesh() 934 | self.collections[name] = objs 935 | 936 | 937 | def exportBakedTextures(self): 938 | # Set the Render Engine to Cycles and set Samples 939 | renderEngine = self.context.scene.render.engine 940 | self.context.scene.render.engine = 'CYCLES' 941 | samples = self.context.scene.cycles.samples 942 | self.context.scene.cycles.samples = self.bakeSamples 943 | # Bake textures for each Object 944 | for obj in self.objMap.values(): 945 | if obj.type == 'MESH': 946 | obj.bakeTextures() 947 | # Restore the previous Render Engine and Samples 948 | self.context.scene.cycles.samples = samples 949 | self.context.scene.render.engine = renderEngine 950 | 951 | 952 | def exportSharedMaterials(self, data): 953 | if len(self.materials) > 0: 954 | looks = data.createChild('Looks', ClassType.Scope) 955 | for mat in self.materials.values(): 956 | mat.exportUsd(looks) 957 | 958 | 959 | def exportSharedMeshes(self, data): 960 | objs = [] 961 | for meshObj in self.meshObjs.values(): 962 | if meshObj.mesh.shared: 963 | objs.append(meshObj) 964 | if len(objs) > 0: 965 | meshes = data.createChild('Meshes', ClassType.Scope) 966 | for meshObj in objs: 967 | usdMesh = meshObj.mesh.exportShared(meshes) 968 | meshObj.exportMaterialSubsets(usdMesh) 969 | 970 | 971 | def exportCollections(self, data): 972 | if len(self.collections) > 0: 973 | collections = data.createChild('Collections', ClassType.Scope) 974 | for name, objs in self.collections.items(): 975 | collection = collections.createChild(name, ClassType.Xform) 976 | collection.specifierType = SpecifierType.Class 977 | for obj in objs: 978 | obj.exportInstanced(collection) 979 | self.usdCollections[name] = collection 980 | 981 | 982 | def exportUsd(self): 983 | data = UsdData() 984 | data['upAxis'] = 'Y' 985 | if self.animated: 986 | data['startTimeCode'] = float(self.startFrame) 987 | data['endTimeCode'] = float(self.endFrame) 988 | data['timeCodesPerSecond'] = float(self.fps) 989 | data['customLayerData'] = self.customLayerData 990 | if self.exportMaterials: 991 | self.exportSharedMaterials(data) 992 | if self.sharedMeshes: 993 | self.exportSharedMeshes(data) 994 | self.exportCollections(data) 995 | for obj in self.objects: 996 | obj.exportUsd(data) 997 | return data 998 | -------------------------------------------------------------------------------- /io_scene_usdz/value_types.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | 3 | TAB = ' ' 4 | 5 | 6 | class SpecifierType(Enum): 7 | Def = 0 8 | Over = 1 9 | Class = 2 10 | 11 | 12 | class SpecType(Enum): 13 | Attribute = 1 14 | Connection = 2 15 | Expression = 3 16 | Mapper = 4 17 | MapperArg = 5 18 | Prim = 6 19 | PseudoRoot = 7 20 | Relationship = 8 21 | RelationshipTarget = 9 22 | Variant = 10 23 | VariantSet = 11 24 | 25 | 26 | class ClassType(Enum): 27 | Scope = 0 28 | Xform = 1 29 | Mesh = 2 30 | SkelRoot = 3 31 | Skeleton = 4 32 | SkelAnimation = 5 33 | Material = 6 34 | Shader = 7 35 | GeomSubset = 8 36 | 37 | 38 | class ValueType(Enum): 39 | Invalid = 0 40 | bool = 1 41 | uchar = 2 42 | int = 3 43 | uint = 4 44 | int64 = 5 45 | uint64 = 6 46 | half = 7 47 | float = 8 48 | double = 9 49 | string = 10 50 | token = 11 51 | asset = 12 52 | matrix2d = 13 53 | matrix3d = 14 54 | matrix4d = 15 55 | quatd = 16 56 | quatf = 17 57 | quath = 18 58 | vec2d = 19 59 | vec2f = 20 60 | vec2h = 21 61 | vec2i = 22 62 | vec3d = 23 63 | vec3f = 24 64 | vec3h = 25 65 | vec3i = 26 66 | vec4d = 27 67 | vec4f = 28 68 | vec4h = 29 69 | vec4i = 30 70 | Dictionary = 31 71 | TokenListOp = 32 72 | StringListOp = 33 73 | PathListOp = 34 74 | ReferenceListOp = 35 75 | IntListOp = 36 76 | Int64ListOp = 37 77 | UIntListOp = 38 78 | UInt64ListOp = 39 79 | PathVector = 40 80 | TokenVector = 41 81 | Specifier = 42 82 | Permission = 43 83 | Variability = 44 84 | VariantSelectionMap = 45 85 | TimeSamples = 46 86 | Payload = 47 87 | DoubleVector = 48 88 | LayerOffsetVector = 49 89 | StringVector = 50 90 | ValueBlock = 51 91 | Value = 52 92 | UnregisteredValue = 53 93 | UnregisteredValueListOp = 54 94 | PayloadListOp = 55 95 | 96 | def toString(self): 97 | if self == ValueType.vec2f: 98 | return 'float2' 99 | if self == ValueType.vec3f: 100 | return 'float3' 101 | if self == ValueType.vec4f: 102 | return 'float4' 103 | return self.name 104 | 105 | 106 | def getTupleValueType(value): 107 | l = len(value) 108 | if l > 0: 109 | t = type(value[0]) 110 | if t == int: 111 | if l == 2: 112 | return ValueType.vec2i 113 | if l == 3: 114 | return ValueType.vec3i 115 | if l == 4: 116 | return ValueType.vec4i 117 | elif t == float: 118 | if l == 2: 119 | return ValueType.vec2f 120 | if l == 3: 121 | return ValueType.vec3f 122 | if l == 4: 123 | return ValueType.vec4f 124 | elif t == tuple and len(value[0]) > 0 and type(value[0][0]) == float: 125 | l = len(value[0]) 126 | if l == 2: 127 | return ValueType.matrix2d 128 | if l == 3: 129 | return ValueType.matrix3d 130 | if l == 4: 131 | return ValueType.matrix4d 132 | return ValueType.Invalid 133 | 134 | 135 | def getValueType(value): 136 | t = type(value) 137 | if t == bool: 138 | return ValueType.bool 139 | if t == int: 140 | return ValueType.int 141 | if t == float: 142 | return ValueType.float 143 | if t == str: 144 | if len(value) > 0 and value[0] == '@': 145 | return ValueType.asset 146 | return ValueType.token 147 | if t == tuple: 148 | return getTupleValueType(value) 149 | if t == list and len(value) > 0: 150 | if type(value[0]) == str: 151 | return ValueType.token 152 | return getValueType(value[0]) 153 | if t == SpecifierType: 154 | return ValueType.Specifier 155 | if t == dict: 156 | return ValueType.Dictionary 157 | return ValueType.Invalid 158 | 159 | def getValueTypeFromStr(typeStr): 160 | typeStr = typeStr.replace('[]', '') 161 | if typeStr in ('float2', 'texCoord2f'): 162 | return ValueType.vec2f 163 | if typeStr in ('float3', 'color3f', 'normal3f', 'point3f'): 164 | return ValueType.vec3f 165 | if typeStr in ('float4', 'color4f'): 166 | return ValueType.vec4f 167 | if typeStr in ('double2', 'texCoord2d'): 168 | return ValueType.vec2d 169 | if typeStr in ('double3', 'color3d', 'normal3d', 'point3d'): 170 | return ValueType.vec3d 171 | if typeStr == 'double4': 172 | return ValueType.vec4d 173 | return ValueType[typeStr] 174 | 175 | def valueToString(value, reduced = False): 176 | if type(value) is str: 177 | return value 178 | if type(value) is int: 179 | return '%d' % value 180 | if type(value) is float: 181 | return '%.6g' % round(value, 6) 182 | if type(value) is bool: 183 | return 'true' if value else 'false' 184 | if type(value) is list: 185 | if reduced and len(value) > 3: 186 | return '[' + ', '.join(valueToString(item) for item in value[:3]) + ', ...]' 187 | else: 188 | return '[' + ', '.join(valueToString(item) for item in value) + ']' 189 | if type(value) is tuple: 190 | return '(' + ', '.join(valueToString(item) for item in value) + ')' 191 | return '' 192 | 193 | def dictionaryToString(dic, space): 194 | indent = space + TAB 195 | ret = '{\n' 196 | for key, value in dic.items(): 197 | if type(value) is dict: 198 | ret += indent + 'dictionary ' + key + ' = ' 199 | ret += dictionaryToString(value, indent) 200 | elif type(value) is str: 201 | ret += indent + 'string ' + key + ' = "' + value + '"\n' 202 | elif type(value) is bool: 203 | ret += indent + 'bool ' + key + ' = ' 204 | ret += '1\n' if value else '0\n' 205 | else: 206 | valueType = getValueType(value) 207 | ret += indent + valueType.toString() + ' ' + key + ' = ' 208 | ret += valueToString(value) + '\n' 209 | return ret + space + '}\n' 210 | 211 | def propertyToString(prop, space): 212 | if type(prop) is str: 213 | return '"' + prop + '"' 214 | if type(prop) is dict: 215 | return dictionaryToString(prop, space) 216 | if type(prop) is UsdAttribute: 217 | return '<' + prop.getPathStr() + '>' 218 | if type(prop) is UsdPrim: 219 | return '<' + prop.getPathStr() + '>' 220 | return valueToString(prop) 221 | 222 | def interleaveLists(lists): 223 | return [x for x in itertools.chain(*itertools.zip_longest(*lists)) if x is not None] 224 | 225 | class UsdAttribute: 226 | def __init__(self, name = '', value = None, type = ValueType.Invalid): 227 | self.name = name 228 | self.value = value 229 | self.frames = [] 230 | self.qualifiers = [] 231 | self.metadata = {} 232 | self.valueType = type 233 | self.valueTypeStr = None 234 | self.parent = None 235 | self.pathIndex = -1 236 | self.pathJump = 0 237 | if type == ValueType.Invalid: 238 | self.valueType = self.getValueType() 239 | if self.isRelationship(): 240 | self.valueTypeStr = 'rel' 241 | 242 | def __str__(self): 243 | return self.toString() 244 | 245 | def __setitem__(self, key, item): 246 | self.metadata[key] = item 247 | 248 | def __getitem__(self, key): 249 | return self.metadata[key] 250 | 251 | def toString(self, space = '', debug = False): 252 | ret = space 253 | att = self.value if self.isConnection() else self 254 | if len(att.qualifiers) > 0: 255 | ret += ' '.join(q for q in att.qualifiers) + ' ' 256 | ret += att.valueTypeToString() 257 | ret += ' ' + self.name 258 | if self.isConnection(): 259 | ret += '.connect = <' + self.value.getPathStr() + '>' 260 | elif self.isRelationship(): 261 | ret += ' = <' + self.value.getPathStr() + '>' 262 | elif self.hasTimeSamples(): 263 | ret += self.framesToString(space, debug) 264 | else: 265 | if self.value != None: 266 | ret += ' = ' + self.valueToString(debug) 267 | if len(self.metadata) > 0: 268 | ret += self.metadataToString(space) 269 | return ret + '\n' 270 | 271 | def metadataToString(self, space): 272 | indent = space + TAB 273 | ret = ' (\n' 274 | for k, v in self.metadata.items(): 275 | ret += indent + k + ' = ' + propertyToString(v, indent) + '\n' 276 | return ret + space + ')' 277 | 278 | def framesToString(self, space, debug = False): 279 | indent = space + TAB 280 | ret = '.timeSamples = {\n' 281 | if debug and len(self.frames) > 3: 282 | for frame, value in self.frames[:3]: 283 | ret += indent + '%d: '%frame + valueToString(value) + ',\n' 284 | ret += indent + '...\n' 285 | else: 286 | for frame, value in self.frames: 287 | ret += indent + '%d: '%frame + valueToString(value) + ',\n' 288 | return ret + space + '}' 289 | 290 | def addQualifier(self, qualifier): 291 | self.qualifiers.append(qualifier) 292 | 293 | def addTimeSample(self, frame, value): 294 | if self.valueType == ValueType.Invalid: 295 | self.valueType = getValueType(value) 296 | self.frames.append((frame, value)) 297 | 298 | def valueToString(self, debug = False): 299 | if self.isConnection(): 300 | return self.value.valueToString(debug) 301 | if self.valueType == ValueType.token or self.valueType == ValueType.string: 302 | if type(self.value) is list: 303 | return '[' + ', '.join('"' + v + '"' for v in self.value) + ']' 304 | return '"' + valueToString(self.value) + '"' 305 | if self.valueType == ValueType.asset: 306 | return '@' + valueToString(self.value) + '@' 307 | return valueToString(self.value, debug) 308 | 309 | def valueTypeToString(self): 310 | if self.valueTypeStr != None: 311 | return self.valueTypeStr + ('[]' if self.isArray() else '') 312 | return self.valueType.toString() + ('[]' if self.isArray() else '') 313 | 314 | def isArray(self): 315 | if self.isConnection(): 316 | return self.value.isArray() 317 | if len(self.frames) > 0: 318 | return type(self.frames[0][1]) is list 319 | return self.value != None and type(self.value) is list 320 | 321 | def isConnection(self): 322 | return type(self.value) is UsdAttribute 323 | 324 | def isRelationship(self): 325 | return type(self.value) is UsdPrim 326 | 327 | def hasTimeSamples(self): 328 | return len(self.frames) > 0 329 | 330 | def getPathStr(self): 331 | if self.isConnection(): 332 | return self.value.getPathStr() 333 | if self.parent == None: 334 | return self.name 335 | return self.parent.getPathStr() + '.' + self.name 336 | 337 | def getPathJump(self): 338 | self.pathJump = 0 339 | if self.parent != None and self.parent.attributes[-1] == self: 340 | self.pathJump = -2 341 | #print(self.name, ':', self.pathJump) 342 | return self.pathJump 343 | 344 | def getValueType(self): 345 | if self.isConnection(): 346 | return self.value.getValueType() 347 | elif self.isRelationship(): 348 | return ValueType.Invalid 349 | return getValueType(self.value) 350 | 351 | 352 | class UsdPrim: 353 | def __init__(self, name = '', type = ClassType.Scope): 354 | self.name = name 355 | self.specifierType = SpecifierType.Def 356 | self.classType = type 357 | self.metadata = {} 358 | self.attributes = [] 359 | self.children = [] 360 | self.parent = None 361 | self.pathIndex = -1 362 | self.pathJump = -1 363 | 364 | def __str__(self): 365 | return self.toString() 366 | 367 | def __setitem__(self, key, item): 368 | if type(item) is ValueType: 369 | self.createAttribute(key, type=item) 370 | else: 371 | self.createAttribute(key, item) 372 | 373 | def __getitem__(self, key): 374 | return next((att for att in self.attributes if att.name == key), None) 375 | 376 | def __contains__(self, key): 377 | return self[key] != None 378 | 379 | def toString(self, space = '', debug = False): 380 | indent = space + TAB 381 | line = indent + '\n' 382 | ret = space + self.specifierType.name.lower() + ' ' 383 | if self.classType != None: 384 | ret += self.classType.name + ' ' 385 | ret += '"' + self.name + '"' 386 | if len(self.metadata) > 0: 387 | ret += self.metadataToString(space) 388 | else: 389 | ret += '\n' 390 | ret += space + '{\n' 391 | ret += ''.join(att.toString(indent, debug) for att in self.attributes) 392 | ret += line if len(self.children) > 0 else '' 393 | ret += line.join(c.toString(indent, debug) for c in self.children) 394 | return ret + space + '}\n' 395 | 396 | def metadataToString(self, space): 397 | ret = ' (\n' 398 | for k, v in self.metadata.items(): 399 | ret += space + TAB + k + ' = ' + propertyToString(v, TAB) + '\n' 400 | return ret + space + ')\n' 401 | 402 | def addAttribute(self, attribute): 403 | attribute.parent = self 404 | self.attributes.append(attribute) 405 | return attribute 406 | 407 | def createAttribute(self, name, value = None, type = ValueType.Invalid): 408 | return self.addAttribute(UsdAttribute(name, value, type)) 409 | 410 | def addChild(self, child): 411 | child.parent = self 412 | self.children.append(child) 413 | return child 414 | 415 | def addChildFront(self, child): 416 | child.parent = self 417 | self.children = [child] + self.children 418 | return child 419 | 420 | def createChild(self, name, type): 421 | return self.addChild(UsdPrim(name, type)) 422 | 423 | def createChildFront(self, name, type): 424 | return self.addChildFront(UsdPrim(name, type)) 425 | 426 | def getAttributesOfTypeStr(self, typeStr): 427 | return [a for a in self.attributes if a.valueTypeToString() == typeStr] 428 | 429 | def getChild(self, name): 430 | return next((c for c in self.children if c.name == name), None) 431 | 432 | def getChildOfType(self, type): 433 | return next((c for c in self.children if c.classType == type), None) 434 | 435 | def getChildrenOfType(self, type): 436 | children = [] 437 | for child in self.children: 438 | if child.classType == type: 439 | children.append(child) 440 | children += child.getChildrenOfType(type) 441 | return children 442 | 443 | def getItemAtPathIndex(self, pathIndex): 444 | for att in self.attributes: 445 | if att.pathIndex == pathIndex: 446 | return att 447 | for child in self.children: 448 | if child.pathIndex == pathIndex: 449 | return child 450 | item = child.getItemAtPathIndex(pathIndex) 451 | if item != None: 452 | return item 453 | return None 454 | 455 | def resolvePaths(self, root): 456 | if 'references' in self.metadata: 457 | pathIndex = self.metadata['references'] 458 | self.metadata['references'] = root.getItemAtPathIndex(pathIndex) 459 | if 'inheritPaths' in self.metadata: 460 | paths = self.metadata.pop('inheritPaths') 461 | self.metadata['inherits'] = root.getItemAtPathIndex(paths['path']) 462 | for att in self.attributes: 463 | if 'connectionChildren' in att.metadata: 464 | pathIndex = att.metadata.pop('connectionChildren') 465 | att.value = root.getItemAtPathIndex(pathIndex) 466 | if 'connectionPaths' in att.metadata: 467 | paths = att.metadata.pop('connectionPaths') 468 | att.value = root.getItemAtPathIndex(paths['path']) 469 | if 'targetChildren' in att.metadata: 470 | pathIndex = att.metadata.pop('targetChildren') 471 | att.value = root.getItemAtPathIndex(pathIndex) 472 | if 'targetPaths' in att.metadata: 473 | paths = att.metadata.pop('targetPaths') 474 | att.value = root.getItemAtPathIndex(paths['path']) 475 | for child in self.children: 476 | child.resolvePaths(root) 477 | 478 | def updatePathIndices(self, pathIndex): 479 | self.pathIndex = pathIndex 480 | pathIndex += 1 481 | for child in self.children: 482 | pathIndex = child.updatePathIndices(pathIndex) 483 | for att in self.attributes: 484 | att.pathIndex = pathIndex 485 | pathIndex += 1 486 | return pathIndex 487 | 488 | def getPathStr(self): 489 | if self.parent == None: 490 | return '/' + self.name 491 | return self.parent.getPathStr() + '/' + self.name 492 | 493 | def countItems(self): 494 | #count = len(self.attributes) + len(self.children) 495 | count = len(self.attributes) + len(self.children) 496 | for child in self.children: 497 | count += child.countItems() 498 | return count 499 | 500 | def getPathJump(self): 501 | if self.parent == None or (self.parent.children[-1] == self and len(self.parent.attributes) == 0): 502 | self.pathJump = -1 503 | else: 504 | self.pathJump = self.countItems() + 1 505 | #print(self.name, ':', self.pathJump) 506 | return self.pathJump 507 | 508 | 509 | class UsdData: 510 | def __init__(self): 511 | self.metadata = {} 512 | self.children = [] 513 | self.attributes = [] 514 | self.pathIndex = 0 515 | self.pathJump = -1 516 | 517 | def __str__(self): 518 | return self.toString() 519 | 520 | def __setitem__(self, key, item): 521 | self.metadata[key] = item 522 | 523 | def __getitem__(self, key): 524 | return self.metadata[key] 525 | 526 | def toString(self, debug = False): 527 | ret = '#usda 1.0\n' 528 | ret += self.metadataToString() 529 | ret += '\n' 530 | return ret + '\n'.join(c.toString('', debug) for c in self.children) 531 | 532 | def getPathStr(self): 533 | return '' 534 | 535 | def metadataToString(self): 536 | ret = '(\n' 537 | for k, v in self.metadata.items(): 538 | ret += TAB + k + ' = ' + propertyToString(v, TAB) + '\n' 539 | return ret + ')\n' 540 | 541 | def addChild(self, child): 542 | child.parent = self 543 | self.children.append(child) 544 | return child 545 | 546 | def createChild(self, name, type): 547 | return self.addChild(UsdPrim(name, type)) 548 | 549 | def getChildrenOfType(self, type): 550 | children = [] 551 | for child in self.children: 552 | if child.classType == type: 553 | children.append(child) 554 | children += child.getChildrenOfType(type) 555 | return children 556 | 557 | def getAllMaterials(self): 558 | return self.getChildrenOfType(ClassType.Material) 559 | 560 | def updatePathIndices(self): 561 | pathIndex = 1 562 | for child in self.children: 563 | pathIndex = child.updatePathIndices(pathIndex) 564 | 565 | def getPathJump(self): 566 | self.pathJump = -1 if len(self.children) > 0 else -2 567 | #print('root:', self.pathJump) 568 | return self.pathJump 569 | 570 | def getItemAtPathIndex(self, pathIndex): 571 | for child in self.children: 572 | if child.pathIndex == pathIndex: 573 | return child 574 | item = child.getItemAtPathIndex(pathIndex) 575 | if item != None: 576 | return item 577 | return None 578 | 579 | def resolvePaths(self): 580 | for child in self.children: 581 | child.resolvePaths(self) 582 | 583 | def writeUsda(self, filePath): 584 | f = open(filePath, 'w') 585 | f.write(str(self)) 586 | f.close() 587 | -------------------------------------------------------------------------------- /testing/TestGrid.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/robmcrosby/BlenderUSDZ/c78edfeeef62d19ce9b04b911492e975be935415/testing/TestGrid.png -------------------------------------------------------------------------------- /testing/TestNormals.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/robmcrosby/BlenderUSDZ/c78edfeeef62d19ce9b04b911492e975be935415/testing/TestNormals.png -------------------------------------------------------------------------------- /testing/TestUSDZ_280.blend: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/robmcrosby/BlenderUSDZ/c78edfeeef62d19ce9b04b911492e975be935415/testing/TestUSDZ_280.blend -------------------------------------------------------------------------------- /testing/TestUSDZ_300_Import.blend: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/robmcrosby/BlenderUSDZ/c78edfeeef62d19ce9b04b911492e975be935415/testing/TestUSDZ_300_Import.blend -------------------------------------------------------------------------------- /testing/TestUSDZ_Import.blend: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/robmcrosby/BlenderUSDZ/c78edfeeef62d19ce9b04b911492e975be935415/testing/TestUSDZ_Import.blend -------------------------------------------------------------------------------- /testing/Test_Export_280.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import os 3 | import sys 4 | import importlib 5 | 6 | #scriptPath = bpy.path.abspath("//") + '//..//io_scene_usdz' 7 | scriptPath = bpy.path.abspath("//") + '//..' 8 | if not scriptPath in sys.path: 9 | sys.path.append(scriptPath) 10 | 11 | import io_scene_usdz 12 | #from io_scene_usdz.object_utils import * 13 | 14 | importlib.reload(io_scene_usdz) 15 | 16 | import io_scene_usdz.compression_utils 17 | import io_scene_usdz.value_types 18 | import io_scene_usdz.crate_file 19 | import io_scene_usdz.object_utils 20 | import io_scene_usdz.material_utils 21 | import io_scene_usdz.scene_data 22 | import io_scene_usdz.export_usdz 23 | 24 | importlib.reload(io_scene_usdz.compression_utils) 25 | importlib.reload(io_scene_usdz.value_types) 26 | importlib.reload(io_scene_usdz.crate_file) 27 | importlib.reload(io_scene_usdz.object_utils) 28 | importlib.reload(io_scene_usdz.material_utils) 29 | importlib.reload(io_scene_usdz.scene_data) 30 | importlib.reload(io_scene_usdz.export_usdz) 31 | 32 | 33 | from io_scene_usdz.export_usdz import export_usdz 34 | 35 | 36 | # Create an Exports Directory 37 | exportsDir = bpy.path.abspath("//") + 'exports/' 38 | if not os.path.exists(exportsDir): 39 | os.makedirs(exportsDir) 40 | 41 | # Call the Export Function 42 | export_usdz( 43 | context = bpy.context, 44 | filepath = exportsDir + 'test.usdz', 45 | exportMaterials = True, 46 | bakeTextures = True, 47 | bakeTextureSize = 512, 48 | bakeAO = False, 49 | bakeAOSamples = 64, 50 | exportAnimations = True, 51 | globalScale = 4.0, 52 | useConverter = False, 53 | ) 54 | -------------------------------------------------------------------------------- /testing/Test_Import_280.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import os 3 | import sys 4 | import importlib 5 | 6 | #scriptPath = bpy.path.abspath("//") + '//..//io_scene_usdz' 7 | scriptPath = bpy.path.abspath("//") + '//..' 8 | if not scriptPath in sys.path: 9 | sys.path.append(scriptPath) 10 | 11 | import io_scene_usdz 12 | #from io_scene_usdz.object_utils import * 13 | 14 | importlib.reload(io_scene_usdz) 15 | 16 | import io_scene_usdz.compression_utils 17 | import io_scene_usdz.value_types 18 | import io_scene_usdz.crate_file 19 | import io_scene_usdz.object_utils 20 | import io_scene_usdz.material_utils 21 | import io_scene_usdz.scene_data 22 | import io_scene_usdz.import_usdz 23 | 24 | importlib.reload(io_scene_usdz.compression_utils) 25 | importlib.reload(io_scene_usdz.value_types) 26 | importlib.reload(io_scene_usdz.crate_file) 27 | importlib.reload(io_scene_usdz.object_utils) 28 | importlib.reload(io_scene_usdz.material_utils) 29 | importlib.reload(io_scene_usdz.scene_data) 30 | importlib.reload(io_scene_usdz.import_usdz) 31 | 32 | 33 | from io_scene_usdz.import_usdz import import_usdz 34 | 35 | 36 | # Create an Exports Directory 37 | exportsDir = bpy.path.abspath("//") + 'exports/' 38 | if not os.path.exists(exportsDir): 39 | os.makedirs(exportsDir) 40 | 41 | #filepath = exportsDir + 'teapot.usdz' 42 | #filepath = exportsDir + 'testCopy.usdz' 43 | filepath = exportsDir + 'test.usdz' 44 | 45 | # Call the Import Function 46 | import_usdz( 47 | context = bpy.context, 48 | filepath = filepath, 49 | materials = True, 50 | animations = True, 51 | ) 52 | -------------------------------------------------------------------------------- /testing/Test_Import_300.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import os 3 | import sys 4 | import importlib 5 | 6 | #scriptPath = bpy.path.abspath("//") + '//..//io_scene_usdz' 7 | scriptPath = bpy.path.abspath("//") + '//..' 8 | if not scriptPath in sys.path: 9 | sys.path.append(scriptPath) 10 | 11 | import io_scene_usdz 12 | #from io_scene_usdz.object_utils import * 13 | 14 | importlib.reload(io_scene_usdz) 15 | 16 | import io_scene_usdz.compression_utils 17 | import io_scene_usdz.value_types 18 | import io_scene_usdz.crate_file 19 | import io_scene_usdz.object_utils 20 | import io_scene_usdz.material_utils 21 | import io_scene_usdz.scene_data 22 | import io_scene_usdz.import_usdz 23 | 24 | importlib.reload(io_scene_usdz.compression_utils) 25 | importlib.reload(io_scene_usdz.value_types) 26 | importlib.reload(io_scene_usdz.crate_file) 27 | importlib.reload(io_scene_usdz.object_utils) 28 | importlib.reload(io_scene_usdz.material_utils) 29 | importlib.reload(io_scene_usdz.scene_data) 30 | importlib.reload(io_scene_usdz.import_usdz) 31 | 32 | 33 | from io_scene_usdz.import_usdz import import_usdz 34 | 35 | 36 | # Create an Exports Directory 37 | exportsDir = bpy.path.abspath("//") + 'exports/' 38 | if not os.path.exists(exportsDir): 39 | os.makedirs(exportsDir) 40 | 41 | #filepath = exportsDir + 'teapot.usdz' 42 | #filepath = exportsDir + 'testCopy.usdz' 43 | filepath = exportsDir + 'test.usdz' 44 | 45 | # Call the Import Function 46 | import_usdz( 47 | context = bpy.context, 48 | filepath = filepath, 49 | materials = True, 50 | animations = True, 51 | ) 52 | -------------------------------------------------------------------------------- /testing/Test_LZ4_Compression.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import os 3 | import sys 4 | import importlib 5 | 6 | from struct import * 7 | 8 | scriptPath = bpy.path.abspath("//") + '//..' 9 | if not scriptPath in sys.path: 10 | sys.path.append(scriptPath) 11 | 12 | import io_scene_usdz 13 | 14 | importlib.reload(io_scene_usdz) 15 | 16 | import io_scene_usdz.compression_utils 17 | 18 | importlib.reload(io_scene_usdz.compression_utils) 19 | 20 | 21 | from io_scene_usdz.compression_utils import lz4Decompress, lz4Compress, usdInt32Decompress, usdInt32Compress 22 | 23 | 24 | exportsDir = bpy.path.abspath("//") + 'exports/' 25 | #filepath = exportsDir + 'test.usdc' 26 | filepath = exportsDir + 'teapot.usdc' 27 | #filepath = exportsDir + 'testMult.usdc' 28 | #filepath = exportsDir + 'testThree.usdc' 29 | #filepath = exportsDir + 'testMat.usdc' 30 | #filepath = exportsDir + 'testTex.usdc' 31 | #filepath = exportsDir + 'testScale.usdc' 32 | #filepath = exportsDir + 'testSkin.usdc' 33 | #filepath = exportsDir + 'testCube.usdc' 34 | #filepath = exportsDir + 'testPlane.usdc' 35 | #filepath = exportsDir + 'testEmpty.usdc' 36 | 37 | print(filepath) 38 | 39 | 40 | def readInt(file, size, byteorder='little', signed=False): 41 | return int.from_bytes(file.read(size), byteorder, signed=signed) 42 | 43 | def readStr(file, size, encoding='utf-8'): 44 | data = file.read(size) 45 | return data[:data.find(0)].decode(encoding=encoding) 46 | 47 | def decodeStrings(data, count): 48 | strings = [] 49 | while count > 0: 50 | p = data.find(0) 51 | if p < 0: 52 | break 53 | strings.append(data[:p].decode("utf-8")) 54 | data = data[p+1:] 55 | count -= 1 56 | return strings 57 | 58 | def decodeInts(data, count, size, byteorder='little', signed=False): 59 | ints = [] 60 | for i in range(count): 61 | if i * size > len(data): 62 | print('Over Run Data') 63 | break 64 | value = int.from_bytes(data[i*size:i*size + size], byteorder, signed=signed) 65 | ints.append(value) 66 | return ints 67 | 68 | def decodeDoubles(data, count): 69 | values = [] 70 | for i in range(count): 71 | if i * 8 > len(data): 72 | print('Over Run Data') 73 | break 74 | values.append(unpack(' 0: 168 | i = fieldSets[index] 169 | while i >= 0 and index+1 < len(fieldSets) and i < len(fields): 170 | fieldSet.append(tokens[fields[i]]) 171 | index += 1 172 | i = fieldSets[index] 173 | return fieldSet 174 | 175 | 176 | ARRAY_BIT = (1 << 63) 177 | INLINE_BIT = (1 << 62) 178 | COMPRESSED_BIT = (1 << 61) 179 | PAYLOAD_MASK = (1 << 48) - 1 180 | 181 | def decodeRep(data): 182 | rep = {} 183 | rep['type'] = getValueType((data >> 48) & 0xFF) 184 | rep['array'] = (data & ARRAY_BIT) != 0 185 | rep['inline'] = (data & INLINE_BIT) != 0 186 | rep['compressed'] = (data & COMPRESSED_BIT) != 0 187 | rep['payload'] = data & PAYLOAD_MASK 188 | return rep 189 | 190 | def decodeReps(data, numReps): 191 | reps = [] 192 | values = decodeInts(data, numFields, 8) 193 | for value in values: 194 | reps.append(decodeRep(value)) 195 | return reps 196 | 197 | def getRepValue(rep, file, tokens): 198 | if rep['type'] == 'Token': 199 | if rep['inline']: 200 | return tokens[rep['payload']] 201 | elif rep['array']: 202 | file.seek(rep['payload']) 203 | num = readInt(file, 4) 204 | values = [] 205 | while num > 0: 206 | values.append(tokens[readInt(file, 4)]) 207 | num -= 1 208 | return values 209 | elif rep['type'] == 'TokenVector': 210 | file.seek(rep['payload']) 211 | num = readInt(file, 8) 212 | values = [] 213 | while num > 0: 214 | values.append(tokens[readInt(file, 4)]) 215 | num -= 1 216 | return values 217 | elif rep['type'] == 'Specifier': 218 | return getSpecifierType(rep['payload']) 219 | elif rep['type'] == 'Int': 220 | if not rep['inline'] and rep['array']: 221 | file.seek(rep['payload']) 222 | num = readInt(file, 4) 223 | values = [] 224 | if rep['compressed']: 225 | size = readInt(file, 8) 226 | buffer = lz4Decompress(file.read(size)) 227 | values = usdInt32Decompress(buffer, num) 228 | else: 229 | while num > 0: 230 | values.append(readInt(file, 4, signed=True)) 231 | num -= 1 232 | return values 233 | else: 234 | return rep['payload'] 235 | elif rep['type'] == 'Float': 236 | if rep['inline'] and not rep['array']: 237 | return unpack(' 0: 244 | values.append(unpack(' 0: 253 | values.append(unpack(' 0: 271 | values.append(unpack(' 0: 328 | values.append(unpack(' 0: 337 | values.append(unpack(' 0: 351 | # values.append(unpack('= 0: 444 | set.append(fieldSets[i]) 445 | i += 1 446 | print(index, ':', set) 447 | i += 1 448 | #print(fieldSets) 449 | 450 | offset, size = toc['PATHS'] 451 | file.seek(offset) 452 | totalPaths = readInt(file, 8) 453 | numPaths = readInt(file, 8) 454 | # Get Path Indices 455 | compressedSize = readInt(file, 8) 456 | data = file.read(compressedSize) 457 | data = lz4Decompress(data) 458 | pathIndices = usdInt32Decompress(data, numPaths) 459 | # Get Element Token Indices 460 | compressedSize = readInt(file, 8) 461 | data = file.read(compressedSize) 462 | data = lz4Decompress(data) 463 | elementTokenIndices = usdInt32Decompress(data, numPaths) 464 | # Get Jumps 465 | compressedSize = readInt(file, 8) 466 | data = file.read(compressedSize) 467 | data = lz4Decompress(data) 468 | jumps = usdInt32Decompress(data, numPaths) 469 | 470 | paths = [] 471 | for i in range(numPaths): 472 | path = {} 473 | path['index'] = pathIndices[i] 474 | path['element'] = tokens[abs(elementTokenIndices[i])] 475 | path['prim'] = elementTokenIndices[i] < 0 476 | path['jump'] = jumps[i] 477 | path['type'] = 'both' 478 | if path['jump'] == 0: 479 | path['type'] = 'sibling' 480 | elif path['jump'] == -1: 481 | path['type'] = 'child' 482 | elif path['jump'] == -2: 483 | path['type'] = 'leaf' 484 | paths.append(path) 485 | 486 | #data = file.read(size) 487 | print('\nPATHS (', offset, ':', offset+size, ')') 488 | for path in paths: 489 | print(path['index'], ':', path['element'], 'prim:', path['prim'], 'jump:', path['jump'], path['type']) 490 | #print('pathIndices:', pathIndices) 491 | #print('elementTokenIndices:', elementTokenIndices) 492 | #print('jumps:', jumps) 493 | #print(data) 494 | 495 | offset, size = toc['SPECS'] 496 | file.seek(offset) 497 | numSpecs = readInt(file, 8) 498 | # Get path indices 499 | compressedSize = readInt(file, 8) 500 | data = file.read(compressedSize) 501 | data = lz4Decompress(data) 502 | pathIndices = usdInt32Decompress(data, numSpecs) 503 | # Get fset indices 504 | compressedSize = readInt(file, 8) 505 | data = file.read(compressedSize) 506 | data = lz4Decompress(data) 507 | fsetIndices = usdInt32Decompress(data, numSpecs) 508 | # Get spec types 509 | compressedSize = readInt(file, 8) 510 | data = file.read(compressedSize) 511 | data = lz4Decompress(data) 512 | specTypes = usdInt32Decompress(data, numSpecs) 513 | 514 | specs = [] 515 | for i in range(numSpecs): 516 | spec = {} 517 | spec['path'] = pathIndices[i] 518 | #spec['fset'] = getFieldSet(tokens, fields, fieldSets, fsetIndices[i]) 519 | spec['fset'] = fsetIndices[i] 520 | spec['type'] = getSpecType(specTypes[i]) 521 | #spec['value'] = 522 | specs.append(spec) 523 | 524 | print('\nSPECS (', offset, ':', offset+size, ')') 525 | for spec in specs: 526 | print(spec['path'], ':', spec['type'], spec['fset']) 527 | #print('pathIndices:', pathIndices) 528 | #print('fsetIndices:', fsetIndices) 529 | #print('specTypes:', specTypes) 530 | #print(data) 531 | """ 532 | -------------------------------------------------------------------------------- /testing/Test_Zip.py: -------------------------------------------------------------------------------- 1 | import zipfile 2 | 3 | 4 | --------------------------------------------------------------------------------