diff --git a/Lattesh/.gitignore b/Lattesh/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a8abd06998d59011a8723b9b050e05f8ee93af32 --- /dev/null +++ b/Lattesh/.gitignore @@ -0,0 +1,64 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Translations +*.mo +*.pot + +# PyBuilder +target/ + + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# dotenv +.env + +# virtualenv +.venv +venv/ +ENV/ + +# Spyder project settings +.spyderproject + +# Rope project settings +.ropeproject diff --git a/Lattesh/LICENSE.txt b/Lattesh/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..f288702d2fa16d3cdf0035b15a9fcbc552cd88e7 --- /dev/null +++ b/Lattesh/LICENSE.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<https://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<https://www.gnu.org/licenses/why-not-lgpl.html>. diff --git a/Lattesh/README.md b/Lattesh/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f28de14a92d4cf15de3e3a70db8b054d1586a010 --- /dev/null +++ b/Lattesh/README.md @@ -0,0 +1,99 @@ +# Lattesh +## A Blender Add-on for mesh-based lattice processing + +The *Lattesh* Add-on contains a set of tools for the creation and manipulation +of lattices in [Blender](https://www.blender.org). There are software tools +with good support for lattices, but those are proprietary and expensive. +This Add-on provides a basic alternative. + +The Add-on is programed in Python. It is designed to process rectangular lattices +of cells composed of strait cylindrical struts. +### Lattices + +The design was focused on speed and ease of lattice processing. This was achieved +by representing lattices as skeletons, were struts are just edges connecting two +vertices. A watertight mesh giving the lattice a volume is only created as a last +step in the lattice processing. + +Internally, lattices are represented in the Add-on as (degeneraded) meshes with only +vertices and edges. The standard mesh object from Blender is used. The generated +lattices can be manipulated using common Blender tools, but lacking faces and +having an unsusual topology make this editing limited. + +### Features + +The main features of the add-on are lattice creation, volume filling, and final +mesh generation. In creating a lattice, the user can choose the grid dimensions, +that is, the number of cells in each direction, the cell size and the cell type. +All these parameters are available in the add-on’s graphic interface. A lattice +is then generated in the form of a rectangular regular grid of cubic cells of +the chosen cell type. + +New cell types can be easily added via a cell definition file, where the cell +geometry is described in a text-based file format. + +More complex lattices can be generated using volume filling. In this feature, +a watertight mesh representing the desired form of the lattice is taken as input. +The add-on then fills this volume with a lattice of the chosen cell geometry. + +Finally, a 3D print-ready lattice can be obtained by giving a thickness to a +lattice skeleton. In this feature, each edge in the input lattice skeleton +will generate a cylindrical strut with a user-defined radius. Strut unions +in vertices are geometrically correct and correspond to geometrical boolean +unions of the cylindrical struts. The generated mesh is watertight and care +was taken to avoid redundant faces and vertices, leading to a smaller mesh size. +The resulting mesh is significantly smaller than what can be obtained by an +algorithm like marching cubes. + +The geometrical boolean operations are computed using the +Open CASCADE Technology library, an open source geometrical library. +These operations are computationally expensive, so the Add-on uses the +regularity of the lattices to reuse the result of these operations on similar +vertices. This leads to very efficient computation on regular lattices. +The boolean operations are also notoriously unreliable. The Add-on then detects +when these fail and takes measures to correct them when needed. + +### User interface + +The Add-on provides a graphical user interface in the form of a panel in the +side bar of the 3D Viewport. The panel is depicted below. + + + +The top part contains the parameters for regular lattice generation. The +parameters are: + - **Cell size**: the length defining the individual cells. + - **Cell type**: the cell type defines the topology of the individual cells. + - **Number of cells**: lattice grid dimensions, that is, how many cells will + be on the *x*, *y*, and *z* directions. + +Clicking on the **Create Mesh Lattice** will create a rectangular lattice with +these parameters. + +If a mesh object is selected, clicking on **Fill Mesh Lattice** will create a +regular lattice of *cell size* and *cell type* that fills the selected object. + +If a lattice is selected (or any mesh object), an **Opencascade fill** menu is +available. Upon clicking on **Lattice Volume (OCC)**, the lattice will be given +a volume, where for each edge in the original object a cylindrical strut will +be created. The strut radius is available as an input parameter. + +This operation will take only some seconds for very regular lattices, but a large +irregular lattice can take several hours to process. In this case, the add-on prints +messages on the terminal relating the progress. + +### Installation + +The Add-on is installed as usual in Blender via the *Preferences* menu. However, +the python distribution in Blender needs extra packages. These are: + - NumPy + - SciPy + - [PythonOCC](https://github.com/tpaviot/pythonocc) + +While the former two can be easily installed via `pip`, the latter needs either +building from source other installing with *conda*. See the installation intructions +in *PythonOCC*. If the *conda* route is used, Blender will need to access the *conda* +python environment. This can be achieved by creating a *conda* environment with +the required packages and copying it to the place where Blender keeps its python +distribution, after moving or deleting the original folder. The *conda* python + version (major and minor) must match the one shipped with Blender. \ No newline at end of file diff --git a/Lattesh/__init__.py b/Lattesh/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e1a07176039a1f96ca215419177b8d79e62f07a6 --- /dev/null +++ b/Lattesh/__init__.py @@ -0,0 +1,177 @@ +# -*- coding: utf-8 -*- + +# Copyright 2023 Ubiratan S. Freitas + + +# This file is part of Lattesh. +# +# Lattesh is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by the +# Free Software Foundation, either version 3 of the License, or (at your option) +# any later version. +# +# Lattesh is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +# more details. +# +# You should have received a copy of the GNU General Public License along with +# Lattice Tools. If not, see <https://www.gnu.org/licenses/>. + + +bl_info = { + "name": "Lattice Tools", + "author": "Ubiratan S. Freitas", + "blender": (2, 80, 0), + "description": "Tools for generating lattice structures", + "category": "Add Mesh", +} + + + + + + +if "bpy" in locals(): + import importlib + importlib.reload(operators) + importlib.reload(ui) +else: + import bpy + from bpy.types import PropertyGroup + from bpy.props import ( + BoolProperty, + FloatProperty, + EnumProperty, + IntVectorProperty, + PointerProperty, + ) + + from . import ( + operators, + ui, + ) + + +cell_items = operators.cell_items + +class SceneProperties(PropertyGroup): + r_ratio: FloatProperty( + name="R_ratio", + description="Ratio of actual radius to metaball radius", + default=0.8, + min=0.01, + max=0.99, + ) + + radius: FloatProperty( + name="Radius", + description="Actual radius of resulting mesh", + default=0.5, + min=1.0e-6, + max=20.0, + unit='LENGTH', + ) + + cellsize: FloatProperty( + name="Cell size", + description="Cell size", + default=10, + min=1.0e-2, + unit='LENGTH', + ) + + nelems: IntVectorProperty( + name="Nr. cells", + description="Number of cells in each direction", + default=(5, 5, 3), + min=1, + size=3, + ) + + celltype: EnumProperty( + items=cell_items, + name="Cell type", + description="Cell type", + default=cell_items[0][0], + ) + + connect_boundary: BoolProperty( + name="Connect Boundary", + description="Connect Boundary", + default=False, + ) + + charac_length: FloatProperty( + name="Caracteristic length", + description="Caracteristic length", + default=10, + min=1.0e-2, + unit='LENGTH', + ) + + lin_deflect: FloatProperty( + name="Linear deflection", + description="Maximum linear deflection for tesselation", + default=0.1, + min=1.0e-6, + max=2.0, + unit='LENGTH', + ) + + ang_deflect: FloatProperty( + name="Angular deflection", + description="Maximum angular deflection for tesselation", + default=1.5707963267948966, # 90 degrees in radians + min=1.0e-3, + max=2.0943951023931953, # 120 degrees in radians + subtype='ANGLE', + unit='ROTATION', + ) + + + + +classes = [ + SceneProperties, + ui.VIEW3D_PT_lattices_generate, + ui.VIEW3D_PT_lattice_metaball, + ui.VIEW3D_PT_lattice_OCC, + operators.ObjectOCCLattice, + operators.ObjectMetaLattice, + operators.ObjectCreateMeshLattice, + operators.ObjectFillMeshLattice, +] + +if operators.have_scipy: + classes.append(operators.ObjectFillVoronoiLattice) + + +def menu_func(self, context): + for cl in classes: + if cl is not SceneProperties: + self.layout.operator(cl.bl_idname) + + + + +def register(): + for cls in classes: + bpy.utils.register_class(cls) + bpy.types.Scene.lattice_mesh = PointerProperty(type=SceneProperties) + bpy.types.VIEW3D_MT_object.append(menu_func) + + + + +def unregister(): + for cls in classes: + bpy.utils.unregister_class(cls) + del bpy.types.Scene.lattice_mesh + bpy.types.VIEW3D_MT_object.remove(menu_func) + +if __name__ == "__main__": + register() + + + diff --git a/Lattesh/cells/hex.cell b/Lattesh/cells/hex.cell new file mode 100644 index 0000000000000000000000000000000000000000..1f8dbdc81351d50bdbe142a64dd53725e22f4151 --- /dev/null +++ b/Lattesh/cells/hex.cell @@ -0,0 +1,21 @@ +HEX +0.0, 0.0, 0.0 +1.0, 0.0, 0.0 +0.0, 1.0, 0.0 +1.0, 1.0, 0.0 +0.0, 0.0, 1.0 +1.0, 0.0, 1.0 +0.0, 1.0, 1.0 +1.0, 1.0, 1.0 +0, 1 +2, 3 +4, 5 +6, 7 +0, 2 +1, 3 +4, 6 +5, 7 +0, 4 +1, 5 +2, 6 +3, 7 diff --git a/Lattesh/cells/type_2.cell b/Lattesh/cells/type_2.cell new file mode 100644 index 0000000000000000000000000000000000000000..c3a4fac207322810d4bb9c1e45a784dc6d321e37 --- /dev/null +++ b/Lattesh/cells/type_2.cell @@ -0,0 +1,16 @@ +TYPE_2 +0.5, 0.5, 0.5 +0, 0.5, 0 +0, 0.5, 1 +1, 0.5, 0 +1, 0.5, 1 +0.5, 0, 0.5 +0.5, 1, 0.5 +0, 1 +0, 2 +0, 3 +0, 4 +1, 5 +4, 5 +2, 6 +3, 6 diff --git a/Lattesh/cells/type_3.cell b/Lattesh/cells/type_3.cell new file mode 100644 index 0000000000000000000000000000000000000000..ee2fb522fdd00cc94635e390c04114ec62a32256 --- /dev/null +++ b/Lattesh/cells/type_3.cell @@ -0,0 +1,18 @@ +TYPE_3 +0.5, 0.5, 0.5 +0.0, 0.0, 0.0 +1.0, 0.0, 0.0 +0.0, 1.0, 0.0 +1.0, 1.0, 0.0 +0.0, 0.0, 1.0 +1.0, 0.0, 1.0 +0.0, 1.0, 1.0 +1.0, 1.0, 1.0 +0, 1 +0, 2 +0, 3 +0, 4 +0, 5 +0, 6 +0, 7 +0, 8 diff --git a/Lattesh/cells/type_4.cell b/Lattesh/cells/type_4.cell new file mode 100644 index 0000000000000000000000000000000000000000..21f2ddbdb1654f6975bf76c9e0e2a4f8735382e8 --- /dev/null +++ b/Lattesh/cells/type_4.cell @@ -0,0 +1,55 @@ +TYPE_4 +0, 1, 1 +1, 0.5, 0.5 +1, 0, 0 +1, 0, 1 +0.5, 0.5, 1 +0, 0, 1 +0.25, 0.75, 0.75 +0.5, 0, 0.5 +0.25, 0.25, 0.25 +0.5, 0.5, 0 +0.75, 0.25, 0.25 +0, 0, 0 +0.75, 0.75, 0.25 +1, 1, 1 +0.25, 0.75, 0.25 +0.25, 0.25, 0.75 +0, 0.5, 0.5 +0.75, 0.25, 0.75 +0.75, 0.75, 0.75 +1, 1, 0 +0, 1, 0 +0.5, 1, 0.5 +8, 11 +8, 9 +10, 1 +12, 1 +14, 20 +14, 9 +15, 16 +17, 3 +17, 4 +18, 13 +18, 4 +6, 16 +8, 7 +8, 16 +10, 2 +10, 9 +10, 7 +12, 19 +12, 9 +12, 21 +14, 21 +14, 16 +15, 5 +15, 4 +15, 7 +17, 7 +17, 1 +18, 21 +18, 1 +6, 0 +6, 4 +6, 21 diff --git a/Lattesh/cells/type_5.cell b/Lattesh/cells/type_5.cell new file mode 100644 index 0000000000000000000000000000000000000000..c61e8e2474b1c3c6be176519d2fad982ece85a30 --- /dev/null +++ b/Lattesh/cells/type_5.cell @@ -0,0 +1,57 @@ +TYPE_5 +0.5, 1, 1 +0.5, 1, 0 +1, 0.75, 0 +1, 0.25, 0 +0.5, 0.5, 1 +0, 0.75, 1 +0, 0.25, 1 +1, 0.25, 1 +1, 0.75, 1 +0.5, 0, 1 +0.6686271292106067, 0.75, 0.5 +0.6686271292106067, 0.25, 0.5 +0.75, 0.5, 0.5 +0, 0.75, 0 +0.3313728707893933, 0.75, 0.5 +0.25, 0.5, 0.5 +0, 0.25, 0 +0.3313728707893933, 0.25, 0.5 +0.5, 0, 0 +0.5, 0.5, 0 +8, 10 +8, 12 +7, 11 +7, 12 +13, 14 +13, 15 +16, 17 +16, 15 +18, 17 +18, 11 +0, 14 +0, 10 +19, 10 +19, 14 +19, 12 +4, 11 +4, 17 +4, 15 +2, 10 +2, 12 +3, 11 +3, 12 +5, 14 +5, 15 +6, 17 +6, 15 +9, 17 +9, 11 +1, 14 +1, 10 +19, 11 +19, 17 +19, 15 +4, 10 +4, 14 +4, 12 diff --git a/Lattesh/cells/type_6.cell b/Lattesh/cells/type_6.cell new file mode 100644 index 0000000000000000000000000000000000000000..b3f519001a6c1835557acfc9b148eae9e5145244 --- /dev/null +++ b/Lattesh/cells/type_6.cell @@ -0,0 +1,51 @@ +TYPE_6 +1.0,1.0,0.0 +0.0,1.0,1.0 +0.0,1.0,0.0 +1.0,0.0,0.0 +1.0,0.5,0.5 +0.0,0.0,1.0 +1.0,0.0,1.0 +0.0,0.0,0.0 +1.0,1.0,1.0 +0.5,0.0,0.5 +0.5,0.5,0.0 +0.5,0.5,1.0 +0.5,1.0,0.5 +0.0,0.5,0.5 +9,6 +12,2 +13,2 +10,0 +11,1 +7,9 +7,10 +6,11 +8,12 +5,13 +9,3 +4,0 +4,8 +12,0 +13,7 +10,2 +11,8 +9,4 +9,13 +9,10 +9,11 +10,4 +10,13 +10,12 +13,12 +12,4 +12,11 +13,11 +4,11 +6,4 +1,12 +1,13 +5,9 +3,4 +3,10 +5,11 diff --git a/Lattesh/cells/type_8.cell b/Lattesh/cells/type_8.cell new file mode 100644 index 0000000000000000000000000000000000000000..f95b06dc67ac376f607786e6fd7a4510418a1040 --- /dev/null +++ b/Lattesh/cells/type_8.cell @@ -0,0 +1,109 @@ +TYPE_8 +0.125, 1.0, 1.0 +0.875, 1.0, 1.0 +0.5, 1.0, 1.0 +1.0, 0.5, 0.0 +1.0, 0.0, 0.125 +1.0, 0.0, 0.875 +1.0, 0.25897457599639895, 0.5 +1.0, 0.0, 0.5 +1.0, 0.125, 0.0 +0.0, 0.7410254001617431, 0.5 +1.0, 0.125, 1.0 +1.0, 0.7410254001617431, 0.5 +1.0, 0.875, 1.0 +0.0, 0.25897457599639895, 0.5 +0.5, 1.0, 0.7410254001617431 +0.25897457599639895, 0.5, 1.0 +0.125, 0.0, 1.0 +0.7410254001617431, 0.5, 1.0 +0.875, 0.0, 1.0 +0.0, 0.125, 1.0 +0.25897457599639895, 0.5, 0.0 +0.125, 0.0, 0.0 +0.7410254001617431, 0.5, 0.0 +0.875, 0.0, 0.0 +0.5, 0.0, 0.25897457599639895 +0.0, 0.0, 0.125 +0.5, 0.0, 0.7410254001617431 +0.0, 0.0, 0.875 +0.0, 0.0, 0.5 +0.0, 0.125, 0.0 +0.0, 0.875, 0.0 +1.0, 1.0, 0.125 +1.0, 1.0, 0.875 +0.125, 1.0, 0.0 +0.5, 1.0, 0.0 +0.0, 1.0, 0.125 +0.0, 1.0, 0.875 +0.0, 1.0, 0.5 +0.5, 1.0, 0.25897457599639895 +0.0, 0.875, 1.0 +1.0, 0.875, 0.0 +0.875, 1.0, 0.0 +0.5, 0.0, 0.0 +0.5, 0.0, 1.0 +1.0, 1.0, 0.5 +0.0, 0.5, 0.0 +0.0, 0.5, 1.0 +1.0, 0.5, 1.0 +20, 21 +20, 33 +22, 3 +22, 23 +22, 41 +42, 23 +15, 16 +15, 0 +17, 18 +17, 1 +43, 18 +24, 25 +24, 4 +26, 27 +26, 5 +38, 34 +38, 35 +38, 31 +14, 2 +14, 36 +14, 32 +44, 32 +13, 28 +13, 29 +13, 19 +9, 37 +9, 30 +9, 39 +45, 30 +46, 39 +6, 7 +6, 8 +6, 10 +11, 40 +11, 12 +47, 12 +21, 42 +16, 43 +31, 44 +29, 45 +19, 46 +10, 47 +20, 45 +34, 41 +15, 46 +17, 47 +2, 1 +24, 42 +26, 43 +28, 27 +7, 5 +37, 36 +11, 44 +3, 40 +33, 34 +0, 2 +25, 28 +4, 7 +35, 37 +8, 3 \ No newline at end of file diff --git a/Lattesh/cells/type_9.cell b/Lattesh/cells/type_9.cell new file mode 100644 index 0000000000000000000000000000000000000000..2090b58e4a8b8bfc3162353322b74880a553b033 --- /dev/null +++ b/Lattesh/cells/type_9.cell @@ -0,0 +1,31 @@ +TYPE_9 +1.0,0.5,0.5 +0.5,0.5,1.0 +0.5,0.0,0.5 +0.0,0.5,0.5 +0.75,0.25,0.5 +0.5,0.5,0.0 +0.5,1.0,0.5 +0.25,0.25,0.5 +0.75,0.75,0.5 +0.25,0.75,0.5 +7,3 +8,0 +5,4 +9,3 +1,4 +2,7 +6,8 +6,9 +7,4 +7,9 +5,8 +1,7 +1,9 +4,0 +8,4 +8,9 +5,7 +5,9 +1,8 +2,4 diff --git a/Lattesh/cells/type_91.cell b/Lattesh/cells/type_91.cell new file mode 100644 index 0000000000000000000000000000000000000000..e1aee3099327011d37ba03bdbc9657c1834fb5ad --- /dev/null +++ b/Lattesh/cells/type_91.cell @@ -0,0 +1,33 @@ +TYPE_91 +1, 1, 0.5 +0, 1, 0.5 +1, 0.5, 0.5 +1, 0, 0.5 +0.5, 0.5, 1 +0.5, 0, 0.5 +0.25, 0.25, 0.5 +0, 0.5, 0.5 +0.75, 0.25, 0.5 +0.25, 0.75, 0.5 +0.5, 0.5, 0 +0.75, 0.75, 0.5 +0.5, 1, 0.5 +0, 0, 0.5 +5, 7 +12, 2 +6, 8 +6, 9 +10, 8 +10, 11 +4, 6 +4, 9 +13, 1 +3, 0 +5, 2 +12, 7 +11, 8 +11, 9 +10, 6 +10, 9 +4, 8 +4, 11 diff --git a/Lattesh/doc/side_panel.png b/Lattesh/doc/side_panel.png new file mode 100644 index 0000000000000000000000000000000000000000..529b5349e154a92c4d2f5581b5881e12488e3a30 Binary files /dev/null and b/Lattesh/doc/side_panel.png differ diff --git a/Lattesh/operators.py b/Lattesh/operators.py new file mode 100644 index 0000000000000000000000000000000000000000..8b6db3ec59714c0b7dfe3188e470fdf4ad11eea4 --- /dev/null +++ b/Lattesh/operators.py @@ -0,0 +1,1271 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Ubiratan S. Freitas + + +# This file is part of Lattesh. +# +# Lattesh is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by the +# Free Software Foundation, either version 3 of the License, or (at your option) +# any later version. +# +# Lattesh is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +# more details. +# +# You should have received a copy of the GNU General Public License along with +# Lattice Tools. If not, see <https://www.gnu.org/licenses/>. + + + +import bpy, bmesh +from mathutils import Vector, Quaternion, Matrix +from mathutils.bvhtree import BVHTree +import numpy as np +import math +import os + +try: + from scipy.spatial import Voronoi, Delaunay + have_scipy = True +except ModuleNotFoundError: + have_scipy = False + + + + + +# Opencascade imports +try: + from OCC.Core.BRep import BRep_Tool + from OCC.Core.BRepPrimAPI import BRepPrimAPI_MakeSphere, BRepPrimAPI_MakeCylinder + from OCC.Core.BRepAlgoAPI import BRepAlgoAPI_Fuse + from OCC.Core.BRepBuilderAPI import BRepBuilderAPI_Transform + from OCC.Core.BRepMesh import BRepMesh_IncrementalMesh + from OCC.Core.TopExp import TopExp_Explorer + from OCC.Core.TopoDS import topods_Face + from OCC.Core.TopTools import TopTools_ListOfShape + from OCC.Core.BRepAdaptor import BRepAdaptor_Surface + from OCC.Core.GeomAbs import GeomAbs_Plane + from OCC.Core.TopAbs import TopAbs_FACE + from OCC.Core.TopLoc import TopLoc_Location + from OCC.Core.gp import gp_Pnt, gp_Trsf, gp_Ax2, gp_Ax1, gp_Dir + have_occ = True +except ModuleNotFoundError: + have_occ = False + + + + + + + +class Cell: + def __init__(self, verts=None, edges=None): + if verts is None: + self.verts = np.zeros((0,3), dtype=np.float32) + self.nverts = 0 + else: + self.verts = verts + self.nverts = verts.shape[0] + if edges is None: + self.edges = np.zeros((0,2), dtype=np.int32) + self.nedges = 0 + else: + self.edges = edges + self.nedges = edges.shape[0] + + self.check() + + def check(self): + if self.nverts == 0: + return + if len(self.verts.shape) != 2 or self.verts.shape[1] != 3: + raise ValueError("verts should be an N x 3 array") + + if len(self.edges.shape) != 2 or self.edges.shape[1] != 2: + raise ValueError("edges should be an M x 2 array") + + if self.verts.min() < 0.0 or self.verts.max() > 1.0: + raise ValueError("All vertices' coordinates must be in [0.0, 1.0]") + + if self.edges.min() < 0 or self.edges.max() > self.nverts: + raise ValueError("Edge(s) referencing inexistent vertex") + + if set(range(self.nverts)) != set(self.edges.flat): + raise ValueError("Each vertex must be part of an edge") + + def from_file(self, fname): + name = '' + verts = [] + edges = [] + with open(fname) as f: + for line in f: + stripped = line.strip() + if len(stripped) > 0 and stripped[0] != '#': + if len(name) == 0: + name = stripped + else: + sp = stripped.split(',') + if len(sp) == 3: + verts.append(list(map(float, sp))) + elif len(sp) == 2: + edges.append(list(map(int, sp))) + self.verts = np.array(verts, dtype=np.float32) + self.nverts = len(verts) + self.edges = np.array(edges, dtype=np.int32) + self.nedges = len(edges) + self.check() + self.name = name + + +cell_files = ['hex.cell', + 'type_2.cell', + 'type_3.cell', + 'type_4.cell', + 'type_5.cell', + 'type_6.cell', + 'type_8.cell', + 'type_9.cell', + 'type_91.cell', + ] + +fpath = os.path.dirname(os.path.abspath(__file__)) + +filepath = os.path.join(fpath, 'cells') +Cells = {} +cell_items = [] +for k, cf in enumerate(cell_files): + c = Cell() + c.from_file(os.path.join(filepath, cf)) + Cells[c.name] = c + cell_items.append((c.name, c.name, c.name, k)) + +def triangulate_verts(bm, max_len): + """Makes a Delaunay triangulation of selected vertices, delete edges longer than max_len""" + verts = [v for v in bm.verts if v.select] + vnp = np.zeros((len(verts),3), dtype=np.float32) + for k, v in enumerate(verts): + vnp[k,:] = np.array(v.co, dtype=np.float32) + tri = Delaunay(vnp) + eds_s = set() + for r in tri.simplices: + for k in range(3): + a = r[k] + b = r[k + 1] + if a < b: + eds_s.add((a, b)) + else: + eds_s.add((b, a)) + for e in eds_s: + if (verts[e[0]].co - verts[e[1]].co).length < max_len: + new_edge = bm.edges.new((verts[e[0]], verts[e[1]])) + new_edge.select = True + + +def make_npvoronoi(carac_length, dims, corner): + """Makes a Voronoi lattice""" + + carac3 = carac_length ** 3 + padding = 2 + + dims = dims + (2 * padding * carac_length) + + npoints = math.ceil(dims.prod() / carac3) + + npoints = max(npoints, 30) # create at least this amount of points + + print('voronoi npoints:', npoints) + + p = np.random.random((npoints,3)) + p = p * dims.reshape((1,3)) + (corner.reshape((1,3)) - padding * carac_length) + + + vor = Voronoi(p) + + verts = vor.vertices + + # mark voronoi vertices outside extended bounding box + lowerlims = corner.reshape((1,3)) - padding * carac_length + upperlims = lowerlims + dims + vertok = np.logical_and(np.all(verts > lowerlims, axis=1), np.all(verts < upperlims, axis=1)) + + # new vertices + new_verts = verts[vertok,:].copy() + + # build a table translating old indexes to new_verts + okidx = np.zeros((len(verts),), dtype=np.int32) + okidx[np.logical_not(vertok)] = -1 + newidx = okidx.cumsum() + np.arange(len(verts), dtype=np.int32) + + eds_s = set() + + for r in vor.ridge_vertices: + if not -1 in r: + for k in range(len(r) - 1): + a = r[k] + b = r[k + 1] + if vertok[a] and vertok[b]: + na = newidx[a] + nb = newidx[b] + if na < nb: + eds_s.add((na,nb)) + else: + eds_s.add((nb,na)) + + edges = np.array([list(x) for x in eds_s], dtype=np.int32) + return new_verts, edges + + + +def make_nplattice(cell, cell_size, nelems, corner): + """Constructs a lattice grid""" + ncells = nelems.prod() + verts = np.zeros((ncells * cell.nverts, 3), dtype=np.float32) + edges = np.zeros((ncells * cell.nedges, 2), dtype=np.int32) + cellcorner = np.zeros((1,3), dtype=np.float32) + edgespos = np.ones((1,2), dtype=np.int32) + + # Generate a lattice with copied cells of unit size + for i in range(nelems[0]): + for j in range(nelems[1]): + for k in range(nelems[2]): + cellcorner[0, 0] = i + cellcorner[0, 1] = j + cellcorner[0, 2] = k + baseidx = i + (j * nelems[0]) + (nelems[0] * nelems[1] * k) + vertpos = baseidx * cell.nverts + cellidx = baseidx * cell.nedges + verts[vertpos : (vertpos + cell.nverts), :] = cellcorner + cell.verts + edges[cellidx: (cellidx + cell.nedges), :] = cell.edges + edgespos * vertpos + + # Scale the whole lattice and translate it to corner + verts = verts * cell_size + corner + + return verts, edges + +def nplattice2meshdata(v, e): + verts = [tuple(v[i,:]) for i in range(v.shape[0]) ] + edges = [tuple(e[i,:]) for i in range(e.shape[0]) ] + return verts, edges + +def make_meshlattice(name, verts, edges, cellsize): + mesh = bpy.data.meshes.new(name+'Mesh') + mesh.from_pydata(verts, edges, []) + + bm = bmesh.new() + + bm.from_mesh(mesh) + bmesh.ops.remove_doubles(bm, verts=bm.verts[:], dist=1.0e-3*cellsize) + return bm, mesh + + +def vor_intersect(vor, obj, depsgraph): + """Clips a Voronoi 3D lattice to object + """ + + tree = BVHTree.FromObject(obj, depsgraph) + disttol = 5.0e-5 + analized_edges = set() + for rg, rv in enumerate(vor.ridge_vertices): + intersec = 0 + for k in range(len(rv) - 1): + v0 = min((rv[k], rv[k + 1])) + v1 = max((rv[k], rv[k + 1])) + if v1 < 0 or (v0, v1) in analized_edges: + continue + p0 = vor.vertices[v0] + p1 = vor.vertices[v1] + d = p1 - p0 + dis = np.linalg.norm(d) + loc, n, idx, hdis = tree.ray_cast(p0, d, dis) + if hdis is not None: + loc2, n2, idx2, hdis2 = tree.ray_cast(p1, -d, dis) + if (loc - loc2).length > disttol / 2.0: + double_edges.add(e) + elif hdis > disttol and abs(dis - hdis) > disttol: + r = hdis/dis + cedges.append((e, r)) + + + +def intersect(bm, obj, depsgraph): + """Clips mesh lattice to object + + Returns a mesh where all vertices and edges are inside or on the surface + of object. Edges that intercept the object are clipped. + """ + tree = BVHTree.FromObject(obj, depsgraph) + outside = set() + inside = set() + valencies = set() + surfverts = set() + cedges = [] + disttol = 5.0e-5 + double_edges = set() + + # Find the edges that cross object + for e in bm.edges: + p0 = e.verts[0].co + p1 = e.verts[1].co + d = p1 - p0 + dis = d.length + loc, n, idx, hdis = tree.ray_cast(p0, d, dis) + if hdis is not None: + # check for multiple crossings + loc2, n2, idx2, hdis2 = tree.ray_cast(p1, -d, dis) + if loc2 and (loc - loc2).length > disttol / 2.0: + double_edges.add(e) + elif hdis > disttol and abs(dis - hdis) > disttol: + r = hdis/dis + cedges.append((e, r)) + + print('edges', len(cedges)) + print('double edges', len(double_edges)) + + # Delete double crossing edges + if double_edges: + bmesh.ops.delete(bm, geom=list(double_edges), context='EDGES') + + + dper = dict() + for k in cedges: + dper[k[0]] = k[1] + + tmp = np.array(list(dper.values())) + print('min dist', tmp.min(), 'max dist', tmp.max()) + + # Split the found edges on crossing point + bmesh.ops.bisect_edges(bm, edges=[ e[0] for e in cedges ], cuts=1, edge_percents=dper)['geom_split'] + + # Find the vertices that are on the surface and identify their outside and inside edges based on + # surface normal + for v in bm.verts: + loc, n, idx, hdis = tree.find_nearest(v.co, 1.1*disttol) + if loc is not None: + surfverts.add(v) + valencies.add(len(v.link_edges)) + for ed in v.link_edges: + p1 = ed.other_vert(v) + u_v = p1.co - v.co + u_v = u_v / u_v.length * 0.2 + pn = v.co + u_v + an1 = n.angle(p1.co - v.co) + loc2, n2, idx, hdis = tree.find_nearest(p1.co, 1.1* ed.calc_length()) + if hdis and hdis > 0: + an2 = n2.angle((p1.co - loc2)) + else: + an2 = math.pi + if hdis and hdis > disttol and (an1 < math.pi / 2 + 1e-3 or an2 < math.pi / 2 + 1e-3) : + outside.add(ed) + else: + inside.add(ed) + + print('Found', len(surfverts), 'surfverts') + + print('Valencies:', valencies) + + print('inside', len(inside), 'outside', len(outside)) + + invalid_out = set([v for v in outside if not v.is_valid]) + outside = outside - invalid_out + + invalid_in = set([v for v in inside if not v.is_valid]) + inside = inside - invalid_in + + print('inv out', len(invalid_out), 'inv in', len(invalid_in), 'in out', len(inside.intersection(outside))) + + # Delete the outside edges from on-the-surface vertices + bmesh.ops.delete(bm, geom=list(outside), context='EDGES') + + # Remove invalid surfverts + invalid = set([v for v in surfverts if not v.is_valid]) + print('Found {} invalid surfverts'.format(len(invalid))) + surfverts = surfverts - invalid + + # Find all vertices linked to the ones on the surface + to_process = surfverts.copy() + processed = set() + while to_process: + v = to_process.pop() + for e in v.link_edges: + other_v = e.other_vert(v) + if other_v not in processed: + to_process.add(other_v) + processed.add(v) + + # Delete gemometry not linked to surface vertices + to_delete = set(bm.verts) - processed + print(len(to_delete), 'to be deleted and', len(processed), 'internal vertices found') + + if len(to_delete) < len(bm.verts): + # do not delete all vertices + bmesh.ops.delete(bm, geom=list(to_delete), context='VERTS') + + + # Leave only surface vertices selected + bm.select_mode = {'VERT'} + + for v in bm.verts: + v.select = False + + for v in surfverts: + v.select = True + + bm.select_flush_mode() + +def test_ring(na, nb): + twopi = 2 * math.pi + ra = np.random.rand(na).cumsum() + rb = np.random.rand(nb).cumsum() + tha = ra / ra[-1] * twopi - math.pi + thb = rb / rb[-1] * twopi - math.pi + verts = np.zeros((na + nb, 3), dtype=np.float32) + verts[:na,:] = np.stack((np.cos(tha), np.sin(tha), np.zeros(na)), axis=1) + verts[na:,:] = np.stack((np.cos(thb), np.sin(thb), np.ones(nb)*2), axis=1) + faces, masq = ring_connect_faces(tha, thb) + faces[np.logical_not(masq)] += na + faces = list(faces) + bottom = list(range(na)) + bottom.reverse() + top = list(range(na,na+nb)) + faces += [bottom, top] + mesh = bpy.data.meshes.new('RingMesh') + mesh.from_pydata(verts, [], faces) + newobj = bpy.data.objects.new('Ring', mesh) + + # Link object to scene + bpy.context.scene.collection.objects.link(newobj) + + + + +def angle_dist(a, b): + d = abs(b-a) + return min(d, 2 * math.pi - d) + +def ring_connect3d(ringa, ringb): + na, nb = len(ringa), len(ringb) + distab = np.zeros((na, nb)) + ran_a = np.arange(na) + ran_b = np.arange(nb) + rankab = np.zeros((na, nb), dtype=np.int32) + rankba = np.zeros((nb, na), dtype=np.int32) + for k in range(na): + distab[k, :] = np.linalg.norm(ringb - ringa[k, :], axis=1) + for k in range(na): + rankab[k, distab[k, :].argsort()] = ran_b + for k in range(nb): + rankba[k, distab[:, k].argsort()] = ran_a + idx = distab.argmin() + posa, posb = np.unravel_index(idx, distab.shape) + nposa = (posa + 1) % na + nposb = (posb + 1) % nb + faces = np.zeros((na + nb, 3), dtype=np.int32) + + ntris = 0 + ntrisa = 0 + ntrisb = 0 + while ntrisa < na and ntrisb < nb: + rnb = rankba[nposb, posa] + rna = rankab[nposa, posb] + if rnb < rna: + make_b = True + elif rna < rnb: + make_b = False + elif distab[posa, nposb] <= distab[nposa, posb]: + #if distab[posa, nposb] <= distab[nposa, posb]: + make_b = True + else: + make_b = False + + if make_b: + faces[ntris, :] = [posa, nposb + na, posb + na] + posb = nposb + nposb = (posb + 1) % nb + ntrisb += 1 + else: + faces[ntris, :] = [posa, nposa , posb + na] + posa = nposa + nposa = (posa + 1) % na + ntrisa += 1 + ntris += 1 + while ntrisa < na: + faces[ntris, :] = [posa, nposa , posb + na] + posa = nposa + nposa = (posa + 1) % na + ntrisa += 1 + ntris += 1 + while ntrisb < nb: + faces[ntris, :] = [posa, nposb + na, posb + na] + posb = nposb + nposb = (posb + 1) % nb + ntrisb += 1 + ntris += 1 + return faces + +def ring_connect_faces(ang_a, ang_b): + twopi = 2 * math.pi + na = len(ang_a) + nb = len(ang_b) + faces = np.zeros((na+nb, 3), dtype=np.int32) + face_masq = np.zeros(faces.shape, dtype=bool) + saidx = ang_a.argsort() + sbidx = ang_b.argsort() + sa = ang_a[saidx] + sb = ang_b[sbidx] + + posa = 0 + nposa = 1 + dists = np.zeros((nb,2), dtype=ang_b.dtype) + dists[:,0] = np.abs(sb - sa[0]) + dists[:,1] = twopi - dists[:,0] + posb = dists.min(axis=1).argmin() + nposb = (posb + 1) % nb + ntris = 0 + ntrisa = 0 + ntrisb = 0 + + while ntrisa < na and ntrisb < nb: + dista = angle_dist(sa[posa], sb[nposb]) + distb = angle_dist(sb[posb], sa[nposa]) + if dista <= distb: + faces[ntris,:] = [saidx[posa], sbidx[nposb], sbidx[posb]] + face_masq[ntris,:] = [True, False, False] + posb = (posb + 1) % nb + nposb = (posb + 1) % nb + ntrisb += 1 + else: + faces[ntris,:] = [saidx[posa], saidx[nposa], sbidx[posb]] + face_masq[ntris,:] = [True, True, False] + posa = (posa + 1) % na + nposa = (posa + 1) % na + ntrisa += 1 + ntris += 1 + while ntrisa < na: + faces[ntris,:] = [saidx[posa], saidx[nposa], sbidx[posb]] + face_masq[ntris,:] = [True, True, False] + posa = (posa + 1) % na + nposa = (posa + 1) % na + ntrisa += 1 + ntris += 1 + while ntrisb < nb: + faces[ntris,:] = [saidx[posa], sbidx[nposb], sbidx[posb]] + face_masq[ntris,:] = [True, False, False] + posb = (posb + 1) % nb + nposb = (posb + 1) % nb + ntrisb += 1 + ntris += 1 + + return faces, face_masq + +vecz = np.array([0, 0, 1], dtype=np.float32) +eye = np.eye(3) +inv_eye = eye.copy() +inv_eye[1,1] = -1.0 +inv_eye[2,2] = -1.0 +twopi = math.pi * 2 +min_crossnorm = 1e-3 + +def make_rotmatrix(x): + """Make a rotation matrix that transform the given unity vector to the z axis""" + c_angle = x @ vecz + raxis = np.cross(x, vecz) + if np.linalg.norm(raxis) < min_crossnorm: + if c_angle > 0.0: + rotmat = eye + elif c_angle < 0.0: + rotmat = inv_eye + else: + rotmat = np.array(Matrix.Rotation(math.acos(c_angle), 3, raxis)) + return rotmat + + +def aux_show_node(): + nodes = [[1, 0, 0], + [0, 1, 0], + [0, 0, 1], + [0, 0.7071067811865475, 0.7071067811865475] + ] + nodes = np.array(nodes) + verts, tris, nsides, shape = occ_compute_node(nodes) + + print('Nverts:', len(verts), 'ntris:', len(tris)) + print('Tris:') + print(tris) + name = 'OCC Node' + mesh = bpy.data.meshes.new(name+'Mesh') + mesh.from_pydata(verts, [], list(tris)) + newobj = bpy.data.objects.new(name, mesh) + + # Link object to scene + bpy.context.scene.collection.objects.link(newobj) + + +def boolean_union(shape_a, shape_b): + lo1 = TopTools_ListOfShape() + lo1.Append(shape_a) + lo2 = TopTools_ListOfShape() + lo2.Append(shape_b) + + op = BRepAlgoAPI_Fuse() + op.SetArguments(lo1) + op.SetTools(lo2) + + op.SetCheckInverted(False) + #op.SetFuzzyValue(r/50) + #op.SetUseOBB(True) + op.Build() + return op.Shape() + + +def occ_compute_node(ev, r=0.5, mesh_pars=(0.1, False, math.radians(60), False), shuffle=False): + node_origin = gp_Ax2(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1)) + shape = BRepPrimAPI_MakeSphere(node_origin, r).Shape() + vecz = np.array([0.0, 0.0, 1.0]) + rotate = gp_Trsf() + nedges = len(ev) + rotmats = np.zeros((2, 3, nedges)) + if shuffle: + seq = np.random.permutation(nedges) + else: + seq = list(range(nedges)) + + for k in seq: + v = ev[k, :] + c_angle = v @ vecz + raxis = np.cross(vecz, v) + if np.linalg.norm(raxis) < min_crossnorm: + if c_angle > 0.0: + rotdir = gp_Dir(0.0, 0.0, 1.0) + elif c_angle < 0.0: + rotdir = gp_Dir(1.0, 0.0, 0.0) + else: + rotdir = gp_Dir(*raxis) + + rotate.SetRotation(gp_Ax1(node_origin.Location(), rotdir), math.acos(c_angle)) + for row in range(2): + for col in range(3): + rotmats[row, col, k] = rotate.Value(col + 1, row + 1) + try: + if nedges == 1: + cyl = BRepPrimAPI_MakeCylinder(node_origin, r, 1.1 * r).Shape() + cyl1 = BRepBuilderAPI_Transform(cyl, rotate, True).Shape() + shape = boolean_union(shape, cyl1) + else: + c_angles = ev @ v + s_arg = c_angles.argsort() + minangle = math.acos(c_angles[s_arg[-2]]) + cyl_len = max(1.1 * r, 1.1 * r /math.tan(minangle/2)) + cyl = BRepPrimAPI_MakeCylinder(node_origin, r, cyl_len ).Shape() + cyl1 = BRepBuilderAPI_Transform(cyl, rotate, True).Shape() + #op = BRepAlgoAPI_Fuse(shape, cyl1) + newshape = boolean_union(shape, cyl1) + while newshape is None: + ang_change = + np.random.randn() / 20 + print(f'Boolean fuse failed. Trying angle change of {math.degrees(ang_change):.2f} degrees') + rotate.SetRotation(gp_Ax1(node_origin.Location(), rotdir), math.acos(c_angle) + ang_change) + cyl1 = BRepBuilderAPI_Transform(cyl, rotate, True).Shape() + newshape = boolean_union(shape, cyl1) + shape = newshape + except: + print('Error in OCC. Type of shape:', type(shape)) + print(shape) + print(f'k: {k}') + print(ev) + raise + + # + # Mesh the shape + # + BRepMesh_IncrementalMesh(shape, *mesh_pars) + + bt = BRep_Tool() + ex = TopExp_Explorer(shape, TopAbs_FACE) + verts = [] + uniq_verts = [] + vertsd = {} + plane_verts = [] + tris = [] + plane_ind = [] + ind_tri = np.array([2, 0, 1], dtype=np.int32) + while ex.More(): + face = topods_Face(ex.Current()) + location = TopLoc_Location() + facing = (bt.Triangulation(face, location)) + if facing is not None: + tab = facing.Nodes() + tri = facing.Triangles() + local_index = [] + for k in range(1, tab.Length() + 1): + pnt = tab.Value(k) + point = list(pnt.Coord()) + dpoint = tuple((np.array(point) * 100).round().astype(np.int32)) + verts.append(point) + if dpoint not in vertsd: + vertsd[dpoint] = len(uniq_verts) + uniq_verts.append(point) + local_index.append(vertsd[dpoint]) + + surf = BRepAdaptor_Surface(face, True) + surf_type = surf.GetType() + local_index = np.array(local_index) + if surf_type == GeomAbs_Plane: + face_plane = surf.Plane() + face_normal = np.array(list(face_plane.Axis().Direction().Coord())) + c_angles = ev @ face_normal + idx = c_angles.argmax() + if idx in plane_ind: + fidx = plane_ind.index(idx) + plane_verts[fidx] = np.unique(np.concatenate((plane_verts[fidx], local_index ))) + else: + plane_ind.append(idx) + plane_verts.append(local_index) + else: + for i in range(1, facing.NbTriangles()+1): + trian = tri.Value(i) + np_tri = np.array(list(trian.Get()), dtype=np.int32) + np_tri = np.array(local_index[np_tri - 1]) + if (np_tri - np_tri[ind_tri]).prod() != 0 : + tris.append(np_tri) + ex.Next() + + uniq_verts = np.array(uniq_verts) + tris = np.array(tris, dtype=np.int32) + ed_verts = [] + if plane_verts: + nsides = len(plane_verts[0]) + all_planeverts = set() + for pl in plane_verts: + all_planeverts.update(pl) + plane_tris = set() + plane_ind = np.array(plane_ind) + edverts = [] + for k in plane_ind.argsort(): + pl = plane_verts[k] + plset = set(pl) + edvert = set() + for k in range(len(tris)): + for x in tris[k]: + if x in plset: + plane_tris.add(k) + edvert.update(set(tris[k]) - all_planeverts) + break + edverts.append(list(edvert)) + verts = np.array(verts) + # Remove tris that contain a vertex in plane_verts (using set operations) + tris = tris[list(set(range(len(tris))) - plane_tris), :] + + nverts = len(uniq_verts) + edge_verts = set() + non_planeedge_verts = set(range(nverts)) -all_planeverts + + # Look for tris with the same verts + repeated_tris = set() + tri_dict = {} + verts_to_check = set() + for k, tr in enumerate(tris): + tr_b = tr.copy() + tr_b.sort() + key = tuple(tr_b) + plist = tri_dict.setdefault(key, []) + plist.append(k) + if len(plist) > 1: + repeated_tris.update(plist) + verts_to_check.update(key) + if repeated_tris: + tris = tris[list(set(range(len(tris))) - repeated_tris), :] + verts_to_remove = verts_to_check - set(tris.ravel()) + non_planeedge_verts -= verts_to_remove + print(f'Found {len(repeated_tris)} repeated tris and removed {len(verts_to_remove)} verts.') + + for x in edverts: + non_planeedge_verts -= set(x) + edge_verts.update(x) + edge_verts = np.array(list(edge_verts), dtype=np.int32) + non_planeedge_verts = np.array(list(non_planeedge_verts), dtype=np.int32) + vert_order = np.concatenate((edge_verts, non_planeedge_verts)) + uniq_verts = uniq_verts[vert_order, :] + vert_ind = -np.ones(nverts, dtype=np.int32) + vert_ind[vert_order] = np.arange(len(vert_order), dtype=np.int32) + tris = vert_ind[tris] + for x in edverts: + ed_verts.append(vert_ind[x]) + else: + nsides = 0 + + +# print('Total vertices') +# print(len(verts)) +# print('Unique verts') +# print(len(uniq_verts)) +# print('Plane faces found:', len(plane_verts)) +# print('Plane nb verts:', plane_nb_verts.min(), 'to', plane_nb_verts.max()) +# print('Non plane verts:', len(uniq_verts) - plane_nb_verts.sum()) +# print('Nb of tris:', len(tris)) + + return uniq_verts, tris, nsides, ed_verts, shape + + + +def createMesh(target, r=0.5, lin_deflect=0.1, ang_deflect=math.radians(60.)): + """Gives a volume to each edge in target using cylinders of radius r and nsides sides""" + min_angle = math.radians(30) + min_length = r / math.tan(min_angle / 2.0) + quantization = 100 + tmesh = target.data + name = target.name + "Cyl" + nverts = len(tmesh.vertices) + nedges = len(tmesh.edges) + + verts = np.empty(nverts * 3, dtype=np.float32) + edges = np.empty(nedges * 2, dtype=np.int32) + + tmesh.vertices.foreach_get('co', verts) + tmesh.edges.foreach_get('vertices', edges) + + verts.shape = (nverts,3) + edges.shape = (nedges,2) + + vec_edges = verts[edges[:,1],:] - verts[edges[:,0],:] + edge_len = np.linalg.norm(vec_edges, axis=1, keepdims=True) + vec_edges /= edge_len + + + # Quantize edge orientations + qedges = (vec_edges * quantization).astype(np.int32) + + dqedges = {} + for k in range(nedges): + qv = tuple(qedges[k,:]) + dqedges.setdefault(qv,[]).append(k) + + edge_t = np.zeros(nedges, dtype=np.int32) + edge_types = [] + for k, t in enumerate(dqedges.keys()): + edge_types.append(t) + edge_t[dqedges[t]] = k + + + mesh = bpy.data.meshes.new(name+'Mesh') + + print(f'{nedges} total edges, {len(dqedges)} quantized orientations, {min_length:.2f}, minimal edge length.') + + + # Generate all possible edge orientations, including reverse + tempset = set() + for k in dqedges.keys(): + tempset.add(k) + bw = -np.array(list(k)) + tempset.add(tuple(bw)) + + dvecs = {} + listdir = list(tempset) + for k, v in enumerate(listdir): + dvecs[v] = k + + # Record all edges and their directions w.r.t. each node (vertex) + # nodes is a list containing, for every vertex, a list of pairs [ind, dir], + # where ind is the index of an edge that is connected with the vertex and + # dir is true if the edge starts in this vertex and false otherwise + nodes = [None] * nverts + for k in range(nedges): + v0, v1 = edges[k,0], edges[k,1] + t = (k, True) + if nodes[v0] is None: + nodes[v0] = [t] + else: + nodes[v0].append(t) + t = (k, False) + if nodes[v1] is None: + nodes[v1] = [t] + else: + nodes[v1].append(t) + + # Classify all nodes based on their (discretized) edge orientations + node_types = {} + single_nodes = set() + discarded_edges = set() + short_edges = set() + for k in range(nverts): + if nodes[k] is None: + # Ignore isolated vertices + continue + if len(nodes[k]) == 1: + single_nodes.add(k) + if edge_len[nodes[k][0][0]] < min_length: + # Discard single nodes with small edge length + discarded_edges.add(nodes[k][0]) + continue + cand_edges = [] + cand_dir = [] + for kk, eddir in nodes[k]: + if kk in discarded_edges: + continue + if edge_len[kk] < min_length: + if len(nodes[edges[kk, int(eddir)]]) == 1: + # Discard single nodes with small edge length + discarded_edges.add(kk) + continue + else: + # Mark short edges between non single nodes + short_edges.add(kk) + cand_edges.append(kk) + cand_dir.append(eddir) + if len(cand_edges) == 0: + continue + node_edges = np.array(cand_edges, dtype=np.int32) # list of edge indeces + edge_dir = np.array(cand_dir, dtype=np.int32) + edge_vec = qedges[node_edges, :].copy() + edge_vec[np.flatnonzero(np.logical_not(edge_dir)),:] *= -1 # flip the edge vector so that all point away from vertex + dir_keya = np.array([dvecs[tuple(x)] for x in edge_vec]) # retrieve the index of each quantitized vector in listdir + sd = dir_keya.argsort() + dir_key = tuple(dir_keya[sd]) + node_types.setdefault(dir_key, []).append(k) + temp = np.stack((node_edges, edge_dir.astype(np.int32)), axis=1) + nodes[k] = temp[sd,:] # sort the node's list of edges according to edge position in dict's keys + + print(nverts, 'total vertices,', len(node_types), 'distinct nodes,', len(single_nodes), 'single nodes,', len(discarded_edges), 'discarded edges and', len(short_edges), 'short edges.') + + + + total_verts = 0 + total_faces = 0 + processed_nodes = [] + occ_nsides = None + nr_nodetypes = len(node_types) + for k, (nt, nodelist) in enumerate(node_types.items()): + if nr_nodetypes > 100: + if k % 10 == 0: + print(f'Processing node {k} of {nr_nodetypes}', end='\r') + # Reconstruct edge vectors based on quantitized vectors + ev = np.array([listdir[d] for d in nt], dtype=np.float32) / quantization + + # Compute node geomery with Opencascade + try: + retry_count = 0 + node_verts, node_faces, node_nsides, node_edverts, shape = occ_compute_node(ev, r, mesh_pars=(lin_deflect, False, ang_deflect, False)) + while len(node_edverts) != len(nt) and retry_count < 20: + retry_count += 1 + print(f'Wrong number of edge verts in processed node {k} with {len(nt)} edges and {len(node_edverts)} found edges. Retry nb. {retry_count}.', end='\r') + node_verts, node_faces, node_nsides, node_edverts, shape = occ_compute_node(ev, r, mesh_pars=(lin_deflect, False, ang_deflect, False), shuffle=True) + if retry_count > 0: + print() + except: + print(f'OCC error in node {k}. Node list:') + print(nodelist) + raise + if occ_nsides is None: + occ_nsides = node_nsides + processed_nodes.append((node_verts, node_faces, node_edverts, nt, nodelist, )) + total_verts += len(node_verts) * len(nodelist) + total_faces += len(node_faces) * len(nodelist) + + nsides = occ_nsides + print('Nsides:', nsides) + newverts = np.empty((total_verts, 3), dtype=np.float32) + newfaces = np.empty((total_faces, 3), dtype=np.int32) + + vert_count = 0 + face_count = 0 + edgefaces = np.zeros((nedges, 2), dtype=np.int32) + ed_nd = np.zeros((nedges, 2, 2), dtype=np.int32) + for k, (node_verts, node_faces, node_edverts, nt, nodelist) in enumerate(processed_nodes): + valency = len(node_edverts) + verts_per_node = len(node_verts) + faces_per_node = len(node_faces) + ed_pos = np.arange(valency, dtype=np.int32) + if valency: + for n in nodelist: + # Translate the vertices of each node type to the actual position of the nodes and + # insert them in newverts + if verts_per_node: + newverts[vert_count:vert_count + verts_per_node, :] = node_verts + verts[n,:] + # Insert the node type faces in newfaces for each of the node instances + if faces_per_node: + newfaces[face_count:face_count + faces_per_node, :] = node_faces + vert_count + edgefaces[nodes[n][:,0], 1 - nodes[n][:,1]] = vert_count + ed_nd[nodes[n][:,0],0, 1 - nodes[n][:,1]] = k + ed_nd[nodes[n][:,0],1, 1 - nodes[n][:,1]] = ed_pos + vert_count += verts_per_node + face_count += faces_per_node + else: + print('Edgeless node found. Node list:', nodelist) + + ed_nd_dict = {} + for k in range(nedges): + if k in discarded_edges: + continue + node_a = tuple(ed_nd[k, :, 0]) + node_b = tuple(ed_nd[k, :, 1]) + edkey = tuple(sorted([node_a, node_b])) + edir = int(node_a == edkey[0]) + ed_nd_dict.setdefault(edkey, []).append([k, edir]) + + print('Edge node types:', len(ed_nd_dict)) + + ed_nd_faces = {} + ed_nd_nfaces = 0 + for ed_ty in ed_nd_dict.keys(): + (na, fa), (nb, fb) = ed_ty + node_verts, node_faces, node_edverts, nt, nodelist = processed_nodes[na] + ed_dir = np.array(listdir[nt[fa]], dtype=np.float32) / quantization + nedidxa = node_edverts[fa] + nva = node_verts[nedidxa, :] + node_verts, node_faces, node_edverts, nt, nodelist = processed_nodes[nb] + nedidxb = node_edverts[fb] + nvb = node_verts[nedidxb, :] + rotmat = make_rotmatrix(ed_dir) + rotmat = rotmat.T[:,:2].copy() + proj_verts = nva @ rotmat + ang_a = np.arctan2(proj_verts[:,1], proj_verts[:,0]) + proj_verts = nvb @ rotmat + ang_b = np.arctan2(proj_verts[:,1], proj_verts[:,0]) + ed_fa, face_masq = ring_connect_faces(ang_a, ang_b) + other_masq = np.logical_not(face_masq) + ed_fanew = np.zeros(ed_fa.shape, dtype=np.int32) + ed_fanew[face_masq] = nedidxa[ed_fa[face_masq]] + ed_fanew[other_masq] = nedidxb[ed_fa[other_masq]] + ed_nd_faces[ed_ty] = [ed_fanew, face_masq] + ed_nd_nfaces += len(ed_nd_dict[ed_ty]) * len(ed_fa) + + newfaces.resize((total_faces + ed_nd_nfaces, 3)) + print('Nb. of edge node faces:', ed_nd_nfaces) + + + processed_faces = 0 + for ed_ty in ed_nd_dict.keys(): + edfaces, face_masq = ed_nd_faces[ed_ty] + other_facemasq = np.logical_not(face_masq) + ed_nfaces = len(edfaces) + faceoffsets = np.zeros(edfaces.shape, dtype=np.int32) + for edidx, edir in ed_nd_dict[ed_ty]: + faceoffsets[face_masq] = edgefaces[edidx, 1-edir] + faceoffsets[other_facemasq] = edgefaces[edidx, edir] + newfaces[total_faces + processed_faces : total_faces + processed_faces + ed_nfaces,:] = edfaces + faceoffsets + processed_faces += ed_nfaces + + + + mesh.from_pydata(newverts, [], list(newfaces)) + newobj = bpy.data.objects.new(name, mesh) + + # Place the lattice at the same position and attitude of original object + newobj.matrix_world = target.matrix_world.copy() + + + # Link object to scene + bpy.context.scene.collection.objects.link(newobj) + + + +def createMetaball(target, r=0.5, p=0.9): + if target.type != 'MESH': + return + + name = target.name + "Rod" + print("Creating", name) + + metaball = bpy.data.metaballs.new(name+'Meta') + obj = bpy.data.objects.new(name, metaball) + bpy.context.scene.collection.objects.link(obj) + stiffness = 10.0 + + # clip p + p = min(p, 0.99); + p = max(p, 0.01) + + # Compute the threashold so that mesh radius is + # exacltly r + metaball.threshold = (1 - p ** 2) ** 3 * stiffness + + radius = r / p + + vec_x = Vector((1.0, 0.0, 0.0)) + + for v in target.data.vertices: + location = v.co.copy() + + element = metaball.elements.new() + element.co = location + element.radius = radius + element.stiffness = stiffness + + for e in target.data.edges: + v0 = target.data.vertices[e.vertices[0]].co + v1 = target.data.vertices[e.vertices[1]].co + edge = v1 - v0 + edge_len = edge.length + + if edge_len > r: + edge_middle = (v1 + v0) / 2.0 + element = metaball.elements.new() + element.co = edge_middle + element.radius = radius + element.stiffness = stiffness + + if edge_len > 2 * r: + element.type = 'CAPSULE' + element.size_x = (edge_len - 2 * r) / 2.0 + angle = edge.angle(vec_x) + if abs(angle) > 1e-3: + axis = edge.cross(vec_x).normalized() + rot = Quaternion(axis, -angle).normalized() + element.rotation = (rot.w, rot.x, rot.y, rot.z) + + + # Place the lattice at the same position and attitude of original object + obj.matrix_world = target.matrix_world.copy() + + return obj + + +class ObjectMetaLattice(bpy.types.Operator): + """Metaball Lattice""" + bl_idname = "object.metalattice" + bl_label = "Meta Lattice" + bl_options = {'REGISTER', 'UNDO'} + + @classmethod + def poll(cls, context): + return context.active_object is not None and context.active_object.type == 'MESH' + + + def execute(self, context): + lattice_mesh = context.scene.lattice_mesh + createMetaball(context.active_object, lattice_mesh.radius, lattice_mesh.r_ratio) + return {'FINISHED'} + + +class ObjectOCCLattice(bpy.types.Operator): + """Metaball Lattice""" + bl_idname = "object.occlattice" + bl_label = "Lattice Volume (OCC)" + bl_options = {'REGISTER', 'UNDO'} + + @classmethod + def poll(cls, context): + return have_occ and context.active_object is not None and context.active_object.type == 'MESH' + + + def execute(self, context): + lattice_mesh = context.scene.lattice_mesh + createMesh(context.active_object, lattice_mesh.radius, lattice_mesh.lin_deflect, lattice_mesh.ang_deflect) + return {'FINISHED'} + + + +class ObjectCreateMeshLattice(bpy.types.Operator): + """Create Mesh Lattice""" + bl_idname = "object.create_meshlattice" + bl_label = "Create Mesh Lattice" + bl_options = {'REGISTER', 'UNDO'} + + + + @classmethod + def poll(cls, context): + return context.mode == 'OBJECT' + + + def execute(self, context): + lattice_mesh = context.scene.lattice_mesh + name = "Lattice" + nelems = np.array(lattice_mesh.nelems) + corner = np.array(context.scene.cursor.location).reshape((1,3)) + v, e = make_nplattice(Cells[lattice_mesh.celltype], lattice_mesh.cellsize, nelems, corner) + verts, edges = nplattice2meshdata(v, e) + bm, mesh = make_meshlattice(name, verts, edges, lattice_mesh.cellsize) + bm.to_mesh(mesh) + bm.free() + + newobj = bpy.data.objects.new(name, mesh) + + # Link object to scene + bpy.context.scene.collection.objects.link(newobj) + + return {'FINISHED'} + + +class ObjectFillMeshLattice(bpy.types.Operator): + """Fill Mesh Lattice""" + bl_idname = "object.fill_meshlattice" + bl_label = "Fill Mesh Lattice" + bl_options = {'REGISTER', 'UNDO'} + + @classmethod + def poll(cls, context): + return context.active_object is not None and context.active_object.type == 'MESH' + + + def execute(self, context): + obj = context.active_object + name = obj.name + "Lattice" + bb = np.array([[x for x in y] for y in obj.bound_box], dtype=np.float32) + minp = bb.min(axis=0) + maxp = bb.max(axis=0) + dims = maxp - minp + lattice_mesh = context.scene.lattice_mesh + nelems = np.ceil((dims + lattice_mesh.cellsize)/ lattice_mesh.cellsize).astype(np.int32) + griddims = nelems.astype(np.float32) * lattice_mesh.cellsize + corner = ((maxp + minp) / 2.0) - (griddims /2.0) + corner = corner.reshape((1,3)) + + v, e = make_nplattice(Cells[lattice_mesh.celltype], lattice_mesh.cellsize, nelems, corner) + verts, edges = nplattice2meshdata(v, e) + bm, mesh = make_meshlattice(name, verts, edges, lattice_mesh.cellsize) + depsgraph = context.evaluated_depsgraph_get() + intersect(bm, obj, depsgraph) + bm.to_mesh(mesh) + bm.free() + + newobj = bpy.data.objects.new(name, mesh) + newobj.matrix_world = obj.matrix_world.copy() + + # Link object to scene + bpy.context.scene.collection.objects.link(newobj) + + return {'FINISHED'} + + +class ObjectFillVoronoiLattice(bpy.types.Operator): + """Fill Voronoi Lattice""" + bl_idname = "object.fill_voronoilattice" + bl_label = "Fill Voronoi Lattice" + bl_options = {'REGISTER', 'UNDO'} + + @classmethod + def poll(cls, context): + return have_scipy and context.active_object is not None and context.active_object.type == 'MESH' + + def execute(self, context): + obj = context.active_object + name = obj.name + "Voronoi" + bb = np.array([[x for x in y] for y in obj.bound_box], dtype=np.float32) + minp = bb.min(axis=0) + maxp = bb.max(axis=0) + dims = maxp - minp + corner = minp + corner = corner.reshape((1,3)) + + lattice_mesh = context.scene.lattice_mesh + v, e = make_npvoronoi(lattice_mesh.charac_length, dims, corner) + verts, edges = nplattice2meshdata(v, e) + bm, mesh = make_meshlattice(name, verts, edges, lattice_mesh.charac_length) + depsgraph = context.evaluated_depsgraph_get() + intersect(bm, obj, depsgraph) + bm.to_mesh(mesh) + bm.free() + + newobj = bpy.data.objects.new(name, mesh) + newobj.matrix_world = obj.matrix_world.copy() + + # Link object to scene + bpy.context.scene.collection.objects.link(newobj) + + return {'FINISHED'} + + + + diff --git a/Lattesh/ui.py b/Lattesh/ui.py new file mode 100644 index 0000000000000000000000000000000000000000..967402207ad19afa35d5589cd8c3dcef82aa3775 --- /dev/null +++ b/Lattesh/ui.py @@ -0,0 +1,126 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Ubiratan S. Freitas + + +# This file is part of Lattesh. +# +# Lattesh is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by the +# Free Software Foundation, either version 3 of the License, or (at your option) +# any later version. +# +# Lattesh is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +# more details. +# +# You should have received a copy of the GNU General Public License along with +# Lattice Tools. If not, see <https://www.gnu.org/licenses/>. + + +from bpy.types import Panel + + +from .operators import have_scipy, have_occ + + +# Test functions for polling +def is_mode_object(context): + return context.mode == 'OBJECT' + +def is_active_object_mesh(context): + return context.active_object is not None and context.active_object.type == 'MESH' + + + + + + + + + +class View3DLatticePanel: + bl_category = "Lattices" + bl_space_type = 'VIEW_3D' + bl_region_type = 'UI' + + + +class VIEW3D_PT_lattices_generate(View3DLatticePanel, Panel): + bl_label = "Generate lattices" + bl_idname = "VIEW3D_PT_lattices_generate" + + def draw(self, context): + layout = self.layout + + lattice_mesh = context.scene.lattice_mesh + + layout.label(text="Regular cells") + row = layout.row(align=True) + row.label(text="Cell size") + row.prop(lattice_mesh, "cellsize", text="") + row = layout.row(align=True) + row.label(text="Cell type") + row.prop(lattice_mesh, "celltype", text="") + row = layout.row(align=True) + row.label(text="Number of cells") + row.prop(lattice_mesh, "nelems", text="") + layout.operator("object.create_meshlattice") + layout.operator("object.fill_meshlattice") + + layout.label(text="Random lattice") + row = layout.row(align=True) + row.label(text="Characteristic length") + row.prop(lattice_mesh, "charac_length", text="") + layout.operator("object.fill_voronoilattice") + + +class VIEW3D_PT_lattice_OCC(View3DLatticePanel, Panel): + bl_label = "Opencascade fill" + bl_idname = "VIEW3D_PT_lattice_OCC" + + @classmethod + def poll(cls, context): + return have_occ and is_mode_object(context) and is_active_object_mesh(context) + + def draw(self, context): + lattice_mesh = context.scene.lattice_mesh + + layout = self.layout + row = layout.row(align=True) + row.label(text="Strut radius") + row.prop(lattice_mesh, "radius", text="") + row = layout.row(align=True) + row.label(text="Linear deflection") + row.prop(lattice_mesh, "lin_deflect", text="") + row = layout.row(align=True) + row.label(text="Angular deflection") + row.prop(lattice_mesh, "ang_deflect", text="") + + layout.operator("object.occlattice") + + +class VIEW3D_PT_lattice_metaball(View3DLatticePanel, Panel): + bl_label = "Metaball fill" + bl_idname = "VIEW3D_PT_lattice_metaball" + bl_options = {"DEFAULT_CLOSED"} + + @classmethod + def poll(cls, context): + return is_mode_object(context) and is_active_object_mesh(context) + + def draw(self, context): + lattice_mesh = context.scene.lattice_mesh + + layout = self.layout + row = layout.row(align=True) + row.label(text="Strut radius") + row.prop(lattice_mesh, "radius", text="") + row = layout.row(align=True) + row.label(text="Radius ratio") + row.prop(lattice_mesh, "r_ratio", text="") + + layout.operator("object.metalattice") + + + \ No newline at end of file