├── LICENSE ├── README.md ├── shapekeyimport.py └── shapekeyimport_2_8.py /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 | ![Demo](https://github.com/Shriinivas/etc/blob/master/shapekeyimport/illustrations/intro.gif) 2 | # Blender add-on to import paths as shape keys
3 | This add-on lets you import paths from an SVG file as paths as well as shape keys

4 | Supported Blender versions
5 | 2.8+ and 3.x (Script File - shapekeyimport_2_8.py)
6 | 2.79b (Script File - shapekeyimport.py)
7 | 8 | # Installation 9 | For Blender 2.8+ and 3.x, download shapekeyimport_2_8.py; for 2.79b download svgimport.py

10 | In Blender select File->User Preferences
11 | Click install Add-ons tab and then Install Add-on from File
12 | Select the downloaded file
13 | Check the 'Import Paths and Shape Keys' option in the add-ons dialog
14 | 15 | You can invoke the add-on in 2.79 by pressing spacebar or in 2.8+ / 3.x by pressing F3 in the 3d view and selecting the
16 | 'Import Paths & Shape Keys' option
The add-on is also accesible from Import menu under File
17 | 18 | 'demo.blend' and 'demo ver 2.blend' illustrate the basic functionality and the new enhancements of version 2. You can import one of the SVGs (via import shape keys option) in a new blender file to verify the functionality. 19 | 20 | 21 | # Quick start 22 | ![Demo](https://github.com/Shriinivas/etc/blob/master/shapekeyimport/illustrations/git.gif) 23 | (SVG Editor: Inkscape)
24 | Group the paths in the SVG editor, make sure the group is in some Layer and the target is the first node in the XML group node <svg:g>
25 | Invoke the add-on in Blender, select the svg file and click 'Import Paths & Shapekeys' button
26 | The target now has the shapekeys that correspond to the paths in the svg group
27 | 28 | (SVG Editor: Inkscape and others)
29 | Alternatively, you can create target-shapekey relationship by adding an xml attribute 'shapekeys' in the
30 | target path and setting its value to the comma separated IDs of the shapekey paths
31 | In case you are using SVG Editor other than Inkscape, you may have to uncheck 'Import by Group' checkbox
32 | 33 | The introductory video and the enhancements overview are a good starting point for exploring the add-on functionality 34 | 35 | # Examples & Demos 36 | You can find [here](https://github.com/Shriinivas/etc/tree/master/shapekeyimport/samples) the demo files used on this page as well as some samples demonstrating the add-on functionality 37 | 38 | # Limitations 39 | Exercise caution when using this add-on in production as it's in beta stage
40 | 41 | As of now the Add-on is tested with Inkscape only. If you face issues with other SVG editors, try exporting the file as plain SVG
Please report such and other issues along with the sample files here and I will look into them as soon as I can
42 | 43 | Keep watching this space, as there will be updates to the code as and when bugs are discovered and fixed
44 | 45 | # Credits 46 | The add-on file includes python converted a2c js function (Copyright (C) 2013-2015 by Vitaly Puzrin) 47 | and some portion imported from svgpathtools (Copyright (c) 2015 Andrew Allan Port, Copyright (c) 2013-2014 Lennart Regebro)
48 | A few of the bezier curve related algorithms were inspired by the answers on stackoverflow; their links can be found in the code. 49 | 50 | # License 51 | MIT 52 | -------------------------------------------------------------------------------- /shapekeyimport.py: -------------------------------------------------------------------------------- 1 | # 2 | # 3 | # This Blender add-on imports paths and shapeKeys from an SVG file 4 | # Supported Blender Version: 2.79b 5 | # 6 | # License: GPL (https://github.com/Shriinivas/shapeKeyimport/blob/master/LICENSE) 7 | # 8 | 9 | # Not yet pep8 compliant 10 | 11 | # Scaling not done based on the unit of the SVG document, but based simply on value 12 | # If precise scaling is needed, appropriate unit (mm) needs to be set in the source SVG 13 | 14 | import bpy, copy, math, re, time 15 | from bpy.props import IntProperty, FloatProperty, BoolProperty, StringProperty 16 | from bpy.props import CollectionProperty, EnumProperty 17 | from xml.dom import minidom 18 | from collections import OrderedDict 19 | from mathutils import Vector, Matrix 20 | from math import sqrt, cos, sin, acos, degrees, radians, tan 21 | from cmath import exp, sqrt as csqrt, phase 22 | from collections import MutableSequence 23 | 24 | #################### UI and Registration Stuff #################### 25 | 26 | bl_info = { 27 | "name": "Import Paths and Shape Keys from SVG", 28 | "category": "Import-Export", 29 | } 30 | 31 | noneStr = "-None-" 32 | CURVE_NAME_PREFIX = 'Curve' 33 | 34 | def getCurveNames(scene, context): 35 | return [(noneStr, noneStr, '-1')] + [(obj.name, obj.name, str(i)) for i, obj in 36 | enumerate(context.scene.objects) if obj.type == 'CURVE'] 37 | 38 | def getAlignmentList(scene, context): 39 | alignListStrs = [*getAlignSegsFn().keys()] 40 | return [(noneStr, noneStr, '-1')] + [(str(align), str(align), str(i)) 41 | for i, align in enumerate(alignListStrs)] 42 | 43 | def getMatchPartList(scene, context): 44 | arrangeListStrs = [*getAlignPartsFn().keys()] 45 | return [(noneStr, noneStr, '-1')] + [(str(arrange), str(arrange), str(i)) 46 | for i, arrange in enumerate(arrangeListStrs)] 47 | 48 | class ObjectImportShapeKeys(bpy.types.Operator): 49 | 50 | bl_idname = "object.import_shapekeys" 51 | bl_label = "Import Paths & Shape Keys" 52 | bl_options = {'REGISTER', 'UNDO'} 53 | 54 | filter_glob = StringProperty(default="*.svg") 55 | filepath = StringProperty(subtype='FILE_PATH') 56 | 57 | #User input 58 | 59 | byGroup = BoolProperty(name="Import By Group", \ 60 | description = "Import target and shape key paths forming a group in SVG", \ 61 | default = True) 62 | 63 | byAttrib = BoolProperty(name="Import By Attribute", \ 64 | description = "Import targets having attribute defining shape key path IDs in SVG", \ 65 | default = True) 66 | 67 | shapeKeyAttribName = StringProperty(name="Attribute", \ 68 | description = "Name of target path attribute used to define shape keys in SVG", 69 | default = 'shapekeys') 70 | 71 | addShapeKeyPaths = BoolProperty(name="Retain Shape Key Paths", \ 72 | description = "Import shape key paths as paths as well as shape keys", \ 73 | default = False) 74 | 75 | addNontargetPaths = BoolProperty(name="Import Non-target Paths", \ 76 | description = "Import paths that are neither targets nor shape keys", \ 77 | default = True) 78 | 79 | addPathsFromHiddenLayer = BoolProperty(name="Import Hidden Layer Paths", 80 | description='Import paths from layers marked as hidden in SVG', \ 81 | default = False) 82 | 83 | originToGeometry = BoolProperty(name="Origin To Geometry", \ 84 | description="Shift the imported path's origin to its geometry center", \ 85 | default = False) 86 | 87 | xScale = FloatProperty(name="X", \ 88 | description="X scale factor for imported paths", \ 89 | default = 0.01) 90 | 91 | yScale = FloatProperty(name="Y", \ 92 | description="Y scale factor for imported paths", \ 93 | default = 0.01) 94 | 95 | zLocation = FloatProperty(name="Z Location", \ 96 | description='Z coordiate value for imported paths', default = 0) 97 | 98 | resolution = IntProperty(name="Resolution", \ 99 | description='Higher value gives smoother transition but more complex geometry', \ 100 | default = 50, min=0) 101 | 102 | objList = EnumProperty(name="Copy Properties From", items = getCurveNames, \ 103 | description='Curve whose material, depth etc. should be copied on to imported paths') 104 | 105 | partMatchList = EnumProperty(name="Match Parts By", items = getMatchPartList, \ 106 | description='Match disconnected parts of target and shape key based on (BBox -> Bounding Box)') 107 | 108 | alignList = EnumProperty(name="Node Alignment Order", items = getAlignmentList, \ 109 | description = 'Start aligning the nodes of target and shape keys (paths or parts) from') 110 | 111 | def execute(self, context): 112 | createdObjsMap = main(infilePath = self.filepath, \ 113 | shapeKeyAttribName = self.shapeKeyAttribName, \ 114 | byGroup = self.byGroup, \ 115 | byAttrib = self.byAttrib, \ 116 | addShapeKeyPaths = self.addShapeKeyPaths, \ 117 | addNontargetPaths = self.addNontargetPaths, \ 118 | scale = [self.xScale, -self.yScale, 1], \ 119 | zVal = self.zLocation, \ 120 | resolution = self.resolution, \ 121 | copyObjName = self.objList, \ 122 | partArrangeOrder = self.partMatchList, \ 123 | alignOrder = self.alignList, \ 124 | pathsFromHiddenLayer = self.addPathsFromHiddenLayer, \ 125 | originToGeometry = self.originToGeometry) 126 | return {'FINISHED'} 127 | 128 | def draw(self, context): 129 | layout = self.layout 130 | col = layout.column() 131 | row = col.row() 132 | row.prop(self, "byGroup") 133 | row = col.row() 134 | row.prop(self, "byAttrib") 135 | row = col.row() 136 | row.prop(self, "shapeKeyAttribName") 137 | row = col.row() 138 | row.prop(self, "addShapeKeyPaths") 139 | row = col.row() 140 | row.prop(self, "addNontargetPaths") 141 | row = col.row() 142 | row.prop(self, "addPathsFromHiddenLayer") 143 | row = col.row() 144 | row.prop(self, "originToGeometry") 145 | layout.row().separator() 146 | row = col.row() 147 | row.label('Scale') 148 | row = col.row() 149 | row.prop(self, "xScale") 150 | row.prop(self, "yScale") 151 | row = col.row() 152 | row.prop(self, "zLocation") 153 | layout.row().separator() 154 | row = col.row() 155 | row.prop(self, "resolution") 156 | row = col.row() 157 | row.prop(self, "objList") 158 | row = col.row() 159 | row.prop(self, "partMatchList") 160 | row = col.row() 161 | row.prop(self, "alignList") 162 | 163 | def invoke(self, context, event): 164 | alignListStrs = [*getAlignSegsFn().keys()] 165 | arrangeListStrs = [*getAlignPartsFn().keys()] 166 | 167 | #default values 168 | self.objList = noneStr 169 | self.partMatchList = str(arrangeListStrs[-1]) 170 | self.alignList = str(alignListStrs[-1]) 171 | 172 | context.window_manager.fileselect_add(self) 173 | 174 | return {'RUNNING_MODAL'} 175 | 176 | def menuImportShapeKeys(self, context): 177 | self.layout.operator(ObjectImportShapeKeys.bl_idname, 178 | text="Import Paths & Shape Keys (.svg)") 179 | 180 | def register(): 181 | bpy.utils.register_class(ObjectImportShapeKeys) 182 | bpy.types.INFO_MT_file_import.append(menuImportShapeKeys) 183 | 184 | def unregister(): 185 | bpy.utils.unregister_class(ObjectImportShapeKeys) 186 | bpy.types.INFO_MT_file_import.remove(menuImportShapeKeys) 187 | 188 | if __name__ == "__main__": 189 | register() 190 | 191 | ###################### addon code start #################### 192 | 193 | DEF_ERR_MARGIN = 0.0001 194 | hiddenLayerAttr = 'display:none' 195 | 196 | def isValidPath(pathElem): 197 | dVal = pathElem.getAttribute('d') 198 | return (dVal != None) and (dVal.strip() != "") and \ 199 | (dVal[0] in set('MLHVCSQTAmlhvcsqa')) 200 | 201 | class OrderedSet(OrderedDict): 202 | def add(self, item): 203 | super(OrderedSet, self).__setitem__(item, '') 204 | 205 | def __iter__(self): 206 | return super.keys().__iter__() 207 | 208 | #...Other methods to be added when needed 209 | 210 | class Part(): 211 | def __init__(self, segments, isClosed): 212 | self.segs = segments 213 | self.isClosed = isClosed 214 | 215 | if(len(segments) > 0): 216 | self.partToClose = self.isContinuous() 217 | 218 | def copy(self, start, end): 219 | if(start == None): 220 | start = 0 221 | if(end == None): 222 | end = len(self.segs) 223 | return Part(self.segs[start:end], None)#IsClosing not defined, so set to None 224 | 225 | def getSeg(self, idx): 226 | return self.segs[idx] 227 | 228 | def getSegs(self): 229 | return self.segs 230 | 231 | def getSegsCopy(self, start, end): 232 | if(start == None): 233 | start = 0 234 | if(end == None): 235 | end = len(self.segs) 236 | return self.segs[start:end] 237 | 238 | def bbox(self): 239 | leftBot_rgtTop = [[None]*2,[None]*2] 240 | for seg in self.segs: 241 | bb = bboxCubicBezier(seg) 242 | for i in range(0, 2): 243 | if (leftBot_rgtTop[0][i] == None or bb[0][i] < leftBot_rgtTop[0][i]): 244 | leftBot_rgtTop[0][i] = bb[0][i] 245 | for i in range(0, 2): 246 | if (leftBot_rgtTop[1][i] == None or bb[1][i] > leftBot_rgtTop[1][i]): 247 | leftBot_rgtTop[1][i] = bb[1][i] 248 | 249 | return leftBot_rgtTop 250 | 251 | def isContinuous(self): 252 | return cmplxCmpWithMargin(self.segs[0].start, self.segs[-1].end) 253 | 254 | def getSegCnt(self): 255 | return len(self.segs) 256 | 257 | def length(self, error): 258 | return sum(seg.length(error = error) for seg in self.segs) 259 | 260 | class PathElem: 261 | def __init__(self, path, attributes, transList, seqId): 262 | self.parts = getDisconnParts(path) 263 | self.pathId = attributes['id'].value 264 | self.attributes = attributes 265 | self.transList = transList 266 | self.seqId = seqId 267 | 268 | def getPartCnt(self): 269 | return len(self.parts) 270 | 271 | def getPartView(self): 272 | p = Part([seg for part in self.parts for seg in part.getSegs()], None) 273 | return p 274 | 275 | def getPartBoundaryIdxs(self): 276 | cumulCntList = set() 277 | cumulCnt = 0 278 | 279 | for p in self.parts: 280 | cumulCnt += p.getSegCnt() 281 | cumulCntList.add(cumulCnt) 282 | 283 | return cumulCntList 284 | 285 | def updatePartsList(self, segCntsPerPart, byPart): 286 | monolithicSegList = [seg for part in self.parts for seg in part.getSegs()] 287 | self.parts.clear() 288 | 289 | for i in range(0, len(segCntsPerPart)): 290 | if( i == 0): 291 | currIdx = 0 292 | else: 293 | currIdx = segCntsPerPart[i-1] 294 | 295 | nextIdx = segCntsPerPart[i] 296 | isClosed = None 297 | 298 | if(byPart == True and i < len(self.parts)): 299 | isClosed = self.parts[i].isClosed # Let's retain as far as possible 300 | 301 | self.parts.append(Part(monolithicSegList[currIdx:nextIdx], isClosed)) 302 | 303 | def __repr__(self): 304 | return self.pathId 305 | 306 | class BlenderBezierPoint: 307 | #all points are complex values not 3d vectors 308 | def __init__(self, pt, handleLeft, handleRight): 309 | self.pt = pt 310 | self.handleLeft = handleLeft 311 | self.handleRight = handleRight 312 | 313 | def __repr__(self): 314 | return str(self.pt) 315 | 316 | def getPathElemMap(doc, pathsFromHiddenLayer): 317 | elemMap = {} 318 | seqId = 0 319 | for pathXMLElem in doc.getElementsByTagName('path'): 320 | if (isElemSelectable(pathXMLElem, pathsFromHiddenLayer) and 321 | isValidPath(pathXMLElem)): 322 | dVal = pathXMLElem.getAttribute('d') 323 | transList = [] 324 | idAttr = pathXMLElem.getAttribute('id') 325 | parsedPath = parse_path(dVal) 326 | getTransformAttribs(pathXMLElem, transList) 327 | pathElem = PathElem(parsedPath, pathXMLElem.attributes, transList, seqId) 328 | elemMap[idAttr] = pathElem 329 | seqId += 1 330 | return elemMap 331 | 332 | def main(infilePath, shapeKeyAttribName, byGroup, byAttrib, addShapeKeyPaths, 333 | addNontargetPaths, scale, zVal, resolution, copyObjName, partArrangeOrder, alignOrder, 334 | pathsFromHiddenLayer, originToGeometry): 335 | 336 | doc = minidom.parse(infilePath) 337 | 338 | pathElemsMap = getPathElemMap(doc, pathsFromHiddenLayer) 339 | 340 | pathElems = [*pathElemsMap.values()] 341 | 342 | normalizePathElems(pathElems, alignOrder, partArrangeOrder) 343 | 344 | targetShapeKeyMap = {} 345 | allShapeKeyIdsSet = set() 346 | 347 | if(byGroup == True): 348 | updateShapeKeyMapByGroup(targetShapeKeyMap, allShapeKeyIdsSet, doc, pathsFromHiddenLayer) 349 | 350 | if(byAttrib == True): 351 | updateShapeKeyMapByAttrib(targetShapeKeyMap, pathElemsMap, allShapeKeyIdsSet, shapeKeyAttribName) 352 | 353 | #List of lists with all the interdependent paths that need to be homogenized 354 | dependentPathIdsSets = getDependentPathIdsSets(targetShapeKeyMap) 355 | 356 | byPart = (partArrangeOrder != noneStr) 357 | for prntIdx, dependentPathIdsSet in enumerate(dependentPathIdsSets): 358 | dependentPathsSet = [pathElemsMap.get(dependentPathId) for dependentPathId in dependentPathIdsSet 359 | if pathElemsMap.get(dependentPathId) != None] 360 | 361 | addMissingSegs(dependentPathsSet, byPart = byPart, resolution = resolution) 362 | 363 | bIdxs = set() 364 | for pathElem in dependentPathsSet: 365 | bIdxs = bIdxs.union(pathElem.getPartBoundaryIdxs()) 366 | 367 | for pathElem in dependentPathsSet: 368 | pathElem.updatePartsList(sorted(list(bIdxs)), byPart) 369 | 370 | #All will have same part count by now 371 | allToClose = [all(pathElem.parts[j].partToClose for pathElem in dependentPathsSet) 372 | for j in range(0, len(dependentPathsSet[0].parts))] 373 | 374 | #All interdependent paths will have the same no of splines with the same no of bezier points 375 | for pathElem in dependentPathsSet: 376 | for j, part in enumerate(pathElem.parts): 377 | part.partToClose = allToClose[j] 378 | 379 | objPathIds = set(targetShapeKeyMap.keys()) 380 | 381 | if(addNontargetPaths == True): 382 | nontargetIds = (pathElemsMap.keys() - targetShapeKeyMap.keys()) - allShapeKeyIdsSet 383 | objPathIds = objPathIds.union(nontargetIds) 384 | 385 | if(addShapeKeyPaths == True): 386 | #in case shapeKeys are also targets 387 | shapeKeyIdsToAdd = allShapeKeyIdsSet - targetShapeKeyMap.keys() 388 | objPathIds = objPathIds.union(shapeKeyIdsToAdd.intersection(pathElemsMap.keys())) 389 | 390 | copyObj = bpy.data.objects.get(copyObjName)#Can be None 391 | 392 | objMap = {} 393 | 394 | for objPathId in objPathIds: 395 | addSvg2Blender(objMap, pathElemsMap[objPathId], scale, zVal, copyObj, originToGeometry) 396 | 397 | for pathElemId in targetShapeKeyMap.keys(): 398 | pathObj = objMap[pathElemId] 399 | pathObj.shape_key_add('Basis') 400 | shapeKeyElemIds = targetShapeKeyMap[pathElemId].keys() 401 | for shapeKeyElemId in shapeKeyElemIds: 402 | shapeKeyElem = pathElemsMap.get(shapeKeyElemId) 403 | if(shapeKeyElem != None):#Maybe no need after so many checks earlier 404 | addShapeKey(pathObj, shapeKeyElem, shapeKeyElemId, scale, zVal, originToGeometry) 405 | 406 | return objMap 407 | 408 | #Avoid errors due to floating point conversions/comparisons 409 | def cmplxCmpWithMargin(complex1, complex2, margin = DEF_ERR_MARGIN): 410 | return floatCmpWithMargin(complex1.real, complex2.real, margin) and \ 411 | floatCmpWithMargin(complex1.imag, complex2.imag, margin) 412 | 413 | def floatCmpWithMargin(float1, float2, margin = DEF_ERR_MARGIN): 414 | return abs(float1 - float2) < margin 415 | 416 | #TODO: Would be more conditions like defs. Need a better solution 417 | def isElemSelectable(elem, pathsFromHiddenLayer): 418 | return getParentInHierarchy(elem, 'defs') == None and \ 419 | (pathsFromHiddenLayer == True or not isInHiddenLayer(elem)) 420 | 421 | def getParentInHierarchy(elem, parentTag): 422 | parent = elem.parentNode 423 | 424 | while(parent != None and parent.parentNode != None and parent.tagName != parentTag): 425 | parent = parent.parentNode 426 | 427 | #TODO: Better way to detect the Document node 428 | if(parent.parentNode == None): 429 | return None 430 | 431 | return parent 432 | 433 | def getTransformAttribs(elem, transList): 434 | if(elem.nodeType == elem.DOCUMENT_NODE): 435 | return 436 | 437 | transAttr = elem.getAttribute('transform') 438 | if(transAttr != None): 439 | transList.append(transAttr) 440 | if(elem.parentNode != None): 441 | getTransformAttribs(elem.parentNode, transList) 442 | 443 | def isInHiddenLayer(elem): 444 | parent = elem.parentNode 445 | 446 | while(parent != None and parent.nodeType == parent.ELEMENT_NODE and \ 447 | (parent.tagName != 'g' or (parent.parentNode != None and \ 448 | parent.parentNode.tagName != 'svg'))): 449 | parent = parent.parentNode 450 | 451 | if(parent != None and parent.nodeType == parent.ELEMENT_NODE): 452 | return parent.getAttribute('style').startswith(hiddenLayerAttr) 453 | 454 | return False 455 | 456 | def getDependentPathIdsSets(shapeKeyMap): 457 | pathIdSets = [] 458 | allAddedPathIds = set() 459 | for targetId in shapeKeyMap.keys(): 460 | #Keep track of the added path Ids since the target can be a shapeKey, 461 | #or a target of one of the shapeKeys of this target (many->many relation) 462 | if(targetId not in allAddedPathIds): 463 | pathIdSet = set() 464 | addDependentPathsToList(shapeKeyMap, pathIdSet, targetId) 465 | pathIdSets.append(pathIdSet) 466 | allAddedPathIds = allAddedPathIds.union(pathIdSet) 467 | return pathIdSets 468 | 469 | #Reverse lookup 470 | def getKeysetWithValue(srcMap, value): 471 | keySet = set() 472 | for key in srcMap: 473 | if(value in srcMap[key]): 474 | keySet.add(key) 475 | return keySet 476 | 477 | #All the shape keys and their other targets are added recursively 478 | def addDependentPathsToList(shapeKeyMap, pathIdSet, targetId): 479 | if(targetId in pathIdSet): 480 | return pathIdSet 481 | 482 | pathIdSet.add(targetId) 483 | shapeKeyElemIdMap = shapeKeyMap.get(targetId) 484 | 485 | if(shapeKeyElemIdMap == None): 486 | return pathIdSet 487 | 488 | shapeKeyElemIdList = shapeKeyElemIdMap.keys() 489 | if(shapeKeyElemIdList == None): 490 | return pathIdSet 491 | 492 | for shapeKeyElemId in shapeKeyElemIdList: 493 | #Recuresively add the Ids that are shape key of this shape key 494 | addDependentPathsToList(shapeKeyMap, pathIdSet, shapeKeyElemId) 495 | 496 | #Recursively add the Ids that are other targets of this shape key 497 | keyset = getKeysetWithValue(shapeKeyMap, shapeKeyElemId) 498 | for key in keyset: 499 | addDependentPathsToList(shapeKeyMap, pathIdSet, key) 500 | 501 | return pathIdSet 502 | 503 | def getAllPathElemsInGroup(parentElem, pathElems): 504 | for childNode in parentElem.childNodes: 505 | if childNode.nodeType == childNode.ELEMENT_NODE: 506 | if(childNode.tagName == 'path' and isValidPath(childNode)): 507 | pathElems.append(childNode) 508 | elif(childNode.tagName == 'g'): 509 | getAllPathElemsInGroup(childNode, pathElems) 510 | 511 | def updateShapeKeyMapByGroup(targetShapeKeyMap, allShapeKeyIdsSet, doc, pathsFromHiddenLayer): 512 | groupElems = [groupElem for groupElem in doc.getElementsByTagName('g') 513 | if (groupElem.parentNode.tagName != 'svg' and 514 | isElemSelectable(groupElem, pathsFromHiddenLayer))] 515 | 516 | for groupElem in groupElems: 517 | pathElems = [] 518 | getAllPathElemsInGroup(groupElem, pathElems) 519 | if(pathElems != None and len(pathElems) > 1 ): 520 | targetId = pathElems[0].getAttribute('id') 521 | if(targetShapeKeyMap.get(targetId) == None): 522 | targetShapeKeyMap[targetId] = OrderedSet() 523 | 524 | for i in range(1, len(pathElems)): 525 | shapeKeyId = pathElems[i].getAttribute('id') 526 | targetShapeKeyMap[targetId].add(shapeKeyId) 527 | allShapeKeyIdsSet.add(shapeKeyId) 528 | 529 | def updateShapeKeyMapByAttrib(targetShapeKeyMap, pathElemsMap, \ 530 | allShapeKeyIdsSet, shapeKeyAttribName): 531 | for key in pathElemsMap.keys(): 532 | targetPathElem = pathElemsMap[key] 533 | attributes = targetPathElem.attributes 534 | shapeKeyIdAttrs = attributes.get(shapeKeyAttribName) 535 | if(shapeKeyIdAttrs != None): 536 | shapeKeyIds = shapeKeyIdAttrs.value 537 | shapeKeyIdsStr = str(shapeKeyIds) 538 | shapeKeyIdList = shapeKeyIdsStr.replace(' ','').split(',') 539 | if(targetShapeKeyMap.get(key) == None): 540 | targetShapeKeyMap[key] = OrderedSet() 541 | for keyId in shapeKeyIdList: 542 | if(pathElemsMap.get(keyId) != None): 543 | targetShapeKeyMap[key].add(keyId) 544 | allShapeKeyIdsSet.add(keyId) 545 | 546 | def bboxArea(leftBot_rgtTop): 547 | return abs((leftBot_rgtTop[1][0]-leftBot_rgtTop[0][0]) * \ 548 | (leftBot_rgtTop[1][1]-leftBot_rgtTop[0][1])) 549 | 550 | #see https://stackoverflow.com/questions/24809978/calculating-the-bounding-box-of-cubic-bezier-curve 551 | #(3 D - 9 C + 9 B - 3 A) t^2 + (6 A - 12 B + 6 C) t + 3 (B - A) 552 | def bboxCubicBezier(bezier): 553 | def evalBez(AA, BB, CC, DD, t): 554 | return AA * (1 - t) * (1 - t) * (1 - t) + \ 555 | 3 * BB * t * (1 - t) * (1 - t) + \ 556 | 3 * CC * t * t * (1 - t) + \ 557 | DD * t * t * t 558 | 559 | A = [bezier.start.real, bezier.start.imag] 560 | B = [bezier.control1.real, bezier.control1.imag] 561 | C = [bezier.control2.real, bezier.control2.imag] 562 | D = [bezier.end.real, bezier.end.imag] 563 | 564 | MINXY = [min([A[0], D[0]]), min([A[1], D[1]])] 565 | MAXXY = [max([A[0], D[0]]), max([A[1], D[1]])] 566 | leftBot_rgtTop = [MINXY, MAXXY] 567 | 568 | a = [3 * D[i] - 9 * C[i] + 9 * B[i] - 3 * A[i] for i in range(0, 2)] 569 | b = [6 * A[i] - 12 * B[i] + 6 * C[i] for i in range(0, 2)] 570 | c = [3 * (B[i] - A[i]) for i in range(0, 2)] 571 | 572 | solnsxy = [] 573 | for i in range(0, 2): 574 | solns = [] 575 | if(a[i] == 0): 576 | if(b[i] == 0): 577 | solns.append(0)#Independent of t so lets take the starting pt 578 | else: 579 | solns.append(c[i] / b[i]) 580 | else: 581 | rootFact = b[i] * b[i] - 4 * a[i] * c[i] 582 | if(rootFact >=0 ): 583 | #Two solutions with + and - sqrt 584 | solns.append((-b[i] + sqrt(rootFact)) / (2 * a[i])) 585 | solns.append((-b[i] - sqrt(rootFact)) / (2 * a[i])) 586 | solnsxy.append(solns) 587 | 588 | for i, soln in enumerate(solnsxy): 589 | for j, t in enumerate(soln): 590 | if(t < 1 and t > 0): 591 | co = evalBez(A[i], B[i], C[i], D[i], t) 592 | if(co < leftBot_rgtTop[0][i]): 593 | leftBot_rgtTop[0][i] = co 594 | if(co > leftBot_rgtTop[1][i]): 595 | leftBot_rgtTop[1][i] = co 596 | 597 | return leftBot_rgtTop 598 | 599 | def getLineSegment(start, end, t0, t1): 600 | xt0, yt0 = (1 - t0) * start.real + t0 * end.real , (1 - t0) * start.imag + t0 * end.imag 601 | xt1, yt1 = (1 - t1) * start.real + t1 * end.real , (1 - t1) * start.imag + t1 * end.imag 602 | 603 | return CubicBezier(complex(xt0, yt0), complex(xt0, yt0), 604 | complex(xt1, yt1), complex(xt1, yt1)) 605 | 606 | #see https://stackoverflow.com/questions/878862/drawing-part-of-a-b%c3%a9zier-curve-by-reusing-a-basic-b%c3%a9zier-curve-function/879213#879213 607 | def getCurveSegment(seg, t0, t1): 608 | ctrlPts = seg 609 | 610 | if(t0 > t1): 611 | tt = t1 612 | t1 = t0 613 | t0 = tt 614 | 615 | #Let's make at least the line segments of predictable length :) 616 | if(ctrlPts[0] == ctrlPts[1] and ctrlPts[2] == ctrlPts[3]): 617 | return getLineSegment(ctrlPts[0], ctrlPts[2], t0, t1) 618 | 619 | x1, y1 = ctrlPts[0].real, ctrlPts[0].imag 620 | bx1, by1 = ctrlPts[1].real, ctrlPts[1].imag 621 | bx2, by2 = ctrlPts[2].real, ctrlPts[2].imag 622 | x2, y2 = ctrlPts[3].real, ctrlPts[3].imag 623 | 624 | u0 = 1.0 - t0 625 | u1 = 1.0 - t1 626 | 627 | qxa = x1*u0*u0 + bx1*2*t0*u0 + bx2*t0*t0 628 | qxb = x1*u1*u1 + bx1*2*t1*u1 + bx2*t1*t1 629 | qxc = bx1*u0*u0 + bx2*2*t0*u0 + x2*t0*t0 630 | qxd = bx1*u1*u1 + bx2*2*t1*u1 + x2*t1*t1 631 | 632 | qya = y1*u0*u0 + by1*2*t0*u0 + by2*t0*t0 633 | qyb = y1*u1*u1 + by1*2*t1*u1 + by2*t1*t1 634 | qyc = by1*u0*u0 + by2*2*t0*u0 + y2*t0*t0 635 | qyd = by1*u1*u1 + by2*2*t1*u1 + y2*t1*t1 636 | 637 | xa = qxa*u0 + qxc*t0 638 | xb = qxa*u1 + qxc*t1 639 | xc = qxb*u0 + qxd*t0 640 | xd = qxb*u1 + qxd*t1 641 | 642 | ya = qya*u0 + qyc*t0 643 | yb = qya*u1 + qyc*t1 644 | yc = qyb*u0 + qyd*t0 645 | yd = qyb*u1 + qyd*t1 646 | 647 | return CubicBezier(complex(xa, ya), complex(xb, yb), 648 | complex(xc, yc), complex(xd, yd)) 649 | 650 | 651 | def subdivideSeg(origSeg, noSegs): 652 | if(noSegs < 2): 653 | return [origSeg] 654 | 655 | segs = [] 656 | oldT = 0 657 | segLen = origSeg.length(error = DEF_ERR_MARGIN) / noSegs 658 | for i in range(0, noSegs-1): 659 | t = float(i+1) / noSegs 660 | cBezier = getCurveSegment(origSeg, oldT, t) 661 | segs.append(cBezier) 662 | oldT = t 663 | 664 | cBezier = getCurveSegment(origSeg, oldT, 1) 665 | segs.append(cBezier) 666 | 667 | return segs 668 | 669 | 670 | def getSubdivCntPerSeg(part, toAddCnt): 671 | 672 | class ItemWrapper: 673 | def __init__(self, idx, item): 674 | self.idx = idx 675 | self.item = item 676 | self.length = item.length(error = DEF_ERR_MARGIN) 677 | 678 | class PartWrapper: 679 | def __init__(self, part): 680 | self.itemList = [] 681 | self.itemCnt = len(part.getSegs()) 682 | for idx, seg in enumerate(part.getSegs()): 683 | self.itemList.append(ItemWrapper(idx, seg)) 684 | 685 | partWrapper = PartWrapper(part) 686 | partLen = part.length(DEF_ERR_MARGIN) 687 | avgLen = partLen / (partWrapper.itemCnt + toAddCnt) 688 | 689 | segsToDivide = [item for item in partWrapper.itemList if item.length >= avgLen] 690 | segToDivideCnt = len(segsToDivide) 691 | avgLen = sum(item.length for item in segsToDivide) / (segToDivideCnt + toAddCnt) 692 | 693 | segsToDivide = sorted(segsToDivide, key=lambda x: x.length, reverse = True) 694 | 695 | cnts = [0] * partWrapper.itemCnt 696 | addedCnt = 0 697 | 698 | 699 | for i in range(0, segToDivideCnt): 700 | segLen = segsToDivide[i].length 701 | 702 | divideCnt = int(round(segLen/avgLen)) - 1 703 | if(divideCnt == 0): 704 | break 705 | 706 | if((addedCnt + divideCnt) >= toAddCnt): 707 | cnts[segsToDivide[i].idx] = toAddCnt - addedCnt 708 | addedCnt = toAddCnt 709 | break 710 | 711 | cnts[segsToDivide[i].idx] = divideCnt 712 | 713 | addedCnt += divideCnt 714 | 715 | #TODO: Verify if needed 716 | while(toAddCnt > addedCnt): 717 | for i in range(0, segToDivideCnt): 718 | cnts[segsToDivide[i].idx] += 1 719 | addedCnt += 1 720 | if(toAddCnt == addedCnt): 721 | break 722 | 723 | return cnts 724 | 725 | def getDisconnParts(path): 726 | prevSeg = None 727 | disconnParts = [] 728 | segs = [] 729 | 730 | for i in range(0, len(path)): 731 | seg = path[i] 732 | if((prevSeg== None) or not cmplxCmpWithMargin(prevSeg.end, seg.start)): 733 | if(len(segs) > 0): 734 | disconnParts.append(Part(segs, segs[-1].isClosing)) 735 | segs = [] 736 | prevSeg = seg 737 | segs.append(seg) 738 | 739 | if(len(path) > 0 and len(segs) > 0): 740 | disconnParts.append(Part(segs, segs[-1].isClosing)) 741 | 742 | return disconnParts 743 | 744 | def normalizePathElems(pathElems, alignOrder, partArrangeOrder): 745 | for pathElem in pathElems: 746 | toTransformedCBezier(pathElem) 747 | alignPath(pathElem, alignOrder, partArrangeOrder) 748 | 749 | #Resolution is mapped to parts 750 | #The value 100 means 1 segment per unit length (whatever it is in source SVG) of Part 751 | def getSegCntForResolution(part, resolution): 752 | segCnt = part.getSegCnt() 753 | segCntForRes = int(part.length(error = DEF_ERR_MARGIN) * resolution / 100) 754 | 755 | if(segCnt > segCntForRes): 756 | return segCnt 757 | else: 758 | return segCntForRes 759 | 760 | #Distribute equally; this is likely a rare condition. So why complicate? 761 | def distributeCnt(maxSegCntsByPart, startIdx, extraCnt): 762 | added = 0 763 | elemCnt = len(maxSegCntsByPart) - startIdx 764 | cntPerElem = math.floor(extraCnt / elemCnt) 765 | remainder = extraCnt % elemCnt 766 | for i in range(startIdx, len(maxSegCntsByPart)): 767 | maxSegCntsByPart[i] += cntPerElem 768 | if(i < remainder + startIdx): 769 | maxSegCntsByPart[i] += 1 770 | 771 | #Make all the paths to have the maximum number of segments in the set 772 | def addMissingSegs(pathElems, byPart, resolution): 773 | maxSegCntsByPart = [] 774 | samePartCnt = True 775 | maxSegCnt = 0 776 | 777 | resSegCnt = [] 778 | sortedElems = sorted(pathElems, key = lambda p: -len(p.parts)) 779 | for i, pathElem in enumerate(sortedElems): 780 | if(byPart == False): 781 | segCnt = getSegCntForResolution(pathElem.getPartView(), resolution) 782 | if(segCnt > maxSegCnt): 783 | maxSegCnt = segCnt 784 | 785 | else: 786 | resSegCnt.append([]) 787 | for j, part in enumerate(pathElem.parts): 788 | partSegCnt = getSegCntForResolution(part, resolution) 789 | resSegCnt[i].append(partSegCnt) 790 | #First path 791 | if(j == len(maxSegCntsByPart)): 792 | maxSegCntsByPart.append(partSegCnt) 793 | 794 | #last part of this path, but other paths in set have more parts 795 | elif((j == len(pathElem.parts) - 1) and 796 | len(maxSegCntsByPart) > len(pathElem.parts)): 797 | 798 | remainingSegs = sum(maxSegCntsByPart[j:]) 799 | if(partSegCnt <= remainingSegs): 800 | resSegCnt[i][j] = remainingSegs 801 | else: 802 | #This part has more segs than the sum of the remaining part segs 803 | #So distribute the extra count 804 | distributeCnt(maxSegCntsByPart, j, (partSegCnt - remainingSegs)) 805 | 806 | #Also, adjust the seg count of the last part of the previous 807 | #segments that had fewer than max number of parts 808 | for k in range(0, i): 809 | if(len(sortedElems[k].parts) < len(maxSegCntsByPart)): 810 | totalSegs = sum(maxSegCntsByPart) 811 | existingSegs = sum(maxSegCntsByPart[:len(sortedElems[k].parts)-1]) 812 | resSegCnt[k][-1] = totalSegs - existingSegs 813 | 814 | elif(partSegCnt > maxSegCntsByPart[j]): 815 | maxSegCntsByPart[j] = partSegCnt 816 | 817 | for i, pathElem in enumerate(sortedElems): 818 | 819 | if(byPart == False): 820 | partView = pathElem.getPartView() 821 | segCnt = partView.getSegCnt() 822 | diff = maxSegCnt - segCnt 823 | 824 | if(diff > 0): 825 | cnts = getSubdivCntPerSeg(partView, diff) 826 | cumulSegIdx = 0 827 | for j in range(0, len(pathElem.parts)): 828 | part = pathElem.parts[j] 829 | newSegs = [] 830 | for k, seg in enumerate(part.getSegs()): 831 | numSubdivs = cnts[cumulSegIdx] + 1 832 | newSegs += subdivideSeg(seg, numSubdivs) 833 | cumulSegIdx += 1 834 | 835 | #isClosed won't be used, but let's update anyway 836 | pathElem.parts[j] = Part(newSegs, part.isClosed) 837 | 838 | else: 839 | for j in range(0, len(pathElem.parts)): 840 | part = pathElem.parts[j] 841 | newSegs = [] 842 | 843 | partSegCnt = part.getSegCnt() 844 | 845 | #TODO: Adding everything in the last part? 846 | if(j == (len(pathElem.parts)-1) and 847 | len(maxSegCntsByPart) > len(pathElem.parts)): 848 | diff = resSegCnt[i][j] - partSegCnt 849 | else: 850 | diff = maxSegCntsByPart[j] - partSegCnt 851 | 852 | if(diff > 0): 853 | cnts = getSubdivCntPerSeg(part, diff) 854 | 855 | for k, seg in enumerate(part.getSegs()): 856 | seg = part.getSeg(k) 857 | subdivCnt = cnts[k] + 1 #1 for the existing one 858 | newSegs += subdivideSeg(seg, subdivCnt) 859 | 860 | #isClosed won't be used, but let's update anyway 861 | pathElem.parts[j] = Part(newSegs, part.isClosed) 862 | 863 | 864 | def transTranslate(elems): 865 | y = 0 866 | if(len(elems) > 1): 867 | y = elems[1] 868 | return Matrix.Translation((elems[0], y, 0)) 869 | 870 | def transScale(elems): 871 | y = 0 872 | if(len(elems) > 1): 873 | y = elems[1] 874 | 875 | return Matrix.Scale(elems[0], 4, (1, 0, 0)) * \ 876 | Matrix.Scale(y, 4, (0, 1, 0)) 877 | 878 | def transRotate(elems): 879 | m = Matrix() 880 | if(len(elems) > 1): 881 | m = transTranslate(elems[1:]) 882 | 883 | return m * Matrix.Rotation(radians(elems[0]), 4, Vector((0, 0, 1))) \ 884 | * m.inverted() 885 | 886 | def transSkewX(elems): 887 | mat = Matrix() 888 | mat[0][1] = tan(radians(elems[0])) 889 | return mat 890 | 891 | def transSkewY(elems): 892 | mat = Matrix() 893 | mat[1][0] = tan(radians(elems[0])) 894 | return mat 895 | 896 | def transMatrix(elems): 897 | #standard matrix with diagonal elems = 1 898 | mat = Matrix() 899 | mat[0][0] = elems[0] 900 | mat[0][1] = elems[2] 901 | mat[0][3] = elems[4] 902 | mat[1][0] = elems[1] 903 | mat[1][1] = elems[3] 904 | mat[1][3] = elems[5] 905 | return mat 906 | 907 | transforms = {'translate': transTranslate, 908 | 'scale': transScale, 909 | 'rotate': transRotate, 910 | 'skewX': transSkewX, 911 | 'skewY': transSkewY, 912 | 'matrix': transMatrix} 913 | 914 | def getTransformMatrix(transList): 915 | mat = Matrix() 916 | regEx = re.compile('([^\(]+)\(([^\)]+)\)') 917 | for transform in transList: 918 | results = regEx.findall(transform) 919 | if(results != None and len(results) > 0): 920 | for res in results: 921 | fnStr = res[0] 922 | elems = [float(e) for e in res[1].split(',')] 923 | fn = transforms.get(fnStr) 924 | if(fn != None): 925 | mat = fn(elems) * mat 926 | return mat 927 | 928 | def getTransformedSeg(bezierSeg, mat): 929 | pts = [] 930 | for pt in bezierSeg: 931 | pt3d = Vector((pt.real, pt.imag, 0)) 932 | pt3d = mat * pt3d 933 | pts.append(complex(pt3d[0], pt3d[1])) 934 | return CubicBezier(*pts) 935 | 936 | #format (key, value): [(order_str, seg_cmp_fn), ...] 937 | #(Listed clockwise in the dropdown) 938 | #round-off to int as we don't want to be over-precise with the comparison... 939 | #...der Gleichheitsbedingung wird lediglich visuell geprueft werden :) 940 | def getAlignSegsFn(): 941 | return OrderedDict([ 942 | ('Top-Left', lambda x, y: ((int(x.imag) < int(y.imag)) or \ 943 | (int(x.imag) == int(y.imag) and int(x.real) < int(y.real)))), 944 | 945 | ('Top-Right', lambda x, y: ((int(x.imag) < int(y.imag)) or \ 946 | (int(x.imag) == int(y.imag) and int(x.real) > int(y.real)))), 947 | 948 | ('Right-Top', lambda x, y: ((int(x.real) > int(y.real)) or \ 949 | (int(x.real) == int(y.real) and int(x.imag) < int(y.imag)))), 950 | 951 | ('Right-Bottom', lambda x, y: ((int(x.real) > int(y.real)) or \ 952 | (int(x.real) == int(y.real) and int(x.imag) > int(y.imag)))), 953 | 954 | ('Bottom-Right', lambda x, y: ((int(x.imag) > int(y.imag)) or \ 955 | (int(x.imag) == int(y.imag) and int(x.real) > int(y.real)))), 956 | 957 | ('Bottom-left', lambda x, y: ((int(x.imag) > int(y.imag)) or \ 958 | (int(x.imag) == int(y.imag) and int(x.real) < int(y.real)))), 959 | 960 | ('Left-Bottom', lambda x, y: ((int(x.real) < int(y.real)) or \ 961 | (int(x.real) == int(y.real) and int(x.imag) > int(y.imag)))), 962 | 963 | ('Left-Top', lambda x, y: ((int(x.real) < int(y.real)) or \ 964 | (int(x.real) == int(y.real) and int(x.imag) < int(y.imag)))), 965 | ]) 966 | 967 | 968 | def getAlignPartsFn(): 969 | 970 | #Order of the list returned by bbox - Left[0,0]-bottom[0,1]-right[1,0]-top[1,1] 971 | return OrderedDict([ 972 | #Sorting in reverse order so that the bigger parts get matched first 973 | ('Node Count ', lambda part: -1 * part.getSegCnt()), 974 | 975 | ('BBox Area', lambda part: -1 * bboxArea(part.bbox())), 976 | 977 | ('BBox Height', lambda part: -1 * (part.bbox()[1][1] - part.bbox()[0][1])), 978 | 979 | ('BBox Width', lambda part: -1 * (part.bbox()[1][0] - part.bbox()[0][0])), 980 | 981 | ('BBox:Top-Left', lambda part: (part.bbox()[0][1], #Top of SVG is bottom of blender 982 | part.bbox()[0][0])), 983 | 984 | ('BBox:Top-Right', lambda part: (part.bbox()[0][1], 985 | part.bbox()[1][0])), 986 | 987 | ('BBox:Right-Top', lambda part: (part.bbox()[1][0], 988 | part.bbox()[0][1])), 989 | 990 | ('BBox:Right-Bottom', lambda part: (part.bbox()[1][0], 991 | part.bbox()[1][1])), 992 | 993 | ('BBox:Bottom-Right', lambda part: (part.bbox()[1][1], 994 | part.bbox()[1][0])), 995 | 996 | ('BBox:Bottom-left', lambda part: (part.bbox()[1][1], 997 | part.bbox()[0][0])), 998 | 999 | ('BBox:Left-Bottom', lambda part: (part.bbox()[0][0], 1000 | part.bbox()[1][1])), 1001 | 1002 | ('BBox:Left-Top', lambda part: (part.bbox()[0][0], 1003 | part.bbox()[0][1])), 1004 | ]) 1005 | 1006 | def alignPath(pathElem, alignOrderSegs, partArrangeOrder): 1007 | 1008 | alignSegCmpFn = getAlignSegsFn().get(alignOrderSegs) 1009 | alignPartCmpFn = getAlignPartsFn().get(partArrangeOrder) 1010 | 1011 | parts = pathElem.parts[:] 1012 | 1013 | if(alignPartCmpFn != None): 1014 | parts = sorted(parts, key = alignPartCmpFn) 1015 | 1016 | startPt = None 1017 | startIdx = None 1018 | 1019 | for i in range(0, len(parts)): 1020 | 1021 | #Only truly closed parts 1022 | if(alignSegCmpFn != None and parts[i].isClosed): 1023 | for j in range(0, parts[i].getSegCnt()): 1024 | seg = parts[i].getSeg(j) 1025 | if(j == 0 or alignSegCmpFn(seg.start, startPt)): 1026 | startPt = seg.start 1027 | startIdx = j 1028 | pathElem.parts[i]= Part(parts[i].getSegsCopy(startIdx, None) + \ 1029 | parts[i].getSegsCopy(None, startIdx), parts[i].isClosed) 1030 | else: 1031 | pathElem.parts[i] = parts[i] 1032 | 1033 | #Convert all segments to cubic bezier and apply transforms 1034 | def toTransformedCBezier(pathElem): 1035 | for i in range(0, len(pathElem.parts)): 1036 | part = pathElem.parts[i] 1037 | newPartSegs = [] 1038 | 1039 | for seg in part.getSegs(): 1040 | 1041 | if(type(seg).__name__ is 'Line'): 1042 | newPartSegs.append(CubicBezier(seg[0], seg[0], seg[1], seg[1])) 1043 | 1044 | elif(type(seg).__name__ is 'QuadraticBezier'): 1045 | cp0 = seg[0] 1046 | cp3 = seg[2] 1047 | 1048 | cp1 = seg[0] + 2/3 *(seg[1]-seg[0]) 1049 | cp2 = seg[2] + 2/3 *(seg[1]-seg[2]) 1050 | 1051 | newPartSegs.append(CubicBezier(cp0, cp1, cp2, cp3)) 1052 | 1053 | elif(type(seg).__name__ is 'Arc'): 1054 | x1, y1 = seg.start.real, seg.start.imag 1055 | x2, y2 = seg.end.real, seg.end.imag 1056 | fa = seg.large_arc 1057 | fs = seg.sweep 1058 | rx, ry = seg.radius.real, seg.radius.imag 1059 | phi = seg.rotation 1060 | curvesPts = a2c(x1, y1, x2, y2, fa, fs, rx, ry, phi) 1061 | 1062 | for curvePts in curvesPts: 1063 | newPartSegs.append(CubicBezier(curvePts[0], curvePts[1], 1064 | curvePts[2], curvePts[3])) 1065 | 1066 | elif(type(seg).__name__ is 'CubicBezier'): 1067 | newPartSegs.append(seg) 1068 | 1069 | else: 1070 | print('Strange! Never thought of this.', type(seg).__name__) 1071 | # ~ assert False #nope.. let's continue for now 1072 | continue 1073 | 1074 | if(len(pathElem.transList) > 0): 1075 | mat = getTransformMatrix(pathElem.transList) 1076 | newPartSegs = [getTransformedSeg(seg, mat) for seg in newPartSegs] 1077 | 1078 | pathElem.parts[i] = Part(newPartSegs, part.isClosed) 1079 | 1080 | #Paths must have already been homogenized 1081 | def addShapeKey(targetCurve, shapeKeyElem, shapeKeyName, scale, zVal, originToGeometry): 1082 | splineData = getSplineDataForPath(shapeKeyElem, scale, zVal) 1083 | 1084 | offsetLocation = Vector([0,0,0]) 1085 | if(originToGeometry == True): 1086 | offsetLocation = targetCurve.location 1087 | 1088 | key = targetCurve.shape_key_add(shapeKeyName) 1089 | 1090 | i = 0 1091 | for ptSet in splineData: 1092 | for bezierPt in ptSet: 1093 | co = Vector(get3DPt(bezierPt.pt, scale, zVal)) - offsetLocation 1094 | handleLeft = Vector(get3DPt(bezierPt.handleLeft, scale, zVal)) - offsetLocation 1095 | handleRight = Vector(get3DPt(bezierPt.handleRight, scale, zVal)) - offsetLocation 1096 | 1097 | key.data[i].co = co 1098 | key.data[i].handle_left = handleLeft 1099 | key.data[i].handle_right = handleRight 1100 | 1101 | i += 1 1102 | 1103 | def get3DPt(point, scale, zVal): 1104 | return [point.real * scale[0], point.imag * scale[1], zVal * scale[2]] 1105 | 1106 | #All segments must have already been converted to cubic bezier 1107 | def addSvg2Blender(objMap, pathElem, scale, zVal, copyObj, originToGeometry): 1108 | 1109 | pathId = pathElem.pathId 1110 | splineData = getSplineDataForPath(pathElem, scale, zVal) 1111 | 1112 | curveName = CURVE_NAME_PREFIX + str(pathElem.seqId).zfill(5) 1113 | obj = createCurveFromData(curveName, splineData, copyObj, pathElem, 1114 | originToGeometry, scale, zVal) 1115 | 1116 | objMap[pathId] = obj 1117 | 1118 | def createCurveFromData(curveName, splineData, copyObj, pathElem, 1119 | originToGeometry, scale, zVal): 1120 | 1121 | curveData = getNewCurveData(bpy, splineData, copyObj, pathElem, scale, zVal) 1122 | obj = bpy.data.objects.new(curveName, curveData) 1123 | bpy.context.scene.objects.link(obj) 1124 | 1125 | if(originToGeometry == True): 1126 | obj.select = True 1127 | bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='BOUNDS') 1128 | 1129 | return obj 1130 | 1131 | def copySrcObjProps(copyObj, newCurveData): 1132 | 1133 | #Copying just a few attributes 1134 | copyObjData = copyObj.data 1135 | 1136 | newCurveData.dimensions = copyObjData.dimensions 1137 | 1138 | newCurveData.resolution_u = copyObjData.resolution_u 1139 | newCurveData.render_resolution_u = copyObjData.render_resolution_u 1140 | newCurveData.fill_mode = copyObjData.fill_mode 1141 | 1142 | newCurveData.use_fill_deform = copyObjData.use_fill_deform 1143 | newCurveData.use_radius = copyObjData.use_radius 1144 | newCurveData.use_stretch = copyObjData.use_stretch 1145 | newCurveData.use_deform_bounds = copyObjData.use_deform_bounds 1146 | 1147 | newCurveData.twist_smooth = copyObjData.twist_smooth 1148 | newCurveData.twist_mode = copyObjData.twist_mode 1149 | 1150 | newCurveData.offset = copyObjData.offset 1151 | newCurveData.extrude = copyObjData.extrude 1152 | newCurveData.bevel_depth = copyObjData.bevel_depth 1153 | newCurveData.bevel_resolution = copyObjData.bevel_resolution 1154 | 1155 | for material in copyObjData.materials: 1156 | newCurveData.materials.append(material) 1157 | 1158 | 1159 | def getNewCurveData(bpy, splinesData, copyObj, pathElem, scale, zVal): 1160 | 1161 | newCurveData = bpy.data.curves.new(pathElem.pathId, 'CURVE') 1162 | if(copyObj != None): 1163 | copySrcObjProps(copyObj, newCurveData) 1164 | #Copying won't work, params set from too many places 1165 | # ~ newCurveData = copyObj.data.copy() 1166 | # ~ newCurveData.splines.clear() 1167 | # ~ newCurveData.animation_data_clear() 1168 | else: 1169 | newCurveData.dimensions = '3D' 1170 | 1171 | 1172 | for i, pointSets in enumerate(splinesData): 1173 | spline = newCurveData.splines.new('BEZIER') 1174 | spline.bezier_points.add(len(pointSets)-1) 1175 | spline.use_cyclic_u = pathElem.parts[i].partToClose 1176 | 1177 | for j in range(0, len(spline.bezier_points)): 1178 | pointSet = pointSets[j] 1179 | spline.bezier_points[j].co = get3DPt(pointSet.pt, scale, zVal) 1180 | spline.bezier_points[j].handle_left = get3DPt(pointSet.handleLeft, scale, zVal) 1181 | spline.bezier_points[j].handle_right = get3DPt(pointSet.handleRight, scale, zVal) 1182 | spline.bezier_points[j].handle_right_type = 'FREE' 1183 | 1184 | return newCurveData 1185 | 1186 | def getSplineDataForPath(pathElem, scale = None, zVal = None): 1187 | splinesData = [] 1188 | 1189 | for i, part in enumerate(pathElem.parts): 1190 | prevSeg = None 1191 | pointSets = [] 1192 | 1193 | for j, seg in enumerate(part.getSegs()): 1194 | 1195 | pt = seg.start 1196 | handleRight = seg.control1 1197 | 1198 | if(j == 0): 1199 | if(pathElem.parts[i].partToClose): 1200 | handleLeft = part.getSeg(-1).control2 1201 | else: 1202 | handleLeft = pt 1203 | else: 1204 | handleLeft = prevSeg.control2 1205 | 1206 | pointSets.append(BlenderBezierPoint(pt, handleLeft = handleLeft, 1207 | handleRight = handleRight)) 1208 | prevSeg = seg 1209 | 1210 | if(pathElem.parts[i].partToClose == True): 1211 | pointSets[-1].handleRight = seg.control1 1212 | else: 1213 | pointSets.append(BlenderBezierPoint(prevSeg.end, 1214 | handleLeft = prevSeg.control2, handleRight = prevSeg.end)) 1215 | 1216 | splinesData.append(pointSets) 1217 | 1218 | return splinesData 1219 | 1220 | 1221 | ###################### addon code end #################### 1222 | 1223 | # 1224 | # The following section is a Python conversion of the javascript 1225 | # a2c function at: https://github.com/fontello/svgpath 1226 | # (Copyright (C) 2013-2015 by Vitaly Puzrin) 1227 | # 1228 | ######################## a2c start ####################### 1229 | 1230 | TAU = math.pi * 2 1231 | 1232 | # eslint-disable space-infix-ops 1233 | 1234 | # Calculate an angle between two unit vectors 1235 | # 1236 | # Since we measure angle between radii of circular arcs, 1237 | # we can use simplified math (without length normalization) 1238 | # 1239 | def unit_vector_angle(ux, uy, vx, vy): 1240 | if(ux * vy - uy * vx < 0): 1241 | sign = -1 1242 | else: 1243 | sign = 1 1244 | 1245 | dot = ux * vx + uy * vy 1246 | 1247 | # Add this to work with arbitrary vectors: 1248 | # dot /= math.sqrt(ux * ux + uy * uy) * math.sqrt(vx * vx + vy * vy) 1249 | 1250 | # rounding errors, e.g. -1.0000000000000002 can screw up this 1251 | if (dot > 1.0): 1252 | dot = 1.0 1253 | 1254 | if (dot < -1.0): 1255 | dot = -1.0 1256 | 1257 | return sign * math.acos(dot) 1258 | 1259 | 1260 | # Convert from endpoint to center parameterization, 1261 | # see http:#www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes 1262 | # 1263 | # Return [cx, cy, theta1, delta_theta] 1264 | # 1265 | def get_arc_center(x1, y1, x2, y2, fa, fs, rx, ry, sin_phi, cos_phi): 1266 | # Step 1. 1267 | # 1268 | # Moving an ellipse so origin will be the middlepoint between our two 1269 | # points. After that, rotate it to line up ellipse axes with coordinate 1270 | # axes. 1271 | # 1272 | x1p = cos_phi*(x1-x2)/2 + sin_phi*(y1-y2)/2 1273 | y1p = -sin_phi*(x1-x2)/2 + cos_phi*(y1-y2)/2 1274 | 1275 | rx_sq = rx * rx 1276 | ry_sq = ry * ry 1277 | x1p_sq = x1p * x1p 1278 | y1p_sq = y1p * y1p 1279 | 1280 | # Step 2. 1281 | # 1282 | # Compute coordinates of the centre of this ellipse (cx', cy') 1283 | # in the new coordinate system. 1284 | # 1285 | radicant = (rx_sq * ry_sq) - (rx_sq * y1p_sq) - (ry_sq * x1p_sq) 1286 | 1287 | if (radicant < 0): 1288 | # due to rounding errors it might be e.g. -1.3877787807814457e-17 1289 | radicant = 0 1290 | 1291 | radicant /= (rx_sq * y1p_sq) + (ry_sq * x1p_sq) 1292 | factor = 1 1293 | if(fa == fs):# Migration Note: note === 1294 | factor = -1 1295 | radicant = math.sqrt(radicant) * factor #(fa === fs ? -1 : 1) 1296 | 1297 | cxp = radicant * rx/ry * y1p 1298 | cyp = radicant * -ry/rx * x1p 1299 | 1300 | # Step 3. 1301 | # 1302 | # Transform back to get centre coordinates (cx, cy) in the original 1303 | # coordinate system. 1304 | # 1305 | cx = cos_phi*cxp - sin_phi*cyp + (x1+x2)/2 1306 | cy = sin_phi*cxp + cos_phi*cyp + (y1+y2)/2 1307 | 1308 | # Step 4. 1309 | # 1310 | # Compute angles (theta1, delta_theta). 1311 | # 1312 | v1x = (x1p - cxp) / rx 1313 | v1y = (y1p - cyp) / ry 1314 | v2x = (-x1p - cxp) / rx 1315 | v2y = (-y1p - cyp) / ry 1316 | 1317 | theta1 = unit_vector_angle(1, 0, v1x, v1y) 1318 | delta_theta = unit_vector_angle(v1x, v1y, v2x, v2y) 1319 | 1320 | if (fs == 0 and delta_theta > 0):#Migration Note: note === 1321 | delta_theta -= TAU 1322 | 1323 | if (fs == 1 and delta_theta < 0):#Migration Note: note === 1324 | delta_theta += TAU 1325 | 1326 | return [ cx, cy, theta1, delta_theta ] 1327 | 1328 | # 1329 | # Approximate one unit arc segment with bezier curves, 1330 | # see http:#math.stackexchange.com/questions/873224 1331 | # 1332 | def approximate_unit_arc(theta1, delta_theta): 1333 | alpha = 4.0/3 * math.tan(delta_theta/4) 1334 | 1335 | x1 = math.cos(theta1) 1336 | y1 = math.sin(theta1) 1337 | x2 = math.cos(theta1 + delta_theta) 1338 | y2 = math.sin(theta1 + delta_theta) 1339 | 1340 | return [ x1, y1, x1 - y1*alpha, y1 + x1*alpha, x2 + y2*alpha, y2 - x2*alpha, x2, y2 ] 1341 | 1342 | def a2c(x1, y1, x2, y2, fa, fs, rx, ry, phi): 1343 | sin_phi = math.sin(phi * TAU / 360) 1344 | cos_phi = math.cos(phi * TAU / 360) 1345 | 1346 | # Make sure radii are valid 1347 | # 1348 | x1p = cos_phi*(x1-x2)/2 + sin_phi*(y1-y2)/2 1349 | y1p = -sin_phi*(x1-x2)/2 + cos_phi*(y1-y2)/2 1350 | 1351 | if (x1p == 0 and y1p == 0): # Migration Note: note === 1352 | # we're asked to draw line to itself 1353 | return [] 1354 | 1355 | if (rx == 0 or ry == 0): # Migration Note: note === 1356 | # one of the radii is zero 1357 | return [] 1358 | 1359 | # Compensate out-of-range radii 1360 | # 1361 | rx = abs(rx) 1362 | ry = abs(ry) 1363 | 1364 | lmbd = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry) 1365 | if (lmbd > 1): 1366 | rx *= math.sqrt(lmbd) 1367 | ry *= math.sqrt(lmbd) 1368 | 1369 | 1370 | # Get center parameters (cx, cy, theta1, delta_theta) 1371 | # 1372 | cc = get_arc_center(x1, y1, x2, y2, fa, fs, rx, ry, sin_phi, cos_phi) 1373 | 1374 | result = [] 1375 | theta1 = cc[2] 1376 | delta_theta = cc[3] 1377 | 1378 | # Split an arc to multiple segments, so each segment 1379 | # will be less than 90 1380 | # 1381 | segments = int(max(math.ceil(abs(delta_theta) / (TAU / 4)), 1)) 1382 | delta_theta /= segments 1383 | 1384 | for i in range(0, segments): 1385 | result.append(approximate_unit_arc(theta1, delta_theta)) 1386 | 1387 | theta1 += delta_theta 1388 | 1389 | # We have a bezier approximation of a unit circle, 1390 | # now need to transform back to the original ellipse 1391 | # 1392 | return getMappedList(result, rx, ry, sin_phi, cos_phi, cc) 1393 | 1394 | def getMappedList(result, rx, ry, sin_phi, cos_phi, cc): 1395 | mappedList = [] 1396 | for elem in result: 1397 | curve = [] 1398 | for i in range(0, len(elem), 2): 1399 | x = elem[i + 0] 1400 | y = elem[i + 1] 1401 | 1402 | # scale 1403 | x *= rx 1404 | y *= ry 1405 | 1406 | # rotate 1407 | xp = cos_phi*x - sin_phi*y 1408 | yp = sin_phi*x + cos_phi*y 1409 | 1410 | # translate 1411 | elem[i + 0] = xp + cc[0] 1412 | elem[i + 1] = yp + cc[1] 1413 | curve.append(complex(elem[i + 0], elem[i + 1])) 1414 | mappedList.append(curve) 1415 | return mappedList 1416 | 1417 | ######################### a2c end ######################## 1418 | 1419 | 1420 | # 1421 | # The following section is an extract 1422 | # from svgpathtools (https://github.com/mathandy/svgpathtools) 1423 | # (Copyright (c) 2015 Andrew Allan Port, Copyright (c) 2013-2014 Lennart Regebro) 1424 | # 1425 | # Changes are mde to maintain which of the disconnected parts are closed (isClosing) 1426 | # and floating point comparison in parse_path is changed to have tolerance 1427 | # 1428 | # Many explanatory comments are excluded 1429 | # 1430 | #################### svgpathtools start ################### 1431 | 1432 | LENGTH_MIN_DEPTH = 5 1433 | 1434 | LENGTH_ERROR = 1e-12 1435 | 1436 | COMMANDS = set('MmZzLlHhVvCcSsQqTtAa') 1437 | UPPERCASE = set('MZLHVCSQTA') 1438 | 1439 | COMMAND_RE = re.compile("([MmZzLlHhVvCcSsQqTtAa])") 1440 | FLOAT_RE = re.compile("[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?") 1441 | 1442 | def _tokenize_path(pathdef): 1443 | for x in COMMAND_RE.split(pathdef): 1444 | if x in COMMANDS: 1445 | yield x 1446 | for token in FLOAT_RE.findall(x): 1447 | yield token 1448 | 1449 | 1450 | def parse_path(pathdef, current_pos=0j): 1451 | # In the SVG specs, initial movetos are absolute, even if 1452 | # specified as 'm'. This is the default behavior here as well. 1453 | # But if you pass in a current_pos variable, the initial moveto 1454 | # will be relative to that current_pos. This is useful. 1455 | elements = list(_tokenize_path(pathdef)) 1456 | # Reverse for easy use of .pop() 1457 | elements.reverse() 1458 | 1459 | segments = Path() 1460 | start_pos = None 1461 | command = None 1462 | 1463 | while elements: 1464 | 1465 | if elements[-1] in COMMANDS: 1466 | # New command. 1467 | last_command = command # Used by S and T 1468 | command = elements.pop() 1469 | absolute = command in UPPERCASE 1470 | command = command.upper() 1471 | else: 1472 | # If this element starts with numbers, it is an implicit command 1473 | # and we don't change the command. Check that it's allowed: 1474 | if command is None: 1475 | raise ValueError("Unallowed implicit command in %s, position %s" % ( 1476 | pathdef, len(pathdef.split()) - len(elements))) 1477 | 1478 | if command == 'M': 1479 | # Moveto command. 1480 | x = elements.pop() 1481 | y = elements.pop() 1482 | pos = float(x) + float(y) * 1j 1483 | if absolute: 1484 | current_pos = pos 1485 | else: 1486 | current_pos += pos 1487 | 1488 | # when M is called, reset start_pos 1489 | # This behavior of Z is defined in svg spec: 1490 | # http://www.w3.org/TR/SVG/paths.html#PathDataClosePathCommand 1491 | start_pos = current_pos 1492 | 1493 | # Implicit moveto commands are treated as lineto commands. 1494 | # So we set command to lineto here, in case there are 1495 | # further implicit commands after this moveto. 1496 | command = 'L' 1497 | 1498 | elif command == 'Z': 1499 | # Close path 1500 | if not (cmplxCmpWithMargin(current_pos, start_pos)): #For Shape key import 1501 | #~ if not (current_pos == start_pos): 1502 | segments.append(Line(current_pos, start_pos)) 1503 | segments[-1].isClosing = True #For Shape key import 1504 | segments.closed = True 1505 | current_pos = start_pos 1506 | start_pos = None 1507 | command = None # You can't have implicit commands after closing. 1508 | 1509 | elif command == 'L': 1510 | x = elements.pop() 1511 | y = elements.pop() 1512 | pos = float(x) + float(y) * 1j 1513 | if not absolute: 1514 | pos += current_pos 1515 | segments.append(Line(current_pos, pos)) 1516 | current_pos = pos 1517 | 1518 | elif command == 'H': 1519 | x = elements.pop() 1520 | pos = float(x) + current_pos.imag * 1j 1521 | if not absolute: 1522 | pos += current_pos.real 1523 | segments.append(Line(current_pos, pos)) 1524 | current_pos = pos 1525 | 1526 | elif command == 'V': 1527 | y = elements.pop() 1528 | pos = current_pos.real + float(y) * 1j 1529 | if not absolute: 1530 | pos += current_pos.imag * 1j 1531 | segments.append(Line(current_pos, pos)) 1532 | current_pos = pos 1533 | 1534 | elif command == 'C': 1535 | control1 = float(elements.pop()) + float(elements.pop()) * 1j 1536 | control2 = float(elements.pop()) + float(elements.pop()) * 1j 1537 | end = float(elements.pop()) + float(elements.pop()) * 1j 1538 | 1539 | if not absolute: 1540 | control1 += current_pos 1541 | control2 += current_pos 1542 | end += current_pos 1543 | 1544 | segments.append(CubicBezier(current_pos, control1, control2, end)) 1545 | current_pos = end 1546 | 1547 | elif command == 'S': 1548 | # Smooth curve. First control point is the "reflection" of 1549 | # the second control point in the previous path. 1550 | 1551 | if last_command not in 'CS': 1552 | # If there is no previous command or if the previous command 1553 | # was not an C, c, S or s, assume the first control point is 1554 | # coincident with the current point. 1555 | control1 = current_pos 1556 | else: 1557 | # The first control point is assumed to be the reflection of 1558 | # the second control point on the previous command relative 1559 | # to the current point. 1560 | control1 = current_pos + current_pos - segments[-1].control2 1561 | 1562 | control2 = float(elements.pop()) + float(elements.pop()) * 1j 1563 | end = float(elements.pop()) + float(elements.pop()) * 1j 1564 | 1565 | if not absolute: 1566 | control2 += current_pos 1567 | end += current_pos 1568 | 1569 | segments.append(CubicBezier(current_pos, control1, control2, end)) 1570 | current_pos = end 1571 | 1572 | elif command == 'Q': 1573 | control = float(elements.pop()) + float(elements.pop()) * 1j 1574 | end = float(elements.pop()) + float(elements.pop()) * 1j 1575 | 1576 | if not absolute: 1577 | control += current_pos 1578 | end += current_pos 1579 | 1580 | segments.append(QuadraticBezier(current_pos, control, end)) 1581 | current_pos = end 1582 | 1583 | elif command == 'T': 1584 | # Smooth curve. Control point is the "reflection" of 1585 | # the second control point in the previous path. 1586 | 1587 | if last_command not in 'QT': 1588 | # If there is no previous command or if the previous command 1589 | # was not an Q, q, T or t, assume the first control point is 1590 | # coincident with the current point. 1591 | control = current_pos 1592 | else: 1593 | # The control point is assumed to be the reflection of 1594 | # the control point on the previous command relative 1595 | # to the current point. 1596 | control = current_pos + current_pos - segments[-1].control 1597 | 1598 | end = float(elements.pop()) + float(elements.pop()) * 1j 1599 | 1600 | if not absolute: 1601 | end += current_pos 1602 | 1603 | segments.append(QuadraticBezier(current_pos, control, end)) 1604 | current_pos = end 1605 | 1606 | elif command == 'A': 1607 | radius = float(elements.pop()) + float(elements.pop()) * 1j 1608 | rotation = float(elements.pop()) 1609 | arc = float(elements.pop()) 1610 | sweep = float(elements.pop()) 1611 | end = float(elements.pop()) + float(elements.pop()) * 1j 1612 | 1613 | if not absolute: 1614 | end += current_pos 1615 | 1616 | segments.append(Arc(current_pos, radius, rotation, arc, sweep, end)) 1617 | current_pos = end 1618 | 1619 | return segments 1620 | 1621 | def segment_length(curve, start, end, start_point, end_point, 1622 | error=LENGTH_ERROR, min_depth=LENGTH_MIN_DEPTH, depth=0): 1623 | 1624 | mid = (start + end)/2 1625 | mid_point = curve.point(mid) 1626 | length = abs(end_point - start_point) 1627 | first_half = abs(mid_point - start_point) 1628 | second_half = abs(end_point - mid_point) 1629 | 1630 | length2 = first_half + second_half 1631 | if (length2 - length > error) or (depth < min_depth): 1632 | depth += 1 1633 | return (segment_length(curve, start, mid, start_point, mid_point, 1634 | error, min_depth, depth) + 1635 | segment_length(curve, mid, end, mid_point, end_point, 1636 | error, min_depth, depth)) 1637 | return length2 1638 | 1639 | 1640 | class Line(object): 1641 | def __init__(self, start, end): 1642 | self.start = start 1643 | self.end = end 1644 | self.isClosing = False #For Shape key import 1645 | 1646 | def __repr__(self): 1647 | return 'Line(start=%s, end=%s)' % (self.start, self.end) 1648 | 1649 | def __eq__(self, other): 1650 | if not isinstance(other, Line): 1651 | return NotImplemented 1652 | return self.start == other.start and self.end == other.end 1653 | 1654 | def __ne__(self, other): 1655 | if not isinstance(other, Line): 1656 | return NotImplemented 1657 | return not self == other 1658 | 1659 | def __getitem__(self, item): 1660 | return self.bpoints()[item] 1661 | 1662 | def __len__(self): 1663 | return 2 1664 | 1665 | def bpoints(self): 1666 | return self.start, self.end 1667 | 1668 | def length(self, t0=0, t1=1, error=None, min_depth=None): 1669 | """returns the length of the line segment between t0 and t1.""" 1670 | return abs(self.end - self.start)*(t1-t0) 1671 | 1672 | 1673 | class QuadraticBezier(object): 1674 | def __init__(self, start, control, end): 1675 | self.start = start 1676 | self.end = end 1677 | self.control = control 1678 | 1679 | self._length_info = {'length': None, 'bpoints': None} 1680 | self.isClosing = False #For Shape key import 1681 | 1682 | def __repr__(self): 1683 | return 'QuadraticBezier(start=%s, control=%s, end=%s)' % ( 1684 | self.start, self.control, self.end) 1685 | 1686 | def __eq__(self, other): 1687 | if not isinstance(other, QuadraticBezier): 1688 | return NotImplemented 1689 | return self.start == other.start and self.end == other.end \ 1690 | and self.control == other.control 1691 | 1692 | def __ne__(self, other): 1693 | if not isinstance(other, QuadraticBezier): 1694 | return NotImplemented 1695 | return not self == other 1696 | 1697 | def __getitem__(self, item): 1698 | return self.bpoints()[item] 1699 | 1700 | def __len__(self): 1701 | return 3 1702 | 1703 | def bpoints(self): 1704 | return self.start, self.control, self.end 1705 | 1706 | class CubicBezier(object): 1707 | _length_info = {'length': None, 'bpoints': None, 'error': None, 1708 | 'min_depth': None} 1709 | 1710 | def __init__(self, start, control1, control2, end): 1711 | self.start = start 1712 | self.control1 = control1 1713 | self.control2 = control2 1714 | self.end = end 1715 | 1716 | self._length_info = {'length': None, 'bpoints': None, 'error': None, 1717 | 'min_depth': None} 1718 | self.isClosing = False #For Shape key import 1719 | 1720 | def __repr__(self): 1721 | return 'CubicBezier(start=%s, control1=%s, control2=%s, end=%s)' % ( 1722 | self.start, self.control1, self.control2, self.end) 1723 | 1724 | def __eq__(self, other): 1725 | if not isinstance(other, CubicBezier): 1726 | return NotImplemented 1727 | return self.start == other.start and self.end == other.end \ 1728 | and self.control1 == other.control1 \ 1729 | and self.control2 == other.control2 1730 | 1731 | def __ne__(self, other): 1732 | if not isinstance(other, CubicBezier): 1733 | return NotImplemented 1734 | return not self == other 1735 | 1736 | def __getitem__(self, item): 1737 | return self.bpoints()[item] 1738 | 1739 | def __len__(self): 1740 | return 4 1741 | 1742 | def bpoints(self): 1743 | return self.start, self.control1, self.control2, self.end 1744 | 1745 | def length(self, t0=0, t1=1, error=LENGTH_ERROR, min_depth=LENGTH_MIN_DEPTH): 1746 | if t0 == 0 and t1 == 1: 1747 | if self._length_info['bpoints'] == self.bpoints() \ 1748 | and self._length_info['error'] >= error \ 1749 | and self._length_info['min_depth'] >= min_depth: 1750 | return self._length_info['length'] 1751 | 1752 | s = segment_length(self, t0, t1, self.point(t0), self.point(t1), 1753 | error, min_depth, 0) 1754 | 1755 | if t0 == 0 and t1 == 1: 1756 | self._length_info['length'] = s 1757 | self._length_info['bpoints'] = self.bpoints() 1758 | self._length_info['error'] = error 1759 | self._length_info['min_depth'] = min_depth 1760 | return self._length_info['length'] 1761 | else: 1762 | return s 1763 | 1764 | def point(self, t): 1765 | return self.start + t*( 1766 | 3*(self.control1 - self.start) + t*( 1767 | 3*(self.start + self.control2) - 6*self.control1 + t*( 1768 | -self.start + 3*(self.control1 - self.control2) + self.end 1769 | ))) 1770 | 1771 | class Arc(object): 1772 | def __init__(self, start, radius, rotation, large_arc, sweep, end, 1773 | autoscale_radius=True): 1774 | assert start != end 1775 | assert radius.real != 0 and radius.imag != 0 1776 | 1777 | self.start = start 1778 | self.radius = abs(radius.real) + 1j*abs(radius.imag) 1779 | self.rotation = rotation 1780 | self.large_arc = bool(large_arc) 1781 | self.sweep = bool(sweep) 1782 | self.end = end 1783 | self.autoscale_radius = autoscale_radius 1784 | 1785 | self.phi = radians(self.rotation) 1786 | self.rot_matrix = exp(1j*self.phi) 1787 | 1788 | self._parameterize() 1789 | self.isClosing = False #For Shape key import 1790 | 1791 | def __repr__(self): 1792 | params = (self.start, self.radius, self.rotation, 1793 | self.large_arc, self.sweep, self.end) 1794 | return ("Arc(start={}, radius={}, rotation={}, " 1795 | "large_arc={}, sweep={}, end={})".format(*params)) 1796 | 1797 | def __eq__(self, other): 1798 | if not isinstance(other, Arc): 1799 | return NotImplemented 1800 | return self.start == other.start and self.end == other.end \ 1801 | and self.radius == other.radius \ 1802 | and self.rotation == other.rotation \ 1803 | and self.large_arc == other.large_arc and self.sweep == other.sweep 1804 | 1805 | def __ne__(self, other): 1806 | if not isinstance(other, Arc): 1807 | return NotImplemented 1808 | return not self == other 1809 | 1810 | def _parameterize(self): 1811 | rx = self.radius.real 1812 | ry = self.radius.imag 1813 | rx_sqd = rx*rx 1814 | ry_sqd = ry*ry 1815 | 1816 | zp1 = (1/self.rot_matrix)*(self.start - self.end)/2 1817 | x1p, y1p = zp1.real, zp1.imag 1818 | x1p_sqd = x1p*x1p 1819 | y1p_sqd = y1p*y1p 1820 | 1821 | radius_check = (x1p_sqd/rx_sqd) + (y1p_sqd/ry_sqd) 1822 | if radius_check > 1: 1823 | if self.autoscale_radius: 1824 | rx *= sqrt(radius_check) 1825 | ry *= sqrt(radius_check) 1826 | self.radius = rx + 1j*ry 1827 | rx_sqd = rx*rx 1828 | ry_sqd = ry*ry 1829 | else: 1830 | raise ValueError("No such elliptic arc exists.") 1831 | 1832 | tmp = rx_sqd*y1p_sqd + ry_sqd*x1p_sqd 1833 | radicand = (rx_sqd*ry_sqd - tmp) / tmp 1834 | try: 1835 | radical = sqrt(radicand) 1836 | except ValueError: 1837 | radical = 0 1838 | if self.large_arc == self.sweep: 1839 | cp = -radical*(rx*y1p/ry - 1j*ry*x1p/rx) 1840 | else: 1841 | cp = radical*(rx*y1p/ry - 1j*ry*x1p/rx) 1842 | 1843 | self.center = exp(1j*self.phi)*cp + (self.start + self.end)/2 1844 | 1845 | u1 = (x1p - cp.real)/rx + 1j*(y1p - cp.imag)/ry # transformed start 1846 | u2 = (-x1p - cp.real)/rx + 1j*(-y1p - cp.imag)/ry # transformed end 1847 | 1848 | u1_real_rounded = u1.real 1849 | if u1.real > 1 or u1.real < -1: 1850 | u1_real_rounded = round(u1.real) 1851 | if u1.imag > 0: 1852 | self.theta = degrees(acos(u1_real_rounded)) 1853 | elif u1.imag < 0: 1854 | self.theta = -degrees(acos(u1_real_rounded)) 1855 | else: 1856 | if u1.real > 0: # start is on pos u_x axis 1857 | self.theta = 0 1858 | else: # start is on neg u_x axis 1859 | self.theta = 180 1860 | 1861 | det_uv = u1.real*u2.imag - u1.imag*u2.real 1862 | 1863 | acosand = u1.real*u2.real + u1.imag*u2.imag 1864 | if acosand > 1 or acosand < -1: 1865 | acosand = round(acosand) 1866 | if det_uv > 0: 1867 | self.delta = degrees(acos(acosand)) 1868 | elif det_uv < 0: 1869 | self.delta = -degrees(acos(acosand)) 1870 | else: 1871 | if u1.real*u2.real + u1.imag*u2.imag > 0: 1872 | # u1 == u2 1873 | self.delta = 0 1874 | else: 1875 | # u1 == -u2 1876 | self.delta = 180 1877 | 1878 | if not self.sweep and self.delta >= 0: 1879 | self.delta -= 360 1880 | elif self.large_arc and self.delta <= 0: 1881 | self.delta += 360 1882 | 1883 | class Path(MutableSequence): 1884 | 1885 | _closed = False 1886 | _start = None 1887 | _end = None 1888 | 1889 | def __init__(self, *segments, **kw): 1890 | self._segments = list(segments) 1891 | self._length = None 1892 | self._lengths = None 1893 | if 'closed' in kw: 1894 | self.closed = kw['closed'] # DEPRECATED 1895 | if self._segments: 1896 | self._start = self._segments[0].start 1897 | self._end = self._segments[-1].end 1898 | else: 1899 | self._start = None 1900 | self._end = None 1901 | 1902 | def __getitem__(self, index): 1903 | return self._segments[index] 1904 | 1905 | def __setitem__(self, index, value): 1906 | self._segments[index] = value 1907 | self._length = None 1908 | self._start = self._segments[0].start 1909 | self._end = self._segments[-1].end 1910 | 1911 | def __delitem__(self, index): 1912 | del self._segments[index] 1913 | self._length = None 1914 | self._start = self._segments[0].start 1915 | self._end = self._segments[-1].end 1916 | 1917 | def __iter__(self): 1918 | return self._segments.__iter__() 1919 | 1920 | def __contains__(self, x): 1921 | return self._segments.__contains__(x) 1922 | 1923 | def insert(self, index, value): 1924 | self._segments.insert(index, value) 1925 | self._length = None 1926 | self._start = self._segments[0].start 1927 | self._end = self._segments[-1].end 1928 | 1929 | def reversed(self): 1930 | newpath = [seg.reversed() for seg in self] 1931 | newpath.reverse() 1932 | return Path(*newpath) 1933 | 1934 | def __len__(self): 1935 | return len(self._segments) 1936 | 1937 | def __repr__(self): 1938 | return "Path({})".format( 1939 | ",\n ".join(repr(x) for x in self._segments)) 1940 | 1941 | def __eq__(self, other): 1942 | if not isinstance(other, Path): 1943 | return NotImplemented 1944 | if len(self) != len(other): 1945 | return False 1946 | for s, o in zip(self._segments, other._segments): 1947 | if not s == o: 1948 | return False 1949 | return True 1950 | 1951 | def __ne__(self, other): 1952 | if not isinstance(other, Path): 1953 | return NotImplemented 1954 | return not self == other 1955 | 1956 | def _calc_lengths(self, error=LENGTH_ERROR, min_depth=LENGTH_MIN_DEPTH): 1957 | if self._length is not None: 1958 | return 1959 | 1960 | lengths = [each.length(error=error, min_depth=min_depth) for each in 1961 | self._segments] 1962 | self._length = sum(lengths) 1963 | self._lengths = [each/self._length for each in lengths] 1964 | 1965 | def length(self, T0=0, T1=1, error=LENGTH_ERROR, min_depth=LENGTH_MIN_DEPTH): 1966 | self._calc_lengths(error=error, min_depth=min_depth) 1967 | if T0 == 0 and T1 == 1: 1968 | return self._length 1969 | else: 1970 | if len(self) == 1: 1971 | return self[0].length(t0=T0, t1=T1) 1972 | idx0, t0 = self.T2t(T0) 1973 | idx1, t1 = self.T2t(T1) 1974 | if idx0 == idx1: 1975 | return self[idx0].length(t0=t0, t1=t1) 1976 | return (self[idx0].length(t0=t0) + 1977 | sum(self[idx].length() for idx in range(idx0 + 1, idx1)) + 1978 | self[idx1].length(t1=t1)) 1979 | 1980 | @property 1981 | def start(self): 1982 | if not self._start: 1983 | self._start = self._segments[0].start 1984 | return self._start 1985 | 1986 | @start.setter 1987 | def start(self, pt): 1988 | self._start = pt 1989 | self._segments[0].start = pt 1990 | 1991 | @property 1992 | def end(self): 1993 | if not self._end: 1994 | self._end = self._segments[-1].end 1995 | return self._end 1996 | 1997 | @end.setter 1998 | def end(self, pt): 1999 | self._end = pt 2000 | self._segments[-1].end = pt 2001 | 2002 | def d(self, useSandT=False, use_closed_attrib=False): 2003 | 2004 | if use_closed_attrib: 2005 | self_closed = self.closed(warning_on=False) 2006 | if self_closed: 2007 | segments = self[:-1] 2008 | else: 2009 | segments = self[:] 2010 | else: 2011 | self_closed = False 2012 | segments = self[:] 2013 | 2014 | current_pos = None 2015 | parts = [] 2016 | previous_segment = None 2017 | end = self[-1].end 2018 | 2019 | for segment in segments: 2020 | seg_start = segment.start 2021 | if current_pos != seg_start or \ 2022 | (self_closed and seg_start == end and use_closed_attrib): 2023 | parts.append('M {},{}'.format(seg_start.real, seg_start.imag)) 2024 | 2025 | if isinstance(segment, Line): 2026 | args = segment.end.real, segment.end.imag 2027 | parts.append('L {},{}'.format(*args)) 2028 | elif isinstance(segment, CubicBezier): 2029 | if useSandT and segment.is_smooth_from(previous_segment, 2030 | warning_on=False): 2031 | args = (segment.control2.real, segment.control2.imag, 2032 | segment.end.real, segment.end.imag) 2033 | parts.append('S {},{} {},{}'.format(*args)) 2034 | else: 2035 | args = (segment.control1.real, segment.control1.imag, 2036 | segment.control2.real, segment.control2.imag, 2037 | segment.end.real, segment.end.imag) 2038 | parts.append('C {},{} {},{} {},{}'.format(*args)) 2039 | elif isinstance(segment, QuadraticBezier): 2040 | if useSandT and segment.is_smooth_from(previous_segment, 2041 | warning_on=False): 2042 | args = segment.end.real, segment.end.imag 2043 | parts.append('T {},{}'.format(*args)) 2044 | else: 2045 | args = (segment.control.real, segment.control.imag, 2046 | segment.end.real, segment.end.imag) 2047 | parts.append('Q {},{} {},{}'.format(*args)) 2048 | 2049 | elif isinstance(segment, Arc): 2050 | args = (segment.radius.real, segment.radius.imag, 2051 | segment.rotation,int(segment.large_arc), 2052 | int(segment.sweep),segment.end.real, segment.end.imag) 2053 | parts.append('A {},{} {} {:d},{:d} {},{}'.format(*args)) 2054 | current_pos = segment.end 2055 | previous_segment = segment 2056 | 2057 | if self_closed: 2058 | parts.append('Z') 2059 | 2060 | return ' '.join(parts) 2061 | 2062 | ##################### svgpathtools end #################### 2063 | 2064 | -------------------------------------------------------------------------------- /shapekeyimport_2_8.py: -------------------------------------------------------------------------------- 1 | # 2 | # 3 | # This Blender add-on imports paths and shapeKeys from an SVG file 4 | # Supported Blender Version: 2.8 Beta 5 | # 6 | # Copyright (C) 2018 Shrinivas Kulkarni 7 | # 8 | # License: GPL (https://github.com/Shriinivas/shapeKeyimport/blob/master/LICENSE) 9 | # 10 | 11 | # Not yet pep8 compliant 12 | 13 | # Scaling not done based on the unit of the SVG document, but based simply on value 14 | # If precise scaling is needed, appropriate unit (mm) needs to be set in the source SVG 15 | 16 | import bpy, copy, math, re, time, os 17 | from bpy.props import IntProperty, FloatProperty, BoolProperty, StringProperty 18 | from bpy.props import CollectionProperty, EnumProperty 19 | from xml.dom import minidom 20 | from collections import OrderedDict 21 | from mathutils import Vector, Matrix 22 | from math import sqrt, cos, sin, acos, degrees, radians, tan 23 | from cmath import exp, sqrt as csqrt, phase 24 | from collections.abc import MutableSequence 25 | 26 | #################### UI and Registration Stuff #################### 27 | 28 | bl_info = { 29 | "name": "Import Paths and Shape Keys from SVG", 30 | "author": "Shrinivas Kulkarni", 31 | "location": "File > Import > Import Paths & Shape Keys (.svg)", 32 | "category": "Import-Export", 33 | "blender": (2, 80, 0), 34 | } 35 | 36 | noneStr = "-None-" 37 | CURVE_NAME_PREFIX = 'Curve' 38 | 39 | def getCurveNames(scene, context): 40 | return [(noneStr, noneStr, '-1')] + [(obj.name, obj.name, str(i)) for i, obj in 41 | enumerate(context.scene.objects) if obj.type == 'CURVE'] 42 | 43 | def getAlignmentList(scene, context): 44 | alignListStrs = [*getAlignSegsFn().keys()] 45 | return [(noneStr, noneStr, '-1')] + [(str(align), str(align), str(i)) 46 | for i, align in enumerate(alignListStrs)] 47 | 48 | def getMatchPartList(scene, context): 49 | arrangeListStrs = [*getAlignPartsFn().keys()] 50 | return [(noneStr, noneStr, '-1')] + [(str(arrange), str(arrange), str(i)) 51 | for i, arrange in enumerate(arrangeListStrs)] 52 | 53 | class ObjectImportShapeKeys(bpy.types.Operator): 54 | 55 | bl_idname = "object.import_shapekeys" 56 | bl_label = "Import Paths & Shape Keys" 57 | bl_options = {'REGISTER', 'UNDO'} 58 | 59 | filter_glob : StringProperty(default="*.svg") 60 | filepath : StringProperty(subtype='FILE_PATH') 61 | 62 | #User input 63 | 64 | byGroup : BoolProperty(name="Import By Group", \ 65 | description = "Import target and shape key paths forming a group in SVG", \ 66 | default = True) 67 | 68 | byAttrib : BoolProperty(name="Import By Attribute", \ 69 | description = "Import targets having attribute defining shape key path IDs in SVG", \ 70 | default = True) 71 | 72 | shapeKeyAttribName : StringProperty(name="Attribute", \ 73 | description = "Name of target path attribute used to define shape keys in SVG", 74 | default = 'shapekeys') 75 | 76 | addShapeKeyPaths : BoolProperty(name="Retain Shape Key Paths", \ 77 | description = "Import shape key paths as paths as well as shape keys", \ 78 | default = False) 79 | 80 | addNontargetPaths : BoolProperty(name="Import Non-target Paths", \ 81 | description = "Import paths that are neither targets nor shape keys", \ 82 | default = True) 83 | 84 | addPathsFromHiddenLayer : BoolProperty(name="Import Hidden Layer Paths", 85 | description='Import paths from layers marked as hidden in SVG', \ 86 | default = False) 87 | 88 | originToGeometry : BoolProperty(name="Origin To Geometry", \ 89 | description="Shift the imported path's origin to its geometry center", \ 90 | default = False) 91 | 92 | xScale : FloatProperty(name="X", \ 93 | description="X scale factor for imported paths", \ 94 | default = 0.01) 95 | 96 | yScale : FloatProperty(name="Y", \ 97 | description="Y scale factor for imported paths", \ 98 | default = 0.01) 99 | 100 | zLocation : FloatProperty(name="Z Location", \ 101 | description='Z coordiate value for imported paths', default = 0) 102 | 103 | resolution : IntProperty(name="Resolution", \ 104 | description='Higher value gives smoother transition but more complex geometry', \ 105 | default = 0, min=0) 106 | 107 | objList : EnumProperty(name="Copy Properties From", items = getCurveNames, \ 108 | description='Curve whose material, depth etc. should be copied on to imported paths') 109 | 110 | partMatchList : EnumProperty(name="Match Parts By", items = getMatchPartList, \ 111 | description='Match disconnected parts of target and shape key based on (BBox -> Bounding Box)') 112 | 113 | alignList : EnumProperty(name="Node Alignment Order", items = getAlignmentList, \ 114 | description = 'Start aligning the nodes of target and shape keys (paths or parts) from') 115 | 116 | def execute(self, context): 117 | createdObjsMap = main(infilePath = self.filepath, \ 118 | shapeKeyAttribName = self.shapeKeyAttribName, \ 119 | byGroup = self.byGroup, \ 120 | byAttrib = self.byAttrib, \ 121 | addShapeKeyPaths = self.addShapeKeyPaths, \ 122 | addNontargetPaths = self.addNontargetPaths, \ 123 | scale = [self.xScale, -self.yScale, 1], \ 124 | zVal = self.zLocation, \ 125 | resolution = self.resolution, \ 126 | copyObjName = self.objList, \ 127 | partArrangeOrder = self.partMatchList, \ 128 | alignOrder = self.alignList, \ 129 | pathsFromHiddenLayer = self.addPathsFromHiddenLayer, \ 130 | originToGeometry = self.originToGeometry) 131 | return {'FINISHED'} 132 | 133 | def draw(self, context): 134 | layout = self.layout 135 | col = layout.column() 136 | row = col.row() 137 | row.prop(self, "byGroup") 138 | row = col.row() 139 | row.prop(self, "byAttrib") 140 | row = col.row() 141 | row.prop(self, "shapeKeyAttribName") 142 | row = col.row() 143 | row.prop(self, "addShapeKeyPaths") 144 | row = col.row() 145 | row.prop(self, "addNontargetPaths") 146 | row = col.row() 147 | row.prop(self, "addPathsFromHiddenLayer") 148 | row = col.row() 149 | row.prop(self, "originToGeometry") 150 | layout.row().separator() 151 | row = col.row() 152 | row.label(text = 'Scale') 153 | row = col.row() 154 | row.prop(self, "xScale") 155 | row.prop(self, "yScale") 156 | row = col.row() 157 | row.prop(self, "zLocation") 158 | layout.row().separator() 159 | row = col.row() 160 | row.prop(self, "resolution") 161 | row = col.row() 162 | row.prop(self, "objList") 163 | row = col.row() 164 | row.prop(self, "partMatchList") 165 | row = col.row() 166 | row.prop(self, "alignList") 167 | 168 | def invoke(self, context, event): 169 | alignListStrs = [*getAlignSegsFn().keys()] 170 | arrangeListStrs = [*getAlignPartsFn().keys()] 171 | 172 | #default values 173 | self.objList = noneStr 174 | self.partMatchList = str(arrangeListStrs[-1]) 175 | self.alignList = str(alignListStrs[-1]) 176 | 177 | context.window_manager.fileselect_add(self) 178 | 179 | return {'RUNNING_MODAL'} 180 | 181 | def menuImportShapeKeys(self, context): 182 | self.layout.operator(ObjectImportShapeKeys.bl_idname, 183 | text="Import Paths & Shape Keys (.svg)") 184 | 185 | def register(): 186 | bpy.utils.register_class(ObjectImportShapeKeys) 187 | bpy.types.TOPBAR_MT_file_import.append(menuImportShapeKeys) 188 | 189 | def unregister(): 190 | bpy.utils.unregister_class(ObjectImportShapeKeys) 191 | bpy.types.TOPBAR_MT_file_import.remove(menuImportShapeKeys) 192 | 193 | if __name__ == "__main__": 194 | register() 195 | 196 | ###################### addon code start #################### 197 | 198 | DEF_ERR_MARGIN = 0.0001 199 | hiddenLayerAttr = 'display:none' 200 | 201 | def isValidPath(pathElem): 202 | dVal = pathElem.getAttribute('d') 203 | return (dVal != None) and (dVal.strip() != "") and \ 204 | (dVal[0] in set('MLHVCSQTAmlhvcsqa')) 205 | 206 | class OrderedSet(OrderedDict): 207 | def add(self, item): 208 | super(OrderedSet, self).__setitem__(item, '') 209 | 210 | def __iter__(self): 211 | return super.keys().__iter__() 212 | 213 | #...Other methods to be added when needed 214 | 215 | class Part(): 216 | def __init__(self, segments, isClosed): 217 | self.segs = segments 218 | self.isClosed = isClosed 219 | 220 | if(len(segments) > 0): 221 | self.partToClose = self.isContinuous() 222 | 223 | def copy(self, start, end): 224 | if(start == None): 225 | start = 0 226 | if(end == None): 227 | end = len(self.segs) 228 | return Part(self.segs[start:end], None)#IsClosing not defined, so set to None 229 | 230 | def getSeg(self, idx): 231 | return self.segs[idx] 232 | 233 | def getSegs(self): 234 | return self.segs 235 | 236 | def getSegsCopy(self, start, end): 237 | if(start == None): 238 | start = 0 239 | if(end == None): 240 | end = len(self.segs) 241 | return self.segs[start:end] 242 | 243 | def bbox(self): 244 | leftBot_rgtTop = [[None]*2,[None]*2] 245 | for seg in self.segs: 246 | bb = bboxCubicBezier(seg) 247 | for i in range(0, 2): 248 | if (leftBot_rgtTop[0][i] == None or bb[0][i] < leftBot_rgtTop[0][i]): 249 | leftBot_rgtTop[0][i] = bb[0][i] 250 | for i in range(0, 2): 251 | if (leftBot_rgtTop[1][i] == None or bb[1][i] > leftBot_rgtTop[1][i]): 252 | leftBot_rgtTop[1][i] = bb[1][i] 253 | 254 | return leftBot_rgtTop 255 | 256 | def isContinuous(self): 257 | return cmplxCmpWithMargin(self.segs[0].start, self.segs[-1].end) 258 | 259 | def getSegCnt(self): 260 | return len(self.segs) 261 | 262 | def length(self, error): 263 | return sum(seg.length(error = error) for seg in self.segs) 264 | 265 | class PathElem: 266 | def __init__(self, path, attributes, transList, seqId): 267 | self.parts = getDisconnParts(path) 268 | self.pathId = attributes['id'].value 269 | self.attributes = attributes 270 | self.transList = transList 271 | self.seqId = seqId 272 | 273 | def getPartCnt(self): 274 | return len(self.parts) 275 | 276 | def getPartView(self): 277 | p = Part([seg for part in self.parts for seg in part.getSegs()], None) 278 | return p 279 | 280 | def getPartBoundaryIdxs(self): 281 | cumulCntList = set() 282 | cumulCnt = 0 283 | 284 | for p in self.parts: 285 | cumulCnt += p.getSegCnt() 286 | cumulCntList.add(cumulCnt) 287 | 288 | return cumulCntList 289 | 290 | def updatePartsList(self, segCntsPerPart, byPart): 291 | monolithicSegList = [seg for part in self.parts for seg in part.getSegs()] 292 | self.parts.clear() 293 | 294 | for i in range(0, len(segCntsPerPart)): 295 | if( i == 0): 296 | currIdx = 0 297 | else: 298 | currIdx = segCntsPerPart[i-1] 299 | 300 | nextIdx = segCntsPerPart[i] 301 | isClosed = None 302 | 303 | if(byPart == True and i < len(self.parts)): 304 | isClosed = self.parts[i].isClosed # Let's retain as far as possible 305 | 306 | self.parts.append(Part(monolithicSegList[currIdx:nextIdx], isClosed)) 307 | 308 | def __repr__(self): 309 | return self.pathId 310 | 311 | class BlenderBezierPoint: 312 | #all points are complex values not 3d vectors 313 | def __init__(self, pt, handleLeft, handleRight): 314 | self.pt = pt 315 | self.handleLeft = handleLeft 316 | self.handleRight = handleRight 317 | 318 | def __repr__(self): 319 | return str(self.pt) 320 | 321 | def getPathElemMap(doc, pathsFromHiddenLayer): 322 | elemMap = {} 323 | seqId = 0 324 | for pathXMLElem in doc.getElementsByTagName('path'): 325 | if (isElemSelectable(pathXMLElem, pathsFromHiddenLayer) and 326 | isValidPath(pathXMLElem)): 327 | dVal = pathXMLElem.getAttribute('d') 328 | transList = [] 329 | idAttr = pathXMLElem.getAttribute('id') 330 | parsedPath = parse_path(dVal) 331 | getTransformAttribs(pathXMLElem, transList) 332 | pathElem = PathElem(parsedPath, pathXMLElem.attributes, transList, seqId) 333 | elemMap[idAttr] = pathElem 334 | seqId += 1 335 | return elemMap 336 | 337 | def main(infilePath, shapeKeyAttribName, byGroup, byAttrib, addShapeKeyPaths, 338 | addNontargetPaths, scale, zVal, resolution, copyObjName, partArrangeOrder, alignOrder, 339 | pathsFromHiddenLayer, originToGeometry): 340 | 341 | doc = minidom.parse(infilePath) 342 | 343 | pathElemsMap = getPathElemMap(doc, pathsFromHiddenLayer) 344 | 345 | pathElems = [*pathElemsMap.values()] 346 | 347 | normalizePathElems(pathElems, alignOrder, partArrangeOrder) 348 | 349 | targetShapeKeyMap = {} 350 | allShapeKeyIdsSet = set() 351 | 352 | if(byGroup == True): 353 | updateShapeKeyMapByGroup(targetShapeKeyMap, allShapeKeyIdsSet, doc, pathsFromHiddenLayer) 354 | 355 | if(byAttrib == True): 356 | updateShapeKeyMapByAttrib(targetShapeKeyMap, pathElemsMap, allShapeKeyIdsSet, shapeKeyAttribName) 357 | 358 | #List of lists with all the interdependent paths that need to be homogenized 359 | dependentPathIdsSets = getDependentPathIdsSets(targetShapeKeyMap) 360 | 361 | byPart = (partArrangeOrder != noneStr) 362 | for prntIdx, dependentPathIdsSet in enumerate(dependentPathIdsSets): 363 | dependentPathsSet = [pathElemsMap.get(dependentPathId) for dependentPathId in dependentPathIdsSet 364 | if pathElemsMap.get(dependentPathId) != None] 365 | 366 | addMissingSegs(dependentPathsSet, byPart = byPart, resolution = resolution) 367 | 368 | bIdxs = set() 369 | for pathElem in dependentPathsSet: 370 | bIdxs = bIdxs.union(pathElem.getPartBoundaryIdxs()) 371 | 372 | for pathElem in dependentPathsSet: 373 | pathElem.updatePartsList(sorted(list(bIdxs)), byPart) 374 | 375 | #All will have same part count by now 376 | allToClose = [all(pathElem.parts[j].partToClose for pathElem in dependentPathsSet) 377 | for j in range(0, len(dependentPathsSet[0].parts))] 378 | 379 | #All interdependent paths will have the same no of splines with the same no of bezier points 380 | for pathElem in dependentPathsSet: 381 | for j, part in enumerate(pathElem.parts): 382 | part.partToClose = allToClose[j] 383 | 384 | objPathIds = set(targetShapeKeyMap.keys()) 385 | 386 | if(addNontargetPaths == True): 387 | nontargetIds = (pathElemsMap.keys() - targetShapeKeyMap.keys()) - allShapeKeyIdsSet 388 | objPathIds = objPathIds.union(nontargetIds) 389 | 390 | if(addShapeKeyPaths == True): 391 | #in case shapeKeys are also targets 392 | shapeKeyIdsToAdd = allShapeKeyIdsSet - targetShapeKeyMap.keys() 393 | objPathIds = objPathIds.union(shapeKeyIdsToAdd.intersection(pathElemsMap.keys())) 394 | 395 | copyObj = bpy.data.objects.get(copyObjName)#Can be None 396 | 397 | objMap = {} 398 | 399 | if(len(objPathIds) > 0): 400 | groupName = os.path.basename(infilePath) 401 | group = bpy.data.collections.new(groupName) 402 | bpy.context.scene.collection.children.link(group) 403 | 404 | for objPathId in objPathIds: 405 | addSvg2Blender(group, objMap, pathElemsMap[objPathId], scale, zVal, copyObj, originToGeometry) 406 | 407 | for pathElemId in targetShapeKeyMap.keys(): 408 | pathObj = objMap[pathElemId] 409 | pathObj.shape_key_add(name = 'Basis') 410 | shapeKeyElemIds = targetShapeKeyMap[pathElemId].keys() 411 | for shapeKeyElemId in shapeKeyElemIds: 412 | shapeKeyElem = pathElemsMap.get(shapeKeyElemId) 413 | if(shapeKeyElem != None):#Maybe no need after so many checks earlier 414 | addShapeKey(pathObj, shapeKeyElem, shapeKeyElemId, scale, zVal, originToGeometry) 415 | 416 | return objMap 417 | 418 | #Avoid errors due to floating point conversions/comparisons 419 | def cmplxCmpWithMargin(complex1, complex2, margin = DEF_ERR_MARGIN): 420 | return floatCmpWithMargin(complex1.real, complex2.real, margin) and \ 421 | floatCmpWithMargin(complex1.imag, complex2.imag, margin) 422 | 423 | def floatCmpWithMargin(float1, float2, margin = DEF_ERR_MARGIN): 424 | return abs(float1 - float2) < margin 425 | 426 | #TODO: Would be more conditions like defs. Need a better solution 427 | def isElemSelectable(elem, pathsFromHiddenLayer): 428 | return getParentInHierarchy(elem, 'defs') == None and \ 429 | (pathsFromHiddenLayer == True or not isInHiddenLayer(elem)) 430 | 431 | def getParentInHierarchy(elem, parentTag): 432 | parent = elem.parentNode 433 | 434 | while(parent != None and parent.parentNode != None and parent.tagName != parentTag): 435 | parent = parent.parentNode 436 | 437 | #TODO: Better way to detect the Document node 438 | if(parent.parentNode == None): 439 | return None 440 | 441 | return parent 442 | 443 | def getTransformAttribs(elem, transList): 444 | if(elem.nodeType == elem.DOCUMENT_NODE): 445 | return 446 | 447 | transAttr = elem.getAttribute('transform') 448 | if(transAttr != None): 449 | transList.append(transAttr) 450 | if(elem.parentNode != None): 451 | getTransformAttribs(elem.parentNode, transList) 452 | 453 | def isInHiddenLayer(elem): 454 | parent = elem.parentNode 455 | 456 | while(parent != None and parent.nodeType == parent.ELEMENT_NODE and \ 457 | (parent.tagName != 'g' or (parent.parentNode != None and \ 458 | parent.parentNode.tagName != 'svg'))): 459 | parent = parent.parentNode 460 | 461 | if(parent != None and parent.nodeType == parent.ELEMENT_NODE): 462 | return parent.getAttribute('style').startswith(hiddenLayerAttr) 463 | 464 | return False 465 | 466 | def getDependentPathIdsSets(shapeKeyMap): 467 | pathIdSets = [] 468 | allAddedPathIds = set() 469 | for targetId in shapeKeyMap.keys(): 470 | #Keep track of the added path Ids since the target can be a shapeKey, 471 | #or a target of one of the shapeKeys of this target (many->many relation) 472 | if(targetId not in allAddedPathIds): 473 | pathIdSet = set() 474 | addDependentPathsToList(shapeKeyMap, pathIdSet, targetId) 475 | pathIdSets.append(pathIdSet) 476 | allAddedPathIds = allAddedPathIds.union(pathIdSet) 477 | return pathIdSets 478 | 479 | #Reverse lookup 480 | def getKeysetWithValue(srcMap, value): 481 | keySet = set() 482 | for key in srcMap: 483 | if(value in srcMap[key]): 484 | keySet.add(key) 485 | return keySet 486 | 487 | #All the shape keys and their other targets are added recursively 488 | def addDependentPathsToList(shapeKeyMap, pathIdSet, targetId): 489 | if(targetId in pathIdSet): 490 | return pathIdSet 491 | 492 | pathIdSet.add(targetId) 493 | shapeKeyElemIdMap = shapeKeyMap.get(targetId) 494 | 495 | if(shapeKeyElemIdMap == None): 496 | return pathIdSet 497 | 498 | shapeKeyElemIdList = shapeKeyElemIdMap.keys() 499 | if(shapeKeyElemIdList == None): 500 | return pathIdSet 501 | 502 | for shapeKeyElemId in shapeKeyElemIdList: 503 | #Recuresively add the Ids that are shape key of this shape key 504 | addDependentPathsToList(shapeKeyMap, pathIdSet, shapeKeyElemId) 505 | 506 | #Recursively add the Ids that are other targets of this shape key 507 | keyset = getKeysetWithValue(shapeKeyMap, shapeKeyElemId) 508 | for key in keyset: 509 | addDependentPathsToList(shapeKeyMap, pathIdSet, key) 510 | 511 | return pathIdSet 512 | 513 | def getAllPathElemsInGroup(parentElem, pathElems): 514 | for childNode in parentElem.childNodes: 515 | if childNode.nodeType == childNode.ELEMENT_NODE: 516 | if(childNode.tagName == 'path' and isValidPath(childNode)): 517 | pathElems.append(childNode) 518 | elif(childNode.tagName == 'g'): 519 | getAllPathElemsInGroup(childNode, pathElems) 520 | 521 | def updateShapeKeyMapByGroup(targetShapeKeyMap, allShapeKeyIdsSet, doc, pathsFromHiddenLayer): 522 | groupElems = [groupElem for groupElem in doc.getElementsByTagName('g') 523 | if (groupElem.parentNode.tagName != 'svg' and 524 | isElemSelectable(groupElem, pathsFromHiddenLayer))] 525 | 526 | for groupElem in groupElems: 527 | pathElems = [] 528 | getAllPathElemsInGroup(groupElem, pathElems) 529 | if(pathElems != None and len(pathElems) > 1 ): 530 | targetId = pathElems[0].getAttribute('id') 531 | if(targetShapeKeyMap.get(targetId) == None): 532 | targetShapeKeyMap[targetId] = OrderedSet() 533 | 534 | for i in range(1, len(pathElems)): 535 | shapeKeyId = pathElems[i].getAttribute('id') 536 | targetShapeKeyMap[targetId].add(shapeKeyId) 537 | allShapeKeyIdsSet.add(shapeKeyId) 538 | 539 | def updateShapeKeyMapByAttrib(targetShapeKeyMap, pathElemsMap, \ 540 | allShapeKeyIdsSet, shapeKeyAttribName): 541 | for key in pathElemsMap.keys(): 542 | targetPathElem = pathElemsMap[key] 543 | attributes = targetPathElem.attributes 544 | shapeKeyIdAttrs = attributes.get(shapeKeyAttribName) 545 | if(shapeKeyIdAttrs != None): 546 | shapeKeyIds = shapeKeyIdAttrs.value 547 | shapeKeyIdsStr = str(shapeKeyIds) 548 | shapeKeyIdList = shapeKeyIdsStr.replace(' ','').split(',') 549 | if(targetShapeKeyMap.get(key) == None): 550 | targetShapeKeyMap[key] = OrderedSet() 551 | for keyId in shapeKeyIdList: 552 | if(pathElemsMap.get(keyId) != None): 553 | targetShapeKeyMap[key].add(keyId) 554 | allShapeKeyIdsSet.add(keyId) 555 | 556 | def bboxArea(leftBot_rgtTop): 557 | return abs((leftBot_rgtTop[1][0]-leftBot_rgtTop[0][0]) * \ 558 | (leftBot_rgtTop[1][1]-leftBot_rgtTop[0][1])) 559 | 560 | #see https://stackoverflow.com/questions/24809978/calculating-the-bounding-box-of-cubic-bezier-curve 561 | #(3 D - 9 C + 9 B - 3 A) t^2 + (6 A - 12 B + 6 C) t + 3 (B - A) 562 | def bboxCubicBezier(bezier): 563 | def evalBez(AA, BB, CC, DD, t): 564 | return AA * (1 - t) * (1 - t) * (1 - t) + \ 565 | 3 * BB * t * (1 - t) * (1 - t) + \ 566 | 3 * CC * t * t * (1 - t) + \ 567 | DD * t * t * t 568 | 569 | A = [bezier.start.real, bezier.start.imag] 570 | B = [bezier.control1.real, bezier.control1.imag] 571 | C = [bezier.control2.real, bezier.control2.imag] 572 | D = [bezier.end.real, bezier.end.imag] 573 | 574 | MINXY = [min([A[0], D[0]]), min([A[1], D[1]])] 575 | MAXXY = [max([A[0], D[0]]), max([A[1], D[1]])] 576 | leftBot_rgtTop = [MINXY, MAXXY] 577 | 578 | a = [3 * D[i] - 9 * C[i] + 9 * B[i] - 3 * A[i] for i in range(0, 2)] 579 | b = [6 * A[i] - 12 * B[i] + 6 * C[i] for i in range(0, 2)] 580 | c = [3 * (B[i] - A[i]) for i in range(0, 2)] 581 | 582 | solnsxy = [] 583 | for i in range(0, 2): 584 | solns = [] 585 | if(a[i] == 0): 586 | if(b[i] == 0): 587 | solns.append(0)#Independent of t so lets take the starting pt 588 | else: 589 | solns.append(c[i] / b[i]) 590 | else: 591 | rootFact = b[i] * b[i] - 4 * a[i] * c[i] 592 | if(rootFact >=0 ): 593 | #Two solutions with + and - sqrt 594 | solns.append((-b[i] + sqrt(rootFact)) / (2 * a[i])) 595 | solns.append((-b[i] - sqrt(rootFact)) / (2 * a[i])) 596 | solnsxy.append(solns) 597 | 598 | for i, soln in enumerate(solnsxy): 599 | for j, t in enumerate(soln): 600 | if(t < 1 and t > 0): 601 | co = evalBez(A[i], B[i], C[i], D[i], t) 602 | if(co < leftBot_rgtTop[0][i]): 603 | leftBot_rgtTop[0][i] = co 604 | if(co > leftBot_rgtTop[1][i]): 605 | leftBot_rgtTop[1][i] = co 606 | 607 | return leftBot_rgtTop 608 | 609 | def getLineSegment(start, end, t0, t1): 610 | xt0, yt0 = (1 - t0) * start.real + t0 * end.real , (1 - t0) * start.imag + t0 * end.imag 611 | xt1, yt1 = (1 - t1) * start.real + t1 * end.real , (1 - t1) * start.imag + t1 * end.imag 612 | 613 | return CubicBezier(complex(xt0, yt0), complex(xt0, yt0), 614 | complex(xt1, yt1), complex(xt1, yt1)) 615 | 616 | #see https://stackoverflow.com/questions/878862/drawing-part-of-a-b%c3%a9zier-curve-by-reusing-a-basic-b%c3%a9zier-curve-function/879213#879213 617 | def getCurveSegment(seg, t0, t1): 618 | ctrlPts = seg 619 | 620 | if(t0 > t1): 621 | tt = t1 622 | t1 = t0 623 | t0 = tt 624 | 625 | #Let's make at least the line segments of predictable length :) 626 | if(ctrlPts[0] == ctrlPts[1] and ctrlPts[2] == ctrlPts[3]): 627 | return getLineSegment(ctrlPts[0], ctrlPts[2], t0, t1) 628 | 629 | x1, y1 = ctrlPts[0].real, ctrlPts[0].imag 630 | bx1, by1 = ctrlPts[1].real, ctrlPts[1].imag 631 | bx2, by2 = ctrlPts[2].real, ctrlPts[2].imag 632 | x2, y2 = ctrlPts[3].real, ctrlPts[3].imag 633 | 634 | u0 = 1.0 - t0 635 | u1 = 1.0 - t1 636 | 637 | qxa = x1*u0*u0 + bx1*2*t0*u0 + bx2*t0*t0 638 | qxb = x1*u1*u1 + bx1*2*t1*u1 + bx2*t1*t1 639 | qxc = bx1*u0*u0 + bx2*2*t0*u0 + x2*t0*t0 640 | qxd = bx1*u1*u1 + bx2*2*t1*u1 + x2*t1*t1 641 | 642 | qya = y1*u0*u0 + by1*2*t0*u0 + by2*t0*t0 643 | qyb = y1*u1*u1 + by1*2*t1*u1 + by2*t1*t1 644 | qyc = by1*u0*u0 + by2*2*t0*u0 + y2*t0*t0 645 | qyd = by1*u1*u1 + by2*2*t1*u1 + y2*t1*t1 646 | 647 | xa = qxa*u0 + qxc*t0 648 | xb = qxa*u1 + qxc*t1 649 | xc = qxb*u0 + qxd*t0 650 | xd = qxb*u1 + qxd*t1 651 | 652 | ya = qya*u0 + qyc*t0 653 | yb = qya*u1 + qyc*t1 654 | yc = qyb*u0 + qyd*t0 655 | yd = qyb*u1 + qyd*t1 656 | 657 | return CubicBezier(complex(xa, ya), complex(xb, yb), 658 | complex(xc, yc), complex(xd, yd)) 659 | 660 | 661 | def subdivideSeg(origSeg, noSegs): 662 | if(noSegs < 2): 663 | return [origSeg] 664 | 665 | segs = [] 666 | oldT = 0 667 | segLen = origSeg.length(error = DEF_ERR_MARGIN) / noSegs 668 | for i in range(0, noSegs-1): 669 | t = float(i+1) / noSegs 670 | cBezier = getCurveSegment(origSeg, oldT, t) 671 | segs.append(cBezier) 672 | oldT = t 673 | 674 | cBezier = getCurveSegment(origSeg, oldT, 1) 675 | segs.append(cBezier) 676 | 677 | return segs 678 | 679 | 680 | def getSubdivCntPerSeg(part, toAddCnt): 681 | 682 | class ItemWrapper: 683 | def __init__(self, idx, item): 684 | self.idx = idx 685 | self.item = item 686 | self.length = item.length(error = DEF_ERR_MARGIN) 687 | 688 | class PartWrapper: 689 | def __init__(self, part): 690 | self.itemList = [] 691 | self.itemCnt = len(part.getSegs()) 692 | for idx, seg in enumerate(part.getSegs()): 693 | self.itemList.append(ItemWrapper(idx, seg)) 694 | 695 | partWrapper = PartWrapper(part) 696 | partLen = part.length(DEF_ERR_MARGIN) 697 | avgLen = partLen / (partWrapper.itemCnt + toAddCnt) 698 | 699 | segsToDivide = [item for item in partWrapper.itemList if item.length >= avgLen] 700 | segToDivideCnt = len(segsToDivide) 701 | avgLen = sum(item.length for item in segsToDivide) / (segToDivideCnt + toAddCnt) 702 | 703 | segsToDivide = sorted(segsToDivide, key=lambda x: x.length, reverse = True) 704 | 705 | cnts = [0] * partWrapper.itemCnt 706 | addedCnt = 0 707 | 708 | 709 | for i in range(0, segToDivideCnt): 710 | segLen = segsToDivide[i].length 711 | 712 | divideCnt = int(round(segLen/avgLen)) - 1 713 | if(divideCnt == 0): 714 | break 715 | 716 | if((addedCnt + divideCnt) >= toAddCnt): 717 | cnts[segsToDivide[i].idx] = toAddCnt - addedCnt 718 | addedCnt = toAddCnt 719 | break 720 | 721 | cnts[segsToDivide[i].idx] = divideCnt 722 | 723 | addedCnt += divideCnt 724 | 725 | #TODO: Verify if needed 726 | while(toAddCnt > addedCnt): 727 | for i in range(0, segToDivideCnt): 728 | cnts[segsToDivide[i].idx] += 1 729 | addedCnt += 1 730 | if(toAddCnt == addedCnt): 731 | break 732 | 733 | return cnts 734 | 735 | def getDisconnParts(path): 736 | prevSeg = None 737 | disconnParts = [] 738 | segs = [] 739 | 740 | for i in range(0, len(path)): 741 | seg = path[i] 742 | if((prevSeg== None) or not cmplxCmpWithMargin(prevSeg.end, seg.start)): 743 | if(len(segs) > 0): 744 | disconnParts.append(Part(segs, segs[-1].isClosing)) 745 | segs = [] 746 | prevSeg = seg 747 | segs.append(seg) 748 | 749 | if(len(path) > 0 and len(segs) > 0): 750 | disconnParts.append(Part(segs, segs[-1].isClosing)) 751 | 752 | return disconnParts 753 | 754 | def normalizePathElems(pathElems, alignOrder, partArrangeOrder): 755 | for pathElem in pathElems: 756 | toTransformedCBezier(pathElem) 757 | alignPath(pathElem, alignOrder, partArrangeOrder) 758 | 759 | #Resolution is mapped to parts 760 | #The value 100 means 1 segment per unit length (whatever it is in source SVG) of Part 761 | def getSegCntForResolution(part, resolution): 762 | segCnt = part.getSegCnt() 763 | segCntForRes = int(part.length(error = DEF_ERR_MARGIN) * resolution / 100) 764 | 765 | if(segCnt > segCntForRes): 766 | return segCnt 767 | else: 768 | return segCntForRes 769 | 770 | #Distribute equally; this is likely a rare condition. So why complicate? 771 | def distributeCnt(maxSegCntsByPart, startIdx, extraCnt): 772 | added = 0 773 | elemCnt = len(maxSegCntsByPart) - startIdx 774 | cntPerElem = math.floor(extraCnt / elemCnt) 775 | remainder = extraCnt % elemCnt 776 | for i in range(startIdx, len(maxSegCntsByPart)): 777 | maxSegCntsByPart[i] += cntPerElem 778 | if(i < remainder + startIdx): 779 | maxSegCntsByPart[i] += 1 780 | 781 | #Make all the paths to have the maximum number of segments in the set 782 | def addMissingSegs(pathElems, byPart, resolution): 783 | maxSegCntsByPart = [] 784 | samePartCnt = True 785 | maxSegCnt = 0 786 | 787 | resSegCnt = [] 788 | sortedElems = sorted(pathElems, key = lambda p: -len(p.parts)) 789 | for i, pathElem in enumerate(sortedElems): 790 | if(byPart == False): 791 | segCnt = getSegCntForResolution(pathElem.getPartView(), resolution) 792 | if(segCnt > maxSegCnt): 793 | maxSegCnt = segCnt 794 | 795 | else: 796 | resSegCnt.append([]) 797 | for j, part in enumerate(pathElem.parts): 798 | partSegCnt = getSegCntForResolution(part, resolution) 799 | resSegCnt[i].append(partSegCnt) 800 | #First path 801 | if(j == len(maxSegCntsByPart)): 802 | maxSegCntsByPart.append(partSegCnt) 803 | 804 | #last part of this path, but other paths in set have more parts 805 | elif((j == len(pathElem.parts) - 1) and 806 | len(maxSegCntsByPart) > len(pathElem.parts)): 807 | 808 | remainingSegs = sum(maxSegCntsByPart[j:]) 809 | if(partSegCnt <= remainingSegs): 810 | resSegCnt[i][j] = remainingSegs 811 | else: 812 | #This part has more segs than the sum of the remaining part segs 813 | #So distribute the extra count 814 | distributeCnt(maxSegCntsByPart, j, (partSegCnt - remainingSegs)) 815 | 816 | #Also, adjust the seg count of the last part of the previous 817 | #segments that had fewer than max number of parts 818 | for k in range(0, i): 819 | if(len(sortedElems[k].parts) < len(maxSegCntsByPart)): 820 | totalSegs = sum(maxSegCntsByPart) 821 | existingSegs = sum(maxSegCntsByPart[:len(sortedElems[k].parts)-1]) 822 | resSegCnt[k][-1] = totalSegs - existingSegs 823 | 824 | elif(partSegCnt > maxSegCntsByPart[j]): 825 | maxSegCntsByPart[j] = partSegCnt 826 | 827 | for i, pathElem in enumerate(sortedElems): 828 | 829 | if(byPart == False): 830 | partView = pathElem.getPartView() 831 | segCnt = partView.getSegCnt() 832 | diff = maxSegCnt - segCnt 833 | 834 | if(diff > 0): 835 | cnts = getSubdivCntPerSeg(partView, diff) 836 | cumulSegIdx = 0 837 | for j in range(0, len(pathElem.parts)): 838 | part = pathElem.parts[j] 839 | newSegs = [] 840 | for k, seg in enumerate(part.getSegs()): 841 | numSubdivs = cnts[cumulSegIdx] + 1 842 | newSegs += subdivideSeg(seg, numSubdivs) 843 | cumulSegIdx += 1 844 | 845 | #isClosed won't be used, but let's update anyway 846 | pathElem.parts[j] = Part(newSegs, part.isClosed) 847 | 848 | else: 849 | for j in range(0, len(pathElem.parts)): 850 | part = pathElem.parts[j] 851 | newSegs = [] 852 | 853 | partSegCnt = part.getSegCnt() 854 | 855 | #TODO: Adding everything in the last part? 856 | if(j == (len(pathElem.parts)-1) and 857 | len(maxSegCntsByPart) > len(pathElem.parts)): 858 | diff = resSegCnt[i][j] - partSegCnt 859 | else: 860 | diff = maxSegCntsByPart[j] - partSegCnt 861 | 862 | if(diff > 0): 863 | cnts = getSubdivCntPerSeg(part, diff) 864 | 865 | for k, seg in enumerate(part.getSegs()): 866 | seg = part.getSeg(k) 867 | subdivCnt = cnts[k] + 1 #1 for the existing one 868 | newSegs += subdivideSeg(seg, subdivCnt) 869 | 870 | #isClosed won't be used, but let's update anyway 871 | pathElem.parts[j] = Part(newSegs, part.isClosed) 872 | 873 | 874 | def transTranslate(elems): 875 | y = 0 876 | if(len(elems) > 1): 877 | y = elems[1] 878 | return Matrix.Translation((elems[0], y, 0)) 879 | 880 | def transScale(elems): 881 | y = 0 882 | if(len(elems) > 1): 883 | y = elems[1] 884 | 885 | return Matrix.Scale(elems[0], 4, (1, 0, 0)) @ \ 886 | Matrix.Scale(y, 4, (0, 1, 0)) 887 | 888 | def transRotate(elems): 889 | m = Matrix() 890 | if(len(elems) > 1): 891 | m = transTranslate(elems[1:]) 892 | 893 | return m @ Matrix.Rotation(radians(elems[0]), 4, Vector((0, 0, 1))) \ 894 | @ m.inverted() 895 | 896 | def transSkewX(elems): 897 | mat = Matrix() 898 | mat[0][1] = tan(radians(elems[0])) 899 | return mat 900 | 901 | def transSkewY(elems): 902 | mat = Matrix() 903 | mat[1][0] = tan(radians(elems[0])) 904 | return mat 905 | 906 | def transMatrix(elems): 907 | #standard matrix with diagonal elems = 1 908 | mat = Matrix() 909 | mat[0][0] = elems[0] 910 | mat[0][1] = elems[2] 911 | mat[0][3] = elems[4] 912 | mat[1][0] = elems[1] 913 | mat[1][1] = elems[3] 914 | mat[1][3] = elems[5] 915 | return mat 916 | 917 | transforms = {'translate': transTranslate, 918 | 'scale': transScale, 919 | 'rotate': transRotate, 920 | 'skewX': transSkewX, 921 | 'skewY': transSkewY, 922 | 'matrix': transMatrix} 923 | 924 | def getTransformMatrix(transList): 925 | mat = Matrix() 926 | regEx = re.compile('([^\(]+)\(([^\)]+)\)') 927 | for transform in transList: 928 | results = regEx.findall(transform) 929 | if(results != None and len(results) > 0): 930 | for res in results: 931 | fnStr = res[0] 932 | elems = [float(e) for e in res[1].split(',')] 933 | fn = transforms.get(fnStr) 934 | if(fn != None): 935 | mat = fn(elems) @ mat 936 | res = regEx.search(transform) 937 | return mat 938 | 939 | def getTransformedSeg(bezierSeg, mat): 940 | pts = [] 941 | for pt in bezierSeg: 942 | pt3d = Vector((pt.real, pt.imag, 0)) 943 | pt3d = mat @ pt3d 944 | pts.append(complex(pt3d[0], pt3d[1])) 945 | return CubicBezier(*pts) 946 | 947 | #format (key, value): [(order_str, seg_cmp_fn), ...] 948 | #(Listed clockwise in the dropdown) 949 | #round-off to int as we don't want to be over-precise with the comparison... 950 | #...der Gleichheitsbedingung wird lediglich visuell geprueft werden :) 951 | def getAlignSegsFn(): 952 | return OrderedDict([ 953 | ('Top-Left', lambda x, y: ((int(x.imag) < int(y.imag)) or \ 954 | (int(x.imag) == int(y.imag) and int(x.real) < int(y.real)))), 955 | 956 | ('Top-Right', lambda x, y: ((int(x.imag) < int(y.imag)) or \ 957 | (int(x.imag) == int(y.imag) and int(x.real) > int(y.real)))), 958 | 959 | ('Right-Top', lambda x, y: ((int(x.real) > int(y.real)) or \ 960 | (int(x.real) == int(y.real) and int(x.imag) < int(y.imag)))), 961 | 962 | ('Right-Bottom', lambda x, y: ((int(x.real) > int(y.real)) or \ 963 | (int(x.real) == int(y.real) and int(x.imag) > int(y.imag)))), 964 | 965 | ('Bottom-Right', lambda x, y: ((int(x.imag) > int(y.imag)) or \ 966 | (int(x.imag) == int(y.imag) and int(x.real) > int(y.real)))), 967 | 968 | ('Bottom-left', lambda x, y: ((int(x.imag) > int(y.imag)) or \ 969 | (int(x.imag) == int(y.imag) and int(x.real) < int(y.real)))), 970 | 971 | ('Left-Bottom', lambda x, y: ((int(x.real) < int(y.real)) or \ 972 | (int(x.real) == int(y.real) and int(x.imag) > int(y.imag)))), 973 | 974 | ('Left-Top', lambda x, y: ((int(x.real) < int(y.real)) or \ 975 | (int(x.real) == int(y.real) and int(x.imag) < int(y.imag)))), 976 | ]) 977 | 978 | 979 | def getAlignPartsFn(): 980 | 981 | #Order of the list returned by bbox - Left[0,0]-bottom[0,1]-right[1,0]-top[1,1] 982 | return OrderedDict([ 983 | #Sorting in reverse order so that the bigger parts get matched first 984 | ('Node Count ', lambda part: -1 * part.getSegCnt()), 985 | 986 | ('BBox Area', lambda part: -1 * bboxArea(part.bbox())), 987 | 988 | ('BBox Height', lambda part: -1 * (part.bbox()[1][1] - part.bbox()[0][1])), 989 | 990 | ('BBox Width', lambda part: -1 * (part.bbox()[1][0] - part.bbox()[0][0])), 991 | 992 | ('BBox:Top-Left', lambda part: (part.bbox()[0][1], #Top of SVG is bottom of blender 993 | part.bbox()[0][0])), 994 | 995 | ('BBox:Top-Right', lambda part: (part.bbox()[0][1], 996 | part.bbox()[1][0])), 997 | 998 | ('BBox:Right-Top', lambda part: (part.bbox()[1][0], 999 | part.bbox()[0][1])), 1000 | 1001 | ('BBox:Right-Bottom', lambda part: (part.bbox()[1][0], 1002 | part.bbox()[1][1])), 1003 | 1004 | ('BBox:Bottom-Right', lambda part: (part.bbox()[1][1], 1005 | part.bbox()[1][0])), 1006 | 1007 | ('BBox:Bottom-left', lambda part: (part.bbox()[1][1], 1008 | part.bbox()[0][0])), 1009 | 1010 | ('BBox:Left-Bottom', lambda part: (part.bbox()[0][0], 1011 | part.bbox()[1][1])), 1012 | 1013 | ('BBox:Left-Top', lambda part: (part.bbox()[0][0], 1014 | part.bbox()[0][1])), 1015 | ]) 1016 | 1017 | def alignPath(pathElem, alignOrderSegs, partArrangeOrder): 1018 | 1019 | alignSegCmpFn = getAlignSegsFn().get(alignOrderSegs) 1020 | alignPartCmpFn = getAlignPartsFn().get(partArrangeOrder) 1021 | 1022 | parts = pathElem.parts[:] 1023 | 1024 | if(alignPartCmpFn != None): 1025 | parts = sorted(parts, key = alignPartCmpFn) 1026 | 1027 | startPt = None 1028 | startIdx = None 1029 | 1030 | for i in range(0, len(parts)): 1031 | 1032 | #Only truly closed parts 1033 | if(alignSegCmpFn != None and parts[i].isClosed): 1034 | for j in range(0, parts[i].getSegCnt()): 1035 | seg = parts[i].getSeg(j) 1036 | if(j == 0 or alignSegCmpFn(seg.start, startPt)): 1037 | startPt = seg.start 1038 | startIdx = j 1039 | pathElem.parts[i]= Part(parts[i].getSegsCopy(startIdx, None) + \ 1040 | parts[i].getSegsCopy(None, startIdx), parts[i].isClosed) 1041 | else: 1042 | pathElem.parts[i] = parts[i] 1043 | 1044 | #Convert all segments to cubic bezier and apply transforms 1045 | def toTransformedCBezier(pathElem): 1046 | for i in range(0, len(pathElem.parts)): 1047 | part = pathElem.parts[i] 1048 | newPartSegs = [] 1049 | 1050 | for seg in part.getSegs(): 1051 | 1052 | if(type(seg).__name__ is 'Line'): 1053 | newPartSegs.append(CubicBezier(seg[0], seg[0], seg[1], seg[1])) 1054 | 1055 | elif(type(seg).__name__ is 'QuadraticBezier'): 1056 | cp0 = seg[0] 1057 | cp3 = seg[2] 1058 | 1059 | cp1 = seg[0] + 2/3 *(seg[1]-seg[0]) 1060 | cp2 = seg[2] + 2/3 *(seg[1]-seg[2]) 1061 | 1062 | newPartSegs.append(CubicBezier(cp0, cp1, cp2, cp3)) 1063 | 1064 | elif(type(seg).__name__ is 'Arc'): 1065 | x1, y1 = seg.start.real, seg.start.imag 1066 | x2, y2 = seg.end.real, seg.end.imag 1067 | fa = seg.large_arc 1068 | fs = seg.sweep 1069 | rx, ry = seg.radius.real, seg.radius.imag 1070 | phi = seg.rotation 1071 | curvesPts = a2c(x1, y1, x2, y2, fa, fs, rx, ry, phi) 1072 | 1073 | for curvePts in curvesPts: 1074 | newPartSegs.append(CubicBezier(curvePts[0], curvePts[1], 1075 | curvePts[2], curvePts[3])) 1076 | 1077 | elif(type(seg).__name__ is 'CubicBezier'): 1078 | newPartSegs.append(seg) 1079 | 1080 | else: 1081 | print('Strange! Never thought of this.', type(seg).__name__) 1082 | # ~ assert False #nope.. let's continue for now 1083 | continue 1084 | 1085 | if(len(pathElem.transList) > 0): 1086 | mat = getTransformMatrix(pathElem.transList) 1087 | newPartSegs = [getTransformedSeg(seg, mat) for seg in newPartSegs] 1088 | 1089 | pathElem.parts[i] = Part(newPartSegs, part.isClosed) 1090 | 1091 | #Paths must have already been homogenized 1092 | def addShapeKey(targetCurve, shapeKeyElem, shapeKeyName, scale, zVal, originToGeometry): 1093 | splineData = getSplineDataForPath(shapeKeyElem, scale, zVal) 1094 | 1095 | offsetLocation = Vector([0,0,0]) 1096 | if(originToGeometry == True): 1097 | offsetLocation = targetCurve.location 1098 | 1099 | key = targetCurve.shape_key_add(name = shapeKeyName) 1100 | 1101 | i = 0 1102 | for ptSet in splineData: 1103 | for bezierPt in ptSet: 1104 | co = Vector(get3DPt(bezierPt.pt, scale, zVal)) - offsetLocation 1105 | handleLeft = Vector(get3DPt(bezierPt.handleLeft, scale, zVal)) - offsetLocation 1106 | handleRight = Vector(get3DPt(bezierPt.handleRight, scale, zVal)) - offsetLocation 1107 | 1108 | key.data[i].co = co 1109 | key.data[i].handle_left = handleLeft 1110 | key.data[i].handle_right = handleRight 1111 | 1112 | i += 1 1113 | 1114 | def get3DPt(point, scale, zVal): 1115 | return [point.real * scale[0], point.imag * scale[1], zVal * scale[2]] 1116 | 1117 | #All segments must have already been converted to cubic bezier 1118 | def addSvg2Blender(group, objMap, pathElem, scale, zVal, copyObj, originToGeometry): 1119 | 1120 | pathId = pathElem.pathId 1121 | splineData = getSplineDataForPath(pathElem, scale, zVal) 1122 | 1123 | curveName = CURVE_NAME_PREFIX + str(pathElem.seqId).zfill(5) 1124 | obj = createCurveFromData(group, curveName, splineData, copyObj, pathElem, 1125 | originToGeometry, scale, zVal) 1126 | 1127 | objMap[pathId] = obj 1128 | 1129 | def createCurveFromData(group, curveName, splineData, copyObj, pathElem, 1130 | originToGeometry, scale, zVal): 1131 | 1132 | curveData = getNewCurveData(bpy, splineData, copyObj, pathElem, scale, zVal) 1133 | obj = bpy.data.objects.new(curveName, curveData) 1134 | # ~ bpy.context.scene.collection.objects.link(obj) 1135 | group.objects.link(obj) 1136 | 1137 | if(originToGeometry == True): 1138 | obj.select_set(True) 1139 | bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='BOUNDS') 1140 | 1141 | return obj 1142 | 1143 | def copySrcObjProps(copyObj, newCurveData): 1144 | 1145 | #Copying just a few attributes 1146 | copyObjData = copyObj.data 1147 | 1148 | newCurveData.dimensions = copyObjData.dimensions 1149 | 1150 | newCurveData.resolution_u = copyObjData.resolution_u 1151 | newCurveData.render_resolution_u = copyObjData.render_resolution_u 1152 | newCurveData.fill_mode = copyObjData.fill_mode 1153 | 1154 | newCurveData.use_fill_deform = copyObjData.use_fill_deform 1155 | newCurveData.use_radius = copyObjData.use_radius 1156 | newCurveData.use_stretch = copyObjData.use_stretch 1157 | newCurveData.use_deform_bounds = copyObjData.use_deform_bounds 1158 | 1159 | newCurveData.twist_smooth = copyObjData.twist_smooth 1160 | newCurveData.twist_mode = copyObjData.twist_mode 1161 | 1162 | newCurveData.offset = copyObjData.offset 1163 | newCurveData.extrude = copyObjData.extrude 1164 | newCurveData.bevel_depth = copyObjData.bevel_depth 1165 | newCurveData.bevel_resolution = copyObjData.bevel_resolution 1166 | 1167 | for material in copyObjData.materials: 1168 | newCurveData.materials.append(material) 1169 | 1170 | 1171 | def getNewCurveData(bpy, splinesData, copyObj, pathElem, scale, zVal): 1172 | 1173 | newCurveData = bpy.data.curves.new(pathElem.pathId, 'CURVE') 1174 | if(copyObj != None): 1175 | copySrcObjProps(copyObj, newCurveData) 1176 | #Copying won't work, params set from too many places 1177 | # ~ newCurveData = copyObj.data.copy() 1178 | # ~ newCurveData.splines.clear() 1179 | # ~ newCurveData.animation_data_clear() 1180 | else: 1181 | newCurveData.dimensions = '3D' 1182 | 1183 | 1184 | for i, pointSets in enumerate(splinesData): 1185 | spline = newCurveData.splines.new('BEZIER') 1186 | spline.bezier_points.add(len(pointSets)-1) 1187 | spline.use_cyclic_u = pathElem.parts[i].partToClose 1188 | 1189 | for j in range(0, len(spline.bezier_points)): 1190 | pointSet = pointSets[j] 1191 | spline.bezier_points[j].co = get3DPt(pointSet.pt, scale, zVal) 1192 | spline.bezier_points[j].handle_left = get3DPt(pointSet.handleLeft, scale, zVal) 1193 | spline.bezier_points[j].handle_right = get3DPt(pointSet.handleRight, scale, zVal) 1194 | spline.bezier_points[j].handle_right_type = 'FREE' 1195 | 1196 | return newCurveData 1197 | 1198 | def getSplineDataForPath(pathElem, scale = None, zVal = None): 1199 | splinesData = [] 1200 | 1201 | for i, part in enumerate(pathElem.parts): 1202 | prevSeg = None 1203 | pointSets = [] 1204 | 1205 | for j, seg in enumerate(part.getSegs()): 1206 | 1207 | pt = seg.start 1208 | handleRight = seg.control1 1209 | 1210 | if(j == 0): 1211 | if(pathElem.parts[i].partToClose): 1212 | handleLeft = part.getSeg(-1).control2 1213 | else: 1214 | handleLeft = pt 1215 | else: 1216 | handleLeft = prevSeg.control2 1217 | 1218 | pointSets.append(BlenderBezierPoint(pt, handleLeft = handleLeft, 1219 | handleRight = handleRight)) 1220 | prevSeg = seg 1221 | 1222 | if(pathElem.parts[i].partToClose == True): 1223 | pointSets[-1].handleRight = seg.control1 1224 | else: 1225 | pointSets.append(BlenderBezierPoint(prevSeg.end, 1226 | handleLeft = prevSeg.control2, handleRight = prevSeg.end)) 1227 | 1228 | splinesData.append(pointSets) 1229 | 1230 | return splinesData 1231 | 1232 | 1233 | ###################### addon code end #################### 1234 | 1235 | # 1236 | # The following section is a Python conversion of the javascript 1237 | # a2c function at: https://github.com/fontello/svgpath 1238 | # (Copyright (C) 2013-2015 by Vitaly Puzrin) 1239 | # 1240 | ######################## a2c start ####################### 1241 | 1242 | TAU = math.pi * 2 1243 | 1244 | # eslint-disable space-infix-ops 1245 | 1246 | # Calculate an angle between two unit vectors 1247 | # 1248 | # Since we measure angle between radii of circular arcs, 1249 | # we can use simplified math (without length normalization) 1250 | # 1251 | def unit_vector_angle(ux, uy, vx, vy): 1252 | if(ux * vy - uy * vx < 0): 1253 | sign = -1 1254 | else: 1255 | sign = 1 1256 | 1257 | dot = ux * vx + uy * vy 1258 | 1259 | # Add this to work with arbitrary vectors: 1260 | # dot /= math.sqrt(ux * ux + uy * uy) * math.sqrt(vx * vx + vy * vy) 1261 | 1262 | # rounding errors, e.g. -1.0000000000000002 can screw up this 1263 | if (dot > 1.0): 1264 | dot = 1.0 1265 | 1266 | if (dot < -1.0): 1267 | dot = -1.0 1268 | 1269 | return sign * math.acos(dot) 1270 | 1271 | 1272 | # Convert from endpoint to center parameterization, 1273 | # see http:#www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes 1274 | # 1275 | # Return [cx, cy, theta1, delta_theta] 1276 | # 1277 | def get_arc_center(x1, y1, x2, y2, fa, fs, rx, ry, sin_phi, cos_phi): 1278 | # Step 1. 1279 | # 1280 | # Moving an ellipse so origin will be the middlepoint between our two 1281 | # points. After that, rotate it to line up ellipse axes with coordinate 1282 | # axes. 1283 | # 1284 | x1p = cos_phi*(x1-x2)/2 + sin_phi*(y1-y2)/2 1285 | y1p = -sin_phi*(x1-x2)/2 + cos_phi*(y1-y2)/2 1286 | 1287 | rx_sq = rx * rx 1288 | ry_sq = ry * ry 1289 | x1p_sq = x1p * x1p 1290 | y1p_sq = y1p * y1p 1291 | 1292 | # Step 2. 1293 | # 1294 | # Compute coordinates of the centre of this ellipse (cx', cy') 1295 | # in the new coordinate system. 1296 | # 1297 | radicant = (rx_sq * ry_sq) - (rx_sq * y1p_sq) - (ry_sq * x1p_sq) 1298 | 1299 | if (radicant < 0): 1300 | # due to rounding errors it might be e.g. -1.3877787807814457e-17 1301 | radicant = 0 1302 | 1303 | radicant /= (rx_sq * y1p_sq) + (ry_sq * x1p_sq) 1304 | factor = 1 1305 | if(fa == fs):# Migration Note: note === 1306 | factor = -1 1307 | radicant = math.sqrt(radicant) * factor #(fa === fs ? -1 : 1) 1308 | 1309 | cxp = radicant * rx/ry * y1p 1310 | cyp = radicant * -ry/rx * x1p 1311 | 1312 | # Step 3. 1313 | # 1314 | # Transform back to get centre coordinates (cx, cy) in the original 1315 | # coordinate system. 1316 | # 1317 | cx = cos_phi*cxp - sin_phi*cyp + (x1+x2)/2 1318 | cy = sin_phi*cxp + cos_phi*cyp + (y1+y2)/2 1319 | 1320 | # Step 4. 1321 | # 1322 | # Compute angles (theta1, delta_theta). 1323 | # 1324 | v1x = (x1p - cxp) / rx 1325 | v1y = (y1p - cyp) / ry 1326 | v2x = (-x1p - cxp) / rx 1327 | v2y = (-y1p - cyp) / ry 1328 | 1329 | theta1 = unit_vector_angle(1, 0, v1x, v1y) 1330 | delta_theta = unit_vector_angle(v1x, v1y, v2x, v2y) 1331 | 1332 | if (fs == 0 and delta_theta > 0):#Migration Note: note === 1333 | delta_theta -= TAU 1334 | 1335 | if (fs == 1 and delta_theta < 0):#Migration Note: note === 1336 | delta_theta += TAU 1337 | 1338 | return [ cx, cy, theta1, delta_theta ] 1339 | 1340 | # 1341 | # Approximate one unit arc segment with bezier curves, 1342 | # see http:#math.stackexchange.com/questions/873224 1343 | # 1344 | def approximate_unit_arc(theta1, delta_theta): 1345 | alpha = 4.0/3 * math.tan(delta_theta/4) 1346 | 1347 | x1 = math.cos(theta1) 1348 | y1 = math.sin(theta1) 1349 | x2 = math.cos(theta1 + delta_theta) 1350 | y2 = math.sin(theta1 + delta_theta) 1351 | 1352 | return [ x1, y1, x1 - y1*alpha, y1 + x1*alpha, x2 + y2*alpha, y2 - x2*alpha, x2, y2 ] 1353 | 1354 | def a2c(x1, y1, x2, y2, fa, fs, rx, ry, phi): 1355 | sin_phi = math.sin(phi * TAU / 360) 1356 | cos_phi = math.cos(phi * TAU / 360) 1357 | 1358 | # Make sure radii are valid 1359 | # 1360 | x1p = cos_phi*(x1-x2)/2 + sin_phi*(y1-y2)/2 1361 | y1p = -sin_phi*(x1-x2)/2 + cos_phi*(y1-y2)/2 1362 | 1363 | if (x1p == 0 and y1p == 0): # Migration Note: note === 1364 | # we're asked to draw line to itself 1365 | return [] 1366 | 1367 | if (rx == 0 or ry == 0): # Migration Note: note === 1368 | # one of the radii is zero 1369 | return [] 1370 | 1371 | # Compensate out-of-range radii 1372 | # 1373 | rx = abs(rx) 1374 | ry = abs(ry) 1375 | 1376 | lmbd = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry) 1377 | if (lmbd > 1): 1378 | rx *= math.sqrt(lmbd) 1379 | ry *= math.sqrt(lmbd) 1380 | 1381 | 1382 | # Get center parameters (cx, cy, theta1, delta_theta) 1383 | # 1384 | cc = get_arc_center(x1, y1, x2, y2, fa, fs, rx, ry, sin_phi, cos_phi) 1385 | 1386 | result = [] 1387 | theta1 = cc[2] 1388 | delta_theta = cc[3] 1389 | 1390 | # Split an arc to multiple segments, so each segment 1391 | # will be less than 90 1392 | # 1393 | segments = int(max(math.ceil(abs(delta_theta) / (TAU / 4)), 1)) 1394 | delta_theta /= segments 1395 | 1396 | for i in range(0, segments): 1397 | result.append(approximate_unit_arc(theta1, delta_theta)) 1398 | 1399 | theta1 += delta_theta 1400 | 1401 | # We have a bezier approximation of a unit circle, 1402 | # now need to transform back to the original ellipse 1403 | # 1404 | return getMappedList(result, rx, ry, sin_phi, cos_phi, cc) 1405 | 1406 | def getMappedList(result, rx, ry, sin_phi, cos_phi, cc): 1407 | mappedList = [] 1408 | for elem in result: 1409 | curve = [] 1410 | for i in range(0, len(elem), 2): 1411 | x = elem[i + 0] 1412 | y = elem[i + 1] 1413 | 1414 | # scale 1415 | x *= rx 1416 | y *= ry 1417 | 1418 | # rotate 1419 | xp = cos_phi*x - sin_phi*y 1420 | yp = sin_phi*x + cos_phi*y 1421 | 1422 | # translate 1423 | elem[i + 0] = xp + cc[0] 1424 | elem[i + 1] = yp + cc[1] 1425 | curve.append(complex(elem[i + 0], elem[i + 1])) 1426 | mappedList.append(curve) 1427 | return mappedList 1428 | 1429 | ######################### a2c end ######################## 1430 | 1431 | 1432 | # 1433 | # The following section is an extract 1434 | # from svgpathtools (https://github.com/mathandy/svgpathtools) 1435 | # (Copyright (c) 2015 Andrew Allan Port, Copyright (c) 2013-2014 Lennart Regebro) 1436 | # 1437 | # Changes are mde to maintain which of the disconnected parts are closed (isClosing) 1438 | # and floating point comparison in parse_path is changed to have tolerance 1439 | # 1440 | # Many explanatory comments are excluded 1441 | # 1442 | #################### svgpathtools start ################### 1443 | 1444 | LENGTH_MIN_DEPTH = 5 1445 | 1446 | LENGTH_ERROR = 1e-12 1447 | 1448 | COMMANDS = set('MmZzLlHhVvCcSsQqTtAa') 1449 | UPPERCASE = set('MZLHVCSQTA') 1450 | 1451 | COMMAND_RE = re.compile("([MmZzLlHhVvCcSsQqTtAa])") 1452 | FLOAT_RE = re.compile("[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?") 1453 | 1454 | def _tokenize_path(pathdef): 1455 | for x in COMMAND_RE.split(pathdef): 1456 | if x in COMMANDS: 1457 | yield x 1458 | for token in FLOAT_RE.findall(x): 1459 | yield token 1460 | 1461 | 1462 | def parse_path(pathdef, current_pos=0j): 1463 | # In the SVG specs, initial movetos are absolute, even if 1464 | # specified as 'm'. This is the default behavior here as well. 1465 | # But if you pass in a current_pos variable, the initial moveto 1466 | # will be relative to that current_pos. This is useful. 1467 | elements = list(_tokenize_path(pathdef)) 1468 | # Reverse for easy use of .pop() 1469 | elements.reverse() 1470 | 1471 | segments = Path() 1472 | start_pos = None 1473 | command = None 1474 | 1475 | while elements: 1476 | 1477 | if elements[-1] in COMMANDS: 1478 | # New command. 1479 | last_command = command # Used by S and T 1480 | command = elements.pop() 1481 | absolute = command in UPPERCASE 1482 | command = command.upper() 1483 | else: 1484 | # If this element starts with numbers, it is an implicit command 1485 | # and we don't change the command. Check that it's allowed: 1486 | if command is None: 1487 | raise ValueError("Unallowed implicit command in %s, position %s" % ( 1488 | pathdef, len(pathdef.split()) - len(elements))) 1489 | 1490 | if command == 'M': 1491 | # Moveto command. 1492 | x = elements.pop() 1493 | y = elements.pop() 1494 | pos = float(x) + float(y) * 1j 1495 | if absolute: 1496 | current_pos = pos 1497 | else: 1498 | current_pos += pos 1499 | 1500 | # when M is called, reset start_pos 1501 | # This behavior of Z is defined in svg spec: 1502 | # http://www.w3.org/TR/SVG/paths.html#PathDataClosePathCommand 1503 | start_pos = current_pos 1504 | 1505 | # Implicit moveto commands are treated as lineto commands. 1506 | # So we set command to lineto here, in case there are 1507 | # further implicit commands after this moveto. 1508 | command = 'L' 1509 | 1510 | elif command == 'Z': 1511 | # Close path 1512 | if not (cmplxCmpWithMargin(current_pos, start_pos)): #For Shape key import 1513 | #~ if not (current_pos == start_pos): 1514 | segments.append(Line(current_pos, start_pos)) 1515 | segments[-1].isClosing = True #For Shape key import 1516 | segments.closed = True 1517 | current_pos = start_pos 1518 | start_pos = None 1519 | command = None # You can't have implicit commands after closing. 1520 | 1521 | elif command == 'L': 1522 | x = elements.pop() 1523 | y = elements.pop() 1524 | pos = float(x) + float(y) * 1j 1525 | if not absolute: 1526 | pos += current_pos 1527 | segments.append(Line(current_pos, pos)) 1528 | current_pos = pos 1529 | 1530 | elif command == 'H': 1531 | x = elements.pop() 1532 | pos = float(x) + current_pos.imag * 1j 1533 | if not absolute: 1534 | pos += current_pos.real 1535 | segments.append(Line(current_pos, pos)) 1536 | current_pos = pos 1537 | 1538 | elif command == 'V': 1539 | y = elements.pop() 1540 | pos = current_pos.real + float(y) * 1j 1541 | if not absolute: 1542 | pos += current_pos.imag * 1j 1543 | segments.append(Line(current_pos, pos)) 1544 | current_pos = pos 1545 | 1546 | elif command == 'C': 1547 | control1 = float(elements.pop()) + float(elements.pop()) * 1j 1548 | control2 = float(elements.pop()) + float(elements.pop()) * 1j 1549 | end = float(elements.pop()) + float(elements.pop()) * 1j 1550 | 1551 | if not absolute: 1552 | control1 += current_pos 1553 | control2 += current_pos 1554 | end += current_pos 1555 | 1556 | segments.append(CubicBezier(current_pos, control1, control2, end)) 1557 | current_pos = end 1558 | 1559 | elif command == 'S': 1560 | # Smooth curve. First control point is the "reflection" of 1561 | # the second control point in the previous path. 1562 | 1563 | if last_command not in 'CS': 1564 | # If there is no previous command or if the previous command 1565 | # was not an C, c, S or s, assume the first control point is 1566 | # coincident with the current point. 1567 | control1 = current_pos 1568 | else: 1569 | # The first control point is assumed to be the reflection of 1570 | # the second control point on the previous command relative 1571 | # to the current point. 1572 | control1 = current_pos + current_pos - segments[-1].control2 1573 | 1574 | control2 = float(elements.pop()) + float(elements.pop()) * 1j 1575 | end = float(elements.pop()) + float(elements.pop()) * 1j 1576 | 1577 | if not absolute: 1578 | control2 += current_pos 1579 | end += current_pos 1580 | 1581 | segments.append(CubicBezier(current_pos, control1, control2, end)) 1582 | current_pos = end 1583 | 1584 | elif command == 'Q': 1585 | control = float(elements.pop()) + float(elements.pop()) * 1j 1586 | end = float(elements.pop()) + float(elements.pop()) * 1j 1587 | 1588 | if not absolute: 1589 | control += current_pos 1590 | end += current_pos 1591 | 1592 | segments.append(QuadraticBezier(current_pos, control, end)) 1593 | current_pos = end 1594 | 1595 | elif command == 'T': 1596 | # Smooth curve. Control point is the "reflection" of 1597 | # the second control point in the previous path. 1598 | 1599 | if last_command not in 'QT': 1600 | # If there is no previous command or if the previous command 1601 | # was not an Q, q, T or t, assume the first control point is 1602 | # coincident with the current point. 1603 | control = current_pos 1604 | else: 1605 | # The control point is assumed to be the reflection of 1606 | # the control point on the previous command relative 1607 | # to the current point. 1608 | control = current_pos + current_pos - segments[-1].control 1609 | 1610 | end = float(elements.pop()) + float(elements.pop()) * 1j 1611 | 1612 | if not absolute: 1613 | end += current_pos 1614 | 1615 | segments.append(QuadraticBezier(current_pos, control, end)) 1616 | current_pos = end 1617 | 1618 | elif command == 'A': 1619 | radius = float(elements.pop()) + float(elements.pop()) * 1j 1620 | rotation = float(elements.pop()) 1621 | arc = float(elements.pop()) 1622 | sweep = float(elements.pop()) 1623 | end = float(elements.pop()) + float(elements.pop()) * 1j 1624 | 1625 | if not absolute: 1626 | end += current_pos 1627 | 1628 | segments.append(Arc(current_pos, radius, rotation, arc, sweep, end)) 1629 | current_pos = end 1630 | 1631 | return segments 1632 | 1633 | def segment_length(curve, start, end, start_point, end_point, 1634 | error=LENGTH_ERROR, min_depth=LENGTH_MIN_DEPTH, depth=0): 1635 | 1636 | mid = (start + end)/2 1637 | mid_point = curve.point(mid) 1638 | length = abs(end_point - start_point) 1639 | first_half = abs(mid_point - start_point) 1640 | second_half = abs(end_point - mid_point) 1641 | 1642 | length2 = first_half + second_half 1643 | if (length2 - length > error) or (depth < min_depth): 1644 | depth += 1 1645 | return (segment_length(curve, start, mid, start_point, mid_point, 1646 | error, min_depth, depth) + 1647 | segment_length(curve, mid, end, mid_point, end_point, 1648 | error, min_depth, depth)) 1649 | return length2 1650 | 1651 | 1652 | class Line(object): 1653 | def __init__(self, start, end): 1654 | self.start = start 1655 | self.end = end 1656 | self.isClosing = False #For Shape key import 1657 | 1658 | def __repr__(self): 1659 | return 'Line(start=%s, end=%s)' % (self.start, self.end) 1660 | 1661 | def __eq__(self, other): 1662 | if not isinstance(other, Line): 1663 | return NotImplemented 1664 | return self.start == other.start and self.end == other.end 1665 | 1666 | def __ne__(self, other): 1667 | if not isinstance(other, Line): 1668 | return NotImplemented 1669 | return not self == other 1670 | 1671 | def __getitem__(self, item): 1672 | return self.bpoints()[item] 1673 | 1674 | def __len__(self): 1675 | return 2 1676 | 1677 | def bpoints(self): 1678 | return self.start, self.end 1679 | 1680 | def length(self, t0=0, t1=1, error=None, min_depth=None): 1681 | """returns the length of the line segment between t0 and t1.""" 1682 | return abs(self.end - self.start)*(t1-t0) 1683 | 1684 | 1685 | class QuadraticBezier(object): 1686 | def __init__(self, start, control, end): 1687 | self.start = start 1688 | self.end = end 1689 | self.control = control 1690 | 1691 | self._length_info = {'length': None, 'bpoints': None} 1692 | self.isClosing = False #For Shape key import 1693 | 1694 | def __repr__(self): 1695 | return 'QuadraticBezier(start=%s, control=%s, end=%s)' % ( 1696 | self.start, self.control, self.end) 1697 | 1698 | def __eq__(self, other): 1699 | if not isinstance(other, QuadraticBezier): 1700 | return NotImplemented 1701 | return self.start == other.start and self.end == other.end \ 1702 | and self.control == other.control 1703 | 1704 | def __ne__(self, other): 1705 | if not isinstance(other, QuadraticBezier): 1706 | return NotImplemented 1707 | return not self == other 1708 | 1709 | def __getitem__(self, item): 1710 | return self.bpoints()[item] 1711 | 1712 | def __len__(self): 1713 | return 3 1714 | 1715 | def bpoints(self): 1716 | return self.start, self.control, self.end 1717 | 1718 | class CubicBezier(object): 1719 | _length_info = {'length': None, 'bpoints': None, 'error': None, 1720 | 'min_depth': None} 1721 | 1722 | def __init__(self, start, control1, control2, end): 1723 | self.start = start 1724 | self.control1 = control1 1725 | self.control2 = control2 1726 | self.end = end 1727 | 1728 | self._length_info = {'length': None, 'bpoints': None, 'error': None, 1729 | 'min_depth': None} 1730 | self.isClosing = False #For Shape key import 1731 | 1732 | def __repr__(self): 1733 | return 'CubicBezier(start=%s, control1=%s, control2=%s, end=%s)' % ( 1734 | self.start, self.control1, self.control2, self.end) 1735 | 1736 | def __eq__(self, other): 1737 | if not isinstance(other, CubicBezier): 1738 | return NotImplemented 1739 | return self.start == other.start and self.end == other.end \ 1740 | and self.control1 == other.control1 \ 1741 | and self.control2 == other.control2 1742 | 1743 | def __ne__(self, other): 1744 | if not isinstance(other, CubicBezier): 1745 | return NotImplemented 1746 | return not self == other 1747 | 1748 | def __getitem__(self, item): 1749 | return self.bpoints()[item] 1750 | 1751 | def __len__(self): 1752 | return 4 1753 | 1754 | def bpoints(self): 1755 | return self.start, self.control1, self.control2, self.end 1756 | 1757 | def length(self, t0=0, t1=1, error=LENGTH_ERROR, min_depth=LENGTH_MIN_DEPTH): 1758 | if t0 == 0 and t1 == 1: 1759 | if self._length_info['bpoints'] == self.bpoints() \ 1760 | and self._length_info['error'] >= error \ 1761 | and self._length_info['min_depth'] >= min_depth: 1762 | return self._length_info['length'] 1763 | 1764 | s = segment_length(self, t0, t1, self.point(t0), self.point(t1), 1765 | error, min_depth, 0) 1766 | 1767 | if t0 == 0 and t1 == 1: 1768 | self._length_info['length'] = s 1769 | self._length_info['bpoints'] = self.bpoints() 1770 | self._length_info['error'] = error 1771 | self._length_info['min_depth'] = min_depth 1772 | return self._length_info['length'] 1773 | else: 1774 | return s 1775 | 1776 | def point(self, t): 1777 | return self.start + t*( 1778 | 3*(self.control1 - self.start) + t*( 1779 | 3*(self.start + self.control2) - 6*self.control1 + t*( 1780 | -self.start + 3*(self.control1 - self.control2) + self.end 1781 | ))) 1782 | 1783 | class Arc(object): 1784 | def __init__(self, start, radius, rotation, large_arc, sweep, end, 1785 | autoscale_radius=True): 1786 | assert start != end 1787 | assert radius.real != 0 and radius.imag != 0 1788 | 1789 | self.start = start 1790 | self.radius = abs(radius.real) + 1j*abs(radius.imag) 1791 | self.rotation = rotation 1792 | self.large_arc = bool(large_arc) 1793 | self.sweep = bool(sweep) 1794 | self.end = end 1795 | self.autoscale_radius = autoscale_radius 1796 | 1797 | self.phi = radians(self.rotation) 1798 | self.rot_matrix = exp(1j*self.phi) 1799 | 1800 | self._parameterize() 1801 | self.isClosing = False #For Shape key import 1802 | 1803 | def __repr__(self): 1804 | params = (self.start, self.radius, self.rotation, 1805 | self.large_arc, self.sweep, self.end) 1806 | return ("Arc(start={}, radius={}, rotation={}, " 1807 | "large_arc={}, sweep={}, end={})".format(*params)) 1808 | 1809 | def __eq__(self, other): 1810 | if not isinstance(other, Arc): 1811 | return NotImplemented 1812 | return self.start == other.start and self.end == other.end \ 1813 | and self.radius == other.radius \ 1814 | and self.rotation == other.rotation \ 1815 | and self.large_arc == other.large_arc and self.sweep == other.sweep 1816 | 1817 | def __ne__(self, other): 1818 | if not isinstance(other, Arc): 1819 | return NotImplemented 1820 | return not self == other 1821 | 1822 | def _parameterize(self): 1823 | rx = self.radius.real 1824 | ry = self.radius.imag 1825 | rx_sqd = rx*rx 1826 | ry_sqd = ry*ry 1827 | 1828 | zp1 = (1/self.rot_matrix)*(self.start - self.end)/2 1829 | x1p, y1p = zp1.real, zp1.imag 1830 | x1p_sqd = x1p*x1p 1831 | y1p_sqd = y1p*y1p 1832 | 1833 | radius_check = (x1p_sqd/rx_sqd) + (y1p_sqd/ry_sqd) 1834 | if radius_check > 1: 1835 | if self.autoscale_radius: 1836 | rx *= sqrt(radius_check) 1837 | ry *= sqrt(radius_check) 1838 | self.radius = rx + 1j*ry 1839 | rx_sqd = rx*rx 1840 | ry_sqd = ry*ry 1841 | else: 1842 | raise ValueError("No such elliptic arc exists.") 1843 | 1844 | tmp = rx_sqd*y1p_sqd + ry_sqd*x1p_sqd 1845 | radicand = (rx_sqd*ry_sqd - tmp) / tmp 1846 | try: 1847 | radical = sqrt(radicand) 1848 | except ValueError: 1849 | radical = 0 1850 | if self.large_arc == self.sweep: 1851 | cp = -radical*(rx*y1p/ry - 1j*ry*x1p/rx) 1852 | else: 1853 | cp = radical*(rx*y1p/ry - 1j*ry*x1p/rx) 1854 | 1855 | self.center = exp(1j*self.phi)*cp + (self.start + self.end)/2 1856 | 1857 | u1 = (x1p - cp.real)/rx + 1j*(y1p - cp.imag)/ry # transformed start 1858 | u2 = (-x1p - cp.real)/rx + 1j*(-y1p - cp.imag)/ry # transformed end 1859 | 1860 | u1_real_rounded = u1.real 1861 | if u1.real > 1 or u1.real < -1: 1862 | u1_real_rounded = round(u1.real) 1863 | if u1.imag > 0: 1864 | self.theta = degrees(acos(u1_real_rounded)) 1865 | elif u1.imag < 0: 1866 | self.theta = -degrees(acos(u1_real_rounded)) 1867 | else: 1868 | if u1.real > 0: # start is on pos u_x axis 1869 | self.theta = 0 1870 | else: # start is on neg u_x axis 1871 | self.theta = 180 1872 | 1873 | det_uv = u1.real*u2.imag - u1.imag*u2.real 1874 | 1875 | acosand = u1.real*u2.real + u1.imag*u2.imag 1876 | if acosand > 1 or acosand < -1: 1877 | acosand = round(acosand) 1878 | if det_uv > 0: 1879 | self.delta = degrees(acos(acosand)) 1880 | elif det_uv < 0: 1881 | self.delta = -degrees(acos(acosand)) 1882 | else: 1883 | if u1.real*u2.real + u1.imag*u2.imag > 0: 1884 | # u1 == u2 1885 | self.delta = 0 1886 | else: 1887 | # u1 == -u2 1888 | self.delta = 180 1889 | 1890 | if not self.sweep and self.delta >= 0: 1891 | self.delta -= 360 1892 | elif self.large_arc and self.delta <= 0: 1893 | self.delta += 360 1894 | 1895 | class Path(MutableSequence): 1896 | 1897 | _closed = False 1898 | _start = None 1899 | _end = None 1900 | 1901 | def __init__(self, *segments, **kw): 1902 | self._segments = list(segments) 1903 | self._length = None 1904 | self._lengths = None 1905 | if 'closed' in kw: 1906 | self.closed = kw['closed'] # DEPRECATED 1907 | if self._segments: 1908 | self._start = self._segments[0].start 1909 | self._end = self._segments[-1].end 1910 | else: 1911 | self._start = None 1912 | self._end = None 1913 | 1914 | def __getitem__(self, index): 1915 | return self._segments[index] 1916 | 1917 | def __setitem__(self, index, value): 1918 | self._segments[index] = value 1919 | self._length = None 1920 | self._start = self._segments[0].start 1921 | self._end = self._segments[-1].end 1922 | 1923 | def __delitem__(self, index): 1924 | del self._segments[index] 1925 | self._length = None 1926 | self._start = self._segments[0].start 1927 | self._end = self._segments[-1].end 1928 | 1929 | def __iter__(self): 1930 | return self._segments.__iter__() 1931 | 1932 | def __contains__(self, x): 1933 | return self._segments.__contains__(x) 1934 | 1935 | def insert(self, index, value): 1936 | self._segments.insert(index, value) 1937 | self._length = None 1938 | self._start = self._segments[0].start 1939 | self._end = self._segments[-1].end 1940 | 1941 | def reversed(self): 1942 | newpath = [seg.reversed() for seg in self] 1943 | newpath.reverse() 1944 | return Path(*newpath) 1945 | 1946 | def __len__(self): 1947 | return len(self._segments) 1948 | 1949 | def __repr__(self): 1950 | return "Path({})".format( 1951 | ",\n ".join(repr(x) for x in self._segments)) 1952 | 1953 | def __eq__(self, other): 1954 | if not isinstance(other, Path): 1955 | return NotImplemented 1956 | if len(self) != len(other): 1957 | return False 1958 | for s, o in zip(self._segments, other._segments): 1959 | if not s == o: 1960 | return False 1961 | return True 1962 | 1963 | def __ne__(self, other): 1964 | if not isinstance(other, Path): 1965 | return NotImplemented 1966 | return not self == other 1967 | 1968 | def _calc_lengths(self, error=LENGTH_ERROR, min_depth=LENGTH_MIN_DEPTH): 1969 | if self._length is not None: 1970 | return 1971 | 1972 | lengths = [each.length(error=error, min_depth=min_depth) for each in 1973 | self._segments] 1974 | self._length = sum(lengths) 1975 | self._lengths = [each/self._length for each in lengths] 1976 | 1977 | def length(self, T0=0, T1=1, error=LENGTH_ERROR, min_depth=LENGTH_MIN_DEPTH): 1978 | self._calc_lengths(error=error, min_depth=min_depth) 1979 | if T0 == 0 and T1 == 1: 1980 | return self._length 1981 | else: 1982 | if len(self) == 1: 1983 | return self[0].length(t0=T0, t1=T1) 1984 | idx0, t0 = self.T2t(T0) 1985 | idx1, t1 = self.T2t(T1) 1986 | if idx0 == idx1: 1987 | return self[idx0].length(t0=t0, t1=t1) 1988 | return (self[idx0].length(t0=t0) + 1989 | sum(self[idx].length() for idx in range(idx0 + 1, idx1)) + 1990 | self[idx1].length(t1=t1)) 1991 | 1992 | @property 1993 | def start(self): 1994 | if not self._start: 1995 | self._start = self._segments[0].start 1996 | return self._start 1997 | 1998 | @start.setter 1999 | def start(self, pt): 2000 | self._start = pt 2001 | self._segments[0].start = pt 2002 | 2003 | @property 2004 | def end(self): 2005 | if not self._end: 2006 | self._end = self._segments[-1].end 2007 | return self._end 2008 | 2009 | @end.setter 2010 | def end(self, pt): 2011 | self._end = pt 2012 | self._segments[-1].end = pt 2013 | 2014 | def d(self, useSandT=False, use_closed_attrib=False): 2015 | 2016 | if use_closed_attrib: 2017 | self_closed = self.closed(warning_on=False) 2018 | if self_closed: 2019 | segments = self[:-1] 2020 | else: 2021 | segments = self[:] 2022 | else: 2023 | self_closed = False 2024 | segments = self[:] 2025 | 2026 | current_pos = None 2027 | parts = [] 2028 | previous_segment = None 2029 | end = self[-1].end 2030 | 2031 | for segment in segments: 2032 | seg_start = segment.start 2033 | if current_pos != seg_start or \ 2034 | (self_closed and seg_start == end and use_closed_attrib): 2035 | parts.append('M {},{}'.format(seg_start.real, seg_start.imag)) 2036 | 2037 | if isinstance(segment, Line): 2038 | args = segment.end.real, segment.end.imag 2039 | parts.append('L {},{}'.format(*args)) 2040 | elif isinstance(segment, CubicBezier): 2041 | if useSandT and segment.is_smooth_from(previous_segment, 2042 | warning_on=False): 2043 | args = (segment.control2.real, segment.control2.imag, 2044 | segment.end.real, segment.end.imag) 2045 | parts.append('S {},{} {},{}'.format(*args)) 2046 | else: 2047 | args = (segment.control1.real, segment.control1.imag, 2048 | segment.control2.real, segment.control2.imag, 2049 | segment.end.real, segment.end.imag) 2050 | parts.append('C {},{} {},{} {},{}'.format(*args)) 2051 | elif isinstance(segment, QuadraticBezier): 2052 | if useSandT and segment.is_smooth_from(previous_segment, 2053 | warning_on=False): 2054 | args = segment.end.real, segment.end.imag 2055 | parts.append('T {},{}'.format(*args)) 2056 | else: 2057 | args = (segment.control.real, segment.control.imag, 2058 | segment.end.real, segment.end.imag) 2059 | parts.append('Q {},{} {},{}'.format(*args)) 2060 | 2061 | elif isinstance(segment, Arc): 2062 | args = (segment.radius.real, segment.radius.imag, 2063 | segment.rotation,int(segment.large_arc), 2064 | int(segment.sweep),segment.end.real, segment.end.imag) 2065 | parts.append('A {},{} {} {:d},{:d} {},{}'.format(*args)) 2066 | current_pos = segment.end 2067 | previous_segment = segment 2068 | 2069 | if self_closed: 2070 | parts.append('Z') 2071 | 2072 | return ' '.join(parts) 2073 | 2074 | ##################### svgpathtools end #################### 2075 | 2076 | --------------------------------------------------------------------------------