├── .gitignore ├── LICENSE ├── README.md ├── __init__.py ├── images ├── pca blendshape AE.png ├── pca_blendshape_ui.png └── regression_ui.png ├── nodes ├── floats_to_transform.py ├── matrix_to_floats.py ├── pca_blendshape.py └── regression_node.py ├── nodes_ui.py └── ui ├── __init__.py ├── add.png ├── maya_utils.py ├── pca_win.py ├── regresion_win.py └── remove-button.svg /.gitignore: -------------------------------------------------------------------------------- 1 | **/__pycache__/ -------------------------------------------------------------------------------- /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 | ## Overview 2 | 3 | This repository contains example implementations of machine learning nodes for Autodesk Maya. These nodes are designed for instructional purposes and are not intended for production use. The nodes included are: 4 | 5 | - Regression Node: Performs linear regression inference based on input features. 6 | - PCA Blendshape Node: Performs Principal Component Analysis (PCA) to create blendshapes for mesh deformation. 7 | 8 | 9 | ## Files 10 | 11 | - `regression_node.py`: Implementation of the Regression node. 12 | - `regression_win.py`: UI for creating and managing Regression nodes in Maya. 13 | - `pca_blendshape.py`: Implementation of the PCA blendshape node. 14 | - `pca_win.py`: UI for creating and managing PCA blendshape nodes in Maya. 15 | 16 | 17 | ## Installation 18 | 19 | 1. Clone the repository: 20 | ```bash 21 | git clone https://github.com/yourusername/ml-example-nodes.git 22 | ``` 23 | 2. Copy the Python files to your Maya scripts directory, or **Add Repository to System Path** using `sys.path.append`. 24 | ```python 25 | import sys 26 | sys.path.append('path/to/your/repo') 27 | ``` 28 | 29 | ## Usage 30 | 31 | ### Regression Node 32 | 33 | 1. Open Maya and load the script editor. 34 | 2. To open the Regression UI execute: 35 | ```python 36 | import nodes_ui 37 | nodes_ui.regrssion_ui() 38 | ``` 39 | 3. Select the input attributes, set the output attribute, and create the Regression node. 40 | 41 | #### Reegression UI 42 | 43 | 1. **Launch the UI**: Run the show() function from regression_ui.py to display the UI. 44 | 2. **Set Input Attributes**: Add input attributes to the input list widget. 45 | 3. **Set Output Attributes**: Add output attributes to the target list widget. 46 | 4. **Get Animation Data**: If the scene has anmation, use it for train else, check the box to generate random animation curves and set the parameters (start frame, end frame, min value, max value). 47 | 5. **Train the Model**: Click the button to train the Linear Regression model using the provided data and settings. 48 | 49 | ### PCA Blendshape Node 50 | 51 | 1. Open Maya and load the script editor. 52 | 2. To open the PCA Blendshape UI execute: 53 | ```python 54 | import nodes_ui 55 | nodes_ui.pca_ui() 56 | ``` 57 | 3. Select the source blendshape node and target mesh. 58 | 4. Click the "Create PCA Blendshape" button to create the PCA blendshape node. 59 | 60 | #### PCA Blendshape Features 61 | The PCA blendshape node converts the selected blendshape to the PCA space. By default, it does not compress the data. Instead, it allows the user to choose the desired level of compression. This means the user can decide how much variation to retain, balancing between data size reduction and the amount of variation preserved. 62 | - **Compression Ratio**: The desired variance to keep for compression. 63 | - **Compression Result**: The actual compression percentage achieved. 64 | 65 | 66 | ## Dependencies 67 | 68 | - Autodesk Maya 69 | - NumPy 70 | - scikit-learn 71 | - PySide2 72 | 73 | ## License 74 | 75 | This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details. 76 | 77 | ## Disclaimer 78 | 79 | These nodes are provided as-is for educational purposes only. They are not intended for production use and come with no warranty or support. -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lopezmauro/ml-example-nodes/ffb7221b4b6f32e1f43a9cd69863a6afaf64cc77/__init__.py -------------------------------------------------------------------------------- /images/pca blendshape AE.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lopezmauro/ml-example-nodes/ffb7221b4b6f32e1f43a9cd69863a6afaf64cc77/images/pca blendshape AE.png -------------------------------------------------------------------------------- /images/pca_blendshape_ui.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lopezmauro/ml-example-nodes/ffb7221b4b6f32e1f43a9cd69863a6afaf64cc77/images/pca_blendshape_ui.png -------------------------------------------------------------------------------- /images/regression_ui.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lopezmauro/ml-example-nodes/ffb7221b4b6f32e1f43a9cd69863a6afaf64cc77/images/regression_ui.png -------------------------------------------------------------------------------- /nodes/floats_to_transform.py: -------------------------------------------------------------------------------- 1 | from maya import mel 2 | import maya.api.OpenMaya as om 3 | import math 4 | 5 | def maya_useNewAPI(): 6 | """ 7 | This function is required by Maya to indicate that this plugin uses the Maya Python API 2.0. 8 | """ 9 | pass 10 | 11 | class FloatsToTransform(om.MPxNode): 12 | """ 13 | A custom Maya node that converts a set of 16 float values (representing a 4x4 matrix) 14 | into a transform node's translation, rotation, and scale attributes. 15 | """ 16 | 17 | # Node name and ID 18 | kNodeName = "floatsToTransform" 19 | kNodeId = om.MTypeId(0x0003A7F2) 20 | 21 | # Input attributes 22 | aInputFloats = None # Compound attribute to store the 16 float input attributes 23 | floatAttributes = [] # List to store the individual float attributes 24 | aOrthoNormalize = None # Attribute to orthogonalize the matrix 25 | 26 | # Output attributes 27 | aOutputTranslate = None # Output attribute for translation 28 | aOutputRotateX = None # Output attribute for rotation around X-axis 29 | aOutputRotateY = None # Output attribute for rotation around Y-axis 30 | aOutputRotateZ = None # Output attribute for rotation around Z-axis 31 | aOutputScale = None # Output attribute for scale 32 | 33 | def __init__(self): 34 | """ 35 | Constructor for the FloatsToTransform node. 36 | """ 37 | om.MPxNode.__init__(self) 38 | 39 | def compute(self, plug, data): 40 | """ 41 | Compute method that is called whenever the node needs to be evaluated. 42 | 43 | Args: 44 | plug (MPlug): The plug that needs to be computed. 45 | data (MDataBlock): The data block containing the node's data. 46 | """ 47 | # Check if the plug is one of the output attributes 48 | compute = False 49 | for attr in [FloatsToTransform.aOutputTranslate, FloatsToTransform.aOutputRotate, 50 | FloatsToTransform.aOutputScale]: 51 | if plug == attr: 52 | compute = True 53 | break 54 | if not compute: 55 | return 56 | 57 | # Get input float values from the compound attribute 58 | inputFloatsHandle = data.inputValue(self.aInputFloats) 59 | inputFloats = [] 60 | for i, attr in enumerate(FloatsToTransform.floatAttributes): 61 | childHandle = inputFloatsHandle.child(attr) 62 | inputFloats.append(childHandle.asFloat()) 63 | 64 | # Create matrix from input floats 65 | matrix = om.MMatrix(inputFloats) 66 | 67 | # Orthogonalize if checked 68 | orthoNormalize = data.inputValue(self.aOrthoNormalize).asBool() 69 | if orthoNormalize: 70 | matrix = self.orthoNormalizeMatrix(matrix) 71 | 72 | 73 | # Decompose matrix into translation, rotation, and scale 74 | transformMatrix = om.MTransformationMatrix(matrix) 75 | translation = transformMatrix.translation(om.MSpace.kWorld) 76 | rotation = transformMatrix.rotation() # Returns MEulerRotation in radians 77 | scale = transformMatrix.scale(om.MSpace.kWorld) 78 | 79 | # Set output values 80 | outputTranslateHandle = data.outputValue(self.aOutputTranslate) 81 | outputTranslateHandle.set3Float(translation.x, translation.y, translation.z) 82 | outputTranslateHandle.setClean() 83 | 84 | # Set rotation values (in degrees) 85 | outputRotateXHandle = data.outputValue(self.aOutputRotateX) 86 | outputRotateXHandle.setMAngle(om.MAngle(math.degrees(rotation.x), om.MAngle.kDegrees)) 87 | outputRotateXHandle.setClean() 88 | 89 | outputRotateYHandle = data.outputValue(self.aOutputRotateY) 90 | outputRotateYHandle.setMAngle(om.MAngle(math.degrees(rotation.y), om.MAngle.kDegrees)) 91 | outputRotateYHandle.setClean() 92 | 93 | outputRotateZHandle = data.outputValue(self.aOutputRotateZ) 94 | outputRotateZHandle.setMAngle(om.MAngle(math.degrees(rotation.z), om.MAngle.kDegrees)) 95 | outputRotateZHandle.setClean() 96 | 97 | # Set scale values 98 | outputScaleHandle = data.outputValue(self.aOutputScale) 99 | outputScaleHandle.set3Float(scale[0], scale[1], scale[2]) 100 | outputScaleHandle.setClean() 101 | 102 | data.setClean(plug) 103 | 104 | def orthoNormalizeMatrix(self, matrix): 105 | """ 106 | Orthogonalizes the vectors of the given matrix. 107 | 108 | Args: 109 | matrix (MMatrix): The matrix to orthogonalize. 110 | 111 | Returns: 112 | MMatrix: The orthogonalized matrix. 113 | """ 114 | xAxis = om.MVector(matrix[0], matrix[1], matrix[2]).normal() 115 | yAxis = om.MVector(matrix[4], matrix[5], matrix[6]).normal() 116 | zAxis = (xAxis ^ yAxis).normal() 117 | yAxis = (zAxis ^ xAxis).normal() 118 | 119 | # Create a new orthogonalized matrix 120 | orthogonalMatrix = matrix 121 | orthogonalMatrix[0] = xAxis.x 122 | orthogonalMatrix[1] = xAxis.y 123 | orthogonalMatrix[2] = xAxis.z 124 | orthogonalMatrix[4] = yAxis.x 125 | orthogonalMatrix[5] = yAxis.y 126 | orthogonalMatrix[6] = yAxis.z 127 | orthogonalMatrix[8] = zAxis.x 128 | orthogonalMatrix[9] = zAxis.y 129 | orthogonalMatrix[10] = zAxis.z 130 | 131 | return orthogonalMatrix 132 | 133 | def creator(): 134 | """ 135 | Creates an instance of the FloatsToTransform node. 136 | 137 | Returns: 138 | FloatsToTransform: A new instance of the FloatsToTransform node. 139 | """ 140 | return FloatsToTransform() 141 | 142 | def initialize(): 143 | """ 144 | Initializes the FloatsToTransform node by creating its attributes and setting up dependencies. 145 | """ 146 | nAttr = om.MFnNumericAttribute() 147 | cAttr = om.MFnCompoundAttribute() 148 | 149 | # Input compound attribute 150 | FloatsToTransform.aInputFloats = cAttr.create("inputFloats", "if") 151 | cAttr.storable = True 152 | cAttr.writable = True 153 | cAttr.readable = False 154 | 155 | # Create and add child float attributes 156 | default_values = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1] 157 | for i, value in enumerate(default_values): 158 | attr = nAttr.create(f"inputFloat{i}", f"if{i}", om.MFnNumericData.kFloat, value) 159 | FloatsToTransform.floatAttributes.append(attr) 160 | cAttr.addChild(attr) 161 | 162 | # Orthogonalize checkbox 163 | nAttr = om.MFnNumericAttribute() 164 | FloatsToTransform.aOrthoNormalize = nAttr.create("orthoNormalize", "on", om.MFnNumericData.kBoolean, True) 165 | nAttr.storable = True 166 | nAttr.writable = True 167 | nAttr.readable = True 168 | 169 | # Output translate attribute 170 | nAttr = om.MFnNumericAttribute() 171 | FloatsToTransform.aOutputTranslate = nAttr.createPoint("outputTranslate", "ot") 172 | nAttr.storable = False 173 | nAttr.writable = False 174 | nAttr.readable = True 175 | 176 | # Output rotate attributes (as angles) 177 | cmpAttr = om.MFnCompoundAttribute() 178 | FloatsToTransform.aOutputRotate = cmpAttr.create("outputRotate", "or") 179 | uAttr = om.MFnUnitAttribute() 180 | FloatsToTransform.aOutputRotateX = uAttr.create("outputRotateX", "orx", om.MFnUnitAttribute.kAngle, 0.0) 181 | uAttr.storable = False 182 | uAttr.writable = False 183 | uAttr.readable = True 184 | cmpAttr.addChild(FloatsToTransform.aOutputRotateX) 185 | 186 | FloatsToTransform.aOutputRotateY = uAttr.create("outputRotateY", "ory", om.MFnUnitAttribute.kAngle, 0.0) 187 | uAttr.storable = False 188 | uAttr.writable = False 189 | uAttr.readable = True 190 | cmpAttr.addChild(FloatsToTransform.aOutputRotateY) 191 | 192 | FloatsToTransform.aOutputRotateZ = uAttr.create("outputRotateZ", "orz", om.MFnUnitAttribute.kAngle, 0.0) 193 | uAttr.storable = False 194 | uAttr.writable = False 195 | uAttr.readable = True 196 | cmpAttr.addChild(FloatsToTransform.aOutputRotateZ) 197 | 198 | # Output scale attribute 199 | nAttr = om.MFnNumericAttribute() 200 | FloatsToTransform.aOutputScale = nAttr.createPoint("outputScale", "os") 201 | nAttr.storable = False 202 | nAttr.writable = False 203 | nAttr.readable = True 204 | 205 | # Add attributes 206 | FloatsToTransform.addAttribute(FloatsToTransform.aInputFloats) 207 | FloatsToTransform.addAttribute(FloatsToTransform.aOrthoNormalize) 208 | FloatsToTransform.addAttribute(FloatsToTransform.aOutputTranslate) 209 | FloatsToTransform.addAttribute(FloatsToTransform.aOutputRotate) 210 | FloatsToTransform.addAttribute(FloatsToTransform.aOutputScale) 211 | 212 | # Set attribute dependencies 213 | FloatsToTransform.attributeAffects(FloatsToTransform.aInputFloats, FloatsToTransform.aOutputTranslate) 214 | FloatsToTransform.attributeAffects(FloatsToTransform.aInputFloats, FloatsToTransform.aOutputRotate) 215 | FloatsToTransform.attributeAffects(FloatsToTransform.aInputFloats, FloatsToTransform.aOutputRotateY) 216 | FloatsToTransform.attributeAffects(FloatsToTransform.aInputFloats, FloatsToTransform.aOutputRotateZ) 217 | FloatsToTransform.attributeAffects(FloatsToTransform.aInputFloats, FloatsToTransform.aOutputScale) 218 | FloatsToTransform.attributeAffects(FloatsToTransform.aOrthoNormalize, FloatsToTransform.aOutputTranslate) 219 | FloatsToTransform.attributeAffects(FloatsToTransform.aOrthoNormalize, FloatsToTransform.aOutputRotate) 220 | FloatsToTransform.attributeAffects(FloatsToTransform.aOrthoNormalize, FloatsToTransform.aOutputRotateY) 221 | FloatsToTransform.attributeAffects(FloatsToTransform.aOrthoNormalize, FloatsToTransform.aOutputRotateZ) 222 | FloatsToTransform.attributeAffects(FloatsToTransform.aOrthoNormalize, FloatsToTransform.aOutputScale) 223 | 224 | def initializePlugin(mobject): 225 | """ 226 | Initializes the plugin by registering the node. 227 | 228 | Args: 229 | mobject (MObject): The plugin object. 230 | """ 231 | vendor = "Mauro Lopez" 232 | version = "1.0" 233 | plugin = om.MFnPlugin(mobject, vendor, version, "Any") 234 | try: 235 | plugin.registerNode(FloatsToTransform.kNodeName, FloatsToTransform.kNodeId, creator, initialize) 236 | mel.eval(aetemplate) 237 | except: 238 | raise RuntimeError("Failed to register nodes") 239 | 240 | def uninitializePlugin(mobject): 241 | """ 242 | Uninitializes the plugin by deregistering the node. 243 | 244 | Args: 245 | mobject (MObject): The plugin object. 246 | """ 247 | plugin = om.MFnPlugin(mobject) 248 | try: 249 | plugin.deregisterNode(FloatsToTransform.kNodeId) 250 | except: 251 | raise RuntimeError("Failed to deregister nodes") 252 | 253 | # Define the MEL AE template as a string 254 | aetemplate = """ 255 | global proc AEfloatsToTransformTemplate(string $nodeName) { 256 | editorTemplate -beginScrollLayout; 257 | 258 | // Input Section 259 | editorTemplate -beginLayout "Input Floats" -collapse 1; 260 | editorTemplate -addControl "inputFloats"; 261 | editorTemplate -endLayout; 262 | 263 | // Options Section 264 | editorTemplate -beginLayout "Options" -collapse 0; 265 | editorTemplate -addControl "orthoNormalize"; 266 | editorTemplate -endLayout; 267 | 268 | // Output Section 269 | editorTemplate -beginLayout "Output" -collapse 0; 270 | editorTemplate -addControl "outputTranslate"; 271 | editorTemplate -addControl "outputRotate"; 272 | editorTemplate -addControl "outputScale"; 273 | editorTemplate -endLayout; 274 | 275 | // Include default Maya attributes 276 | AEdependNodeTemplate $nodeName; 277 | 278 | editorTemplate -addExtraControls; 279 | editorTemplate -endScrollLayout; 280 | }""" -------------------------------------------------------------------------------- /nodes/matrix_to_floats.py: -------------------------------------------------------------------------------- 1 | import maya.api.OpenMaya as om 2 | from maya import mel 3 | 4 | def maya_useNewAPI(): 5 | """ 6 | This function is required by Maya to indicate that this plugin uses the Maya Python API 2.0. 7 | """ 8 | pass 9 | 10 | class MatrixToFloats(om.MPxNode): 11 | """ 12 | A custom Maya node that converts a 4x4 matrix into 16 float values, 13 | representing the individual elements of the matrix. 14 | """ 15 | 16 | # Node name and ID 17 | kNodeName = "matrixToFloats" 18 | kNodeId = om.MTypeId(0x0005C1B8) 19 | 20 | # Input attributes 21 | aInputMatrix = None # Attribute for the input matrix 22 | 23 | # Output attributes 24 | aOutputFloats = None # Compound attribute to store the 16 float output attributes 25 | floatAttributes = [] # List to store the individual float attributes 26 | 27 | def __init__(self): 28 | """ 29 | Constructor for the MatrixToFloats node. 30 | """ 31 | om.MPxNode.__init__(self) 32 | 33 | def compute(self, plug, data): 34 | """ 35 | Compute method that is called whenever the node needs to be evaluated. 36 | 37 | Args: 38 | plug (MPlug): The plug that needs to be computed. 39 | data (MDataBlock): The data block containing the node's data. 40 | """ 41 | # Check if the plug is the output compound attribute or one of its children 42 | if plug == self.aOutputFloats or plug.isChild: 43 | # Get the input matrix value 44 | inputMatrixHandle = data.inputValue(self.aInputMatrix) 45 | inputMatrix = inputMatrixHandle.asMatrix() 46 | 47 | # Get the output compound attribute handle 48 | outputFloatsHandle = data.outputValue(self.aOutputFloats) 49 | 50 | # Set the output float values from the matrix elements 51 | for i, attr in enumerate(MatrixToFloats.floatAttributes): 52 | childHandle = outputFloatsHandle.child(attr) 53 | childHandle.setFloat(inputMatrix[i]) 54 | childHandle.setClean() 55 | 56 | # Mark the plug as clean to indicate it has been computed 57 | data.setClean(plug) 58 | 59 | def creator(): 60 | """ 61 | Creates an instance of the MatrixToFloats node. 62 | 63 | Returns: 64 | MatrixToFloats: A new instance of the MatrixToFloats node. 65 | """ 66 | return MatrixToFloats() 67 | 68 | def initialize(): 69 | """ 70 | Initializes the MatrixToFloats node by creating its attributes and setting up dependencies. 71 | """ 72 | nAttr = om.MFnNumericAttribute() 73 | mAttr = om.MFnMatrixAttribute() 74 | cAttr = om.MFnCompoundAttribute() 75 | 76 | # Input matrix attribute 77 | MatrixToFloats.aInputMatrix = mAttr.create("inputMatrix", "im", om.MFnMatrixAttribute.kDouble) 78 | mAttr.storable = True # Allow the attribute to be stored in the Maya file 79 | mAttr.writable = True # Allow the attribute to be written to 80 | mAttr.readable = False # The attribute is not directly readable (used for computation) 81 | mAttr.keyable = True # Allow the attribute to be keyable in the timeline 82 | 83 | # Output compound attribute 84 | MatrixToFloats.aOutputFloats = cAttr.create("outputFloats", "of") 85 | cAttr.storable = False # Output attributes are not stored in the Maya file 86 | cAttr.writable = False # Output attributes are not writable 87 | cAttr.readable = True # Output attributes are readable 88 | 89 | # Create and add child float attributes 90 | for i in range(16): 91 | attr = nAttr.create(f"outputFloat{i}", f"of{i}", om.MFnNumericData.kFloat, 0.0) 92 | nAttr.storable = False # Output attributes are not stored in the Maya file 93 | nAttr.writable = False # Output attributes are not writable 94 | nAttr.readable = True # Output attributes are readable 95 | MatrixToFloats.floatAttributes.append(attr) 96 | cAttr.addChild(attr) 97 | 98 | # Add attributes to the node 99 | MatrixToFloats.addAttribute(MatrixToFloats.aInputMatrix) 100 | MatrixToFloats.addAttribute(MatrixToFloats.aOutputFloats) 101 | 102 | # Set attribute dependencies 103 | MatrixToFloats.attributeAffects(MatrixToFloats.aInputMatrix, MatrixToFloats.aOutputFloats) 104 | 105 | def initializePlugin(mobject): 106 | """ 107 | Initializes the plugin by registering the node. 108 | 109 | Args: 110 | mobject (MObject): The plugin object. 111 | """ 112 | vendor = "Mauro Lopez" 113 | version = "1.0" 114 | plugin = om.MFnPlugin(mobject, vendor, version, "Any") 115 | try: 116 | # Register the node with Maya 117 | plugin.registerNode(MatrixToFloats.kNodeName, MatrixToFloats.kNodeId, creator, initialize) 118 | # Evaluate the MEL template for the node's attribute editor 119 | mel.eval(aetemplate) 120 | except: 121 | raise RuntimeError("Failed to register nodes") 122 | 123 | def uninitializePlugin(mobject): 124 | """ 125 | Uninitializes the plugin by deregistering the node. 126 | 127 | Args: 128 | mobject (MObject): The plugin object. 129 | """ 130 | plugin = om.MFnPlugin(mobject) 131 | try: 132 | # Deregister the node from Maya 133 | plugin.deregisterNode(MatrixToFloats.kNodeId) 134 | except: 135 | raise RuntimeError("Failed to deregister nodes") 136 | 137 | # Define the MEL AE template as a string 138 | aetemplate = """ 139 | global proc AEmatrixToFloatsTemplate(string $nodeName) { 140 | editorTemplate -beginScrollLayout; 141 | 142 | // Input Section 143 | editorTemplate -beginLayout "Input" -collapse 0; 144 | editorTemplate -addControl "inputMatrix"; 145 | editorTemplate -endLayout; 146 | 147 | // Output Section 148 | editorTemplate -beginLayout "Output Floats" -collapse 0; 149 | editorTemplate -addControl "outputFloats"; 150 | editorTemplate -endLayout; 151 | 152 | // Include default Maya attributes 153 | AEdependNodeTemplate $nodeName; 154 | 155 | editorTemplate -addExtraControls; 156 | editorTemplate -endScrollLayout; 157 | }""" -------------------------------------------------------------------------------- /nodes/pca_blendshape.py: -------------------------------------------------------------------------------- 1 | from maya import OpenMaya as om, OpenMayaMPx as ompx 2 | from maya import cmds, mel 3 | 4 | import numpy as np 5 | 6 | class PCABlendshapeDeformer(ompx.MPxDeformerNode): 7 | kPluginNodeId = om.MTypeId(0x0007F7FC) # Replace with a unique ID 8 | kPluginNodeName = "pcaBlendshape" 9 | 10 | # Attributes 11 | aShapesWeightsAttr = None 12 | aPCAComponents = None 13 | aPCAMean = None 14 | aPCAWeights = None 15 | aCumulativeVarianceRatio = None 16 | aCompresionRatio = None 17 | aCompresionResult = None 18 | 19 | @staticmethod 20 | def creator(): 21 | return ompx.asMPxPtr(PCABlendshapeDeformer()) 22 | 23 | 24 | @staticmethod 25 | def initialize(): 26 | nAttr = om.MFnNumericAttribute() 27 | tAttr = om.MFnTypedAttribute() 28 | 29 | # shapes weights (array of floats) 30 | PCABlendshapeDeformer.aShapesWeightsAttr = nAttr.create("shapeWeights", "sw", om.MFnNumericData.kFloat) 31 | nAttr.setArray(True) 32 | nAttr.setReadable(True) 33 | nAttr.setWritable(True) 34 | nAttr.setStorable(True) 35 | nAttr.setKeyable (True) 36 | PCABlendshapeDeformer.addAttribute(PCABlendshapeDeformer.aShapesWeightsAttr) 37 | 38 | # PCA Components 39 | PCABlendshapeDeformer.aPCAComponents = tAttr.create("pcaComponents", "pcc", om.MFnData.kDoubleArray) 40 | tAttr.setArray(True) 41 | PCABlendshapeDeformer.addAttribute(PCABlendshapeDeformer.aPCAComponents) 42 | 43 | # PCA Weights 44 | PCABlendshapeDeformer.aPCAWeights = tAttr.create("pcaWeights", "pcw", om.MFnData.kDoubleArray) 45 | tAttr.setArray(True) 46 | PCABlendshapeDeformer.addAttribute(PCABlendshapeDeformer.aPCAWeights) 47 | 48 | # PCA Mean 49 | PCABlendshapeDeformer.aPCAMean = tAttr.create("pcaMean", "pcm", om.MFnData.kDoubleArray) 50 | PCABlendshapeDeformer.addAttribute(PCABlendshapeDeformer.aPCAMean) 51 | 52 | # Explained Variance 53 | PCABlendshapeDeformer.aCumulativeVarianceRatio = tAttr.create("cumulativeVarianceRatio", "pev", om.MFnData.kDoubleArray) 54 | PCABlendshapeDeformer.addAttribute(PCABlendshapeDeformer.aCumulativeVarianceRatio) 55 | 56 | # Desired Variance 57 | PCABlendshapeDeformer.aCompresionRatio = nAttr.create("pcaCompressionRatio", "pcr", om.MFnNumericData.kFloat, 0.05) 58 | nAttr.setKeyable(True) 59 | nAttr.setMax(1.0) 60 | nAttr.setMin(0.0) 61 | PCABlendshapeDeformer.addAttribute(PCABlendshapeDeformer.aCompresionRatio) 62 | 63 | # Jusnt an output attribute to show how much we compressed the data 64 | PCABlendshapeDeformer.aCompresionResult = nAttr.create("compresionPercentage", "cpr", om.MFnNumericData.kFloat) 65 | nAttr.setWritable(False) 66 | nAttr.setStorable(False) 67 | PCABlendshapeDeformer.addAttribute(PCABlendshapeDeformer.aCompresionResult) 68 | 69 | # Affects output 70 | kOutputGeom = ompx.cvar.MPxGeometryFilter_outputGeom 71 | PCABlendshapeDeformer.attributeAffects(PCABlendshapeDeformer.aShapesWeightsAttr, kOutputGeom) 72 | PCABlendshapeDeformer.attributeAffects(PCABlendshapeDeformer.aPCAComponents, kOutputGeom) 73 | PCABlendshapeDeformer.attributeAffects(PCABlendshapeDeformer.aPCAMean, kOutputGeom) 74 | PCABlendshapeDeformer.attributeAffects(PCABlendshapeDeformer.aCumulativeVarianceRatio, kOutputGeom) 75 | PCABlendshapeDeformer.attributeAffects(PCABlendshapeDeformer.aCompresionRatio, kOutputGeom) 76 | PCABlendshapeDeformer.attributeAffects(PCABlendshapeDeformer.aCompresionRatio, PCABlendshapeDeformer.aCompresionResult) 77 | 78 | 79 | 80 | def deform(self, dataBlock, geoIter, matrix, multiIndex): 81 | 82 | # get shapes weights 83 | shapesWeightsHandle = dataBlock.inputArrayValue(self.aShapesWeightsAttr) 84 | shapesWeights = [] 85 | for i in range(shapesWeightsHandle.elementCount()): 86 | shapesWeightsHandle.jumpToElement(i) 87 | weight = shapesWeightsHandle.inputValue().asFloat() 88 | shapesWeights.append(weight) 89 | shapesWeights = np.array(shapesWeights) 90 | 91 | # Read PCA attributes 92 | pcaComponents_handle = dataBlock.inputArrayValue(self.aPCAComponents) 93 | pcaComponents = list() 94 | for i in range(pcaComponents_handle.elementCount()): 95 | pcaComponents_handle.jumpToElement(i) 96 | component_handle = pcaComponents_handle.inputValue() 97 | pcaComponents_data = component_handle.data() 98 | if pcaComponents_data.isNull(): 99 | return 100 | pcaComponents_fn = om.MFnDoubleArrayData(pcaComponents_data) 101 | pcaComponents.append(pcaComponents_fn.array()) 102 | pcaComponents = np.array(pcaComponents) 103 | 104 | pcaMean_handle = dataBlock.inputValue(self.aPCAMean) 105 | pcaMean_data = pcaMean_handle.data() 106 | if pcaMean_data.isNull(): 107 | return 108 | pcaMean_fn = om.MFnDoubleArrayData(pcaMean_data) 109 | pcaMean = np.array(pcaMean_fn.array()) 110 | 111 | 112 | cumulativeVarianceRatio_handle = dataBlock.inputValue(self.aCumulativeVarianceRatio) 113 | cumulativeVarianceRatio_data = cumulativeVarianceRatio_handle.data() 114 | if cumulativeVarianceRatio_data.isNull(): 115 | return 116 | cumulativeVarianceRatio_fn = om.MFnDoubleArrayData(cumulativeVarianceRatio_data) 117 | cumulativeVarianceRatio = np.array(cumulativeVarianceRatio_fn.array()) 118 | 119 | compresionRatio = dataBlock.inputValue(self.aCompresionRatio).asFloat() 120 | variance_keept = 1 - compresionRatio 121 | 122 | # Retrieve weights and bias 123 | pcaWeights_handle = dataBlock.inputArrayValue(self.aPCAWeights) 124 | pcaWeights = [] 125 | for i in range(pcaWeights_handle.elementCount()): 126 | pcaWeights_handle.jumpToElement(i) 127 | weight_handle = pcaWeights_handle.inputValue() 128 | weights_data = weight_handle.data() 129 | if weights_data.isNull(): 130 | continue 131 | weights_fn = om.MFnDoubleArrayData(weights_data) 132 | pcaWeights.append(weights_fn.array()) 133 | pcaWeights = np.array(pcaWeights) 134 | 135 | # Use cumulative variance and determine number of components 136 | nComponents = np.searchsorted(cumulativeVarianceRatio, variance_keept) + 1 137 | # Select relevant components 138 | selectedComponents = pcaComponents[:nComponents] 139 | selectedWeights = pcaWeights[:, :nComponents] 140 | 141 | # Get defomration prediction 142 | # (weightsArray @ selectedComponents) computes the batch matrix multiplication 143 | reconstructedData = selectedWeights @ selectedComponents + pcaMean 144 | recontructed_shapes = reconstructedData.reshape(reconstructedData.shape[0], -1, 3) 145 | recontructed_shapes *= shapesWeights[:, None, None] 146 | result_points = np.sum(recontructed_shapes, axis=0) 147 | # Apply deformed points back to the geometry 148 | geoIter.reset() 149 | while not geoIter.isDone(): 150 | pt = geoIter.position(); 151 | result_point = result_points[geoIter.index()] + np.array([pt.x, pt.y, pt.z]) 152 | geoIter.setPosition(om.MPoint(*result_point)) 153 | geoIter.next() 154 | 155 | # set how much we comrpessed the data just for debugging purposes 156 | compresionResult_handle = dataBlock.outputValue(self.aCompresionResult) 157 | compressed_size = (selectedComponents.nbytes + selectedWeights.nbytes + pcaMean.nbytes) / (1024 ** 2) 158 | original_size = reconstructedData.nbytes / (1024 ** 2) 159 | compresionResult_handle.setFloat((1 - compressed_size / original_size) * 100) 160 | compresionResult_handle.setClean() 161 | # Plugin registration 162 | def initializePlugin(mobject): 163 | vendor = "Mauro Lopez" 164 | version = "1.0" 165 | pluginFn = ompx.MFnPlugin(mobject, vendor, version) 166 | 167 | try: 168 | pluginFn.registerNode( 169 | PCABlendshapeDeformer.kPluginNodeName, 170 | PCABlendshapeDeformer.kPluginNodeId, 171 | PCABlendshapeDeformer.creator, 172 | PCABlendshapeDeformer.initialize, 173 | ompx.MPxNode.kDeformerNode, 174 | ) 175 | mel.eval(aetemplate) 176 | except Exception as e: 177 | om.MGlobal.displayError(f"Failed to register node: {e}") 178 | 179 | def uninitializePlugin(mobject): 180 | pluginFn = ompx.MFnPlugin(mobject) 181 | try: 182 | pluginFn.deregisterNode(PCABlendshapeDeformer.kPluginNodeId) 183 | except Exception as e: 184 | om.MGlobal.displayError(f"Failed to deregister node: {e}") 185 | 186 | # Define the MEL AE template as a string 187 | aetemplate = """ 188 | 189 | global proc AEpcaBlendshapeTemplate(string $nodeName) 190 | { 191 | editorTemplate -beginScrollLayout; 192 | 193 | // Add a section for PCA-related attributes 194 | editorTemplate -beginLayout "PCA Attributes" -collapse false; 195 | editorTemplate -addControl "pcaCompressionRatio"; 196 | editorTemplate -addControl "compresionPercentage"; 197 | editorTemplate -addControl "shapeWeights"; 198 | editorTemplate -endLayout; 199 | 200 | // Add other controls (extras) 201 | editorTemplate -addExtraControls; 202 | 203 | editorTemplate -endScrollLayout; 204 | } 205 | """ 206 | -------------------------------------------------------------------------------- /nodes/regression_node.py: -------------------------------------------------------------------------------- 1 | import maya.api.OpenMaya as om 2 | import numpy as np 3 | 4 | def maya_useNewAPI(): 5 | """ 6 | The presence of this function tells Maya that the plugin produces, and 7 | expects to be passed, objects created using the Maya Python API 2.0. 8 | """ 9 | pass 10 | 11 | 12 | class RegressionNode(om.MPxNode): 13 | """ 14 | RegressionNode is a custom Maya node that performs linear regression inference. 15 | Attributes: 16 | kNodeName (str): The name of the node. 17 | kNodeId (om.MTypeId): The unique Autodesk ID of the node. 18 | featuresAttr (om.MObject): Attribute for input features. 19 | weightsAttr (om.MObject): Attribute for regression weights. 20 | biasAttr (om.MObject): Attribute for regression bias. 21 | predictionAttr (om.MObject): Attribute for output prediction. 22 | normalizeInputAttr (om.MObject): Attribute to enable input normalization. 23 | inputMeanAttr (om.MObject): Attribute for input mean values. 24 | inputStdAttr (om.MObject): Attribute for input standard deviation values. 25 | denormalizeOutputAttr (om.MObject): Attribute to enable output denormalization. 26 | outputMeanAttr (om.MObject): Attribute for output mean value. 27 | outputStdAttr (om.MObject): Attribute for output standard deviation value. 28 | Methods: 29 | __init__(): Initializes the RegressionNode instance. 30 | compute(plug, dataBlock): Computes the output prediction based on input features, weights, and bias. 31 | """ 32 | 33 | kNodeName = "RegressionNode" 34 | kNodeId = om.MTypeId(0x0007F7FB) # Replace with a unique ID 35 | 36 | # Attributes 37 | featuresAttr = None 38 | weightsAttr = None 39 | biasAttr = None 40 | predictionAttr = None 41 | 42 | normalizeInputAttr = None 43 | inputMeanAttr = None 44 | inputStdAttr = None 45 | 46 | denormalizeOutputAttr = None 47 | outputMeanAttr = None 48 | outputStdAttr = None 49 | 50 | def __init__(self): 51 | super(RegressionNode, self).__init__() 52 | 53 | def compute(self, plug, dataBlock): 54 | """ 55 | Compute the output prediction based on input features, weights, and bias. 56 | Args: 57 | plug (om.MPlug): The plug to compute. 58 | dataBlock (om.MDataBlock): The data block containing input and output attributes. 59 | Returns: 60 | om.kUnknownParameter if the plug is not the prediction attribute. 61 | """ 62 | if plug != RegressionNode.predictionAttr: 63 | return 64 | 65 | # Retrieve input features 66 | featuresHandle = dataBlock.inputArrayValue(self.featuresAttr) 67 | features = [] 68 | while not featuresHandle.isDone(): 69 | features.append(featuresHandle.inputValue().asFloat()) 70 | featuresHandle.next() 71 | features = np.array(features) 72 | 73 | # Retrieve weights and bias 74 | weightsHandle = dataBlock.inputArrayValue(self.weightsAttr) 75 | weights = [] 76 | while not weightsHandle.isDone(): 77 | weights_handle = weightsHandle.inputValue() 78 | weights_data = weights_handle.data() 79 | weights_fn = om.MFnDoubleArrayData(weights_data) 80 | weights.append(weights_fn.array()) 81 | weightsHandle.next() 82 | weights = np.array(weights) 83 | 84 | bias_handle = dataBlock.inputValue(self.biasAttr) 85 | bias_data = bias_handle.data() 86 | bias_fn = om.MFnDoubleArrayData(bias_data) 87 | bias = np.array(bias_fn.array()) 88 | 89 | # Retrieve normalization settings 90 | normalizeInput = dataBlock.inputValue(self.normalizeInputAttr).asBool() 91 | inputMean = np.zeros_like(features) 92 | inputStd = np.ones_like(features) 93 | if normalizeInput: 94 | inputsMean_handle = dataBlock.inputValue(self.inputMeanAttr) 95 | inputsMean_data = inputsMean_handle.data() 96 | inputsMean_fn = om.MFnDoubleArrayData(inputsMean_data) 97 | if len(inputsMean_fn): 98 | inputMean = np.asarray(inputsMean_fn.array()) 99 | inputStd_handle = dataBlock.inputValue(self.inputStdAttr) 100 | inputStd_data = inputStd_handle.data() 101 | inputStd_fn = om.MFnDoubleArrayData(inputStd_data) 102 | if len(inputStd_fn): 103 | inputStd = np.asarray(inputStd_fn.array()) 104 | 105 | denormalizeOutput = dataBlock.inputValue(self.denormalizeOutputAttr).asBool() 106 | outputMean = np.zeros_like(features) 107 | outputStd = np.ones_like(features) 108 | if denormalizeOutput: 109 | outputMean_handle = dataBlock.inputValue(self.outputMeanAttr) 110 | outputMean_data = outputMean_handle.data() 111 | outputMean_fn = om.MFnDoubleArrayData(outputMean_data) 112 | if len(outputMean_fn): 113 | outputMean = np.asarray(outputMean_fn.array()) 114 | outputStd_handle = dataBlock.inputValue(self.outputStdAttr) 115 | outputStd_data = outputStd_handle.data() 116 | outputStd_fn = om.MFnDoubleArrayData(outputStd_data) 117 | if len(outputStd_fn): 118 | outputStd = np.asarray(outputStd_fn.array()) 119 | # Validation 120 | # Ensure the number of features matches the number of weights 121 | if len(features) != weights.shape[1]: 122 | om.MGlobal.displayError("Mismatch: The number of features must match the number of weights rows.") 123 | return 124 | if len(bias) != weights.shape[0]: 125 | om.MGlobal.displayError("Mismatch: The number of bias must match the number of weights columns.") 126 | return 127 | # Ensure input mean and std match the number of features if normalization is enabled 128 | if normalizeInput and (len(inputMean) != len(features) or len(inputStd) != len(features)): 129 | om.MGlobal.displayError("Mismatch: Input mean and std must match the number of features.") 130 | return 131 | 132 | # Ensure output mean and std have exactly one value if denormalization is enabled 133 | if denormalizeOutput and (len(outputMean) != 1 or len(outputStd) != 1): 134 | om.MGlobal.displayError("Mismatch: Output mean and std must have exactly one value.") 135 | return 136 | 137 | # Normalize inputs 138 | # If normalization is enabled, adjust the features using the mean and std 139 | if normalizeInput: 140 | features = (features - inputMean) / inputStd 141 | 142 | # Linear regression inference 143 | # Compute the prediction using the linear regression formula 144 | prediction = np.dot(features, weights.T) + bias 145 | 146 | # Denormalize output 147 | # If denormalization is enabled, adjust the prediction using the output mean and std 148 | if denormalizeOutput: 149 | prediction = prediction * outputStd + outputMean 150 | 151 | # Set output prediction 152 | # Set the computed prediction to the output attribute 153 | predictionHandle = dataBlock.outputArrayValue(self.predictionAttr) 154 | builder = predictionHandle.builder() 155 | for i, pred in enumerate(prediction): 156 | outputHandle = builder.addElement(i) 157 | outputHandle.setFloat(pred) 158 | 159 | predictionHandle.set(builder) 160 | dataBlock.setClean(plug) 161 | 162 | # Plugin Initialization 163 | def nodeCreator(): 164 | return RegressionNode() 165 | 166 | def nodeInitializer(): 167 | # Create attribute functions 168 | numericAttr = om.MFnNumericAttribute() 169 | typedAttr = om.MFnTypedAttribute() 170 | 171 | # Features (array of floats) 172 | RegressionNode.featuresAttr = numericAttr.create("features", "feat", om.MFnNumericData.kFloat) 173 | numericAttr.array = True 174 | numericAttr.usesArrayDataBuilder = True 175 | numericAttr.readable = True 176 | numericAttr.writable = True 177 | numericAttr.storable = True 178 | numericAttr.keyable = True 179 | RegressionNode.addAttribute(RegressionNode.featuresAttr) 180 | 181 | # Weights (double array) 182 | RegressionNode.weightsAttr = typedAttr.create("weights", "wght", om.MFnData.kDoubleArray) 183 | typedAttr.array = True 184 | typedAttr.usesArrayDataBuilder = True 185 | typedAttr.readable = True 186 | typedAttr.writable = True 187 | typedAttr.storable = True 188 | typedAttr.keyable = False 189 | RegressionNode.addAttribute(RegressionNode.weightsAttr) 190 | 191 | 192 | # Bias (double) 193 | RegressionNode.biasAttr = typedAttr.create("bias", "bias", om.MFnNumericData.kDoubleArray) 194 | typedAttr.readable = True 195 | typedAttr.writable = True 196 | typedAttr.storable = True 197 | typedAttr.keyable = False 198 | RegressionNode.addAttribute(RegressionNode.biasAttr) 199 | 200 | # Normalize input attributes 201 | RegressionNode.normalizeInputAttr = numericAttr.create("normalizeInput", "normIn", om.MFnNumericData.kBoolean, False) 202 | numericAttr.readable = True 203 | numericAttr.writable = True 204 | numericAttr.storable = True 205 | numericAttr.keyable = True 206 | RegressionNode.addAttribute(RegressionNode.normalizeInputAttr) 207 | 208 | RegressionNode.inputMeanAttr = typedAttr.create("inputMean", "inMean", om.MFnData.kDoubleArray) 209 | numericAttr.readable = True 210 | numericAttr.writable = True 211 | numericAttr.storable = True 212 | numericAttr.keyable = False 213 | RegressionNode.addAttribute(RegressionNode.inputMeanAttr) 214 | 215 | RegressionNode.inputStdAttr = typedAttr.create("inputStd", "inStd", om.MFnData.kDoubleArray) 216 | numericAttr.readable = True 217 | numericAttr.writable = True 218 | numericAttr.storable = True 219 | numericAttr.keyable = False 220 | RegressionNode.addAttribute(RegressionNode.inputStdAttr) 221 | 222 | # Denormalize output attributes 223 | RegressionNode.denormalizeOutputAttr = numericAttr.create("denormalizeOutput", "denormOut", om.MFnNumericData.kBoolean, False) 224 | numericAttr.readable = True 225 | numericAttr.writable = True 226 | numericAttr.storable = True 227 | numericAttr.keyable = True 228 | RegressionNode.addAttribute(RegressionNode.denormalizeOutputAttr) 229 | 230 | RegressionNode.outputMeanAttr = typedAttr.create("outputMean", "outMean", om.MFnData.kDoubleArray) 231 | numericAttr.readable = True 232 | numericAttr.writable = True 233 | numericAttr.storable = True 234 | numericAttr.keyable = False 235 | RegressionNode.addAttribute(RegressionNode.outputMeanAttr) 236 | 237 | RegressionNode.outputStdAttr = typedAttr.create("outputStd", "outStd", om.MFnData.kDoubleArray) 238 | numericAttr.readable = True 239 | numericAttr.writable = True 240 | numericAttr.storable = True 241 | numericAttr.keyable = False 242 | RegressionNode.addAttribute(RegressionNode.outputStdAttr) 243 | 244 | # Prediction (array of floats, output) 245 | RegressionNode.predictionAttr = numericAttr.create("prediction", "pred", om.MFnNumericData.kFloat) 246 | numericAttr.array = True 247 | numericAttr.usesArrayDataBuilder = True 248 | numericAttr.readable = True 249 | numericAttr.writable = False 250 | numericAttr.storable = False 251 | RegressionNode.addAttribute(RegressionNode.predictionAttr) 252 | 253 | # Set attribute dependencies 254 | RegressionNode.attributeAffects(RegressionNode.featuresAttr, RegressionNode.predictionAttr) 255 | RegressionNode.attributeAffects(RegressionNode.weightsAttr, RegressionNode.predictionAttr) 256 | RegressionNode.attributeAffects(RegressionNode.biasAttr, RegressionNode.predictionAttr) 257 | RegressionNode.attributeAffects(RegressionNode.normalizeInputAttr, RegressionNode.predictionAttr) 258 | RegressionNode.attributeAffects(RegressionNode.inputMeanAttr, RegressionNode.predictionAttr) 259 | RegressionNode.attributeAffects(RegressionNode.inputStdAttr, RegressionNode.predictionAttr) 260 | RegressionNode.attributeAffects(RegressionNode.denormalizeOutputAttr, RegressionNode.predictionAttr) 261 | RegressionNode.attributeAffects(RegressionNode.outputMeanAttr, RegressionNode.predictionAttr) 262 | RegressionNode.attributeAffects(RegressionNode.outputStdAttr, RegressionNode.predictionAttr) 263 | 264 | # Plugin Registration 265 | def initializePlugin(mobject): 266 | vendor = "Mauro Lopez" 267 | version = "1.0" 268 | plugin = om.MFnPlugin(mobject, vendor, version) 269 | try: 270 | plugin.registerNode( 271 | RegressionNode.kNodeName, 272 | RegressionNode.kNodeId, 273 | nodeCreator, 274 | nodeInitializer 275 | ) 276 | except: 277 | om.MGlobal.displayError("Failed to register node: " + RegressionNode.kNodeName) 278 | 279 | def uninitializePlugin(mobject): 280 | plugin = om.MFnPlugin(mobject) 281 | try: 282 | plugin.deregisterNode(RegressionNode.kNodeId) 283 | except: 284 | om.MGlobal.displayError("Failed to deregister node: " + RegressionNode.kNodeName) 285 | -------------------------------------------------------------------------------- /nodes_ui.py: -------------------------------------------------------------------------------- 1 | # Show the UI 2 | import importlib 3 | from ui import regresion_win 4 | from ui import pca_win 5 | importlib.reload(regresion_win) 6 | importlib.reload(pca_win) 7 | 8 | def regrssion_ui(): 9 | ui = regresion_win.RegressionUI() 10 | ui.show() 11 | ui.load_needed_nodes() 12 | 13 | def pca_ui(): 14 | ui = pca_win.PCAUI() 15 | ui.show() -------------------------------------------------------------------------------- /ui/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lopezmauro/ml-example-nodes/ffb7221b4b6f32e1f43a9cd69863a6afaf64cc77/ui/__init__.py -------------------------------------------------------------------------------- /ui/add.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lopezmauro/ml-example-nodes/ffb7221b4b6f32e1f43a9cd69863a6afaf64cc77/ui/add.png -------------------------------------------------------------------------------- /ui/maya_utils.py: -------------------------------------------------------------------------------- 1 | import pathlib 2 | import json 3 | import random 4 | import numpy as np 5 | from maya import cmds 6 | from maya.api import OpenMaya as om 7 | from maya.api import OpenMayaAnim as oma 8 | from maya import OpenMayaUI as omui 9 | from shiboken2 import wrapInstance 10 | from PySide2 import QtWidgets 11 | 12 | _file_path = pathlib.Path(__file__) 13 | 14 | def maya_main_window(): 15 | main_window_ptr = omui.MQtUtil.mainWindow() 16 | return wrapInstance(int(main_window_ptr), QtWidgets.QWidget) 17 | 18 | def load_node(node_name): 19 | """ 20 | Load a node in Maya. 21 | 22 | Parameters: 23 | node_name (str): The name of the node to load. 24 | 25 | """ 26 | plugin_name = f"{node_name}.py" 27 | if cmds.pluginInfo(plugin_name, query=True, loaded=True): 28 | return 29 | file_dir = _file_path.parent.parent 30 | file_found = list(file_dir.joinpath('nodes').glob(plugin_name)) 31 | if not file_found: 32 | raise ValueError(f"Node {node_name} not found.") 33 | plugin_path = str(file_found[0].resolve()) 34 | cmds.loadPlugin(plugin_path) 35 | 36 | def get_long_attr_name(node, short_attr): 37 | """Convert short attribute name to long name.""" 38 | try: 39 | return cmds.attributeQuery(short_attr, node=node, longName=True) 40 | except: 41 | return short_attr # If the query fails, return the short name 42 | 43 | def get_attribute_mplug(attribute_string): 44 | """ 45 | Get the MPlug of an attribute in Maya. 46 | 47 | Parameters: 48 | attribute_string (str): A string in the format "node_name.attribute". 49 | 50 | Returns: 51 | MPlug: The MPlug of the attribute. 52 | """ 53 | node_name, attribute_name = attribute_string.split('.') 54 | m_obj = om.MSelectionList().add(node_name).getDependNode(0) 55 | m_fn = om.MFnDependencyNode(m_obj) 56 | m_plug = m_fn.findPlug(attribute_name, False) 57 | return m_plug 58 | 59 | def get_values_at_frames(attributes, frames): 60 | """ 61 | Query all values of given attributes in a frame range in Maya. 62 | 63 | Parameters: 64 | attributes (list): A list of attribute names to query. 65 | frames (list): A list of frame numbers to query. 66 | 67 | Returns: 68 | dict: A dictionary with the queried frame numbers and their corresponding attribute values. 69 | """ 70 | result = dict([(a, []) for a in attributes]) 71 | for frame in frames: 72 | for attribute in attributes: 73 | value = cmds.getAttr(attribute, time=frame) 74 | result[attribute].append(value) 75 | return result 76 | 77 | def get_node_dag_path(node_name): 78 | """ 79 | Get the DAG path of a node in Maya. 80 | 81 | Parameters: 82 | node_name (str): The name of the node to query. 83 | 84 | Returns: 85 | MDagPath: The DAG path of the node. 86 | """ 87 | selection_list = om.MSelectionList() 88 | selection_list.add(node_name) 89 | return selection_list.getDagPath(0) 90 | 91 | def get_mesh_fn(object_name): 92 | """ 93 | Get the MFnMesh object of the selected mesh in Maya. 94 | 95 | Returns: 96 | MFnMesh: The MFnMesh object of the selected mesh. 97 | """ 98 | node_dag_path = get_node_dag_path(object_name) 99 | # Create an MFnMesh object 100 | fn_mesh = om.MFnMesh(node_dag_path) 101 | return fn_mesh 102 | 103 | def get_original_shape(mesh_name): 104 | """ 105 | Get the original shape of a mesh. 106 | 107 | Parameters: 108 | mesh_name (str): The name of the mesh. 109 | 110 | Returns: 111 | str: The name of the original shape of the mesh. 112 | """ 113 | # Get the shapes of the mesh 114 | shapes = cmds.listRelatives(mesh_name, shapes=True, noIntermediate=False) 115 | 116 | # Filter out the original shape 117 | original_shape = [shape for shape in shapes if cmds.getAttr(shape + ".intermediateObject")] 118 | 119 | return original_shape[0] if original_shape else None 120 | 121 | def get_orig_mesh_points(object_name): 122 | """ 123 | Query all mesh points of a given object in Maya. 124 | 125 | Parameters: 126 | object_name (str): The name of the object to query. 127 | 128 | Returns: 129 | list: A list of mesh points. 130 | """ 131 | # Create an MFnMesh object 132 | orig_mesh = get_original_shape(object_name) 133 | fn_mesh = get_mesh_fn(orig_mesh) 134 | # Get the vertices 135 | return fn_mesh.getPoints(om.MSpace.kObject) 136 | 137 | def get_mesh_points_at_frames(object_name, frames): 138 | """ 139 | Query all mesh points of a given object in a frame range in Maya. 140 | 141 | Parameters: 142 | object_name (str): The name of the object to query. 143 | frames (list): A list of frame numbers to query. 144 | 145 | Returns: 146 | dict: A dictionary with the queried frame numbers and their corresponding mesh points. 147 | """ 148 | result = {} 149 | # Create an MFnMesh object 150 | fn_mesh = get_mesh_fn(object_name) 151 | 152 | for frame in frames: 153 | oma.MAnimControl.setCurrentTime(om.MTime(frame)) 154 | # Get the vertices 155 | result[frame] = fn_mesh.getPoints(om.MSpace.kObject) 156 | return result 157 | 158 | def _create_random_animation_curve(curve_type, start_frame, end_frame, min_value, max_value): 159 | """ 160 | Create a random animation curve in a frame range in Maya. 161 | 162 | Parameters: 163 | curve_type (str): The type of the animation curve. It can be 'animCurveTL', 'animCurveTA', 'animCurveTT', or 'animCurveTU'. 164 | start_frame (int): The start frame of the animation. 165 | end_frame (int): The end frame of the animation. 166 | min_value (float): The minimum value for the animation. 167 | max_value (float): The maximum value for the animation. 168 | """ 169 | # Create an animCurve node 170 | curve = cmds.createNode(curve_type) 171 | 172 | # Set random keyframes 173 | for frame in range(start_frame, end_frame + 1): 174 | value = random.uniform(min_value, max_value) 175 | cmds.setKeyframe(curve, time=frame, value=value) 176 | 177 | return curve 178 | 179 | def _get_anim_curve_type(attribute_name): 180 | """ 181 | Get the correct animation curve type based on an attribute name. 182 | 183 | Parameters: 184 | attribute_name (str): The name of the attribute. 185 | 186 | Returns: 187 | str: The type of the animation curve. It can be 'animCurveTL', 'animCurveTA', 'animCurveTT', or 'animCurveTU'. 188 | """ 189 | # Map attribute types to animation curve types 190 | attribute_type_to_curve_type = { 191 | 'doubleLinear': 'animCurveTL', 192 | 'doubleAngle': 'animCurveTA', 193 | 'time': 'animCurveTT', 194 | 'double': 'animCurveTU', 195 | } 196 | 197 | # Get the attribute type 198 | attribute_type = cmds.getAttr(attribute_name, type=True) 199 | 200 | # Get the animation curve type 201 | curve_type = attribute_type_to_curve_type.get(attribute_type) 202 | 203 | if curve_type is None: 204 | raise ValueError(f"Unsupported attribute type: {attribute_type}") 205 | 206 | return curve_type 207 | 208 | def create_random_animation(attribute_name, start_frame, end_frame, min_value, max_value): 209 | """ 210 | Create a random animation for a given attribute in a frame range in Maya. 211 | 212 | Parameters: 213 | - attribute_name (str): The name of the attribute to animate. 214 | - start_frame (int): The start frame of the animation. 215 | - end_frame (int): The end frame of the animation. 216 | - min_value (float): The minimum value for the random animation. 217 | - max_value (float): The maximum value for the random animation. 218 | 219 | Returns: 220 | None 221 | """ 222 | curve_type = _get_anim_curve_type(attribute_name) 223 | anim_curve = _create_random_animation_curve(curve_type, start_frame, end_frame, min_value, max_value) 224 | cmds.connectAttr(f"{anim_curve}.output", attribute_name) 225 | return anim_curve 226 | 227 | def get_animation_range(attributes): 228 | """ 229 | Get the animation range of a list of attributes in Maya. 230 | 231 | Parameters: 232 | attributes (list): A list of attribute names. 233 | 234 | Returns: 235 | tuple: A tuple with the start frame and end frame of the animation. 236 | """ 237 | frames = set() 238 | 239 | for attribute in attributes: 240 | keyframes = cmds.keyframe(attribute, query=True) 241 | if keyframes: 242 | frames.update(keyframes) 243 | 244 | return int(min(frames)), int(max(frames)) 245 | 246 | def normalize_features(inputs): 247 | """ 248 | Normalize the input features by subtracting the mean and dividing by the standard deviation. 249 | 250 | Args: 251 | inputs (torch.Tensor): The input features to be normalized. 252 | 253 | Returns: 254 | tuple: A tuple containing the normalized inputs, mean, and standard deviation. 255 | 256 | """ 257 | mean = np.mean(inputs, axis=0) 258 | std = np.std(inputs, axis=0) + np.finfo(float).eps 259 | normalized_inputs = (inputs - mean) / std 260 | return normalized_inputs, mean, std 261 | 262 | def get_blendshape_data(blendshape_node): 263 | """ 264 | Retrieve deltas from a blendshape node using the `inputPointsTarget` and `inputComponentsTarget` attributes. 265 | 266 | :param blendshape_node: The name of the blendshape node. 267 | :return: A dictionary containing deltas for each target. 268 | """ 269 | def getDigits(s): 270 | return int(''.join([i for i in s if i.isdigit()])) 271 | # Dictionary to store deltas for each target 272 | deltas = {} 273 | 274 | # Check the inputTarget attribute 275 | input_target_attr = f"{blendshape_node}.inputTarget" 276 | if not cmds.attributeQuery("inputTarget", node=blendshape_node, exists=True): 277 | print(f"Blendshape node {blendshape_node} has no inputTarget attribute.") 278 | return deltas 279 | 280 | # Iterate over target indices 281 | target_indices = cmds.getAttr(input_target_attr, multiIndices=True) 282 | if not target_indices: 283 | print(f"No targets found on blendshape node {blendshape_node}.") 284 | return deltas 285 | 286 | for target_index in target_indices: 287 | # Access inputTargetGroup for the target 288 | input_target_group_attr = f"{input_target_attr}[{target_index}].inputTargetGroup" 289 | weight_indices = cmds.getAttr(input_target_group_attr, multiIndices=True) 290 | if not weight_indices: 291 | continue 292 | 293 | for weight_index in weight_indices: 294 | # Access inputPointsTarget 295 | input_points_attr = f"{input_target_group_attr}[{weight_index}].inputPointsTarget" 296 | if cmds.getAttr(input_points_attr, size=True) > 0: 297 | points = cmds.getAttr(input_points_attr) 298 | 299 | # Access inputComponentsTarget 300 | input_components_attr = f"{input_target_group_attr}[{weight_index}].inputComponentsTarget" 301 | if cmds.getAttr(input_components_attr, size=True) > 0: 302 | components = cmds.getAttr(input_components_attr) 303 | indices = list() 304 | for vtx in components: 305 | if ':' in vtx: 306 | start, end = [getDigits(a) for a in vtx.split(':')] 307 | indices.extend(range(start, end + 1)) 308 | else: 309 | indices.append(getDigits(vtx)) 310 | # Combine points and components into a delta dictionary 311 | deltas[weight_index] = { 312 | "points": points, 313 | "indices": indices, 314 | } 315 | 316 | return deltas 317 | 318 | def get_blenshape_points(mesh, blendshape_node): 319 | """ 320 | Retrieve blendshape points for a given mesh and blendshape node. 321 | """ 322 | fn = get_mesh_fn(mesh) 323 | bshape_data = get_blendshape_data(blendshape_node) 324 | shapes_deltas = list() 325 | for _, delta_data in bshape_data.items(): 326 | deltas = np.zeros((fn.numVertices,3)) 327 | deltas[delta_data['indices']] = np.asarray(delta_data['points'])[:, :3] 328 | shapes_deltas.append(deltas) 329 | return np.asarray(shapes_deltas) 330 | 331 | def export_regression_node(regression_node, file_path): 332 | """ 333 | Export the trained regression node's attributes and connections to a JSON file. 334 | """ 335 | indices = cmds.getAttr(f"{regression_node}.weights", mi=1) 336 | weights = list() 337 | for i in indices: 338 | weights.append(cmds.getAttr(f"{regression_node}.weights[{i}]")) 339 | matrix_to_floats = set(cmds.listConnections(regression_node, s=1, d=0, type='matrixToFloats') or list()) 340 | matrix_to_floats_data = dict() 341 | for node in matrix_to_floats: 342 | src_connections = cmds.listConnections(node, s=1, d=0, p=1, c=1) or list() 343 | matrix_to_floats_data[node] = list(zip(src_connections[1::2], src_connections[::2])) 344 | 345 | floats_to_transforms = set(cmds.listConnections(regression_node, s=0, d=1, type='floatsToTransform') or list()) 346 | floats_to_transforms_data = dict() 347 | for node in floats_to_transforms: 348 | dest_connections = cmds.listConnections(node, s=0, d=1, p=1, c=1) or list() 349 | floats_to_transforms_data[node] = list(zip(dest_connections[::2], dest_connections[1::2])) 350 | node_data = {"node_name": regression_node, 351 | "weights": weights, 352 | "bias": cmds.getAttr(f"{regression_node}.bias"), 353 | "input_connections": cmds.listConnections(f"{regression_node}.features", source=True, destination=False, plugs=True) or [], 354 | "output_connections": cmds.listConnections(f"{regression_node}.prediction", source=False, destination=True, plugs=True) or [], 355 | "matrix_to_floats": matrix_to_floats_data, 356 | "floats_to_transforms": floats_to_transforms_data 357 | } 358 | with open(file_path, "w") as f: 359 | json.dump(node_data, f, indent=4) 360 | 361 | def import_regression_node(file_path): 362 | """ 363 | Import trained regression node data from a JSON file and recreate the node with connections. 364 | """ 365 | load_node('regression_node') 366 | load_node('matrix_to_floats') 367 | load_node('floats_to_transform') 368 | with open(file_path, "r") as f: 369 | node_data = json.load(f) 370 | # create auxilary nodes if they are needed 371 | matrix_to_floats_data = node_data.get('matrix_to_floats', dict()) 372 | for node, connections in matrix_to_floats_data.items(): 373 | if not cmds.ls(node): 374 | cmds.createNode("matrixToFloats", name=node) 375 | for src, dest in connections: 376 | cmds.connectAttr(src, dest, force=1) 377 | floats_to_transforms = node_data.get('floats_to_transforms', dict()) 378 | for node, connections in floats_to_transforms.items(): 379 | if not cmds.ls(node): 380 | cmds.createNode("floatsToTransform", name=node) 381 | for src, dest in connections: 382 | cmds.connectAttr(src, dest, force=1) 383 | node = create_regression_node(node_data["node_name"], 384 | node_data["weights"], 385 | node_data["bias"], 386 | node_data["input_connections"], 387 | node_data["output_connections"]) 388 | return node 389 | 390 | def create_regression_node(name, weights, bias, input_attributes, target_attributes, 391 | input_mean=None, input_std=None): 392 | node = cmds.createNode("RegressionNode", name=name) 393 | for i, attr in enumerate(input_attributes): 394 | cmds.connectAttr(attr, f"{node}.features[{i}]", force=True) 395 | for i, weight in enumerate(weights): 396 | cmds.setAttr(f"{node}.weights[{i}]", weight, type="doubleArray") 397 | cmds.setAttr(f"{node}.bias", bias, type="doubleArray") 398 | if input_mean: 399 | cmds.setAttr(f"{node}.inputMean", input_mean, type="doubleArray") 400 | if input_std: 401 | cmds.setAttr(f"{node}.inputStd", input_std, type="doubleArray") 402 | for i, attr in enumerate(target_attributes): 403 | cmds.connectAttr(f"{node}.prediction[{i}]", attr, force=True) 404 | return node 405 | 406 | def create_matrix_to_floats_node(node): 407 | 408 | """ 409 | Create a MatrixToFloats node and connect it to the given node. 410 | 411 | Parameters: 412 | node (str): The name of the node to connect the MatrixToFloats node to. 413 | 414 | Returns: 415 | str: The name of the created MatrixToFloats node. 416 | """ 417 | matrix_to_floats_node = cmds.createNode("matrixToFloats", name=f"{node}_matrix_to_floats") 418 | cmds.connectAttr(f"{node}.matrix", f"{matrix_to_floats_node}.inputMatrix") 419 | return matrix_to_floats_node 420 | 421 | def create_floats_to_transform_node(node): 422 | """ 423 | Create a FloatsToTransform node and connect it to the given node. 424 | 425 | Parameters: 426 | node (str): The name of the node to connect the FloatsToTransform node to. 427 | 428 | Returns: 429 | str: The name of the created FloatsToTransform node. 430 | """ 431 | floats_to_transform_node = cmds.createNode("floatsToTransform", name=f"{node}_floats_to_transform") 432 | cmds.connectAttr(f"{node}.outputFloats", f"{floats_to_transform_node}.inputFloats") 433 | return floats_to_transform_node -------------------------------------------------------------------------------- /ui/pca_win.py: -------------------------------------------------------------------------------- 1 | import importlib 2 | import maya.cmds as cmds 3 | from PySide2 import QtWidgets, QtGui, QtCore 4 | import numpy as np 5 | from sklearn.decomposition import PCA 6 | from ui import maya_utils 7 | importlib.reload(maya_utils) 8 | 9 | class PCAUI(QtWidgets.QDialog): 10 | def __init__(self, parent=maya_utils.maya_main_window()): 11 | super(PCAUI, self).__init__(parent) 12 | self.setWindowTitle("PCA Blendshape UI") 13 | self.setFixedSize(450, 200) 14 | 15 | self.init_ui() 16 | 17 | def init_ui(self): 18 | # Main layout 19 | main_layout = QtWidgets.QVBoxLayout(self) 20 | 21 | # Menu bar 22 | self.menu_bar = QtWidgets.QMenuBar(self) 23 | main_layout.setMenuBar(self.menu_bar) 24 | 25 | # About menu 26 | self.about_menu = self.menu_bar.addMenu("Help") 27 | # Create an action for the 'Help' menu with a clickable link 28 | open_link_action = QtWidgets.QAction('Visit tool wiki page', self) 29 | self.about_menu.addAction(open_link_action) 30 | # Connect the action to a function to open the URL 31 | open_link_action.triggered.connect(self.open_link) 32 | 33 | # Source Blendshape Layout 34 | source_layout = QtWidgets.QHBoxLayout() 35 | source_label = QtWidgets.QLabel("Source Blendshape:") 36 | self.source_text_field = QtWidgets.QLineEdit() 37 | self.source_button = QtWidgets.QPushButton("Get Blendshape Node") 38 | self.source_button.clicked.connect(self.populate_source) 39 | 40 | source_layout.addWidget(source_label) 41 | source_layout.addWidget(self.source_text_field) 42 | source_layout.addWidget(self.source_button) 43 | 44 | # Target Mesh Layout 45 | target_layout = QtWidgets.QHBoxLayout() 46 | target_label = QtWidgets.QLabel("Target Mesh:") 47 | self.target_text_field = QtWidgets.QLineEdit() 48 | self.target_button = QtWidgets.QPushButton("Get Target Mesh") 49 | self.target_button.clicked.connect(self.populate_target) 50 | 51 | target_layout.addWidget(target_label) 52 | target_layout.addWidget(self.target_text_field) 53 | target_layout.addWidget(self.target_button) 54 | 55 | # Create PCA Blendshape Button 56 | self.create_button = QtWidgets.QPushButton("Create PCA Blendshape") 57 | self.create_button.clicked.connect(self.do_it) 58 | 59 | # Add layouts to the main layout 60 | main_layout.addLayout(source_layout) 61 | main_layout.addLayout(target_layout) 62 | main_layout.addWidget(self.create_button) 63 | 64 | def open_link(self): 65 | # Open the link in the default web browser 66 | link = "https://github.com/lopezmauro/ml-example-nodes/wiki/PCA-Blendshape-Node-for-Autodesk-Maya" 67 | QtGui.QDesktopServices.openUrl(QtCore.QUrl(link)) 68 | 69 | def populate_source(self): 70 | """Populate the source blendshape field.""" 71 | selected = cmds.ls(selection=True) 72 | if not selected: 73 | cmds.warning("No object selected.") 74 | return 75 | 76 | node = selected[0] 77 | blendshape_node = None 78 | if cmds.nodeType(node) == "blendShape": 79 | blendshape_node = node 80 | else: 81 | bs_nodes = [a for a in cmds.listHistory(node, pdo=1) if cmds.nodeType(a) == "blendShape"] 82 | if not bs_nodes: 83 | cmds.warning(f"No blendshape node found for {node}.") 84 | return 85 | blendshape_node = bs_nodes[0] 86 | self.source_text_field.setText(blendshape_node) 87 | 88 | 89 | def populate_target(self): 90 | """Populate the target mesh field.""" 91 | selected = cmds.ls(selection=True, type="transform") 92 | if not selected: 93 | cmds.warning("No object selected.") 94 | return 95 | 96 | shapes = cmds.listRelatives(selected[0], shapes=True, fullPath=True) or [] 97 | if shapes and cmds.nodeType(shapes[0]) == "mesh": 98 | self.target_text_field.setText(selected[0]) 99 | else: 100 | cmds.warning("The selected object is not a valid mesh.") 101 | 102 | def get_blendshape_data(self, mesh, blendshape_node): 103 | """ 104 | Retrieves blendshape data from the source mesh and blendshape node. 105 | 106 | Args: 107 | source_mesh (str): The name of the source mesh. 108 | source_blendshape (str): The name of the source blendshape node. 109 | 110 | Returns: 111 | tuple: A tuple containing shapes deltas and aliases dictionary. 112 | """ 113 | shapes_deltas = maya_utils.get_blenshape_points(mesh, blendshape_node) 114 | aliases = cmds.aliasAttr(blendshape_node, q=1) 115 | aliases_dict = dict(zip(aliases[1::2], aliases[::2])) 116 | return shapes_deltas, aliases_dict 117 | 118 | def get_pca_data(self, shapes_deltas): 119 | """ 120 | This method takes a list of shape deltas, flattens the data, and applies Principal Component Analysis (PCA) 121 | to extract the principal components, the mean of the data, the weights of the data in the PCA space, 122 | and the cumulative variance ratio explained by the components. 123 | 124 | Args: 125 | shapes_deltas (list): A list of shape deltas. Each element in the list represents the delta of a shape. 126 | 127 | Returns: 128 | tuple: A tuple containing the following elements: 129 | - pca.mean_ (numpy.ndarray): The mean of the shape deltas. 130 | - pca.components_ (numpy.ndarray): The principal components of the shape deltas. 131 | - pcaWeights (numpy.ndarray): The weights of the shape deltas in the PCA space. 132 | - cumulative_variance_ratio (numpy.ndarray): The cumulative variance ratio explained by the principal components. 133 | """ 134 | 135 | ### get PCA data 136 | # Flatten the data 137 | delta_data_flat = shapes_deltas.reshape(shapes_deltas.shape[0], -1) 138 | # Fit PCA 139 | pca = PCA() 140 | pca.fit(delta_data_flat) 141 | # Transform data to get the PCA weights 142 | pcaWeights = pca.transform(delta_data_flat) 143 | 144 | # Get explained variance in order to compress the data in the node 145 | explained_variance = pca.explained_variance_ 146 | total_variance = np.sum(explained_variance) 147 | cumulative_variance_ratio = np.cumsum(explained_variance) / total_variance 148 | return pca.mean_, pca.components_, pcaWeights, cumulative_variance_ratio 149 | 150 | def create_pca_blendshape(self, mesh, pca_mean, pca_components, pca_weights, cumulative_variance_ratio, aliases_dict): 151 | """ 152 | Creates a PCA blendshape node on the target mesh using the provided PCA data. 153 | 154 | Args: 155 | target_mesh (str): The name of the target mesh. 156 | pca_mean (np.array): The mean of the PCA. 157 | pca_components (np.array): The components of the PCA. 158 | pca_weights (np.array): The weights of the PCA. 159 | cumulative_variance_ratio (np.array): The cumulative variance ratio of the PCA. 160 | aliases_dict (dict): A dictionary of aliases. 161 | 162 | Returns: 163 | str: The name of the created PCA blendshape node. 164 | """ 165 | node = cmds.deformer(mesh, type='pcaBlendshape')[0] 166 | # set main PCA data 167 | cmds.setAttr(f'{node}.pcaMean', pca_mean, type="doubleArray") 168 | for i, each in enumerate(pca_components): 169 | cmds.setAttr(f'{node}.pcaComponents[{i}]', each, type="doubleArray") 170 | # get the cached weight to recontruct the shapes 171 | for i, each in enumerate(pca_weights): 172 | cmds.setAttr(f'{node}.pcaWeights[{i}]', each, type="doubleArray") 173 | # set the explained variance in order to compress on the fly 174 | cmds.setAttr(f'{node}.cumulativeVarianceRatio', cumulative_variance_ratio, type="doubleArray") 175 | 176 | # create shape weights and rename them with the blendshape weights aliases 177 | for i in range(pca_weights.shape[0]): 178 | cmds.setAttr(f'{node}.shapeWeights[{i}]', 0) 179 | cmds.aliasAttr(aliases_dict[f'weight[{i}]'], f'{node}.shapeWeights[{i}]') 180 | return node 181 | 182 | def do_it(self): 183 | """ 184 | This method performs a series of checks and operations to create a PCA blendshape node. 185 | It verifies the target mesh, source mesh, and their vertex counts, then loads the PCA blendshape node, 186 | retrieves blendshape data, performs PCA, and creates the PCA blendshape node. 187 | 188 | Returns: 189 | None 190 | """ 191 | source_blendshape = self.source_text_field.text() 192 | target_mesh = self.target_text_field.text() 193 | 194 | if not source_blendshape: 195 | cmds.warning("Source blendshape node is not specified.") 196 | return 197 | if not target_mesh: 198 | cmds.warning("Target mesh is not specified.") 199 | return 200 | 201 | # Verify vertex count 202 | source_mesh = cmds.listConnections(source_blendshape, type="mesh") or [] 203 | if not source_mesh: 204 | cmds.warning("Cannot find source mesh for the blendshape node.") 205 | return 206 | 207 | source_vertex_count = cmds.polyEvaluate(source_mesh[0], vertex=True) 208 | target_vertex_count = cmds.polyEvaluate(target_mesh, vertex=True) 209 | 210 | if source_vertex_count != target_vertex_count: 211 | cmds.warning("Source and target meshes do not have the same number of vertices.") 212 | return 213 | maya_utils.load_node('pca_blendshape') 214 | shapes_deltas, aliases_dict = self.get_blendshape_data(source_mesh[0], source_blendshape) 215 | pca_mean, pca_components, pca_weights, cumulative_variance_ratio = self.get_pca_data(shapes_deltas) 216 | # Create the deformer node 217 | node = self.create_pca_blendshape(target_mesh, pca_mean, pca_components, pca_weights, cumulative_variance_ratio, aliases_dict) 218 | cmds.select(node) 219 | QtWidgets.QMessageBox.information(self, "Success", f"PCA Node {node} created and initialized.") 220 | 221 | 222 | -------------------------------------------------------------------------------- /ui/regresion_win.py: -------------------------------------------------------------------------------- 1 | import importlib 2 | import numpy as np 3 | import json 4 | from functools import partial, wraps 5 | from PySide2 import QtWidgets, QtCore, QtGui 6 | from maya import cmds as cmds 7 | from . import maya_utils 8 | from sklearn.linear_model import ElasticNet 9 | importlib.reload(maya_utils) 10 | 11 | ROT_MATRIX_INDICES = [0, 1, 2, 4, 5, 6] 12 | 13 | def wait_cursor(func): 14 | @wraps(func) 15 | def wrapper(*args, **kwargs): 16 | QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor) 17 | try: 18 | return func(*args, **kwargs) 19 | finally: 20 | QtWidgets.QApplication.restoreOverrideCursor() 21 | return wrapper 22 | 23 | def show_message(title, message): 24 | msg_box = QtWidgets.QMessageBox() 25 | msg_box.setWindowTitle(title) 26 | msg_box.setText(message) 27 | msg_box.exec_() 28 | 29 | class MyDoubleSpinBox(QtWidgets.QDoubleSpinBox): 30 | def textFromValue(self, value): 31 | return "{:g}".format(value) 32 | 33 | 34 | class RegressionUI(QtWidgets.QDialog): 35 | update_progress = QtCore.Signal(int) 36 | update_status = QtCore.Signal(str) 37 | 38 | def __init__(self, parent=maya_utils.maya_main_window()): 39 | super(RegressionUI, self).__init__(parent) 40 | 41 | self.setWindowTitle("Train Regression Model") 42 | self.setWindowFlags(self.windowFlags() ^ QtCore.Qt.WindowContextHelpButtonHint) 43 | 44 | self.layout = QtWidgets.QVBoxLayout(self) 45 | 46 | # Menu bar 47 | self.menu_bar = QtWidgets.QMenuBar(self) 48 | self.layout.setMenuBar(self.menu_bar) 49 | 50 | # File menu 51 | style = QtWidgets.QApplication.style() 52 | 53 | self.file_menu = self.menu_bar.addMenu("File") 54 | self.import_action = QtWidgets.QAction(style.standardIcon(QtWidgets.QStyle.SP_DialogOpenButton), "Import Trained Data", self) 55 | self.export_action = QtWidgets.QAction(style.standardIcon(QtWidgets.QStyle.SP_DialogSaveButton), "Export Trained Data", self) 56 | 57 | self.file_menu.addAction(self.import_action) 58 | self.file_menu.addAction(self.export_action) 59 | self.import_action.triggered.connect(self.import_trained_data) 60 | self.export_action.triggered.connect(self.export_trained_data) 61 | 62 | # About menu 63 | self.about_menu = self.menu_bar.addMenu("Help") 64 | # Create an action for the 'Help' menu with a clickable link 65 | open_link_action = QtWidgets.QAction(style.standardIcon(QtWidgets.QStyle.SP_MessageBoxQuestion), 'Visit tool wiki page', self) 66 | self.about_menu.addAction(open_link_action) 67 | 68 | # Connect the action to a function to open the URL 69 | open_link_action.triggered.connect(self.open_link) 70 | 71 | # Input attributes layout 72 | self.input_layout = QtWidgets.QVBoxLayout() 73 | self.input_layout.addWidget(QtWidgets.QLabel("Input Attributes")) 74 | self.inputs_attributes = QtWidgets.QListWidget() 75 | self.input_layout.addWidget(self.inputs_attributes) 76 | 77 | self.button_layout = QtWidgets.QHBoxLayout() 78 | self.add_button = QtWidgets.QPushButton("Add") 79 | self.remove_button = QtWidgets.QPushButton("Remove") 80 | self.clear_button = QtWidgets.QPushButton("Clear") 81 | self.button_layout.addWidget(self.add_button) 82 | self.button_layout.addWidget(self.remove_button) 83 | self.button_layout.addWidget(self.clear_button) 84 | self.input_layout.addLayout(self.button_layout) 85 | 86 | self.input_widget = QtWidgets.QWidget() 87 | self.input_widget.setLayout(self.input_layout) 88 | self.splitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal, self) 89 | self.splitter.addWidget(self.input_widget) 90 | 91 | # Output attributes layout 92 | self.outputs_attributes_widget = QtWidgets.QWidget() 93 | self.outputs_attributes = QtWidgets.QListWidget() 94 | self.output_attr_layout = QtWidgets.QVBoxLayout() 95 | self.output_attr_layout.addWidget(QtWidgets.QLabel("Target Attributes")) 96 | self.output_attr_layout.addWidget(self.outputs_attributes) 97 | self.button_layout2 = QtWidgets.QHBoxLayout() 98 | self.add_button2 = QtWidgets.QPushButton("Add") 99 | self.remove_button2 = QtWidgets.QPushButton("Remove") 100 | self.clear_button2 = QtWidgets.QPushButton("Clear") 101 | self.button_layout2.addWidget(self.add_button2) 102 | self.button_layout2.addWidget(self.remove_button2) 103 | self.button_layout2.addWidget(self.clear_button2) 104 | self.output_attr_layout.addLayout(self.button_layout2) 105 | self.outputs_attributes_widget.setLayout(self.output_attr_layout) 106 | 107 | self.output_widget = QtWidgets.QWidget() 108 | self.output_layout = QtWidgets.QVBoxLayout() 109 | self.output_widget.setLayout(self.output_layout) 110 | self.output_layout.addWidget(self.outputs_attributes_widget) 111 | self.splitter.addWidget(self.output_widget) 112 | # Separator 113 | self.separator1 = QtWidgets.QFrame(frameShape=QtWidgets.QFrame.HLine) 114 | 115 | # Animation layout 116 | self.animation_layout = QtWidgets.QVBoxLayout() 117 | 118 | # Radio buttons for animation type 119 | self.animation_radio_layout = QtWidgets.QHBoxLayout() 120 | self.use_current_animation = QtWidgets.QRadioButton("Use current animation") 121 | self.generate_random_animation = QtWidgets.QRadioButton("Generate random animation") 122 | self.animation_button_group = QtWidgets.QButtonGroup(self) 123 | self.animation_button_group.addButton(self.use_current_animation) 124 | self.animation_button_group.addButton(self.generate_random_animation) 125 | self.animation_radio_layout.addWidget(self.use_current_animation) 126 | self.animation_radio_layout.addWidget(self.generate_random_animation) 127 | self.animation_layout.addLayout(self.animation_radio_layout) 128 | self.use_current_animation.setChecked(True) 129 | 130 | # Random animation widget 131 | self.random_animation = QtWidgets.QWidget() 132 | self.random_animation_layout = QtWidgets.QHBoxLayout(self.random_animation) 133 | self.amount_of_frames = QtWidgets.QSpinBox() 134 | self.amount_of_frames.setRange(0, 10000) 135 | self.amount_of_frames.setValue(1000) 136 | self.amount_of_frames.setPrefix("Amount of Frames: ") 137 | self.min_value = QtWidgets.QDoubleSpinBox() 138 | self.min_value.setRange(-1000, 1000) 139 | self.min_value.setValue(-50) 140 | self.min_value.setPrefix("Min: ") 141 | self.max_value = QtWidgets.QDoubleSpinBox() 142 | self.max_value.setRange(-1000, 1000) 143 | self.max_value.setValue(50) 144 | self.max_value.setPrefix("Max: ") 145 | self.random_animation_layout.addWidget(self.amount_of_frames) 146 | self.random_animation_layout.addWidget(self.min_value) 147 | self.random_animation_layout.addWidget(self.max_value) 148 | self.animation_layout.addWidget(self.random_animation) 149 | self.random_animation.setVisible(False) 150 | 151 | # Separator 152 | self.separator2 = QtWidgets.QFrame(frameShape=QtWidgets.QFrame.HLine) 153 | 154 | 155 | # Animation range widget 156 | self.animation_range_widget = QtWidgets.QWidget() 157 | self.animation_range_layout = QtWidgets.QHBoxLayout(self.animation_range_widget) 158 | #self.use_input_range_checkbox = QtWidgets.QCheckBox("Use input animation range") 159 | #self.use_input_range_checkbox.setChecked(True) 160 | self.start_frame = QtWidgets.QSpinBox() 161 | self.start_frame.setPrefix("Start Frame: ") 162 | self.end_frame = QtWidgets.QSpinBox() 163 | self.end_frame.setPrefix("End Frame: ") 164 | #self.animation_range_layout.addWidget(self.use_input_range_checkbox) 165 | self.animation_range_layout.addWidget(self.start_frame) 166 | self.animation_range_layout.addWidget(self.end_frame) 167 | self.animation_layout.addWidget(self.animation_range_widget) 168 | 169 | # Hyperparameters 170 | self.alpha = MyDoubleSpinBox() 171 | self.alpha.setPrefix("Alpha: ") 172 | self.alpha.setMinimum(0) 173 | self.alpha.setDecimals(4) 174 | self.alpha.setValue(.01) 175 | self.alpha.setToolTip("Regularization strength for ElasticNet.") 176 | 177 | self.l1_ratio = MyDoubleSpinBox() 178 | self.l1_ratio.setPrefix("L1 ratio: ") 179 | self.l1_ratio.setMinimum(0) 180 | self.l1_ratio.setDecimals(4) 181 | self.l1_ratio.setValue(0.5) 182 | self.l1_ratio.setToolTip("Mixing parameter for L1/L2 regularization (0 = L2, 1 = L1).") 183 | 184 | self.tol = MyDoubleSpinBox() 185 | self.tol.setPrefix("Tolerance: ") 186 | self.tol.setMinimum(0) 187 | self.tol.setDecimals(6) 188 | self.tol.setValue(0.001) 189 | self.tol.setToolTip("Optimization tolerance for stopping criteria.") 190 | 191 | self.train_parameters_frame = QtWidgets.QGroupBox("Train Parameters") 192 | self.train_parameters_layout = QtWidgets.QHBoxLayout() 193 | self.train_parameters_layout.addWidget(self.alpha) 194 | self.train_parameters_layout.addWidget(self.l1_ratio) 195 | self.train_parameters_layout.addWidget(self.tol) 196 | self.train_parameters_frame.setLayout(self.train_parameters_layout) 197 | 198 | # Separator 199 | self.separator3 = QtWidgets.QFrame(frameShape=QtWidgets.QFrame.HLine) 200 | 201 | # Train button 202 | self.max_iter = QtWidgets.QSpinBox() 203 | self.max_iter.setPrefix("Max Iter: ") 204 | self.max_iter.setMinimum(0) 205 | self.max_iter.setMaximum(100000) 206 | self.max_iter.setValue(1000) 207 | self.max_iter.setToolTip("Maximum number of iterations for training.") 208 | 209 | self.train_button = QtWidgets.QPushButton("Train") 210 | self.duplicate_checkbox = QtWidgets.QCheckBox("Duplicate output node (for debugging purposes)") 211 | 212 | self.max_iter_train_layout = QtWidgets.QHBoxLayout() 213 | self.max_iter_train_layout.addWidget(self.max_iter) 214 | self.max_iter_train_layout.addWidget(self.train_button) 215 | self.max_iter_train_layout.setStretch(1, 1) 216 | 217 | self.status_bar = QtWidgets.QStatusBar(self) 218 | 219 | # Add elements to the main layout 220 | self.layout.addWidget(self.splitter) 221 | self.layout.addWidget(self.separator1) 222 | self.layout.addLayout(self.animation_layout) 223 | self.layout.addWidget(self.separator2) 224 | self.layout.addWidget(self.train_parameters_frame) 225 | self.layout.addWidget(self.separator3) 226 | self.layout.addWidget(self.duplicate_checkbox) 227 | self.layout.addLayout(self.max_iter_train_layout) 228 | self.layout.addWidget(self.status_bar) 229 | 230 | # Set button sizes and tooltips 231 | self.add_button.setFixedSize(50, 15) 232 | self.add_button.setIcon(QtGui.QIcon(":/addClip.png")) 233 | self.add_button.setIconSize(QtCore.QSize(15, 15)) 234 | self.add_button.setToolTip("Add selected attributes to the list.") 235 | 236 | self.remove_button.setFixedSize(50, 15) 237 | self.remove_button.setToolTip("Remove selected attributes from the list.") 238 | 239 | self.clear_button.setFixedSize(50, 15) 240 | self.clear_button.setIcon(QtGui.QIcon(":/smallTrash.png")) 241 | self.clear_button.setIconSize(QtCore.QSize(15, 15)) 242 | self.clear_button.setToolTip("Clear all attributes from the list.") 243 | 244 | self.add_button2.setFixedSize(50, 15) 245 | self.add_button2.setIcon(QtGui.QIcon(":/addClip.png")) 246 | self.add_button2.setIconSize(QtCore.QSize(15, 15)) 247 | self.add_button2.setToolTip("Add selected attributes to the list.") 248 | 249 | self.remove_button2.setFixedSize(50, 15) 250 | self.remove_button2.setToolTip("Remove selected attributes from the list.") 251 | 252 | self.clear_button2.setFixedSize(50, 15) 253 | self.clear_button2.setIcon(QtGui.QIcon(":/smallTrash.png")) 254 | self.clear_button2.setIconSize(QtCore.QSize(15, 15)) 255 | self.clear_button2.setToolTip("Clear all attributes from the list.") 256 | 257 | # Connect signals 258 | self.generate_random_animation.toggled.connect(self.random_animation.setVisible) 259 | self.use_current_animation.toggled.connect(self.animation_range_widget.setVisible) 260 | #self.use_input_range_checkbox.toggled.connect(self.toggle_animation_range_controls) 261 | #self.toggle_animation_range_controls(True) 262 | self.add_button.clicked.connect(partial(self.add_attributes, self.inputs_attributes, True)) 263 | self.add_button2.clicked.connect(partial(self.add_attributes, self.outputs_attributes, False)) 264 | self.train_button.clicked.connect(self.train) 265 | self.update_status.connect(self.status_bar.showMessage) 266 | self.clear_button.clicked.connect(partial(self.clear_list, self.inputs_attributes)) 267 | self.remove_button.clicked.connect(partial(self.remove_selected_item, self.inputs_attributes)) 268 | self.clear_button2.clicked.connect(partial(self.clear_list, self.outputs_attributes)) 269 | self.remove_button2.clicked.connect(partial(self.remove_selected_item, self.outputs_attributes)) 270 | 271 | def toggle_animation_range_controls(self, checked): 272 | self.start_frame.setEnabled(not checked) 273 | self.end_frame.setEnabled(not checked) 274 | 275 | def open_link(self): 276 | link = "https://github.com/lopezmauro/ml-example-nodes/wiki/Linear-Regression-Tool-for-Autodesk-Maya" 277 | QtGui.QDesktopServices.openUrl(QtCore.QUrl(link)) 278 | 279 | 280 | def add_attributes(self, list_widget, update_range=True): 281 | selected_nodes = cmds.ls(sl=1) 282 | selected_attr = cmds.channelBox('mainChannelBox', query=True, selectedMainAttributes=True) 283 | attributes_list = [] 284 | rot_attributes = list() 285 | for node in selected_nodes: 286 | for attr in selected_attr: 287 | long_attr = maya_utils.get_long_attr_name(node, attr) 288 | full_attr = f'{node}.{long_attr}' 289 | if long_attr in ['rotateX', 'rotateY', 'rotateZ']: 290 | rot_attributes.append(full_attr) 291 | else: 292 | attributes_list.append(full_attr) 293 | 294 | if rot_attributes: 295 | # Ask the user if they want the rotation matrix instead 296 | msg_box = QtWidgets.QMessageBox() 297 | msg_box.setIcon(QtWidgets.QMessageBox.Question) 298 | msg_box.setWindowTitle("Rotation Attribute Detected") 299 | msg_box.setText("You have selected a rotation attribute.\n" 300 | "Linear Regression often struggles with Euler rotations due to gimbal lock and non-linearities.\n" 301 | "Would you like to use the rotation matrix instead, which may provide better results?") 302 | msg_box.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No) 303 | response = msg_box.exec_() 304 | 305 | if response == QtWidgets.QMessageBox.Yes: 306 | # Replace rotation attributes with rotation matrix attributes 307 | attributes_list.extend([f"{node}.rotMatrix" for node in selected_nodes]) 308 | else: 309 | attributes_list.extend(rot_attributes) 310 | 311 | if attributes_list: 312 | listed_attributes = {list_widget.item(i).text() for i in range(list_widget.count())} 313 | missing_attributes = sorted(set(attributes_list) - listed_attributes) 314 | list_widget.addItems(missing_attributes) 315 | if update_range: 316 | self.get_animation_range() 317 | 318 | def get_animation_range(self): 319 | input_attributes = [self.inputs_attributes.item(i).text() for i in range(self.inputs_attributes.count())] 320 | if not input_attributes: 321 | return 322 | rot_matrices = [a for a in input_attributes if a.endswith('.rotMatrix')] 323 | for rot_matrix in rot_matrices: 324 | node = rot_matrix.split('.')[0] 325 | input_attributes.remove(rot_matrix) 326 | input_attributes.extend([f'{node}.{a}' for a in ['rotateX', 'rotateY', 'rotateZ']]) 327 | frame_range = maya_utils.get_animation_range(input_attributes) 328 | if not frame_range: 329 | cmds.error("No keyframes found in the selected attributes.") 330 | return 331 | self.start_frame.setValue(frame_range[0]) 332 | self.end_frame.setValue(frame_range[1]) 333 | 334 | 335 | def clear_list(self, list_widget): 336 | list_widget.clear() 337 | 338 | def remove_selected_item(self, list_widget): 339 | list_items = list_widget.selectedItems() 340 | if not list_items: 341 | return 342 | for item in list_items: 343 | list_widget.takeItem(list_widget.row(item)) 344 | 345 | def trainLinearRegression(self, X, y, **kwargs): 346 | model = ElasticNet(**kwargs) 347 | model.fit(X, y) 348 | weights = model.coef_ 349 | bias = model.intercept_ 350 | return weights, bias 351 | 352 | @wait_cursor 353 | def train(self): 354 | 355 | duplicates = dict() 356 | input_attributes = [self.inputs_attributes.item(i).text() for i in range(self.inputs_attributes.count())] 357 | target_attributes = [self.outputs_attributes.item(i).text() for i in range(self.outputs_attributes.count())] 358 | if not input_attributes or not target_attributes: 359 | cmds.warning("Please select input and target attributes.") 360 | return 361 | if self.use_current_animation.isChecked(): 362 | frame_range = (self.start_frame.value(), self.end_frame.value()) 363 | else: 364 | frame_range = (0, self.amount_of_frames.value()) 365 | if self.duplicate_checkbox.isChecked(): 366 | target_attributes, duplicates = self.duplicate_target_nodes(target_attributes) 367 | 368 | # handle if any attribute is a rotation matrix 369 | input_attributes = self.handle_input_attributes(input_attributes) 370 | target_attributes, target_attr_mapping, floats_to_transforms, temp_matrix_to_floats = self.handle_target_attributes(target_attributes) 371 | print(input_attributes) 372 | print(target_attributes) 373 | # get animation data 374 | frames = range(frame_range[0], frame_range[1] + 1) 375 | input_anim = maya_utils.get_values_at_frames(input_attributes, frames) 376 | target_anim = maya_utils.get_values_at_frames(target_attributes, frames) 377 | # train model and create regression node 378 | # return 379 | try: 380 | X = np.array([input_anim[a] for a in input_attributes]).T 381 | y = np.array([target_anim[a] for a in target_attributes]).T 382 | #X_mean, X_std = None, None 383 | #normalize = self.normalizeInput.isChecked() 384 | #if normalize: 385 | X, X_mean, X_std = maya_utils.normalize_features(X) 386 | self.status_bar.showMessage("Training Linear Regression model...") 387 | weights, bias = self.trainLinearRegression(X, y, 388 | max_iter=self.max_iter.value(), 389 | alpha=self.alpha.value(), 390 | l1_ratio=self.l1_ratio.value(), 391 | tol=self.tol.value()) 392 | 393 | # if there are any rot matrix as target, we need to connect the output of the floatsToTransform node to the target node 394 | attr_to_connect = self.get_target_attributes_to_connect(target_attributes, target_attr_mapping) 395 | for node, floats_to_transform_node in floats_to_transforms.items(): 396 | cmds.connectAttr(f"{floats_to_transform_node}.outputRotate", f"{node}.rotate", f=1) 397 | cmds.connectAttr(f"{floats_to_transform_node}.outputRotateX", f"{node}.rotateX", f=1) 398 | cmds.connectAttr(f"{floats_to_transform_node}.outputRotateY", f"{node}.rotateY", f=1) 399 | cmds.connectAttr(f"{floats_to_transform_node}.outputRotateZ", f"{node}.rotateZ", f=1) 400 | print(attr_to_connect) 401 | maya_utils.create_regression_node('regressionNode', 402 | weights, 403 | bias, 404 | input_attributes, 405 | attr_to_connect, 406 | X_mean.tolist(), X_std.tolist()) 407 | 408 | self.status_bar.showMessage("Linear Regression Node created and initialized.") 409 | #if temp_matrix_to_floats: 410 | # cmds.delete(temp_matrix_to_floats) 411 | show_message("Success", "Linear Regression Node created and initialized.") 412 | 413 | except Exception as e: 414 | for node in duplicates.values(): 415 | cmds.delete(node) 416 | cmds.error(f"An error occurred during training: {str(e)}") 417 | self.status_bar.showMessage("Training failed.") 418 | show_message("Error", "Training Failed.") 419 | 420 | def handle_input_attributes(self, input_attributes): 421 | input_rot_matrices = [a for a in input_attributes if a.endswith('.rotMatrix')] 422 | for rot_matrix in input_rot_matrices: 423 | node = rot_matrix.split('.')[0] 424 | input_attributes.remove(rot_matrix) 425 | matrix_to_floats = maya_utils.create_matrix_to_floats_node(node) 426 | input_attributes.extend([f'{matrix_to_floats}.outputFloat{i}' for i in ROT_MATRIX_INDICES]) 427 | return input_attributes 428 | 429 | def handle_target_attributes(self, target_attributes): 430 | target_rot_matrices = [a for a in target_attributes if a.endswith('.rotMatrix')] 431 | target_attr_mapping = dict() 432 | floats_to_transforms = dict() 433 | temp_matrix_to_floats = list() 434 | for rot_matrix in target_rot_matrices: 435 | node = rot_matrix.split('.')[0] 436 | target_attributes.remove(rot_matrix) 437 | matrix_to_floats = maya_utils.create_matrix_to_floats_node(node) 438 | temp_matrix_to_floats.append(matrix_to_floats) 439 | floats_to_transform_node = cmds.createNode("floatsToTransform", name=f"{node}_floats_to_transform") 440 | for i in ROT_MATRIX_INDICES: 441 | mtx_to_float = f"{matrix_to_floats}.outputFloat{i}" 442 | target_attr_mapping[mtx_to_float] = f"{floats_to_transform_node}.inputFloat{i}" 443 | target_attributes.append(mtx_to_float) 444 | floats_to_transforms[node] = floats_to_transform_node 445 | return target_attributes, target_attr_mapping, floats_to_transforms, temp_matrix_to_floats 446 | 447 | def get_target_attributes_to_connect(self, target_attributes, target_attr_mapping): 448 | attr_to_connect = list() 449 | for attr in target_attributes: 450 | if attr in target_attr_mapping: 451 | attr_to_connect.append(target_attr_mapping[attr]) 452 | else: 453 | attr_to_connect.append(attr) 454 | return attr_to_connect 455 | 456 | def duplicate_target_nodes(self, target_attributes): 457 | new_target_attributes = list() 458 | target_nodes = {a: a.split('.')[0] for a in target_attributes} 459 | duplicates = dict() 460 | for node in set(target_nodes.values()): 461 | duplicates[node] = cmds.duplicate(node)[0] 462 | src_connections = cmds.listConnections(node, d=False, s=True, p=True, c=True) or list() 463 | for src, dst in zip(src_connections[1::2], src_connections[0::2]): 464 | cmds.connectAttr(src, dst.replace(node, duplicates[node])) 465 | for attr in target_attributes: 466 | new_attr = attr.replace(target_nodes[attr], duplicates[target_nodes[attr]]) 467 | new_target_attributes.append(new_attr) 468 | target_attributes = new_target_attributes[:] 469 | return target_attributes, duplicates 470 | 471 | def export_trained_data(self): 472 | # Open file dialog to exort trained data 473 | export_iu = RegressionNodeExporterUI() 474 | export_iu.exec_() 475 | 476 | def import_trained_data(self): 477 | # Open file dialog to import trained data 478 | file_path, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Import Trained Data", "", "JSON Files (*.json)") 479 | if file_path: 480 | created_node = maya_utils.import_regression_node(file_path) 481 | show_message("Success", f"{created_node} created and initialized.") 482 | 483 | def load_needed_nodes(self): 484 | maya_utils.load_node('regression_node') 485 | maya_utils.load_node('matrix_to_floats') 486 | maya_utils.load_node('floats_to_transform') 487 | 488 | 489 | class RegressionNodeExporterUI(QtWidgets.QDialog): 490 | def __init__(self): 491 | super().__init__() 492 | self.setWindowTitle("Regression Node Exporter") 493 | self.setLayout(QtWidgets.QVBoxLayout()) 494 | 495 | self.node_list = QtWidgets.QListWidget() 496 | self.refresh_nodes() 497 | self.layout().addWidget(self.node_list) 498 | 499 | file_layout = QtWidgets.QHBoxLayout() 500 | self.file_path_edit = QtWidgets.QLineEdit() 501 | self.browse_btn = QtWidgets.QPushButton() 502 | self.browse_btn.setIcon(QtGui.QIcon(QtWidgets.QApplication.style().standardIcon(QtWidgets.QStyle.SP_DirOpenIcon))) 503 | self.browse_btn.clicked.connect(self.browse_file) 504 | file_layout.addWidget(self.file_path_edit) 505 | file_layout.addWidget(self.browse_btn) 506 | self.layout().addLayout(file_layout) 507 | 508 | btn_layout = QtWidgets.QHBoxLayout() 509 | self.export_btn = QtWidgets.QPushButton("Export Selected") 510 | self.export_btn.clicked.connect(self.export_selected_node) 511 | self.close_btn = QtWidgets.QPushButton("Close") 512 | self.close_btn.clicked.connect(self.close) 513 | 514 | btn_layout.addWidget(self.export_btn) 515 | btn_layout.addWidget(self.close_btn) 516 | self.layout().addLayout(btn_layout) 517 | 518 | def refresh_nodes(self): 519 | self.node_list.clear() 520 | nodes = cmds.ls(type="RegressionNode") 521 | if nodes: 522 | self.node_list.addItems(nodes) 523 | else: 524 | self.node_list.addItem("No RegressionNodes found") 525 | 526 | def browse_file(self): 527 | file_path, _ = QtWidgets.QFileDialog.getSaveFileName(self, "Export Trained Data", "", "JSON Files (*.json)") 528 | if file_path: 529 | self.file_path_edit.setText(file_path) 530 | 531 | def export_selected_node(self): 532 | selected_item = self.node_list.currentItem() 533 | if not selected_item or selected_item.text() == "No RegressionNodes found": 534 | show_message("Warning", "Please select a valid RegressionNode to export.") 535 | return 536 | 537 | file_path = self.file_path_edit.text() 538 | if not file_path: 539 | show_message("Warning", "Please select a file path for export.") 540 | return 541 | 542 | maya_utils.export_regression_node(selected_item.text(), file_path) 543 | show_message("Success", f"Exported trained data to {file_path}") 544 | self.accept() # Close and delete the UI after exporting -------------------------------------------------------------------------------- /ui/remove-button.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 6 | 7 | 11 | 12 | 13 | 14 | 15 | --------------------------------------------------------------------------------