diff --git a/.gitmodules b/.gitmodules index ea20c57..39904c4 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,9 @@ +[submodule "rcg_pipeline"] + path = rcg_pipeline + url = https://gitlab.com/robossembler/rcg-pipeline.git +[submodule "freecad_workbench"] + path = freecad_workbench + url = https://gitlab.com/robossembler/robossembler-freecad-workbench.git [submodule "simulation/insertion_vector_predicate/assembly"] - path = insertion_vector_predicate/assembly + path = simulation/insertion_vector_predicate/assembly url = https://github.com/yunshengtian/Assemble-Them-All diff --git a/freecad_workbench b/freecad_workbench new file mode 160000 index 0000000..08db658 --- /dev/null +++ b/freecad_workbench @@ -0,0 +1 @@ +Subproject commit 08db6583ce94895103c94b1b70b4846ef581e624 diff --git a/freecad_workbench/LICENSE b/freecad_workbench/LICENSE deleted file mode 100644 index 5f2dd7f..0000000 --- a/freecad_workbench/LICENSE +++ /dev/null @@ -1,505 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -(This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.) - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -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 this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -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 -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser 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 Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "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 -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY 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 -LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Libraries - - If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms of the -ordinary General Public License). - - To apply these terms, attach the following notices to the library. It is -safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least the -"copyright" line and a pointer to where the full notice is found. - - {description} - Copyright (C) {year} {fullname} - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 - USA - -Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the library, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James Random - Hacker. - - {signature of Ty Coon}, 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! - diff --git a/freecad_workbench/MANIFEST.in b/freecad_workbench/MANIFEST.in deleted file mode 100644 index 7887a18..0000000 --- a/freecad_workbench/MANIFEST.in +++ /dev/null @@ -1 +0,0 @@ -recursive-include freecad/robossembler/resources * diff --git a/freecad_workbench/Makefile b/freecad_workbench/Makefile deleted file mode 100644 index ff13730..0000000 --- a/freecad_workbench/Makefile +++ /dev/null @@ -1,51 +0,0 @@ -# Makefile for string replacement tasks -# Replace values from starterkit to your workbench name - -# Define replacements as variables -WORKBENCH_DIR_NAME = robossembler -WORKBENCH_CLASS_NAME = Robossembler -WORKBENCH_MENUTEXT = Robossembler -WORKBENCH_TOOLTIP = FreeCAD Robossembler Workbench -WORKBENCH_ICON = robossembler.svg -WORKBENCH_TRANSLATION_CONTEXT = cool -MAINTAINER = Mark Voltov -EMAIL = ius.mark.alex@gmail.com -URL = https://gitlab.com/robossembler/framework -DESCRIPTION = FreeCAD Robossembler Workbench - Assembly Sequence Planning, Analysis -DEPENDENCIES_LIST = [] - -.PHONY: all replace_strings - -all: replace_strings - -replace_strings: - @echo -e "\033[1;34mReplacing strings\033[0m" - @# Update instances of 'workbench_starterkit' on different files - sed -i 's/workbench_starterkit/$(WORKBENCH_DIR_NAME)/g' MANIFEST.in - sed -i 's/workbench_starterkit/$(WORKBENCH_DIR_NAME)/g' freecad/workbench_starterkit/init_gui.py - sed -i 's/workbench_starterkit/$(WORKBENCH_DIR_NAME)/g' freecad/workbench_starterkit/resources/translations/update_translation.sh - sed -i 's/workbench_starterkit/$(WORKBENCH_DIR_NAME)/g' freecad/workbench_starterkit/resources/translations/workbench_starterkit_es-ES.ts - sed -i 's/workbench_starterkit/$(WORKBENCH_DIR_NAME)/g' setup.py - @# Rename workbench class name - sed -i 's/TemplateWorkbench/$(WORKBENCH_CLASS_NAME)/g' freecad/workbench_starterkit/init_gui.py - @# Rename workbench class properties - sed -i 's/template workbench/$(WORKBENCH_MENUTEXT)/g' freecad/workbench_starterkit/init_gui.py - sed -i 's/a simple template workbench/$(WORKBENCH_TOOLTIP)/g' freecad/workbench_starterkit/init_gui.py - sed -i 's/template_resource.svg/$(WORKBENCH_ICON)/g' freecad/workbench_starterkit/init_gui.py - @# Rename workbench icon - mv freecad/workbench_starterkit/resources/template_resource.svg freecad/workbench_starterkit/resources/$(WORKBENCH_ICON) - @# Rename context string for translation of workbench name - sed -i 's/starterkit/$(WORKBENCH_TRANSLATION_CONTEXT)/g' freecad/workbench_starterkit/init_gui.py - sed -i 's/starterkit/$(WORKBENCH_TRANSLATION_CONTEXT)/g' freecad/workbench_starterkit/resources/translations/workbench_starterkit_es-ES.ts - @# Rename workbench directory - mv freecad/workbench_starterkit freecad/$(WORKBENCH_DIR_NAME) - @# Update setup.py file - sed -i 's/looooo/$(MAINTAINER)/g' setup.py - sed -i 's/sppedflyer@gmail.com/$(EMAIL)/g' setup.py - sed -i 's|https://github.com/FreeCAD/Workbench-Starterkit|$(URL)|g' setup.py - sed -i 's/template for a freecad extensions\, installable with pip/$(DESCRIPTION)/g' setup.py - sed -i "s/\['numpy'\]/$(DEPENDENCIES_LIST)/g" setup.py - -self-destruction: - echo "Remove Makefile" - rm Makefile diff --git a/freecad_workbench/README.md b/freecad_workbench/README.md deleted file mode 100644 index d841211..0000000 --- a/freecad_workbench/README.md +++ /dev/null @@ -1,9 +0,0 @@ -## Модули проекта Robossembler для FreeCAD - -Верстак протестирован в FreeCAD версии 21.2 - -### Инструкция по установке -1. Установить FreeCAD (https://www.freecadweb.org/wiki/Installing) -2. Клонировать папку ```freecad_workbench``` в директорию установки верстаков согласно [инструкции по установке верстаков](https://wiki.freecad.org/How_to_install_additional_workbenches) -3. Для пользователей Ubuntu - скопировать папку ```freecad_workbench``` в директорию ```~/.local/share/FreeCAD/Mod``` - diff --git a/freecad_workbench/docs/commands.md b/freecad_workbench/docs/commands.md deleted file mode 100644 index 8259a5c..0000000 --- a/freecad_workbench/docs/commands.md +++ /dev/null @@ -1,127 +0,0 @@ -# Code Snippets -There is no way to add a button, menu entry from python to a workbench which is added with c++. So here is a comparison how to do that with python and with c++. - -## Adding a command: -This can be done either with python or c++. - -### 1. python - -```python -import FreeCAD as App - -class MyCommand(object): - def IsActive(self): - """ - availability of the command (eg.: check for existence of a document,...) - if this function returns False, the menu/ buttons are ßdisabled (gray) - """ - if App.ActiveDocument is None: - return False - else: - return True - - def GetResources(self): - """ - resources which are used by buttons and menu-items - """ - return {'Pixmap': 'path_to_icon.svg', 'MenuText': 'my command', 'ToolTip': 'very short description'} - - def Activated(self): - """ - the function to be handled, when a user starts the command - """ -``` -To register the command in FreeCAD: - -```python -import FreeCADGui as Gui -Gui.addCommand('MyCommand', MyCommand()) -``` - -Adding a new toolbar/menu: -```python -from FreeCADGui import Workbench -class myWorkbench(Workbench): - MenuText = "name_of_workbench" - ToolTip = "short description of workbench" - Icon = "path_to_icon.svg" - - def GetClassName(self): - return "Gui::PythonWorkbench" - - def Initialize(self): - self.appendToolbar("Gear", ["MyCommand"]) - self.appendMenu("Gear", ["MyCommand"]) -``` - -### 2. C++ - -```c++ - -#include -#include -#include -#include - -using namespace std; - -DEF_STD_CMD_A(MyCommand) - -MyCommand::MyCommand() - : Command("MyCommand") -{ - sAppModule = "module"; - sGroup = QT_TR_NOOP("Mesh"); - sMenuText = QT_TR_NOOP("my command"); - sToolTipText = QT_TR_NOOP("very short description"); - sWhatsThis = "MyCommand"; - sStatusTip = sToolTipText; -} - -void MyCommand::activated(int) -{ - // the function to be handled, when a user starts the command -} - -bool MyCommand::isActive(void) -{ - // availability of the command (eg.: check for existence of a document,...) - // if this function returns False, the menu/ buttons are ßdisabled (gray) - return (hasActiveDocument() && !Gui::Control().activeDialog()); -} -``` -To register the command in FreeCAD: - -```c++ -#include - -Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); -rcCmdMgr.addCommand(new MyCommand()); -``` -Adding a item to a menu/toolbar: - -if your command is added with python you have to run this code: -in src/module/Gui/AppModuleGui.cpp add to PyMOD_INIT_FUNC: - -```c++ -// try to instantiate a python module -try{ - Base::Interpreter().runStringObject("import MyCommands"); -} catch (Base::PyException &err){ - err.ReportException(); -} -``` - -and add the name of the command to a tooltip/menu in src/module/Gui/Workbench.cpp Workbench::setupToolBars - - -```c++ -Gui::ToolBarItem* Workbench::setupToolBars() const -{ - Gui::ToolBarItem* root = StdWorkbench::setupToolBars(); - Gui::ToolBarItem* myToolbar = new Gui::ToolBarItem(root); - myToolbar->setCommand("my_commands"); - *myToolbar << "MyCommand"; - return root; -} -``` diff --git a/freecad_workbench/freecad/robossembler/BoMList.py b/freecad_workbench/freecad/robossembler/BoMList.py deleted file mode 100644 index 1cca0c0..0000000 --- a/freecad_workbench/freecad/robossembler/BoMList.py +++ /dev/null @@ -1,110 +0,0 @@ -import FreeCAD as App -import Spreadsheet - -from .helper.is_solid import is_object_solid - -def createSpreadsheet(): - - if App.ActiveDocument.getObject("BoM_List") == None: - - sheet = App.activeDocument().addObject('Spreadsheet::Sheet', 'BoM_List') - sheet.set('A1', 'п.п.') - sheet.set('B1', 'Наименование детали') - sheet.set('C1', 'Количество') - else: - - sheet = App.ActiveDocument.getObject("BoM_List") - App.ActiveDocument.BoM_List.clear('A1:ZZ16384') - sheet.set('A1', 'п.п.') - sheet.set('B1', 'Наименование детали') - sheet.set('C1', 'Количество') - - return (sheet) - - -class SolidBodiesParcer: - _asmThere = [] - - def __init__(self) -> None: - if (self._asmThere.__len__() == 0): - - self.initParse() - pass - - def initParse(self): - for el in App.ActiveDocument.RootObjects: - if (is_object_solid(el) and hasattr(el, 'Group')): - self.getSubPartsLink(el.Group, el.Label) - - def getSubPartsLink(self, group, label): - groupLink = {label: []} - for el in group: - if (is_object_solid(el)): - groupLink[label].append( - {'label': el.Label, 'isGroup': hasattr(el, 'Group'), 'solid': el}) - - for el in groupLink[label]: - if ('isGroup' in el): - if (el['isGroup'] == False): - self._asmThere.append(el['solid'].Label) - if (el['isGroup']): - self.getSubPartsLink(el['solid'].Group, el['label']), - - return groupLink - - -def uniquePartsSort(labelParts): - - uniquePartsLabels = {} - - for el in labelParts: - for k in labelParts: - if (App.ActiveDocument.getObjectsByLabel(str(el))[0].Shape.isPartner(App.ActiveDocument.getObjectsByLabel(str(k))[0].Shape)): - - if uniquePartsLabels.get(el) == None: - uniquePartsLabels[el] = k - - sortedParts = {} - - for k, v in uniquePartsLabels.items(): - - if sortedParts.get(v) == None: - sortedParts[v] = [k] - else: - sortedParts[v].append(k) - - return sortedParts - - -def countForUniques(sortedParts): - countedParts = {} - for k in sortedParts: - countedParts[k] = len(sortedParts[k]) - return countedParts - - -def fillInBoMList(sheet, countedParts): - - a = 1 - - for label, count in countedParts.items(): - a += 1 - b = label - c = count - sheet.set('A' + str(a), str(a-1)) - sheet.set('B' + str(a), str(b)) - sheet.set('C' + str(a), str(c)) - - total_count = sum(countedParts.values()) - sheet.set('B'+str(a+1), 'Итого') - - sheet.set('C' + str(a+1), str(total_count)) - - -def run_BoM_list(): - createSpreadsheet() - sheet = App.ActiveDocument.getObject("BoM_List") - labelParts = SolidBodiesParcer()._asmThere - sortedParts = uniquePartsSort(labelParts) - countedParts = countForUniques(sortedParts) - fillInBoMList(sheet, countedParts) diff --git a/freecad_workbench/freecad/robossembler/CHANGELOG.md b/freecad_workbench/freecad/robossembler/CHANGELOG.md deleted file mode 100644 index 7412819..0000000 --- a/freecad_workbench/freecad/robossembler/CHANGELOG.md +++ /dev/null @@ -1,19 +0,0 @@ -# Change Log -All notable changes to this project will be documented in this file. - -The format is based on [Keep a Changelog](http://keepachangelog.com/) -and this project adheres to [Semantic Versioning](http://semver.org/). - -## [0.1] - Robbossembler FreeCAD Workbench - 2024.04.07 - -Верстак для предподготовки CAD-модели изделия к автоматизированному производству. - -### Added -- - -### Changed -- Изменена компоновка в директории верстака. Все относящиеся к работе верстака элементы теперь находятся в его директории. -- Добавлен инструмент публикации проекта и создания всех необходимых файлов через верстак. - -### Fixed -- \ No newline at end of file diff --git a/freecad_workbench/freecad/robossembler/DatumCommand.py b/freecad_workbench/freecad/robossembler/DatumCommand.py deleted file mode 100644 index a7db4fd..0000000 --- a/freecad_workbench/freecad/robossembler/DatumCommand.py +++ /dev/null @@ -1,49 +0,0 @@ -import FreeCAD -import FreeCADGui -from PySide import QtGui, QtCore - -class DatumTool: - """ - A tool for creating datums in existing models - """ - def __init__(self): - self.active = False - - def activate(self): - self.active = True - FreeCAD.Console.PrintMessage("Datum tool activatedn") - - def deactivate(self): - self.active = False - FreeCAD.Console.PrintMessage("Datum tool deactivatedn") - - def mousePressEvent(self, event): - if self.active: - # Create a datum at the position of the mouse click - pos = FreeCADGui.ActiveDocument.ActiveView.getCursorPos() - point = FreeCADGui.ActiveDocument.ActiveView.getPoint(pos) - datum = FreeCAD.ActiveDocument.addObject("Part::Datum", "Datum") - datum.Placement.Base = point - datum.ViewObject.ShapeColor = (0.0, 1.0, 0.0) # Set the color of the datum to green - FreeCAD.ActiveDocument.recompute() - -class DatumCommand: - """ - A command for activating and deactivating the datum tool - """ - def __init__(self): - self.tool = DatumTool() - - def Activated(self): - self.tool.activate() - FreeCADGui.ActiveDocument.ActiveView.addEventCallback("SoMouseButtonEvent", self.tool.mousePressEvent) - - def Deactivated(self): - self.tool.deactivate() - FreeCADGui.ActiveDocument.ActiveView.removeEventCallback("SoMouseButtonEvent", self.tool.mousePressEvent) - - def GetResources(self): - return {'Pixmap': 'path/to/icon.png', 'MenuText': 'Datum Tool', 'ToolTip': 'Creates datum elements in existing models'} - -# Add the command to the Draft Workbench -FreeCADGui.addCommand('DatumCommand', DatumCommand()) \ No newline at end of file diff --git a/freecad_workbench/freecad/robossembler/Frames.py b/freecad_workbench/freecad/robossembler/Frames.py deleted file mode 100644 index cd26ab8..0000000 --- a/freecad_workbench/freecad/robossembler/Frames.py +++ /dev/null @@ -1,826 +0,0 @@ -import FreeCAD - -from . import ICONPATH, TRANSLATIONSPATH -from .Tools import spawnClassCommand, placement2axisvec, describeSubObject, getPrimitiveInfo #, RobossemblerFreeCadExportScenario -from .pddl import freecad2pddl -from .BoMList import run_BoM_list -from .export_entities import export_coordinate_systems -from .utils.freecad_processor import process_file -from .project_validator import validate_project -from .usecases.asm4parser_usecase import Asm4StructureParseUseCase -from .constraints_operator import create_assembly_parameters, create_fastener_set, create_assembly_sequence, create_clearance_constraint, export_assembly_settings -from .geometric_feasibility_predicate.main import main as structure_analysis -from .asm_graph import main as asm_graph -# from .autodock_generator import main as asm_layers -from .assembly_graph_generation import main as structure_graph - -if FreeCAD.GuiUp: - import FreeCADGui - from pivy import coin - from PySide import QtCore, QtGui, QtSvg - import Part - import os - -############################################################ -# Frame Objects -############################################################ -class Frame(object): - """Basic freestanding frame""" - def __init__(self, obj): - obj.addProperty("App::PropertyPlacement", - "Placement", "Base", - "Placement of the frame") - obj.Placement = FreeCAD.Placement() - obj.Proxy = self - self.obj = obj - self.additional_data = {} - - def onChanged(self, fp, prop): - pass - - def execute(self, obj): - pass - - def __getstate__(self): - return None - - def __setstate__(self, state): - return None - - def getDict(self): - d = {} - d["label"] = str(self.obj.Label) - d["placement"] = placement2axisvec(self.obj.Placement) - d.update(self.additional_data) - return d - - -class PartFrame(Frame): - """Frame rigidly attached to a part frame. - Inherits the base placement from the part's frame, and placement is - relative to the part frame. - """ - def __init__(self, obj, partobj): - Frame.__init__(self, obj) - obj.addProperty("App::PropertyPlacementLink", - "Part", "Parent", - "The part to attach to.") - obj.Part = partobj - obj.setEditorMode("Part", 1) - - def execute(self, obj): - if FreeCAD.GuiUp: - obj.ViewObject.Proxy.updateData(obj, "Placement") - - def getDict(self): - d = Frame.getDict(self) - d["part"] = str(self.obj.Part.Label) - return d - - -class FeatureFrame(PartFrame): - """Frame rigidly attached to a feature. - The feature frame is attached to a feature on a part. It gives both the - placement of the feature w.r.t. the part, and the placement from the - feature.""" - def __init__(self, obj, partobj, featurePlacement): - PartFrame.__init__(self, obj, partobj) - obj.addProperty("App::PropertyPlacement", - "FeaturePlacement", "Feature", - "The frame attached to the feature.") - obj.addProperty("App::PropertyString", - "PrimitiveType", "Feature", - "The primitive type of the feature.") - obj.addProperty("App::PropertyString", - "ShapeType", "Feature", - "The shape type of the feature.") - obj.addProperty("App::PropertyString", - "Positioning", "Feature", - "The type of positioning used during creation.") - obj.FeaturePlacement = featurePlacement - - def getDict(self): - d = PartFrame.getDict(self) - d["featureplacement"] = placement2axisvec(self.obj.FeaturePlacement) - d["shapetype"] = str(self.obj.ShapeType) - d["positioning"] = str(self.obj.Positioning) - return d - - -############################################################ -# ViewProvider to the frames -############################################################ -class ViewProviderFrame(object): - """ViewProvider for the basic frame. - Uses the SOAxiscrosskit to create axises with constant length regardless - of zoom. Updates position when placement is changed. - """ - def __init__(self, vobj): - vobj.addProperty("App::PropertyFloat", "Scale") - vobj.Scale = 0.12 - vobj.addProperty("App::PropertyFloat", "HeadSize") - vobj.HeadSize = 3.0 - vobj.addProperty("App::PropertyFloat", "LineWidth") - vobj.LineWidth = 2.0 - vobj.Proxy = self - - def attach(self, vobj): - # We only have a shaded visual group - self.shaded = coin.SoGroup() - - # Takes heavily from SoAxisCrosskit.h, - # and Toggle_DH_Frames by galou_breizh on the forums - self.vframe = coin.SoType.fromName("SoShapeScale").createInstance() - self.vframe.setPart("shape", coin.SoType.fromName("SoAxisCrossKit").createInstance()) - self.vframe.scaleFactor.setValue(0.2) - ax = self.vframe.getPart("shape", 0) - cone = ax.getPart("xHead.shape", 0) - cone.bottomRadius.setValue(vobj.HeadSize) - cone = ax.getPart("yHead.shape", 0) - cone.bottomRadius.setValue(vobj.HeadSize) - cone = ax.getPart("zHead.shape", 0) - cone.bottomRadius.setValue(vobj.HeadSize) - lwstring = "lineWidth {0}".format(vobj.LineWidth) - ax.set("xAxis.appearance.drawStyle", lwstring) - ax.set("yAxis.appearance.drawStyle", lwstring) - ax.set("zAxis.appearance.drawStyle", lwstring) - ax.set("xAxis.pickStyle", "style SHAPE") - ax.set("yAxis.pickStyle", "style SHAPE") - ax.set("zAxis.pickStyle", "style SHAPE") - - # Then remember to make it selectable in the viewer - selectionNode = coin.SoType.fromName("SoFCSelection").createInstance() - selectionNode.documentName.setValue(FreeCAD.ActiveDocument.Name) - selectionNode.objectName.setValue(vobj.Object.Name) - selectionNode.subElementName.setValue("Frame") - selectionNode.addChild(self.vframe) - - # We would like to place it where we want - self.transform = coin.SoTransform() - self.shaded.addChild(self.transform) - self.shaded.addChild(self.vframe) - self.shaded.addChild(selectionNode) - vobj.addDisplayMode(self.shaded, "Shaded") - - def updateData(self, fp, prop): - if prop == "Placement": - pl = fp.getPropertyByName("Placement") - self.transform.translation = (pl.Base.x, - pl.Base.y, - pl.Base.z) - self.transform.rotation = pl.Rotation.Q - - def getDisplayModes(self, vobj): - modes = ["Shaded"] - return modes - - def getDefaultDisplayMode(self): - return "Shaded" - - def onChanged(self, vp, prop): - if prop == "Scale": - s = vp.getPropertyByName("Scale") - self.vframe.scaleFactor.setValue(float(s)) - elif prop == "HeadSize": - hs = vp.getPropertyByName("HeadSize") - xcone = self.vframe.getPart("shape", 0).getPart("xHead.shape", 0) - xcone.bottomRadius.setValue(float(hs)) - ycone = self.vframe.getPart("shape", 0).getPart("yHead.shape", 0) - ycone.bottomRadius.setValue(float(hs)) - zcone = self.vframe.getPart("shape", 0).getPart("zHead.shape", 0) - zcone.bottomRadius.setValue(float(hs)) - elif prop == "LineWidth": - lw = vp.getPropertyByName("LineWidth") - lwstring = "lineWidth {0}".format(lw) - ax = self.vframe.getPart("shape", 0) - ax.set("xAxis.appearance.drawStyle", lwstring) - ax.set("yAxis.appearance.drawStyle", lwstring) - ax.set("zAxis.appearance.drawStyle", lwstring) - - def __getstate__(self): - return None - - def __setstate__(self, state): - pass - - -class ViewProviderPartFrame(ViewProviderFrame): - """View provider to the part frame.""" - def updateData(self, fp, prop): - if prop == "Placement": - parentpl = fp.getPropertyByName("Part").Placement - localpl = fp.Placement - pl = parentpl.multiply(localpl) - self.transform.translation = (pl.Base.x, - pl.Base.y, - pl.Base.z) - self.transform.rotation = pl.Rotation.Q - - -class ViewProviderFeatureFrame(ViewProviderFrame): - """View provider to the feature frames.""" - def updateData(self, fp, prop): - if prop == "Placement": - parentpl = fp.getPropertyByName("Part").Placement - featurepl = fp.getPropertyByName("FeaturePlacement") - localpl = fp.Placement - pl = parentpl.multiply(featurepl.multiply(localpl)) - self.transform.translation = (pl.Base.x, - pl.Base.y, - pl.Base.z) - self.transform.rotation = pl.Rotation.Q - - -################################################################### -# Base functions -################################################################### - -def makeFrame(placement=FreeCAD.Placement()): - obj = FreeCAD.ActiveDocument.addObject("App::FeaturePython", "Frame") - Frame(obj) - if FreeCAD.GuiUp: - ViewProviderFrame(obj.ViewObject) - return obj - - -def makePartFrame(part): - obj = FreeCAD.ActiveDocument.addObject("App::FeaturePython", "PartFrame") - PartFrame(obj, part) - #if int(FreeCAD.Version()[1]) > 16: - # geo_feature_group = part.getParentGeoFeatureGroup() - # geo_feature_group.addObject(obj) - if FreeCAD.GuiUp: - ViewProviderPartFrame(obj.ViewObject) - return obj - - -def makeFeatureFrame(part, featurepl): - obj = FreeCAD.ActiveDocument.addObject("App::FeaturePython", - "FeatureFrame") - FeatureFrame(obj, part, featurepl) - # If we're >0.16, add the feature frame to the assembly - #if int(FreeCAD.Version()[1]) > 16: - # geo_feature_group = part.getParentGeoFeatureGroup() - # geo_feature_group.addObject(obj) - if FreeCAD.GuiUp: - ViewProviderFeatureFrame(obj.ViewObject) - return obj - -def makeSelectedPartFrames(): - for part in FreeCADGui.Selection.getSelection(): - if isinstance(part, Part.Feature): - pf = makePartFrame(part) - pf.Label = "Frame"+str(part.Label) - -def makeAllPartFrames(): - dc = FreeCAD.activeDocument() - for part in dc.Objects: - if isinstance(part, Part.Feature): - pf = makePartFrame(part) - pf.Label = "Frame"+str(part.Label) - - -def spawnFeatureFrameCreator(): - ffpanel = FeatureFramePanel() - FreeCADGui.Control.showDialog(ffpanel) - - - -################################################################### -# GUI Related -################################################################### - -spawnClassCommand("BoMGeneration", - run_BoM_list, - {"Pixmap": str(os.path.join(ICONPATH, "BoMList.svg")), - "MenuText": "Generate Bill of Materials", - "ToolTip": "Press the button to create big BoM"}) -spawnClassCommand("FrameCommand", - makeFrame, - {"Pixmap": str(os.path.join(ICONPATH, "frame.svg")), - "MenuText": "Make a free frame", - "ToolTip": "Make a freestanding reference frame."}) - - -spawnClassCommand("SelectedPartFrameCommand", - makeSelectedPartFrames, - {"Pixmap": str(os.path.join(ICONPATH, "partframe.svg")), - "MenuText": "selected parts frames", - "ToolTip": "Make selected parts frames."}) - -spawnClassCommand("AllPartFramesCommand", - makeAllPartFrames, - {"Pixmap": str(os.path.join(ICONPATH, "allpartframes.svg")), - "MenuText": "All parts frames", - "ToolTip": "Make all parts frames."}) -spawnClassCommand("FeatureFrameCommand", - spawnFeatureFrameCreator, - {"Pixmap": str(os.path.join(ICONPATH, "featureframecreator.svg")), - "MenuText": "frame on selected primitive", - "ToolTip": "Create a frame on selected primitive."}) - -spawnClassCommand("Export_Entities", - export_coordinate_systems, - {"Pixmap": str(os.path.join(ICONPATH, "BoMList.svg")), - "MenuText": "ExportLCS", - "ToolTip": "Export all the markups"}) - -spawnClassCommand("Validate_Project", - validate_project, - {"Pixmap": str(os.path.join(ICONPATH, "")), - "MenuText": "Validate Project", - "ToolTip": "Check errors in project file"}) -spawnClassCommand("Publish_Project", - process_file, - {"Pixmap": str(os.path.join(ICONPATH, "publish.svg")), - "MenuText": "Publish Project", - "ToolTip": "Save and export project files"}) -spawnClassCommand("Create Assembly Parameters", - create_assembly_parameters, - {"Pixmap": str(os.path.join(ICONPATH, "galternatives.ico")), - "MenuText": "Create Assembly Parameters", - "ToolTip": "Create Assembly Parameters"}) -spawnClassCommand("Create Fastener Set", - create_fastener_set, - {"Pixmap": str(os.path.join(ICONPATH, "screw26.ico")), - "MenuText": "Create Fastener Set", - "ToolTip": "Create Fastener Set"}) -spawnClassCommand("Compute Assembly Sequence", - structure_analysis, - {"Pixmap": str(os.path.join(ICONPATH, "free-icon-software-5741483.png")), - "MenuText": "Compute Assembly Sequence", - "ToolTip": "Compute Assembly Sequence"}) -spawnClassCommand("Create Assembly Sequence", - create_assembly_sequence, - {"Pixmap": str(os.path.join(ICONPATH, "assembly.ico")), - "MenuText": "Create Assembly Sequence", - "ToolTip": "Create Assembly Sequence"}) -spawnClassCommand("Export Assembly Settings", - export_assembly_settings, - {"Pixmap": str(os.path.join(ICONPATH, "free-icon-export-724827.ico")), - "MenuText": "Export Assembly Settings", - "ToolTip": "Export Assembly Settings"}) -# spawnClassCommand("Create Assembly Layers", -# asm_layers, -# {"Pixmap": str(os.path.join(ICONPATH, ".svg")), -# "MenuText": "Create Assembly Layers", -# "ToolTip": "Create Assembly Layers"}) -spawnClassCommand("Create Structure Graph", - structure_graph, - {"Pixmap": str(os.path.join(ICONPATH, "pngwing.com.ico")), - "MenuText": "Create Structure Graph", - "ToolTip": "Create Structure Graph"}) -spawnClassCommand("Create Assembly Graph", - asm_graph, - {"Pixmap": str(os.path.join(ICONPATH, "iteration_3316689.ico")), - "MenuText": "Create Assembly Graph", - "ToolTip": "Create Assembly Graph"}) - - - -################################################################### -# GUI buttons -################################################################### -class FeatureFramePanel: - """Spawn panel choices for a feature.""" - def __init__(self): - selected = FreeCADGui.Selection.getSelectionEx() - # Check selection - if len(selected) == 1: - selected = selected[0] - self.selected = selected - else: - FreeCAD.Console.PrintError("Multipart selection not available.") - self.reject() - - if not selected.HasSubObjects: - FreeCAD.Console.PrintError("Part selected not feature.") - self.reject() - elif not len(selected.SubObjects) == 1: - FreeCAD.Console.PrintError("Multifeature selection not available") - self.reject() - - # Choices related to selection - so_desc = describeSubObject(selected.SubObjects[0]) - self.so_desc = so_desc - shape_choices = { - "Vertex": [], - "Edge": ["PointOnEdge"], - "Face": ["PointOnSurface"] - } - prim_choices = { - "ArcOfCircle": ["Center"], - "ArcOfEllipse": ["Center"], - "ArcOfHyperBola": ["Center"], - "ArcOfParabola": ["Center"], - "BSplineCurve": ["Center"], - "BezierCurve": ["Center"], - "Circle": ["Center"], - "Ellipse": ["Center"], - "Hyperbola": ["Center"], - "Parabola": ["Center"], - "Line": [], - "BSplineSurface": ["Center"], - "BezierSurface": ["Center"], - "Cylinder": ["PointOnCenterline"], - "Plane": ["Center"], - "Sphere": ["Center"], - "Toroid": ["Center"], - "Cone": ["PointOnCenterline"] - } - self.choices = ["PickedPoint"] - self.choices = self.choices + shape_choices[so_desc[1]] - self.choices = self.choices + prim_choices[so_desc[0]] - # Setting up QT form - uiform_path = os.path.join(UIPATH, "FeatureFrameCreator.ui") - self.form = FreeCADGui.PySideUic.loadUi(uiform_path) - self.form.ChoicesBox.addItems(self.choices) - self.form.PickedTypeLabel.setText(so_desc[0]) - QtCore.QObject.connect(self.form.ChoicesBox, - QtCore.SIGNAL("currentIndexChanged(QString)"), - self.choiceChanged) - self.scenes = {} - for choice in self.choices: - sc = QtGui.QGraphicsScene() - icon = str(os.path.join(ICONPATH, choice+".svg")) - sc.addItem(QtSvg.QGraphicsSvgItem(icon)) - self.scenes[choice] = sc - self.choiceChanged(self.form.ChoicesBox.currentText()) - - def choiceChanged(self, choice): - if choice in self.scenes.keys(): - self.form.Preview.setScene(self.scenes[choice]) - - def accept(self): - sel_choice = self.form.ChoicesBox.currentText() - paneldict = {"PickedPoint": PickedPointPanel, - "PointOnEdge": PointOnEdgePanel, - "PointOnSurface": PointOnSurfacePanel, - "Center": CenterPanel, - "PointOnCenterline": PointOnCenterlinePanel} - pan = paneldict[sel_choice](self.selected, self.so_desc) - FreeCADGui.Control.closeDialog() - # The dialog is actually closed after the accept function has - # completed. So we need to use a delayed task to open the new dialog: - QtCore.QTimer.singleShot(0, - lambda: FreeCADGui.Control.showDialog(pan)) - - def reject(self): - FreeCADGui.Control.closeDialog() - - -class BaseFeaturePanel(object): - """Base feature panel to be inherited from.""" - def __init__(self, selected, so_desc): - # Handle selected and FF placement - self.selected = selected - self.so_desc = so_desc - # Connect offset to spinboxes - QtCore.QObject.connect(self.form.XBox, - QtCore.SIGNAL("valueChanged(double)"), - self.offsetChanged) - QtCore.QObject.connect(self.form.YBox, - QtCore.SIGNAL("valueChanged(double)"), - self.offsetChanged) - QtCore.QObject.connect(self.form.ZBox, - QtCore.SIGNAL("valueChanged(double)"), - self.offsetChanged) - QtCore.QObject.connect(self.form.RollBox, - QtCore.SIGNAL("valueChanged(double)"), - self.offsetChanged) - QtCore.QObject.connect(self.form.PitchBox, - QtCore.SIGNAL("valueChanged(double)"), - self.offsetChanged) - QtCore.QObject.connect(self.form.YawBox, - QtCore.SIGNAL("valueChanged(double)"), - self.offsetChanged) - QtCore.QObject.connect(self.form.ScaleBox, - QtCore.SIGNAL("valueChanged(double)"), - self.scaleChanged) - - def createFrame(self): - self.fframe = makeFeatureFrame(self.selected.Object, self.local_ffpl) - self.fframe.PrimitiveType = self.so_desc[0] - self.fframe.ShapeType = self.so_desc[1] - ad = getPrimitiveInfo(self.so_desc[0], - self.selected.SubObjects[0]) - self.fframe.Proxy.additional_data.update(ad) - - def scaleChanged(self): - scale = self.form.ScaleBox.value() - self.fframe.ViewObject.Scale = scale - - def offsetChanged(self): - disp = FreeCAD.Vector(self.form.XBox.value(), - self.form.YBox.value(), - self.form.ZBox.value()) - rot = FreeCAD.Rotation(self.form.YawBox.value(), - self.form.PitchBox.value(), - self.form.RollBox.value()) - offset = FreeCAD.Placement(disp, rot) - self.fframe.Placement = offset - - def accept(self): - framelabel = self.form.FrameLabelField.toPlainText() - if not len(framelabel) == 0: - self.fframe.Label = framelabel - FreeCADGui.Control.closeDialog() - - def reject(self): - FreeCAD.activeDocument().removeObject(self.fframe.Name) - FreeCADGui.Control.closeDialog() - - -class PickedPointPanel(BaseFeaturePanel): - """Create a feature frame at the picked point.""" - # Not very clever. It just places the frame with default rotation. - def __init__(self, selected, so_desc): - uiform_path = os.path.join(UIPATH, "FramePlacer.ui") - self.form = FreeCADGui.PySideUic.loadUi(uiform_path) - BaseFeaturePanel.__init__(self, selected, so_desc) - parent_pl = selected.Object.Placement - abs_pl = FreeCAD.Placement(selected.PickedPoints[0], - FreeCAD.Rotation()) - self.local_ffpl = parent_pl.inverse().multiply(abs_pl) - self.createFrame() - self.fframe.Positioning = "PickedPoint" - - -class PointOnEdgePanel(BaseFeaturePanel): - """Create a feature frame on an edge.""" - def __init__(self, selected, so_desc): - uiform_path = os.path.join(UIPATH, "FramePlacer.ui") - self.form = FreeCADGui.PySideUic.loadUi(uiform_path) - # Enable the first parameter - self.form.VLabel.setEnabled(True) - self.form.VLabel.setVisible(True) - self.form.VLabel.setText("u") - self.form.VBox.setEnabled(True) - self.form.VBox.setVisible(True) - QtCore.QObject.connect(self.form.VBox, - QtCore.SIGNAL("valueChanged(double)"), - self.parameterChanged) - - # Enable percentage or param selection - self.form.OptionsLabel.setEnabled(True) - self.form.OptionsLabel.setVisible(True) - self.form.OptionsLabel.setText("Arc param.") - self.form.OptionsBox.setEnabled(True) - self.form.OptionsBox.setVisible(True) - self.form.OptionsBox.addItems(["mm", "%"]) - QtCore.QObject.connect(self.form.OptionsBox, - QtCore.SIGNAL("currentIndexChanged(QString)"), - self.choiceChanged) - BaseFeaturePanel.__init__(self, selected, so_desc) - - # Place the frame wherever the values are atm - self.local_ffpl = FreeCAD.Placement() - self.createFrame() - self.fframe.Positioning = "PointOnEdge" - self.choiceChanged(self.form.OptionsBox.currentText()) - self.parameterChanged() - - def parameterChanged(self): - value = self.form.VBox.value() - if self.form.OptionsBox.currentText() == "%": - value = self.p2mm(value) - edge = self.selected.SubObjects[0] - point = edge.valueAt(value) - tangentdir = edge.tangentAt(value) - rot = FreeCAD.Rotation(FreeCAD.Vector(1, 0, 0), - tangentdir) - abs_ffpl = FreeCAD.Placement(point, rot) - parent_pl = self.selected.Object.Placement - self.local_ffpl = parent_pl.inverse().multiply(abs_ffpl) - self.fframe.FeaturePlacement = self.local_ffpl - # force recompute of placement? - self.fframe.Placement = self.fframe.Placement - - def choiceChanged(self, choice): - value = self.form.VBox.value() - if choice == "mm": - value = self.p2mm(value) - self.form.VBox.setSuffix("mm") - parameter_range = self.selected.SubObjects[0].ParameterRange - self.form.VBox.setRange(*parameter_range) - self.form.VBox.setSingleStep(0.1) - elif choice == "%": - value = self.mm2p(value) - self.form.VBox.setSuffix("%") - self.form.VBox.setRange(0, 100.0) - self.form.VBox.setSingleStep(1.0) - self.form.VBox.setValue(value) - - def p2mm(self, value): - parameter_range = self.selected.SubObjects[0].ParameterRange - delta = parameter_range[1] - parameter_range[0] - return 0.01*value*delta + parameter_range[0] - - def mm2p(self, value): - parameter_range = self.selected.SubObjects[0].ParameterRange - delta = parameter_range[1] - parameter_range[0] - return 100.0*(value - parameter_range[0])/delta - - -class PointOnSurfacePanel(BaseFeaturePanel): - """Create a feature on a surface.""" - def __init__(self, selected, so_desc): - uiform_path = os.path.join(UIPATH, "FramePlacer.ui") - self.form = FreeCADGui.PySideUic.loadUi(uiform_path) - # Enable both parameters - self.form.ULabel.setVisible(True) - self.form.VLabel.setVisible(True) - self.form.UBox.setVisible(True) - self.form.VBox.setVisible(True) - QtCore.QObject.connect(self.form.VBox, - QtCore.SIGNAL("valueChanged(double)"), - self.parameterChanged) - QtCore.QObject.connect(self.form.UBox, - QtCore.SIGNAL("valueChanged(double)"), - self.parameterChanged) - # Enable percentage or param selection - self.form.OptionsLabel.setEnabled(True) - self.form.OptionsLabel.setVisible(True) - self.form.OptionsLabel.setText("Surf. param.") - self.form.OptionsBox.setEnabled(True) - self.form.OptionsBox.setVisible(True) - self.form.OptionsBox.addItems(["mm", "%"]) - QtCore.QObject.connect(self.form.OptionsBox, - QtCore.SIGNAL("currentIndexChanged(QString)"), - self.choiceChanged) - BaseFeaturePanel.__init__(self, selected, so_desc) - - # Place the frame wherever the values are atm - self.local_ffpl = FreeCAD.Placement() - self.createFrame() - self.fframe.Positioning = "PointOnSurface" - self.choiceChanged(self.form.OptionsBox.currentText()) - self.parameterChanged() - - def parameterChanged(self): - value = (self.form.UBox.value(), self.form.VBox.value()) - if self.form.OptionsBox.currentText() == "%": - value = self.p2mm(value) - face = self.selected.SubObjects[0] - point = face.valueAt(*value) - normaldir = face.normalAt(*value) - rotation = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), - normaldir) - abs_ffpl = FreeCAD.Placement(point, rotation) - parent_pl = self.selected.Object.Placement - self.local_ffpl = parent_pl.inverse().multiply(abs_ffpl) - self.fframe.FeaturePlacement = self.local_ffpl - # Force recompute of placement - self.fframe.Placement = self.fframe.Placement - - def choiceChanged(self, choice): - value = (self.form.UBox.value(), self.form.VBox.value()) - if choice == "mm": - value = self.p2mm(value) - parameter_range = self.selected.SubObjects[0].ParameterRange - self.form.UBox.setRange(parameter_range[0], parameter_range[1]) - self.form.UBox.setSuffix("mm") - self.form.UBox.setSingleStep(0.1) - self.form.VBox.setRange(parameter_range[2], parameter_range[3]) - self.form.VBox.setSuffix("mm") - self.form.VBox.setSingleStep(0.1) - elif choice == "%": - value = self.mm2p(value) - self.form.UBox.setRange(0.0, 100.0) - self.form.UBox.setSuffix("%") - self.form.VBox.setRange(0.0, 100.0) - self.form.UBox.setSingleStep(1.0) - self.form.VBox.setSuffix("%") - self.form.VBox.setSingleStep(1.0) - self.form.UBox.setValue(value[0]) - self.form.VBox.setValue(value[1]) - - def p2mm(self, value): - parameter_range = self.selected.SubObjects[0].ParameterRange - delta = [parameter_range[1] - parameter_range[0], - parameter_range[3] - parameter_range[2]] - u = 0.01*value[0]*delta[0] + parameter_range[0] - v = 0.01*value[1]*delta[1] + parameter_range[2] - return (u, v) - - def mm2p(self, value): - parameter_range = self.selected.SubObjects[0].ParameterRange - delta = [parameter_range[1] - parameter_range[0], - parameter_range[3] - parameter_range[2]] - u = 100.0*(value[0] - parameter_range[0])/delta[0] - v = 100.0*(value[1] - parameter_range[2])/delta[1] - return (u, v) - - -class CenterPanel(BaseFeaturePanel): - """Create a feature frame on center.""" - def __init__(self, selected, so_desc): - uiform_path = os.path.join(UIPATH, "FramePlacer.ui") - self.form = FreeCADGui.PySideUic.loadUi(uiform_path) - BaseFeaturePanel.__init__(self, selected, so_desc) - edge_curve_list = ["ArcOfCircle", - "ArcOfEllipse", - "ArcOfHyperbola", - "ArcOfParabola", - "Circle", - "Ellipse", - "Hyperbola", - "Parabola"] - face_surf_list = ["Sphere", - "Toroid"] - if so_desc[0] in edge_curve_list: - edge = selected.SubObjects[0] - axis = edge.Curve.Axis - rotation = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), - axis) - center_point = edge.Curve.Center - elif so_desc[0] in face_surf_list: - face = selected.SubObjects[0] - axis = face.Surface.Axis - rotation = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), - axis) - center_point = face.Surface.Center - else: - rotation = FreeCAD.Rotation() - center_point = selected.SubObjects[0].CenterOfMass - parent_pl = selected.Object.Placement - abs_pl = FreeCAD.Placement(center_point, - rotation) - self.local_ffpl = parent_pl.inverse().multiply(abs_pl) - self.createFrame() - self.fframe.Positioning = "Center" - - -class PointOnCenterlinePanel(BaseFeaturePanel): - """Create a point on centerline of primitive.""" - def __init__(self, selected, so_desc): - uiform_path = os.path.join(UIPATH, "FramePlacer.ui") - self.form = FreeCADGui.PySideUic.loadUi(uiform_path) - BaseFeaturePanel.__init__(self, selected, so_desc) - # Enable the along line parameter - self.form.VLabel.setVisible(True) - self.form.VLabel.setText("u") - self.form.VBox.setVisible(True) - QtCore.QObject.connect(self.form.VBox, - QtCore.SIGNAL("valueChanged(double)"), - self.parameterChanged) - # Enable percentage of param selection - self.form.OptionsLabel.setVisible(True) - self.form.OptionsLabel.setText("Line param.") - self.form.OptionsBox.setVisible(True) - self.form.OptionsBox.addItems(["mm", "%"]) - QtCore.QObject.connect(self.form.OptionsBox, - QtCore.SIGNAL("currentIndexChanged(QString)"), - self.choiceChanged) - # Place the frame wherever the values are atm - self.local_ffpl = FreeCAD.Placement() - self.createFrame() - self.fframe.Positioning = "PointOnCenterline" - self.parameterChanged() - - def parameterChanged(self): - value = self.form.VBox.value() - if self.form.OptionsBox.currentText() == "%": - value = self.p2mm(value) - displacement_pl = FreeCAD.Placement(FreeCAD.Vector(0, 0, value), - FreeCAD.Rotation()) - # Find the center - axis = self.selected.SubObjects[0].Surface.Axis - rotation = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), - axis) - center_point = self.selected.SubObjects[0].Surface.Center - center_pl = FreeCAD.Placement(center_point, rotation) - abs_ffpl = center_pl.multiply(displacement_pl) - parent_pl = self.selected.Object.Placement - self.local_ffpl = parent_pl.inverse().multiply(abs_ffpl) - self.fframe.FeaturePlacement = self.local_ffpl - # force recompute of placement - self.fframe.Placement = self.fframe.Placement - - def choiceChanged(self, choice): - FreeCAD.Console.PrintMessage("choiceChanged\n") - value = self.form.VBox.value() - FreeCAD.Console.PrintMessage("preval:"+str(value)+"\n") - if choice == "mm": - value = self.p2mm(value) - self.form.VBox.setSuffix("mm") - parameter_range = self.selected.SubObjects[0].ParameterRange[2:] - self.form.VBox.setRange(*parameter_range) - self.form.VBox.setSingleStep(0.1) - elif choice == "%": - value = self.mm2p(value) - self.form.VBox.setSuffix("%") - self.form.VBox.setRange(0, 100) - self.form.VBox.setSingleStep(1.0) - self.form.VBox.setValue(value) - FreeCAD.Console.PrintMessage("postval:"+str(value)+"\n") - - def p2mm(self, value): - parameter_range = self.selected.SubObjects[0].ParameterRange[2:] - delta = parameter_range[1] - parameter_range[0] - return 0.01*value*delta + parameter_range[0] - - def mm2p(self, value): - parameter_range = self.selected.SubObjects[0].ParameterRange[2:] - delta = parameter_range[1] - parameter_range[0] - return 100.0*(value - parameter_range[0])/delta diff --git a/freecad_workbench/freecad/robossembler/GazeboExport.py b/freecad_workbench/freecad/robossembler/GazeboExport.py deleted file mode 100644 index 2cba055..0000000 --- a/freecad_workbench/freecad/robossembler/GazeboExport.py +++ /dev/null @@ -1,566 +0,0 @@ -import FreeCAD, Mesh, os, numpy as np -import yaml -import argparse -import collada -from xml.etree import ElementTree as ET -from xml.dom.minidom import parseString -from math import radians as _radians -import Part - -# Takes subassembly or parts dictionary { part_label: { "obj": , "mesh": } } -# and generate SDF for them - -def export_sdf(objects, export_dir, modelname, configs={}): - model_dir = os.path.join(export_dir, modelname) - - scale = configs.get('scale', 0.001) - scale_vec = FreeCAD.Vector([scale]*3) - density = configs.get('density', 1000) - - shapes = list(map(lambda x: x["obj"].Shape, objects.values())) - bounding_box = Part.makeCompound(shapes).BoundBox - bounding_box.scale(*scale_vec) - global_pose_base = FreeCAD.Vector(bounding_box.XLength/2, - bounding_box.YLength/2, - bounding_box.ZLength/2) - global_pose_base -= bounding_box.Center - global_pose = FreeCAD.Placement() - global_pose.Base = global_pose_base - - model = Model(name=modelname, pose=global_pose) - model.self_collide = False - model.sdf_version = '1.5' - - for label in objects.keys(): - shape = objects[label]["obj"].Shape - mass = shape.Mass * scale**3 * density - com = shape.CenterOfMass * scale - inr = shape.MatrixOfInertia - inr.scale(*scale_vec*(scale**4) * density) - placement = shape.Placement - placement.Base.scale(*scale_vec) - pose = placement.copy() - pose.Base = com - pose_rpy = pose.copy() - pose_rpy.Base=(np.zeros(3)) - inertia = Inertia(inertia=np.array(inr.A)[[0,1,2,5,6,10]]) - inertial = Inertial(pose=pose_rpy, mass=mass, inertia=inertia) - - mesh_uri = os.path.normpath(os.path.relpath(objects[label]["mesh"], export_dir)) - visual = Visual(name=label+'_visual', mesh=mesh_uri) - collision = Collision(name=label+'_collision', mesh=mesh_uri) - - link = Link(name=label, - pose=pose, - inertial=inertial, - visual=visual, - collision=collision) - model.links.append(link) - - with open(os.path.join(model_dir, 'model.sdf'), 'w') as sdf_file: - sdf_file.write(model.to_xml_string('sdf')) - -################################################################### -# Export helpers -################################################################### - - - -def export_collada(exportList, filename, scale=0.001, quality=1, offset=np.zeros(3)): - '''FreeCAD collada exporter - exportList - list of objects - scale - scaling factor for the mesh - quality - mesh tessellation quality - offset - offset of the origin of the resulting mesh''' - - colmesh = collada.Collada() - colmesh.assetInfo.upaxis = collada.asset.UP_AXIS.Z_UP - objind = 0 - scenenodes = [] - - for obj in exportList: - bHandled = False - if obj.isDerivedFrom("Part::Feature"): - bHandled = True - m = obj.Shape.tessellate(quality) - vindex = [] - nindex = [] - findex = [] - # vertex indices - for v in m[0]: - vindex.extend([a*scale+b for a, b in zip(v, offset)]) - # normals - for f in obj.Shape.Faces: - n = f.normalAt(0,0) - for i in range(len(f.tessellate(quality)[1])): - nindex.extend([n.x,n.y,n.z]) - # face indices - for i in range(len(m[1])): - f = m[1][i] - findex.extend([f[0],i,f[1],i,f[2],i]) - elif obj.isDerivedFrom("Mesh::Feature"): - bHandled = True - print("exporting mesh ",obj.Name, obj.Mesh) - m = obj.Mesh - vindex = [] - nindex = [] - findex = [] - # vertex indices - for v in m.Topology[0]: - vindex.extend([a*scale+b for a, b in zip(v, offset)]) - # normals - for f in m.Facets: - n = f.Normal - nindex.extend([n.x,n.y,n.z]) - # face indices - for i in range(len(m.Topology[1])): - f = m.Topology[1][i] - findex.extend([f[0],i,f[1],i,f[2],i]) - - if bHandled: - vert_src = collada.source.FloatSource("cubeverts-array"+str(objind), - np.array(vindex), - ('X', 'Y', 'Z')) - normal_src = collada.source.FloatSource("cubenormals-array"+str(objind), - np.array(nindex), - ('X', 'Y', 'Z')) - geom = collada.geometry.Geometry(colmesh, - "geometry"+str(objind), - obj.Label, - [vert_src, normal_src]) - - input_list = collada.source.InputList() - input_list.addInput(0, 'VERTEX', "#cubeverts-array"+str(objind)) - input_list.addInput(1, 'NORMAL', "#cubenormals-array"+str(objind)) - triset = geom.createTriangleSet(np.array(findex), - input_list, - "materialref") - geom.primitives.append(triset) - colmesh.geometries.append(geom) - - geomnode = collada.scene.GeometryNode(geom) - node = collada.scene.Node("node"+str(objind), children=[geomnode]) - - #TODO: Add materials handling - scenenodes.append(node) - - objind += 1 - - scene = collada.scene.Scene("scene", scenenodes) - colmesh.scenes.append(scene) - colmesh.scene = scene - - colmesh.write(filename) - print("file %s successfully created\n" % filename) - - -################################################################### -# Conversion Helpers -################################################################### - -def deg2rad(d): - '''Converts degrees to radians''' - return _radians(d) - -def flt2str(f): - '''Converts floats to formatted string''' - return '{:.6f}'.format(f) - - -################################################################### -# Model Helpers -################################################################### - -def add_poses(p1, p2): - return FreeCAD.Placement(p1.toMatrix() + p2.toMatrix()) - -def subtract_poses(p1, p2): - return FreeCAD.Placement(p1.toMatrix() + p2.toMatrix().inverse()) - -def pose_to_xml(pose, fmt='sdf'): - '''Converts a pose/freecad placement/ to xml element - with tag "pose" for sdf and "origin" for urdf''' - xyz = pose.Base - rpy = pose.Rotation.toEuler() - - if fmt == 'urdf': - args = {'xyz': ' '.join([flt2str(i) for i in xyz]), - 'rpy': ' '.join([flt2str(deg2rad(j)) for j in rpy])} - return ET.Element('origin', args) - - pose_elem = ET.Element('pose') - pose_elem.text = ' '.join([flt2str(i) for i in xyz] - + [flt2str(deg2rad(j)) for j in rpy]) - - return pose_elem - -def pose_xyz(pose): - '''Returns the xyz/Base portion of a pose as string''' - xyz = pose.Base if hasattr(pose, 'Base') else pose - return ' '.join([flt2str(i) for i in xyz]) - -def config(model_name, sdf, author, email, desc, version): - top = ET.Element('model') - name = ET.SubElement(top, 'name') - name.text = model_name - ver = ET.SubElement(top, 'version') - ver.text = version - sdf_file = ET.SubElement(top, 'sdf') - sdf_file.text = sdf - sdf_file.set('version', '1.5') - - author_tag = ET.SubElement(top, 'author') - author_name = ET.SubElement(author_tag, 'name') - author_name.text = author - email_address = ET.SubElement(author_tag, 'email') - email_address.text = email - - description = ET.SubElement(top, 'description') - description.text = desc - - dom = parseString(ET.tostring(top, encoding="unicode")) - return dom.toprettyxml(indent=' '*2) - - -class SpatialEntity(object): - '''A base class for sdf/urdf elements containing name, pose and urdf_pose''' - def __init__(self, **kwargs): - self.name = kwargs.get('name', '') - self.pose = kwargs.get('pose', FreeCAD.Placement()) - self.global_pose = kwargs.get('global_pose', FreeCAD.Placement()) - self.urdf_pose = kwargs.get('urdf_pose', FreeCAD.Placement()) - - self.formats = ['sdf', 'urdf'] - - def to_xml(self, fmt='sdf'): - '''Call this to check if a format is supported or not''' - if not fmt in self.formats: - raise Exception('Invalid export format') - - -class Model(SpatialEntity): - '''A class representing a model/robot''' - def __init__(self, **kwargs): - super(Model, self).__init__(**kwargs) - self.static = kwargs.get('static', False) - self.self_collide = kwargs.get('self_collide', False) - self.sdf_version = kwargs.get('sdf_version', 1.5) - - self.links = [] - self.joints = [] - - if 'link' in kwargs: - self.links.append(kwargs.get('link', Link())) - self.links.extend(kwargs.get('links', [])) - - if 'joint' in kwargs: - self.joints.append(kwargs.get('joint', Joint())) - self.joints.extend(kwargs.get('joints', [])) - - def get_link(self, link_name): - for link in self.links: - if link_name == link.name: - return link - - def get_joint(self, joint_name): - pass - - def get_root_link(self): - root_link = None - for link in self.links: - if not link.parent_joint: - root_link = link - return root_link - - def build_tree(self): - for joint in self.joints: - joint.parent_link = self.get_link(joint.parent) - if not joint.parent_link: - raise Exception('Parent not found for joint %s' % joint.name) - joint.parent_link.child_joints.append(joint) - - joint.child_link = self.get_link(joint.child) - if not joint.child_link: - raise Exception('Child not found for joint %s' % joint.name) - joint.child_link.parent_joint = joint - - def calculate_global_poses(self): - for link in self.links: - link.global_pose = add_poses(self.pose, link.pose) - for joint in self.joints: - joint.global_pose = add_poses(joint.child_link.global_pose, joint.pose) - - def to_xml(self, fmt='sdf'): - '''returns xml element of a model/robot''' - super(Model, self).to_xml(fmt) - - self.build_tree() - self.calculate_global_poses() - - tag = 'robot' if fmt=='urdf' else 'model' - model = ET.Element(tag, name=self.name) - - if fmt == 'sdf': - model.append(pose_to_xml(self.pose)) - static = ET.SubElement(model, 'static') - static.text = str(self.static).lower() - self_collide = ET.SubElement(model, 'self_collide') - self_collide.text = str(self.self_collide).lower() - else: - model.set('static', str(self.static).lower()) - - root_link = self.get_root_link() - if not root_link: - raise Exception("Couldn't find root link") - model.append(ET.Element('link', name=root_link.name+'_root')) - for link in self.links: - model.append(link.to_xml(fmt)) - - if fmt=='urdf': - root_joint = ET.Element('joint', - {"name": root_link.name+'_root', - "type": "fixed"}) - root_joint.append(pose_to_xml(root_link.global_pose, fmt)) - ET.SubElement(root_joint, 'parent', link= root_link.name+'_root') - ET.SubElement(root_joint, 'child', link= root_link.name) - model.append(root_joint) - - for joint in self.joints: - model.append(joint.to_xml(fmt)) - - if fmt == 'sdf': - sdf = ET.Element('sdf', version=str(self.sdf_version)) - sdf.append(model) - return sdf - - return model - - def to_xml_string(self, fmt='sdf', header=True): - dom = parseString(ET.tostring(self.to_xml(fmt))) - return dom.toprettyxml(indent=' '*2) - - -class Inertia(object): - '''A clss representing an inertia element''' - def __init__(self, **kwargs): - self.ixx = kwargs.get('ixx', 0) - self.ixy = kwargs.get('ixy', 0) - self.ixz = kwargs.get('ixz', 0) - self.iyy = kwargs.get('iyy', 0) - self.iyz = kwargs.get('iyz', 0) - self.izz = kwargs.get('izz', 0) - if 'inertia' in kwargs: - self.ixx, self.ixy, self.ixz = kwargs.get('inertia', [0]*6)[:3] - self.iyy, self.iyz, self.izz = kwargs.get('inertia', [0]*6)[3:] - self.coords = 'ixx', 'ixy', 'ixz', 'iyy', 'iyz', 'izz' - - def to_xml(self, fmt='sdf'): - '''returns inetria xml element''' - inertia = ET.Element('inertia') - for coord in self.coords: - if fmt == 'sdf': - elem = ET.SubElement(inertia, coord) - elem.text = flt2str(getattr(self, coord, 0)) - else: - inertia.set(coord, flt2str(getattr(self, coord, 0))) - return inertia - - -class Inertial(SpatialEntity): - '''A class representing an inertial element''' - def __init__(self, **kwargs): - super(Inertial, self).__init__(**kwargs) - self.mass = kwargs.get('mass', 0) - self.inertia = kwargs.get('inertia', Inertia()) - - def to_xml(self, fmt='sdf'): - '''returns inertial xml element''' - super(Inertial, self).to_xml(fmt) - inertial = ET.Element('inertial') - pose = self.pose if fmt=='sdf' else self.urdf_pose - inertial.append(pose_to_xml(pose, fmt=fmt)) - mass = ET.SubElement(inertial, 'mass') - if fmt == 'sdf': - mass.text = flt2str(self.mass) - else: - mass.set('value', flt2str(self.mass)) - inertial.append(self.inertia.to_xml(fmt=fmt)) - - return inertial - - -class Geom(SpatialEntity): - '''A base class for collision and visual classes''' - def __init__(self, **kwargs): - super(Geom, self).__init__(**kwargs) - self.mesh = kwargs.get('mesh', '') - self.type = kwargs.get('type', 'visual') - - def to_xml(self, fmt='sdf'): - '''returns visual or collision xml element''' - super(Geom, self).to_xml(fmt) - elem = ET.Element(self.type, name=self.name) - pose = self.pose if fmt=='sdf' else self.urdf_pose - elem.append(pose_to_xml(pose, fmt=fmt)) - geom = ET.SubElement(elem, 'geometry') - mesh = ET.SubElement(geom, 'mesh') - if fmt=='urdf': - mesh.set('filename', 'package://' + self.mesh) - else: - uri = ET.SubElement(mesh, 'uri') - uri.text = 'model://' + self.mesh - - return elem - - -class Visual(Geom): - '''A class representing a visual element''' - def __init__(self, **kwargs): - super(Visual, self).__init__(type='visual', **kwargs) - - -class Collision(Geom): - '''A class representing a collision element''' - def __init__(self, **kwargs): - super(Collision, self).__init__(type='collision', **kwargs) - - -class Link(SpatialEntity): - '''A class representing a link element''' - def __init__(self, **kwargs): - super(Link, self).__init__(**kwargs) - self.inertial = kwargs.get('inertial', Inertial()) - self.visuals = [] - self.collisions = [] - - self.parent_joint = None - self.child_joints = [] - - if 'visual' in kwargs: - self.visuals.append(kwargs.get('visual', Visual())) - self.visuals.extend(kwargs.get('visuals', [])) - - if 'collision' in kwargs: - self.visuals.append(kwargs.get('collision', Collision())) - self.collisions.extend(kwargs.get('collisions', [])) - - def to_xml(self, fmt='sdf'): - '''returns link xml element''' - super(Link, self).to_xml(fmt) - link = ET.Element('link', name=self.name) - - if self.parent_joint: - self.urdf_pose = subtract_poses(self.global_pose, - self.parent_joint.global_pose) - else: - self.urdf_pose = FreeCAD.Placement() - - if fmt == 'sdf': - link.append(pose_to_xml(self.pose, fmt=fmt)) - - self.inertial.urdf_pose = add_poses(self.inertial.pose, self.urdf_pose) - link.append(self.inertial.to_xml(fmt=fmt)) - - for visual in self.visuals: - visual.urdf_pose = self.urdf_pose.copy() - link.append(visual.to_xml(fmt=fmt)) - for collision in self.collisions: - collision.urdf_pose = self.urdf_pose.copy() - link.append(collision.to_xml(fmt=fmt)) - - return link - - -class Axis(SpatialEntity): - '''A class representing an axis element''' - def __init__(self, **kwargs): - super(Axis, self).__init__(**kwargs) - self.lower_limit = kwargs.get('lower_limit', 0) - self.upper_limit = kwargs.get('upper_limit', 0) - self.effort_limit = kwargs.get('effort_limit', 0) - self.velocity_limit = kwargs.get('velocity_limit', 0) - self.friction = kwargs.get('friction', 0) - self.damping = kwargs.get('damping', 0) - self.use_parent_frame = kwargs.get('use_parent_frame', False) - - def to_xml(self, fmt='sdf'): - '''returns an axis xml element for sdf - or an array of axis and limit xml elements for urdf''' - super(Axis, self).to_xml(fmt) - - axis = ET.Element('axis') - if fmt=='sdf': - xyz = ET.SubElement(axis, 'xyz') - xyz.text = pose_xyz(self.pose) - limit = ET.SubElement(axis, 'limit') - lower = ET.SubElement(limit, 'lower') - lower.text = flt2str(deg2rad(self.lower_limit)) - upper = ET.SubElement(limit, 'upper') - upper.text = flt2str(deg2rad(self.upper_limit)) - effort = ET.SubElement(limit, 'effort') - effort.text = flt2str(self.effort_limit) - velocity = ET.SubElement(limit, 'velocity') - velocity.text = flt2str(self.velocity_limit) - dynamics = ET.SubElement(axis, 'dynamics') - friction = ET.SubElement(dynamics, 'friction') - friction.text = flt2str(self.friction) - damping = ET.SubElement(dynamics, 'damping') - damping.text = flt2str(self.damping) - use_parent_frame = ET.SubElement(axis, 'use_parent_model_frame') - use_parent_frame.text = str(self.use_parent_frame).lower() - else: - axis.set('xyz', pose_xyz(self.pose)) - axis.set('use_parent_model_frame', str(self.use_parent_frame).lower()) - limit = ET.Element('limit') - limit.set('lower', flt2str(deg2rad(self.lower_limit))) - limit.set('upper', flt2str(deg2rad(self.upper_limit))) - limit.set('effort', flt2str(self.effort_limit)) - limit.set('velocity', flt2str(self.velocity_limit)) - - dynamics = ET.Element('dynamics') - dynamics.set('friction', flt2str(self.friction)) - dynamics.set('damping', flt2str(self.damping)) - - return [axis, limit, dynamics] - return axis - - -class Joint(SpatialEntity): - '''A class representing a joint element''' - def __init__(self, **kwargs): - super(Joint, self).__init__(**kwargs) - self.parent = kwargs.get('parent', '') - self.child = kwargs.get('child', '') - self.type = kwargs.get('type', '') - self.axis = kwargs.get('axis', Axis()) - - self.parent_link = None - self.child_link = None - - def to_xml(self, fmt='sdf'): - '''returns a joint xml element''' - super(Joint, self).to_xml(fmt) - - if self.parent_link.parent_joint: - self.urdf_pose = subtract_poses(self.global_pose, - self.parent_link.parent_joint.global_pose) - else: - self.urdf_pose = subtract_poses(self.global_pose, self.parent_link.global_pose) - - joint = ET.Element('joint', {'name': self.name, 'type': self.type}) - pose = self.pose if fmt=='sdf' else self.urdf_pose - joint.append(pose_to_xml(pose, fmt=fmt)) - - parent = ET.SubElement(joint, 'parent') - child = ET.SubElement(joint, 'child') - if fmt == 'sdf': - parent.text = self.parent - child.text = self.child - joint.append(self.axis.to_xml(fmt=fmt)) - else: - parent.set('link', self.parent) - child.set('link', self.child) - joint.extend(self.axis.to_xml(fmt=fmt)) - - return joint - diff --git a/freecad_workbench/freecad/robossembler/GraspPose.py b/freecad_workbench/freecad/robossembler/GraspPose.py deleted file mode 100644 index 6c996b1..0000000 --- a/freecad_workbench/freecad/robossembler/GraspPose.py +++ /dev/null @@ -1,168 +0,0 @@ -import FreeCAD -import Part -import PySide -from FreeCAD import Base, Placement -from time import sleep - -# MACRO 1: -# Select part and run it to insert gripper pose (red) -# Select gripper body and run it to insert second pose (pre-gripper, blue) -# Select pre-gripper body and run it to insert 3D printer table (green) - -# Current gripper -# https://gitlab.com/robosphere/robossembler-ros2/-/blob/71938716043c35689a1058b29cefb1997a8bcf0a/rasmt_support/meshes/collision/Grip_Body.STL -# https://gitlab.com/robosphere/robossembler-ros2/-/blob/71938716043c35689a1058b29cefb1997a8bcf0a/rasmt_support/meshes/collision/Grip_L.STL -# https://gitlab.com/robosphere/robossembler-ros2/-/blob/71938716043c35689a1058b29cefb1997a8bcf0a/rasmt_support/meshes/collision/Grip_R.STL -# https://gitlab.com/robosphere/robossembler-ros2/-/blob/71938716043c35689a1058b29cefb1997a8bcf0a/rasmt_support/urdf/tools/rasmt_hand_macro.xacro - -def insert(): - if len(FreeCAD.Gui.Selection.getSelection())>0: - active_body = FreeCAD.Gui.Selection.getSelection()[0] - if "IsMainPosition" in active_body.PropertiesList: - if active_body.IsMainPosition == False: - p = controlled_insert("P") - p.addProperty("App::PropertyLink", "PartToPrint", "Parameter", "Part to be printed on this table") - p.ViewObject.ShapeColor=(0.0,1.0,0.0,0.0) - p.PartToPrint = active_body.PartToHandle - p.ViewObject.Transparency = 90 - p.Placement = active_body.PartToHandle.getGlobalPlacement() - p.Label = '3D_printer_table_for_'+p.PartToPrint.Name - else: - b = grip_helper((0.0,0.0,1.0,0.0)) - b.addProperty("App::PropertyLink", "MainPosition", "Parameter", "Main position") - b.PartToHandle = active_body.PartToHandle - b.MainPosition = active_body - b.IsMainPosition = False - b.GripSize = b.MainPosition.GripSize - b.Container.Placement = b.MainPosition.Container.Placement - b.Container.Label = 'PreGripper_for_'+b.PartToHandle.Name - tempshape = Part.getShape(b.PartToHandle,'',needSubElement=False,refine=False) - FreeCAD.ActiveDocument.addObject('Part::Feature','PartToHandle').Shape = tempshape - n = FreeCAD.ActiveDocument.ActiveObject - n.Label = b.PartToHandle.Label - n.ViewObject.ShapeColor = (0.0,0.0,1.0,0.0) - n.adjustRelativeLinks(b.Container) - b.Container.addObject(n) - n.Placement.Base = n.getGlobalPlacement().Base.sub(b.Container.Placement) - n.Placement.Rotation.Axis = n.getGlobalPlacement().Rotation.Axis.sub(b.Container.Placement.Rotation.Axis) - n.Placement.Rotation.Angle = n.getGlobalPlacement().Rotation.Angle-b.Container.Placement.Rotation.Angle - n.ViewObject.ShowInTree = False - n.ViewObject.Transparency = 90 - - else: - b = grip_helper((1.0,0.0,0.0,0.0)) - b.addProperty("App::PropertyInteger", "OperationPriority", "Parameter", "Priority of the operation") - b.addProperty("App::PropertyInteger", "OperationType", "Parameter", "Priority of the operation") - b.addProperty("App::PropertyFloat", "OperationParameter1", "Parameter", "Priority of the operation") - b.addProperty("App::PropertyFloat", "OperationParameter2", "Parameter", "Priority of the operation") - b.addProperty("App::PropertyFloat", "OperationParameter3", "Parameter", "Priority of the operation") - b.PartToHandle = active_body - b.IsMainPosition = True - b.GripSize = active_body.Shape.BoundBox.YLength - b.Container.Placement = active_body.getGlobalPlacement() - b.Container.Label = 'Gripper_for_'+b.PartToHandle.Name - - -def controlled_insert(code): - a = FreeCAD.ActiveDocument.Objects - Part.insert(u"~/.local/share/FreeCAD/Mod/Frames/"+code+".brep",FreeCAD.ActiveDocument.Name) - b = FreeCAD.ActiveDocument.Objects - return list(set(b) - set(a))[0] - -def grip_helper(color): - b = controlled_insert("B") - r = controlled_insert("R") - l = controlled_insert("L") - b.addProperty("App::PropertyFloat", "GripSize", "Parameter", "Size between fingers") - b.addProperty("App::PropertyLink", "Container", "Parameter", "Part Container") - b.addProperty("App::PropertyBool", "IsMainPosition", "Parameter", "Is it main or supportive position") - b.addProperty("App::PropertyLink", "PartToHandle", "Parameter", "Part to be manipulated by this gripper") - r.setExpression('.Placement.Base.y', b.Name+'.GripSize / 2') - l.setExpression('.Placement.Base.y', '-'+b.Name+'.GripSize / 2') - b.ViewObject.ShapeColor = color - r.ViewObject.ShapeColor = color - l.ViewObject.ShapeColor = color - NewPart = FreeCAD.activeDocument().addObject('App::Part','Part') - b.adjustRelativeLinks(NewPart) - NewPart.addObject(b) - r.adjustRelativeLinks(NewPart) - NewPart.addObject(r) - l.adjustRelativeLinks(NewPart) - NewPart.addObject(l) - r.ViewObject.ShowInTree = False - l.ViewObject.ShowInTree = False - b.Container = NewPart - b.ViewObject.Transparency = 90 - r.ViewObject.Transparency = 90 - l.ViewObject.Transparency = 90 - return b - -# MACRO 3: -# Select pre-gripper body and run it to animate its movement -def select_pregripper(): - apart = FreeCAD.Gui.Selection.getSelection()[0] - sp = apart.Container.Placement.Base - ep = apart.MainPosition.Container.Placement.Base - sa = apart.Container.Placement.Rotation.Angle - ea = apart.MainPosition.Container.Placement.Rotation.Angle - print (sp,ep) - - i = 0.0 - def updatePlacement(): - global timer - global i - global sp - global ep - global sa - global ea - apart.Container.Placement.Base = ep.multiply(i).add(sp.multiply(1.0-i)) - apart.Container.Placement.Rotation.Angle = (ea*i)+(sa*(1.0-i)) - i += 0.02 - if i>=1: - #apart.Container.Placement.Base=sp - #apart.Container.Placement.Rotation.Angle=sa - timer.stop() - FreeCAD.Gui.updateGui() - - timer = PySide.QtCore.QTimer() - timer.timeout.connect(updatePlacement) - timer.start(100) - -# MACRO 4: -#Raw advanced version of MACRO 1 -#Does not work properly yet - -def insert_advanced(): - if len(FreeCAD.Gui.Selection.getSelection())>0: - active_body = FreeCAD.Gui.Selection.getSelection()[0] - b = controlled_insert("B") - r = controlled_insert("R") - l = controlled_insert("L") - b.ViewObject.ShapeColor = (1.0,0.0,0.0,0.0) - r.ViewObject.ShapeColor = (1.0,0.0,0.0,0.0) - l.ViewObject.ShapeColor = (1.0,0.0,0.0,0.0) - b.ViewObject.ShowInTree = False - r.ViewObject.ShowInTree = False - l.ViewObject.ShowInTree = False - b.ViewObject.Transparency = 90 - r.ViewObject.Transparency = 90 - l.ViewObject.Transparency = 90 - a = FreeCAD.ActiveDocument.addObject("App::FeaturePython",'Gripper_for_'+active_body.Name) - a.addProperty("App::PropertyFloat", "GripSize", "Parameter", "Size between fingers") - a.addProperty("App::PropertyLink", "PartToHandle", "Parameter", "Part to be manipulated by this gripper") - a.addProperty("App::PropertyLink", "GripperBody", "Parameter", "Body") - a.addProperty("App::PropertyLink", "GripperLF", "Parameter", "Body") - a.addProperty("App::PropertyLink", "GripperRF", "Parameter", "Body") - a.GripperBody = b - a.GripperLF = l - a.GripperRF = r - #r.setExpression('.Placement.Base.y', a.Name+'.GripSize / 2') - #l.setExpression('.Placement.Base.y', '-'+a.Name+'.GripSize / 2') - a.addProperty("App::PropertyInteger", "OperationPriority", "Parameter", "Priority of the operation") - a.addProperty("App::PropertyInteger", "OperationType", "Parameter", "Priority of the operation") - a.addProperty("App::PropertyFloat", "OperationParameter1", "Parameter", "Priority of the operation") - a.addProperty("App::PropertyFloat", "OperationParameter2", "Parameter", "Priority of the operation") - a.addProperty("App::PropertyFloat", "OperationParameter3", "Parameter", "Priority of the operation") - a.PartToHandle = active_body - a.GripSize = active_body.Shape.BoundBox.YLength - diff --git a/freecad_workbench/freecad/robossembler/GripPoseGenerator.py b/freecad_workbench/freecad/robossembler/GripPoseGenerator.py deleted file mode 100644 index f0589c8..0000000 --- a/freecad_workbench/freecad/robossembler/GripPoseGenerator.py +++ /dev/null @@ -1,287 +0,0 @@ -import FreeCAD -import Part - -doc = FreeCAD.ActiveDocument - - -def check_capture_positions(): - # Получаем активный документ - doc = FreeCAD.ActiveDocument - - # Список тел без позиций захвата - bodies_without_capture_positions = [] - - # Перебираем все объекты в документе - for obj in doc.Objects: - if obj.isDerivedFrom("Part::Feature"): - # Проверяем, есть ли атрибут "Placement" у объекта - if not hasattr(obj, "Placement"): - # Если нет, добавляем его в список - bodies_without_capture_positions.append(obj.Label) - - # Проверяем результат - if len(bodies_without_capture_positions) > 0: - print("Следующие тела не имеют позиции захвата:") - for body in bodies_without_capture_positions: - print(body) - else: - print("Все тела имеют позиции захвата.") - - -check_capture_positions() - - - - - - - -import FreeCAD as App -doc = App.ActiveDocument - -def check_capture_positions(): - bodies_without_grip_pose = [] - solid_bodies_list = [] - lcs_list = [] - bodies_with_grip_pose = [] - for obj in doc.Objects: - if hasattr(obj, 'Shape') and hasattr(obj.Shape, 'Volume') and obj.Shape.Volume: - # if obj.Shape and obj.Shape.Volume: - solid_bodies_list.append(obj) - print(solid_bodies_list) - - for obj in doc.Objects: - if obj.TypeId =='PartDesign::CoordinateSystem': - lcs_list.append(obj) - print(lcs_list) - - for body in solid_bodies_list: - checker = 0 - for lcs in lcs_list: - - print(checker) - if lcs.Attachment_ParentObject == body.Label: - checker =+1 - if checker == 0: - bodies_without_grip_pose.append(body) - print(bodies_without_grip_pose) - - if len(bodies_without_grip_pose) == 0: - print('Все тела имеют позиции захвата') - else: - print('Имеются тела без позиций захвата:') - for body in bodies_without_grip_pose: - print(body.Label) - -check_capture_positions() - - -def create_grip_positions(obj, face1, face2): - if not (face1 and face2): - App.Console.PrintError("Не выбраны обе грани\n") - return - - normal1 = face1.normalAt(0, 0) - normal2 = face2.normalAt(0, 0) - - if normal1.isParallel(normal2): - # Найдите центры граней - center1 = face1.CenterOfMass - center2 = face2.CenterOfMass - - # Вычислите расстояние между центрами граней - distance = center2 - center1 - distance = distance.Length - - # Создайте вспомогательную систему координат между гранями - coordinate_system = App.ActiveDocument.addObject("Part::CoordinateSystem", "CoordinateSystem") - coordinate_system.Placement.Base = center1 + 0.5 * distance * normal1 - coordinate_system.Placement.Rotation = normal1.getRotationTo(App.Vector(0, 0, 1)) - - # Выведите информацию о расстоянии - App.Console.PrintMessage(f"Расстояние межу гранью 1 и гранью 2: {distance} мм\n") - - # Обновите графический интерфейс FreeCAD - App.ActiveDocument.recompute() - else: - App.Console.PrintError("Выбранные грани не являются параллельными\n") - - - - - -create_grip_positions() - -# Добавление обзервера для касаний -v=Gui.activeDocument().activeView() - -#This class logs any mouse button events. As the registered callback function fires twice for 'down' and -#'up' events we need a boolean flag to handle this. -class ViewObserver: - def __init__(self, view): - self.view = view - - def logPosition(self, info): - down = (info["State"] == "DOWN") - pos = info["Position"] - if (down): - FreeCAD.Console.PrintMessage("Clicked on position: ("+str(pos[0])+", "+str(pos[1])+")\n") - pnt = self.view.getPoint(pos) - FreeCAD.Console.PrintMessage("World coordinates: " + str(pnt) + "\n") - info = self.view.getObjectInfo(pos) - FreeCAD.Console.PrintMessage("Object info: " + str(info) + "\n") - - - - - -o = ViewObserver(v) -c = v.addEventCallback("SoMouseButtonEvent",o.logPosition) - - - - -### getObjectInfo работает -import FreeCAD as App -import FreeCADGui as Gui - -def getFaceInfo(face): - if face: - App.Console.PrintMessage(f"Информация о грани: {face}\n") - - # Получите позицию (Base) и ориентацию (Rotation) грани в глобальных координатах - placement = face.Placement - position = App.Vector(placement.Base) - orientation = App.Rotation(placement.Rotation) - - App.Console.PrintMessage(f"Позиция грани: {position}\n") - App.Console.PrintMessage(f"Ориентация грани: {orientation}\n") - -def getObjectInfo(): - selection = Gui.Selection.getSelectionEx() - if selection: - selected_object = selection[0].Object - if selected_object: - subelement_name = selection[0].SubElementNames[0] - if "Face" in subelement_name: - face = selected_object.Shape.Faces[int(subelement_name.split("Face")[1])] - getFaceInfo(face) - else: - App.Console.PrintError("Выберите грань, а не тело или другой элемент\n") - else: - App.Console.PrintError("Объект не найден\n") - else: - App.Console.PrintError("Не выбраны объекты\n") - -getObjectInfo() - - - -import FreeCAD as App -import FreeCADGui as Gui -import Part - - - -# Функция для получения списка всех объектов с заданным свойством -def get_objects_with_property(property_name, property_value): - result = [] - for obj in FreeCAD.ActiveDocument.Objects: - if hasattr(obj, "PropertiesList") and property_name in obj.PropertiesList: - if obj.getPropertyByName(property_name) == property_value: - result.append(obj) - return result - -# Получение списка всех объектов с названием тела в свойстве -bodies = get_objects_with_property("BodyName", "Body") - -# Получение списка всех объектов -all_objects = FreeCAD.ActiveDocument.Objects - -# Поиск и вывод тел, у которых нет связанных вспомогательных объектов -for body in bodies: - linked_objects = [] - for obj in all_objects: - if obj.hasLinkOf(body): - linked_objects.append(obj.Name) - if not linked_objects: - print(f"Тело без связанных объектов: {body.Name}") - - - - - -def create_coordinate_system(surface1, surface2): - if surface1 is None or surface2 is None: - App.Console.PrintError("Не удалось найти одну из поверхностей\n") - return - - # Проверка, являются ли поверхности плоскими - if surface1.Shape.Faces[0].Surface.TypeId == "Part::Plane" and surface2.Shape.Faces[0].Surface.TypeId == "Part::Plane": - # Проверка, являются ли поверхности параллельными - normal1 = surface1.Shape.normalAt(0, 0) - normal2 = surface2.Shape.normalAt(0, 0) - - if normal1.isParallel(normal2): - # центры поверхностей - center1 = surface1.Shape.BoundBox.Center - center2 = surface2.Shape.BoundBox.Center - - # Вычисление расстояние между центрами поверхностей - distance = center2 - center1 - distance = distance.Length - - # Создание вспомогательную систему координат между поверхностями - coordinate_system = App.ActiveDocument.addObject("Part::CoordinateSystem", "CoordinateSystem") - coordinate_system.Placement.Base = center1 + 0.5 * distance * normal1 - coordinate_system.Placement.Rotation = normal1.getRotationTo(App.Vector(0, 0, 1)) - - # Выведите информацию о расстоянии - App.Console.PrintMessage(f"Расстояние между поверхностью 1 и поверхностью 2: {distance} мм\n") - - # Обновите графический интерфейс FreeCAD - App.ActiveDocument.recompute() - else: - App.Console.PrintError("Выбранные поверхности не являются параллельными\n") - else: - App.Console.PrintError("Выбранные поверхности не являются плоскими\n") - -# Создайте пользовательский интерфейс кнопки для вызова функции -class CoordinateSystemTool: - def Activated(self): - selection = Gui.Selection.getSelectionEx() - if len(selection) == 2: - create_coordinate_system(selection[0].Object, selection[1].Object) - else: - App.Console.PrintError("Выберите две параллельные плоскости\n") - - def GetResources(self): - return { - 'Pixmap': 'path/to/your/icon.png', # Замените на путь к значку кнопки - 'MenuText': 'Создать вспомогательную систему координат', - 'ToolTip': 'Создать вспомогательную систему координат между двумя плоскостями' - } - -# Зарегистрируйте пользовательский инструмент -Gui.addCommand('My_Coordinate_System_Tool', CoordinateSystemTool()) - - -#### эта штука работает vvv - -# Функция для создания вспомогательного объекта и установки свойства "AttachmentType" -def create_helper_object_with_attribute(body, attribute_value): - helper_object = FreeCAD.ActiveDocument.addObject("App::FeaturePython", "HelperObject") - helper_object.addProperty("App::PropertyString", "AttachmentType").AttachmentType = attribute_value - helper_object.addProperty("App::PropertyString", "AttachedObject") - helper_object.AttachedObject = body.Label - - -# Пример использования: -# Замените "MyBody" на имя тела, к которому вы хотите привязать вспомогательный объект -body_to_attach = FreeCAD.ActiveDocument.getObjectsByLabel("gear_frame_221213")[0] -if body_to_attach: - create_helper_object_with_attribute(body_to_attach, "Body") -else: - print("Тело не найдено в активном документе.") - - diff --git a/freecad_workbench/freecad/robossembler/LICENSE b/freecad_workbench/freecad/robossembler/LICENSE deleted file mode 100644 index 8000a6f..0000000 --- a/freecad_workbench/freecad/robossembler/LICENSE +++ /dev/null @@ -1,504 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -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 this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -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 -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser 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 Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "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 -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY 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 -LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Libraries - - If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms of the -ordinary General Public License). - - To apply these terms, attach the following notices to the library. It is -safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least the -"copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 - USA - -Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the library, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James Random - Hacker. - - , 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! diff --git a/freecad_workbench/freecad/robossembler/Tools.py b/freecad_workbench/freecad/robossembler/Tools.py deleted file mode 100644 index 904ea2e..0000000 --- a/freecad_workbench/freecad/robossembler/Tools.py +++ /dev/null @@ -1,665 +0,0 @@ -import FreeCAD -import Part -import json -import os -import time - -from .GazeboExport import export_collada, export_sdf, config -from .GraspPose import insert -from . import ICONPATH, UIPATH -# from .scenarios.robossembler_freecad_export_scenario import RobossemblerFreeCadExportScenario - -if FreeCAD.GuiUp: - import FreeCADGui - from PySide import QtGui - -################################################################### -# Module functions -################################################################### - -def vector2list(vec, scale=1e-3): - """Gives the vector as a list, set scale for scaling factor. - default scale = 1e-3 for units in m.""" - return [vec.x*scale, vec.y*scale, vec.z*scale] - - -def matrix2list(mat, scale=1e-3): - """Gives the transformation matrix as a list, set scale 1 to get in mm.""" - return [[mat.A11, mat.A12, mat.A13, mat.A14*scale], - [mat.A21, mat.A22, mat.A23, mat.A24*scale], - [mat.A31, mat.A32, mat.A33, mat.A34*scale], - [mat.A41, mat.A42, mat.A43, mat.A44]] - -def placement2pose(pl, scale=1e-3): - """Gives the placement as an dictionary for geometry_msgs/Pose type.""" - return {"position": { - "x": pl.Base.x*scale, - "y": pl.Base.y*scale, - "z": pl.Base.z*scale - }, - "orientation": { - "x": pl.Rotation.Q[0], - "y": pl.Rotation.Q[1], - "z": pl.Rotation.Q[2], - "w": pl.Rotation.Q[3] - } - } - -def placement2axisvec(pl, scale=1e-3): - """Gives the placement as an dictionary of origin and rotation. - origin: [x,y,z], rotation:{axis:[ax,ay,az], angle:ang}""" - return {"origin": vector2list(pl.Base, scale), - "rotation": {"axis": vector2list(pl.Rotation.Axis, scale=1), - "angle": pl.Rotation.Angle}} - - -def boundingBox2list(bb, scale=1e-3): - """Gives the bounding box as a list in m instead of mm""" - return [bb.XMin*scale, bb.XMax*scale, - bb.YMin*scale, bb.YMax*scale, - bb.ZMin*scale, bb.ZMax*scale] - - -def principalProperties2dict(pp, scale=1e-3): - npp = {} - for key, value in pp.items(): - if type(value) is FreeCAD.Vector: - npp[key.lower()] = vector2list(value, scale=1e-3) - else: - npp[key.lower()] = value - return npp - - -def describeSubObject(subobj): - """Returns PrimitiveType, ShapeType.""" - if isinstance(subobj, Part.Vertex): - return "Vertex", "Vertex" - elif isinstance(subobj, Part.Edge): - if isinstance(subobj.Curve, Part.Arc): - return "Arc", "Edge" - elif isinstance(subobj.Curve, Part.ArcOfCircle): - return "ArcOfCircle", "Edge" - elif isinstance(subobj.Curve, Part.ArcOfEllipse): - return "ArcOfEllipse", "Edge" - elif isinstance(subobj.Curve, Part.ArcOfHyperbola): - return "ArcOfHyperbola", "Edge" - elif isinstance(subobj.Curve, Part.ArcOfParabola): - return "ArcOfParabola", "Edge" - elif isinstance(subobj.Curve, Part.BSplineCurve): - return "BSplineCurve", "Edge" - elif isinstance(subobj.Curve, Part.BezierCurve): - return "BezierCurve", "Edge" - elif isinstance(subobj.Curve, Part.Circle): - return "Circle", "Edge" - elif isinstance(subobj.Curve, Part.Ellipse): - return "Ellipse", "Edge" - elif isinstance(subobj.Curve, Part.Hyperbola): - return "Hyperbola", "Edge" - elif isinstance(subobj.Curve, Part.Line): - return "Line", "Edge" - elif isinstance(subobj.Curve, Part.Parabola): - return "Parabola", "Edge" - else: - FreeCAD.Console.PrintError("Unknown edge type") - elif isinstance(subobj, Part.Face): - if isinstance(subobj.Surface, Part.BSplineSurface): - return "BSplineSurface", "Face" - elif isinstance(subobj.Surface, Part.BezierSurface): - return "BezierSurface", "Face" - elif isinstance(subobj.Surface, Part.Cylinder): - return "Cylinder", "Face" - elif isinstance(subobj.Surface, Part.Plane): - return "Plane", "Face" - elif isinstance(subobj.Surface, Part.Sphere): - return "Sphere", "Face" - elif isinstance(subobj.Surface, Part.Toroid): - return "Toroid", "Face" - elif isinstance(subobj.Surface, Part.Cone): - return "Cone", "Face" - else: - FreeCAD.Console.PrintError("Unknown surface type") - # Better strategy desirable for the following: - elif isinstance(subobj, Part.Wire): - return "Wire", "Wire" - elif isinstance(subobj, Part.Shell): - return "Shell", "Shell" - elif isinstance(subobj, Part.Solid): - return "Solid", "Solid" - elif isinstance(subobj, Part.Compsolid): - return "Compsolid", "Compsolid" - elif isinstance(subobj, Part.Compound): - return "Compound", "Compound" - else: - FreeCAD.Console.PrintError("Unable to identify subobject.") - - -def closeToZero(a, tol=1e-10): - return abs(a) < tol - - -def spawnClassCommand(classname, function, resources): - """ - Commands, or buttons, are tedious to write. So this function spawns - one if the function to be executed takes no arguments. - Example usage: - spawnClassCommand("testcommand", testfunc, - {"Pixmap":"", "MenuText":"menutext","ToolTip":"tooltiptext"}) - then add "testcommand" to commandlist in InitGui.py - """ - def Activated(s): - function() - - def GetResources(s): - return resources - CommandClass = type("classname", (object,), {"Activated": Activated, - "GetResources": GetResources}) - FreeCADGui.addCommand(classname, CommandClass()) - - -def getLocalPartProps(obj): - old_placement = obj.Placement - obj_parent_label = '' - if obj.getParentGeoFeatureGroup(): - obj_parent_label = obj.getParentGeoFeatureGroup().Label - # obj.Placement = FreeCAD.Placement() - """ Part properties """ - partprops = { - "label": obj.Label, - "parent_label": obj_parent_label, - "placement": placement2pose(old_placement), - # "grip properties": { "grip open": obj.GripOpen, "grip depth": obj.GripDepth, "grip width": obj.GripWidth} - # "boundingbox": boundingBox2list(obj.Shape.BoundBox), - # "volume": obj.Shape.Volume*1e-9, - # "centerofmass": vector2list(obj.Shape.CenterOfMass), - # "principalproperties": principalProperties2dict(obj.Shape.PrincipalProperties) - } - - if obj.Type == 'grip': - partprops["grip properties"] = { "grip open": obj.GripOpen, "grip depth": obj.GripDepth, "grip width": obj.GripWidth} - - elif obj.Type == 'area': - partprops["area dim"] = { } #свойства, описывающие размер - - elif obj.Type == 'vol': - partprops["vol dim"] = { } #свойства, описывающие размер области - - - # obj.Placement = old_placement - return partprops - -# Longest match for mesh name - -def longest_match(seq1, seq2): - from difflib import SequenceMatcher as SM - - sm = SM(lambda c: c in set(' ,'), seq1, seq2) - m = sm.find_longest_match(0, len(seq1), 0, len(seq2)) - return seq1[m.a:m.b] - - -################################################################### -# Export functions -################################################################### - -def exportGazeboModels(): - """Export packages for Gazebo Simulator.""" - doc = FreeCAD.activeDocument() - selected_objects = FreeCADGui.Selection.getSelection() - FreeCADGui.Selection.clearSelection() - if len(selected_objects) == 0: - FreeCAD.Console.PrintError("No part selected.") - return False - - export_dir = QtGui.QFileDialog.getExistingDirectory(None, "Choose Export Directory", - os.path.split(doc.FileName)[0]) - - # Gather the unique shapes, and clone parts as - # dict = { partX : { obj1: , graspposes: {}, placements : {}, mesh: } } - unique_objs = [] - parts = {} - num_objs = 0 - for obj in doc.Objects: - new_shape = True - model_dir = os.path.join(export_dir, obj.Label) - mesh_dir = os.path.join(model_dir, 'meshes') - mesh_file = os.path.join(mesh_dir, obj.Label + '.dae') - mesh_uri = os.path.normpath(os.path.relpath(mesh_file, export_dir)) - # Select only Parts, not Grasp Poses or Gripper - if obj.TypeId == "Part::Feature" and not "PartToHandle" in obj.PropertiesList and not "Container" in obj.PropertiesList: - num_objs += 1 - for uobj in unique_objs: - if uobj.Shape.isPartner(obj.Shape): - new_shape = False - # parts[obj.Label]["mesh"] += parts[uobj.Label]["mesh"] - parts[obj.Label] = {"obj": obj, - "graspposes": {}, - "mesh": parts[uobj.Label]["mesh"] - } - # if Shape is unique export mesh - if new_shape: - unique_objs.append(obj) - parts[obj.Label] = {"obj": obj, "graspposes": {}, "placements": {}, "mesh": mesh_file} - - for obj in doc.Objects: - # Add grasp poses to parts dictionary - if "PartToHandle" in obj.PropertiesList: - graspposes = { obj.Container.Label: { - "placement": placement2pose(obj.Container.Placement), - "distance": obj.GripSize*1e-3 - # "OperationType" : obj.OperationType - # "Operation Priority" : obj.OperationPriority - # obj.Operation Parameter 1 : obj.OperationParameter1 - # obj.Operation Parameter 2 : obj.OperationParameter2 - # obj.Operation Parameter 3 : obj.OperationParameter3 - } - } - parts[obj.PartToHandle.Label].update({"graspposes" : graspposes}) - - # Add part placement position on Plane surface - import Frames - if hasattr(obj, 'Proxy') and "ShapeType" in obj.PropertiesList: - if isinstance(obj.Proxy, Frames.FeatureFrame) and obj.ShapeType == 'Face': - parts[obj.Part.Label].update({ "placements": { obj.Label: placement2pose(obj.Placement) } }) - - # Create SDF package from Parts or other packages - def create_package(name, objects, export_dir): - model_dir = os.path.join(export_dir, name) - mesh_dir = os.path.join(model_dir, 'meshes') - os.makedirs(mesh_dir, exist_ok=True) - - GazeboExport.export_collada(objects, parts[name]["mesh"]) - GazeboExport.export_sdf({ name: parts[name] }, export_dir, obj.Label) - - with open(os.path.join(model_dir, 'model.config'), 'w') as config_file: - config_file.write(GazeboExport.config(name, - 'model.sdf', 'Author', 'Email', 'Comment', 'Version')) - ''' - with open(os.path.join(model_dir, 'frames.json'), 'w') as frames_file: - json.dump({"label": name, - "placement": placement2pose(parts[name]["obj"].Placement), - "features": - { "graspposes" : parts[name]["graspposes"] - , "placements" : parts[name]["placements"]}}, - frames_file, indent=1, separators=(',', ': ')) - ''' - - - - # Export assets for parts - for obj in selected_objects: - create_package(obj.Label, [obj], export_dir) - exportPartInfo(obj, os.path.join(export_dir, obj.Label, 'frames.json') ) - appendFeatureFrames(obj, os.path.join(export_dir, obj.Label, 'frames.json')) - - # Export asset for subassembly - # subasm_name = "_".join(list(map(lambda x: x.Label[:8], selected_objects))) - # create_package(subasm_name, selected_objects, export_dir) - - return True - - -def exportPartInfo(obj, ofile): - """ - Exports part info to a new json file. - The part info includes: - Placement relative to world frame, bounding box, volume, center of mass, - principal properties. - For more information on principal properties, see TopoShape in OCCT - documentation. - """ - - partprops = getLocalPartProps(obj) - with open(ofile, "w", encoding="utf8") as propfile: - json.dump(partprops, propfile, indent=1, separators=(',', ': ')) - return ofile - - -def appendPartInfo(obj, ofile): - """Rewrites/appends part info to an existing json file. - The part info includes: - Placement relative to world frame, bounding box, volume, center of mass, - principal properties. - For more information on principal properties, see TopoShape in OCCT - documentation. - """ - with open(ofile, "r", encoding="utf8") as propfile: - partprops = json.load(propfile) - new_props = getLocalPartProps(obj) - partprops.update(new_props) - with open(ofile, "w", encoding="utf8") as propfile: - json.dump(partprops, propfile, indent=1, separators=(',', ': ')) - return True - - -def exportFeatureFrames(obj, ofile): - """Exports feature frames attached to a part.""" - # Get the feature frames - import Frames - ff_check = lambda x: isinstance(x.Proxy, Frames.FeatureFrame) if hasattr(x, 'Proxy') else False - ff_list = filter(ff_check, obj.InList) - ff_named = { ff.Label: ff.Proxy.getDict() for ff in ff_list } - feature_dict = { "features": ff_named } - - with open(ofile, "w", encoding="utf8") as propfile: - json.dump(feature_dict, propfile, indent=1, separators=(',', ': ')) - return True - - -def appendFeatureFrames(obj, ofile): - """Rewrites/appends featureframes attached to a part to an existing json - file.""" - # Get the feature frames - import Frames - with open(ofile, "r", encoding="utf8") as propfile: - partprops = json.load(propfile) - ff_check = lambda x: isinstance(x.Proxy, Frames.FeatureFrame) if hasattr(x, 'Proxy') else False - # part's children list - ff_list = filter(ff_check, obj.InList) - ff_named = { ff.Label: {"label": ff.Label, "placement": placement2pose(ff.FeaturePlacement)} for ff in ff_list } - feature_dict = { "features": ff_named } - if "features" not in partprops.keys(): - partprops.update(feature_dict) - else: - partprops["features"].update(feature_dict["features"]) - with open(ofile, "w", encoding="utf8") as propfile: - json.dump(partprops, propfile, indent=1, separators=(',', ': ')) - return True - - -def exportPartInfoDialogue(): - """Spawns a dialogue window for part info exporting""" - # Select only true parts - s = FreeCADGui.Selection.getSelection() - FreeCADGui.Selection.clearSelection() - if len(s) == 0: - FreeCAD.Console.PrintError("No part selected.") - return False - unique_selected = [] - for item in s: - if item not in unique_selected and isinstance(item, Part.Feature): - # Ensuring that we are parts - unique_selected.append(item) - FreeCADGui.Selection.addSelection(item) - # Fix wording - textprompt = "Save the properties of the part" - if len(unique_selected) > 1: - textprompt = textprompt + "s" - opts = QtGui.QFileDialog.DontConfirmOverwrite - # Create file dialog - ofile, filt = QtGui.QFileDialog.getSaveFileName(None, textprompt, - os.getenv("HOME"), - "*.json", options=opts) - if ofile == "": - # User cancelled - return False - if os.path.exists(ofile): - msgbox = QtGui.QMessageBox() - msgbox.setText("File already exists. We can overwrite the file, or add the information/rewrite only relevant sections.") - append_button = msgbox.addButton("Append", QtGui.QMessageBox.YesRole) - overwrite_button = msgbox.addButton("Overwrite", QtGui.QMessageBox.NoRole) - msgbox.exec_() - if msgbox.clickedButton() == append_button: - NEWFILE = False - elif msgbox.clickedButton() == overwrite_button: - NEWFILE = True - else: - return False - else: - NEWFILE = True - if NEWFILE: - exportPartInfo(unique_selected[0], ofile) - else: - appendPartInfo(unique_selected[0], ofile) - - if len(unique_selected) > 1: - FreeCAD.Console.PrintWarning("Multi-part export not yet supported\n") - FreeCAD.Console.PrintMessage("Properties exported to "+str(ofile)+"\n") - - -def exportFeatureFramesDialogue(): - """Spawns a dialogue window for a part's feature frames to be exported.""" - # Select only true parts - import Frames - s = FreeCADGui.Selection.getSelection() - FreeCADGui.Selection.clearSelection() - if len(s) == 0: - FreeCAD.Console.PrintError("No part selected.") - return False - unique_selected = [] - for item in s: - if item not in unique_selected and isinstance(item.Proxy, Frames.FeatureFrame): - # Ensuring that we are parts - unique_selected.append(item) - FreeCADGui.Selection.addSelection(item) - # Fix wording - textprompt = "Save the feature frames attached to the part" - if len(unique_selected) > 1: - textprompt = textprompt + "s" - opts = QtGui.QFileDialog.DontConfirmOverwrite - # Create file dialog - ofile, filt = QtGui.QFileDialog.getSaveFileName(None, textprompt, os.getenv("HOME"), - "*.json", options=opts) - if ofile == "": - # User cancelled - return False - if os.path.exists(ofile): - msgbox = QtGui.QMessageBox() - msgbox.setText("File already exists. We can overwrite the file, or add the information/rewrite only relevant sections.") - append_button = msgbox.addButton("Append", QtGui.QMessageBox.YesRole) - overwrite_button = msgbox.addButton("Overwrite", QtGui.QMessageBox.NoRole) - msgbox.exec_() - if msgbox.clickedButton() == append_button: - NEWFILE = False - elif msgbox.clickedButton() == overwrite_button: - NEWFILE = True - else: - return False - else: - NEWFILE = True - if NEWFILE: - exportFeatureFrames(unique_selected[0], ofile) - else: - appendFeatureFrames(unique_selected[0], ofile) - if len(unique_selected) > 1: - FreeCAD.Console.PrintWarning("Multi-part export not yet supported\n") - FreeCAD.Console.PrintMessage("Feature frames of " + str(unique_selected[0].Label) + " exported to " + str(ofile) + "\n") - - -def exportPlacementAndProperties(): - """Spawns a dialogue window for exporting both.""" - import Frames - s = FreeCADGui.Selection.getSelection() - FreeCADGui.Selection.clearSelection() - if len(s) == 0: - FreeCAD.Console.PrintError("No part selected") - return False - unique_selected = [] - for item in s: - if item not in unique_selected: - # Ensuring that we are parts - unique_selected.append(item) - FreeCADGui.Selection.addSelection(item) - FreeCAD.Console.PrintMessage("Added for export "+str(item.FullName)+"\n") - # Fix wording - textprompt = "Save the part info and feature frames attached to the part" - if len(unique_selected) > 1: - textprompt = textprompt + "s" - opts = QtGui.QFileDialog.DontConfirmOverwrite - # Create file dialog - ofile, filt = QtGui.QFileDialog.getSaveFileName(None, textprompt, - os.getenv("HOME"), - "*.json", options=opts) - if ofile == "": - # User cancelled - return False - - # File path stuff - odir, of = os.path.split(ofile) - if not os.path.exists(odir): - os.makedirs(odir) - if not of.lower().endswith(".json"): - ofile = ofile + ".json" - - if os.path.exists(ofile): - msgbox = QtGui.QMessageBox() - msgbox.setText("File already exists. We can overwrite the file, or add the information/rewrite only relevant sections.") - append_button = msgbox.addButton("Append", QtGui.QMessageBox.YesRole) - overwrite_button = msgbox.addButton("Overwrite", QtGui.QMessageBox.NoRole) - msgbox.exec_() - if msgbox.clickedButton() == append_button: - NEWFILE = False - elif msgbox.clickedButton() == overwrite_button: - NEWFILE = True - else: - return False - else: - NEWFILE = True - if NEWFILE: - exportPartInfo(unique_selected[0], ofile) - appendFeatureFrames(unique_selected[0], ofile) - else: - appendPartInfo(unique_selected[0], ofile) - appendFeatureFrames(unique_selected[0], ofile) - if len(unique_selected) > 1: - FreeCAD.Console.PrintWarning("Multi-part export not yet supported.\n") - FreeCAD.Console.PrintMessage("Feature frames of " - + str(unique_selected[0].Label) - + " exported to " + str(ofile) + "\n") - - -################################################################### -# GUI Commands -################################################################### - -spawnClassCommand("ExportPlacementAndPropertiesCommand", - exportPlacementAndProperties, - {"Pixmap": str(os.path.join(ICONPATH, "parttojson.svg")), - "MenuText": "Export placement and properties", - "ToolTip": "Export object placement and properties and feature frames"}) - -spawnClassCommand("ExportGazeboModels", - exportGazeboModels, - {"Pixmap": str(os.path.join(ICONPATH, "gazeboexport.svg")), - "MenuText": "Export SDF-models to Gazebo", - "ToolTip": "Export SDF-models for all solid parts"}) - -spawnClassCommand("InsertGraspPose", - insert, - {"Pixmap": str(os.path.join(ICONPATH, "addgrasppose.svg")), - "MenuText": "Insert Grasp Pose", - "ToolTip": "Insert Grasp Pose for Selected Part"}) - -# spawnClassCommand("ASM4StructureParsing", -# RobossemblerFreeCadExportScenario().call, -# {"Pixmap": str(os.path.join(ICONPATH, "assembly4.svg")), -# "MenuText": "Make a ASM4 parsing", -# "ToolTip": "Make a ASM4 1"}) - - -################################################################### -# Information from primitive type -################################################################### -def getPrimitiveInfo(prim_type, subobj, scale=1e-3): - """returns a dictionary of the primitive's specific information.""" - d = {} - if prim_type == "ArcOfCircle": - d["radius"] = scale*subobj.Curve.Radius - d["center"] = vector2list(subobj.Curve.Center, scale) - d["axis"] = vector2list(subobj.Curve.Axis, scale=1) - d["parameterrange"] = subobj.ParameterRange - elif prim_type == "ArcOfEllipse": - d["center"] = vector2list(subobj.Curve.Center, scale) - d["axis"] = vector2list(subobj.Curve.Axis, scale=1) - d["majorradius"] = scale*subobj.Curve.MajorRadius - d["minorradius"] = scale*subobj.Curve.MinorRadius - d["parameterrange"] = subobj.ParameterRange - elif prim_type == "ArcOfHyperBola": - d["anglexu"] = subobj.Curve.AngleXU - d["axis"] = vector2list(subobj.Curve.Axis, scale=1) - d["center"] = vector2list(subobj.Curve.Center, scale) - d["majorradius"] = scale*subobj.Curve.MajorRadius - d["minorradius"] = scale*subobj.Curve.MinorRadius - d["parameterrange"] = subobj.ParameterRange - elif prim_type == "ArcOfParabola": - d["anglexu"] = subobj.Curve.AngleXU - d["axis"] = vector2list(subobj.Curve.Axis, scale=1) - d["center"] = vector2list(subobj.Curve.Center, scale) - d["focal"] = scale*subobj.Curve.Focal - elif prim_type == "BSplineCurve": - FreeCAD.Console.PrintWarning("getPrimitiveInfo of BSpline incomplete.") - elif prim_type == "BezierCurve": - FreeCAD.Console.PrintWarning("getPrimitiveInfo of Bezier incomplete.") - elif prim_type == "Circle": - d["radius"] = scale*subobj.Curve.Radius - d["center"] = vector2list(subobj.Curve.Center, scale) - d["axis"] = vector2list(subobj.Curve.Axis, scale=1) - d["parameterrange"] = subobj.ParameterRange - elif prim_type == "Ellipse": - d["center"] = vector2list(subobj.Curve.Center, scale) - d["axis"] = vector2list(subobj.Curve.Axis, scale=1) - d["majorradius"] = scale*subobj.Curve.MajorRadius - d["minorradius"] = scale*subobj.Curve.MinorRadius - d["parameterrange"] = subobj.ParameterRange - elif prim_type == "Hyperbola": - d["anglexu"] = subobj.Curve.AngleXU - d["axis"] = vector2list(subobj.Curve.Axis, scale=1) - d["center"] = vector2list(subobj.Curve.Center, scale) - d["majorradius"] = scale*subobj.Curve.MajorRadius - d["minorradius"] = scale*subobj.Curve.MinorRadius - d["parameterrange"] = subobj.ParameterRange - elif prim_type == "Parabola": - d["anglexu"] = subobj.Curve.AngleXU - d["axis"] = vector2list(subobj.Curve.Axis, scale=1) - d["center"] = vector2list(subobj.Curve.Center, scale) - d["focal"] = scale*subobj.Curve.Focal - elif prim_type == "Line": - if int(FreeCAD.Version()[1]) > 16: - sp = subobj.valueAt(subobj.FirstParameter) - ep = subobj.valueAt(subobj.LastParameter) - d["startpoint"] = vector2list(sp) - d["endpoint"] = vector2list - else: - if not hasattr(subobj.Curve, "Infinite"): - d["startpoint"] = vector2list(subobj.Curve.StartPoint) - d["endpoint"] = vector2list(subobj.Curve.EndPoint) - if hasattr(subobj.Curve, "Infinite"): - if subobj.Curve.Infinite: - d["infinite"] = subobj.Curve.Infinite - else: - d["startpoint"] = vector2list(subobj.Curve.StartPoint) - d["endpoint"] = vector2list(subobj.Curve.EndPoint) - elif prim_type == "BSplineSurface": - FreeCAD.Console.PrintWarning("getPrimitiveInfo of BSpline incomplete.") - elif prim_type == "BezierSurface": - FreeCAD.Console.PrintWarning("getPrimitiveInfo of Bezier incomplete.") - elif prim_type == "Cylinder": - d["axis"] = vector2list(subobj.Surface.Axis, scale=1) - d["radius"] = scale*subobj.Surface.Radius - d["center"] = vector2list(subobj.Surface.Center) - PR = list(subobj.ParameterRange) - PR[2] = PR[2]*scale - PR[3] = PR[3]*scale - d["parameterrange"] = PR - elif prim_type == "Plane": - d["axis"] = vector2list(subobj.Surface.Axis, scale=1) - d["position"] = vector2list(subobj.Surface.Position, scale) - d["parameterrange"] = [scale*i for i in subobj.ParameterRange] - elif prim_type == "Sphere": - d["axis"] = vector2list(subobj.Surface.Axis, scale=1) - d["center"] = vector2list(subobj.Surface.Center, scale) - d["radius"] = scale*subobj.Surface.Radius - d["parameterrange"] = subobj.ParameterRange - elif prim_type == "Toroid": - d["axis"] = vector2list(subobj.Surface.Axis, scale=1) - d["center"] = vector2list(subobj.Surface.Center, scale) - d["majorradius"] = scale*subobj.Surface.MajorRadius - d["minorradius"] = scale*subobj.Surface.MinorRadius - d["parameterrange"] = subobj.Surface.ParameterRange - elif prim_type == "Cone": - d["axis"] = vector2list(subobj.Surface.Axis, scale=1) - d["center"] = vector2list(subobj.Surface.Center, scale) - d["radius"] = scale*subobj.Surface.Radius - d["semiangle"] = subobj.Surface.SemiAngle - d["parameterrange"] = subobj.ParameterRange - FreeCAD.Console.PrintWarning("getPrimitiveInfo of Cone may have wrong ParameterRange.") - return d diff --git a/freecad_workbench/freecad/robossembler/TranslateUtils.py b/freecad_workbench/freecad/robossembler/TranslateUtils.py deleted file mode 100644 index fc91518..0000000 --- a/freecad_workbench/freecad/robossembler/TranslateUtils.py +++ /dev/null @@ -1,37 +0,0 @@ -# -*- coding: utf8 -*- - -#*************************************************************************** -#* * -#* Copyright (c) 2020 kbwbe * -#* * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* 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 Library General Public License for more details. * -#* * -#* You should have received a copy of the GNU Library General Public * -#* License along with this program; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#*************************************************************************** - -import FreeCAD - - -if FreeCAD.GuiUp: - from PySide.QtCore import QT_TRANSLATE_NOOP - from DraftGui import translate -else: - def QT_TRANSLATE_NOOP(context, text): - return text - - def translate(context, text): - return text diff --git a/freecad_workbench/freecad/robossembler/UI/FeatureFrameCreator.ui b/freecad_workbench/freecad/robossembler/UI/FeatureFrameCreator.ui deleted file mode 100644 index 1eb41b6..0000000 --- a/freecad_workbench/freecad/robossembler/UI/FeatureFrameCreator.ui +++ /dev/null @@ -1,73 +0,0 @@ - - - FeatureFrameCreator - - - - 0 - 0 - 235 - 238 - - - - - 0 - 0 - - - - - 235 - 238 - - - - - 235 - 238 - - - - Feature Frame - - - - - 30 - 29 - 170 - 151 - - - - - - - 30 - 190 - 171 - 27 - - - - - - - 35 - 10 - 161 - 20 - - - - TextLabel - - - Qt::AlignCenter - - - - - - diff --git a/freecad_workbench/freecad/robossembler/UI/FramePlacer.ui b/freecad_workbench/freecad/robossembler/UI/FramePlacer.ui deleted file mode 100644 index 335f3a7..0000000 --- a/freecad_workbench/freecad/robossembler/UI/FramePlacer.ui +++ /dev/null @@ -1,520 +0,0 @@ - - - dialog - - - - 0 - 0 - 299 - 292 - - - - - 0 - 0 - - - - - 299 - 292 - - - - Part Frame Creator - - - - - 52 - 85 - 103 - 27 - - - - Offset in part frame x direction - - - mm - - - -1000.000000000000000 - - - 1000.000000000000000 - - - - - - 52 - 118 - 103 - 27 - - - - offset in part frame z direction - - - mm - - - -1000.000000000000000 - - - 1000.000000000000000 - - - - - - 52 - 151 - 103 - 27 - - - - offset in part frame z direction - - - mm - - - 2 - - - -1000.000000000000000 - - - 1000.000000000000000 - - - - - - 9 - 85 - 16 - 17 - - - - x - - - XBox - - - - - - 9 - 118 - 16 - 17 - - - - y - - - YBox - - - - - - 9 - 151 - 16 - 17 - - - - z - - - ZBox - - - - - - 161 - 85 - 24 - 17 - - - - roll offset from part frame - - - roll - - - RollBox - - - - - - 161 - 118 - 35 - 17 - - - - pitch offset from part frame - - - pitch - - - PitchBox - - - - - - 161 - 151 - 29 - 17 - - - - yaw offset from part frame - - - yaw - - - YawBox - - - - - - 228 - 85 - 61 - 27 - - - - roll offset from part frame - - - ° - - - 1 - - - 360.000000000000000 - - - - - - 228 - 118 - 61 - 27 - - - - pitch offset from part frame - - - ° - - - 1 - - - 360.000000000000000 - - - - - - 228 - 151 - 61 - 27 - - - - yaw offset from part frame - - - ° - - - 1 - - - 360.000000000000000 - - - - - - 94 - 9 - 195 - 31 - - - - - 0 - 0 - - - - Label of the frame - - - Label of the new frame - - - Label of the new frame, must be unique - - - Qt::ScrollBarAlwaysOff - - - - - - 9 - 9 - 79 - 31 - - - - Frame label - - - - - - 9 - 48 - 281 - 31 - - - - Define an offset from the part frame if needed - - - Offset from part frame - - - Qt::AlignCenter - - - - - - 160 - 180 - 71 - 21 - - - - Scale of the axis arrows - - - Scale of the axis arrows - - - Scale of the axis arrows - - - Axis scale - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - - - - 230 - 180 - 60 - 27 - - - - Scale of the axis arrows - - - Scale of the axis arrows - - - Scale of the axis arrows - - - 0.100000000000000 - - - 2.000000000000000 - - - 0.010000000000000 - - - 0.110000000000000 - - - - - true - - - - 20 - 220 - 66 - 31 - - - - false - - - Options - - - OptionsBox - - - - - true - - - - 210 - 220 - 78 - 27 - - - - false - - - - - true - - - - 100 - 250 - 62 - 27 - - - - false - - - - - true - - - - 220 - 250 - 62 - 27 - - - - false - - - - - true - - - - 80 - 250 - 16 - 31 - - - - false - - - u - - - UBox - - - - - true - - - - 200 - 250 - 16 - 31 - - - - false - - - v - - - VBox - - - - - true - - - - 20 - 256 - 51 - 21 - - - - false - - - Coords: - - - - - - diff --git a/freecad_workbench/freecad/robossembler/UI/InsertTaskCreator.ui b/freecad_workbench/freecad/robossembler/UI/InsertTaskCreator.ui deleted file mode 100644 index f2830c3..0000000 --- a/freecad_workbench/freecad/robossembler/UI/InsertTaskCreator.ui +++ /dev/null @@ -1,262 +0,0 @@ - - - Dialog - - - - 0 - 0 - 323 - 325 - - - - - 316 - 325 - - - - Dialog - - - - - 10 - 20 - 71 - 21 - - - - Task Label - - - - - - 150 - 290 - 161 - 27 - - - - Get from selection - - - - - - 100 - 20 - 211 - 27 - - - - - 0 - 0 - - - - - - - 10 - 50 - 31 - 21 - - - - Hole - - - - - - 10 - 130 - 31 - 21 - - - - Peg - - - - - - 50 - 70 - 41 - 21 - - - - Part: - - - - - - 50 - 90 - 41 - 21 - - - - Face: - - - - - - 50 - 150 - 41 - 21 - - - - Part: - - - - - - 50 - 170 - 41 - 21 - - - - Face: - - - - - - 100 - 70 - 231 - 21 - - - - PartLabel - - - - - - 100 - 90 - 231 - 21 - - - - FaceID - - - - - - 100 - 170 - 231 - 21 - - - - FaceID - - - - - - 100 - 150 - 231 - 21 - - - - PartLabel - - - - - - 100 - 110 - 231 - 21 - - - - Feature Description - - - - - - 30 - 110 - 61 - 21 - - - - Feature: - - - - - - 100 - 190 - 231 - 21 - - - - Feature Description - - - - - - 30 - 190 - 61 - 21 - - - - Feature: - - - - - - 10 - 290 - 131 - 27 - - - - Animate - - - - - - diff --git a/freecad_workbench/freecad/robossembler/UI/PartFrameCreator.ui b/freecad_workbench/freecad/robossembler/UI/PartFrameCreator.ui deleted file mode 100644 index 335f3a7..0000000 --- a/freecad_workbench/freecad/robossembler/UI/PartFrameCreator.ui +++ /dev/null @@ -1,520 +0,0 @@ - - - dialog - - - - 0 - 0 - 299 - 292 - - - - - 0 - 0 - - - - - 299 - 292 - - - - Part Frame Creator - - - - - 52 - 85 - 103 - 27 - - - - Offset in part frame x direction - - - mm - - - -1000.000000000000000 - - - 1000.000000000000000 - - - - - - 52 - 118 - 103 - 27 - - - - offset in part frame z direction - - - mm - - - -1000.000000000000000 - - - 1000.000000000000000 - - - - - - 52 - 151 - 103 - 27 - - - - offset in part frame z direction - - - mm - - - 2 - - - -1000.000000000000000 - - - 1000.000000000000000 - - - - - - 9 - 85 - 16 - 17 - - - - x - - - XBox - - - - - - 9 - 118 - 16 - 17 - - - - y - - - YBox - - - - - - 9 - 151 - 16 - 17 - - - - z - - - ZBox - - - - - - 161 - 85 - 24 - 17 - - - - roll offset from part frame - - - roll - - - RollBox - - - - - - 161 - 118 - 35 - 17 - - - - pitch offset from part frame - - - pitch - - - PitchBox - - - - - - 161 - 151 - 29 - 17 - - - - yaw offset from part frame - - - yaw - - - YawBox - - - - - - 228 - 85 - 61 - 27 - - - - roll offset from part frame - - - ° - - - 1 - - - 360.000000000000000 - - - - - - 228 - 118 - 61 - 27 - - - - pitch offset from part frame - - - ° - - - 1 - - - 360.000000000000000 - - - - - - 228 - 151 - 61 - 27 - - - - yaw offset from part frame - - - ° - - - 1 - - - 360.000000000000000 - - - - - - 94 - 9 - 195 - 31 - - - - - 0 - 0 - - - - Label of the frame - - - Label of the new frame - - - Label of the new frame, must be unique - - - Qt::ScrollBarAlwaysOff - - - - - - 9 - 9 - 79 - 31 - - - - Frame label - - - - - - 9 - 48 - 281 - 31 - - - - Define an offset from the part frame if needed - - - Offset from part frame - - - Qt::AlignCenter - - - - - - 160 - 180 - 71 - 21 - - - - Scale of the axis arrows - - - Scale of the axis arrows - - - Scale of the axis arrows - - - Axis scale - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - - - - 230 - 180 - 60 - 27 - - - - Scale of the axis arrows - - - Scale of the axis arrows - - - Scale of the axis arrows - - - 0.100000000000000 - - - 2.000000000000000 - - - 0.010000000000000 - - - 0.110000000000000 - - - - - true - - - - 20 - 220 - 66 - 31 - - - - false - - - Options - - - OptionsBox - - - - - true - - - - 210 - 220 - 78 - 27 - - - - false - - - - - true - - - - 100 - 250 - 62 - 27 - - - - false - - - - - true - - - - 220 - 250 - 62 - 27 - - - - false - - - - - true - - - - 80 - 250 - 16 - 31 - - - - false - - - u - - - UBox - - - - - true - - - - 200 - 250 - 16 - 31 - - - - false - - - v - - - VBox - - - - - true - - - - 20 - 256 - 51 - 21 - - - - false - - - Coords: - - - - - - diff --git a/freecad_workbench/freecad/robossembler/UI/ScrewTaskCreator.ui b/freecad_workbench/freecad/robossembler/UI/ScrewTaskCreator.ui deleted file mode 100644 index fc20be0..0000000 --- a/freecad_workbench/freecad/robossembler/UI/ScrewTaskCreator.ui +++ /dev/null @@ -1,239 +0,0 @@ - - - Dialog - - - - 0 - 0 - 337 - 322 - - - - - 337 - 322 - - - - Dialog - - - - - 20 - 50 - 31 - 21 - - - - Hole - - - - - - 60 - 150 - 41 - 21 - - - - Part: - - - - - - 60 - 170 - 41 - 21 - - - - Face: - - - - - - 110 - 170 - 231 - 21 - - - - FaceID - - - - - - 20 - 20 - 71 - 21 - - - - Task Label - - - - - - 110 - 20 - 211 - 27 - - - - - 0 - 0 - - - - - - - 20 - 290 - 131 - 27 - - - - Animate - - - - - - 160 - 290 - 161 - 27 - - - - Get from selection - - - - - - 110 - 90 - 231 - 21 - - - - FaceID - - - - - - 60 - 70 - 41 - 21 - - - - Part: - - - - - - 60 - 90 - 41 - 21 - - - - Face: - - - - - - 20 - 130 - 41 - 21 - - - - Screw - - - - - - 110 - 70 - 231 - 21 - - - - PartLabel - - - - - - 110 - 150 - 231 - 21 - - - - PartLabel - - - - - - 30 - 190 - 66 - 17 - - - - Type: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - 110 - 190 - 161 - 17 - - - - ThreadType - - - - - - diff --git a/freecad_workbench/freecad/robossembler/__init__.py b/freecad_workbench/freecad/robossembler/__init__.py deleted file mode 100644 index 5078ca2..0000000 --- a/freecad_workbench/freecad/robossembler/__init__.py +++ /dev/null @@ -1,7 +0,0 @@ -import os -import freecad.robossembler.utils -from .version import __version__ - -UIPATH = os.path.join(os.path.dirname(__file__), "UI") -ICONPATH = os.path.join(os.path.dirname(__file__), "resources/icons") -TRANSLATIONSPATH = os.path.join(os.path.dirname(__file__), "resources/translations") \ No newline at end of file diff --git a/freecad_workbench/freecad/robossembler/asm_graph.py b/freecad_workbench/freecad/robossembler/asm_graph.py deleted file mode 100644 index dddb6fc..0000000 --- a/freecad_workbench/freecad/robossembler/asm_graph.py +++ /dev/null @@ -1,40 +0,0 @@ -import json -import networkx as nx -import matplotlib.pyplot as plt -import os - -def load_sequences(filename): - with open(filename, 'r') as f: - data = json.load(f) - return data['sequences'] - -def create_graph(sequences): - G = nx.DiGraph() - #for seq in sequences: - for i in range(len(sequences) - 1): - G.add_edge(sequences[i], sequences[i + 1]) - return G - -def draw_graph_with_thumbnails(G, image_folder): - pos = {} - x = 1 - for node in G.nodes(): - pos[node] = (1, -x) # Устанавливаем позиции узлов по вертикали - x += 1 - - plt.figure(figsize=(8, 6)) - nx.draw(G, pos, with_labels=True, node_size=100, node_color='skyblue', font_size=10, font_weight='bold') - - # for node, (x, y) in pos.items(): - # image_path = f"{image_folder}/{node}.svg" - # if os.path.exists(image_path): - # img = plt.imread(image_path) - # plt.imshow(img, aspect='auto', extent=(x - 0.5, x + 0.5, y - 0.5, y + 0.5), zorder=0) - - plt.gca().invert_yaxis() # Инвертируем ось y для вертикального отображения - plt.show() - -def main(): - sequences = load_sequences('valid_sequences.json') - G = create_graph(sequences) - draw_graph_with_thumbnails(G, '/home/markvoltov/GitProjects/framework/test_models/img') diff --git a/freecad_workbench/freecad/robossembler/assembly_graph_generation.py b/freecad_workbench/freecad/robossembler/assembly_graph_generation.py deleted file mode 100644 index 8265ac4..0000000 --- a/freecad_workbench/freecad/robossembler/assembly_graph_generation.py +++ /dev/null @@ -1,42 +0,0 @@ -import json -import networkx as nx -import matplotlib.pyplot as plt -from PIL import Image -import matplotlib.image as mpimg -from networkx.drawing.nx_agraph import graphviz_layout - -def load_assembly_sequence(filepath): - with open(filepath, 'r') as file: - return json.load(file) - -def create_assembly_graph(sequence): - G = nx.DiGraph() - - for i, part in enumerate(sequence): - G.add_node(part, image=f'{part}.svg') - if i > 0: - G.add_edge(sequence[i-1], part) - - return G - -def draw_graph(G): - pos = graphviz_layout(G, prog='dot') - fig, ax = plt.subplots(figsize=(12, 8)) - - for node in G.nodes(data=True): - x, y = pos[node[0]] - img = mpimg.imread(node[1]['image']) - ax.imshow(img, aspect='auto', extent=(x-0.5, x+0.5, y-0.5, y+0.5), zorder=1) - - ax.text(x, y-0.6, s=node[0], horizontalalignment='center', fontsize=12, zorder=2) - - nx.draw_networkx_edges(G, pos, ax=ax, arrows=True) - plt.axis('off') - plt.show() - -def main(): - sequence = load_assembly_sequence('assembly_sequence.json') - assembly_graph = create_assembly_graph(sequence) - - draw_graph(assembly_graph) - diff --git a/freecad_workbench/freecad/robossembler/autodock_generator.py b/freecad_workbench/freecad/robossembler/autodock_generator.py deleted file mode 100644 index b15c191..0000000 --- a/freecad_workbench/freecad/robossembler/autodock_generator.py +++ /dev/null @@ -1,23 +0,0 @@ -import FreeCAD as App -import FreeCADGui as Gui -import Draft -import json - -sequence_file = '/home/markvoltov/GitProjects/framework/freecad_workbench/freecad/robossembler/sequences.json' - -def load_assembly_sequence(filepath): - with open(filepath, 'r') as file: - sequences = json.load(file) - return sequences - -print(load_assembly_sequence(sequence_file)) - - -sequence = load_assembly_sequence(sequence_file)['sequences'] - -for part in sequence: - _layer = Draft.make_layer() - App.ActiveDocument.recompute() - _layer.Group = App.ActiveDocument.getObjectsByLabel('part') - - diff --git a/freecad_workbench/freecad/robossembler/cad_generation/env.json b/freecad_workbench/freecad/robossembler/cad_generation/env.json deleted file mode 100644 index 7cbd24f..0000000 --- a/freecad_workbench/freecad/robossembler/cad_generation/env.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "cadFilePath": "path/to/file", - "outPath": "out/path" -} diff --git a/freecad_workbench/freecad/robossembler/cad_generation/helper/file_system_repository.py b/freecad_workbench/freecad/robossembler/cad_generation/helper/file_system_repository.py deleted file mode 100644 index 92fd1d1..0000000 --- a/freecad_workbench/freecad/robossembler/cad_generation/helper/file_system_repository.py +++ /dev/null @@ -1,28 +0,0 @@ -import os -import json -import shutil - - -class FileSystemRepository: - def readJSON(path: str): - return json.loads((open(path)).read()) - - def recursiveDeleteFolder(path: str): - shutil.rmtree(path) - pass - - def deletingOldAndCreatingNewFolder(path: str): - if FileSystemRepository.isExistsPath(path): - FileSystemRepository.recursiveDeleteFolder(path) - os.makedirs(path) - pass - - def isExistsPath(path: str): - return os.path.exists(path) - - def writeFile(data, filePath, fileName): - file_to_open = filePath + fileName - - f = open(file_to_open, "w", encoding="utf-8") - f.write(data) - f.close() diff --git a/freecad_workbench/freecad/robossembler/cad_generation/helper/is_solid.py b/freecad_workbench/freecad/robossembler/cad_generation/helper/is_solid.py deleted file mode 100644 index 431c814..0000000 --- a/freecad_workbench/freecad/robossembler/cad_generation/helper/is_solid.py +++ /dev/null @@ -1,18 +0,0 @@ -import FreeCAD - - -def is_object_solid(obj): - """If obj is solid return True""" - if not isinstance(obj, FreeCAD.DocumentObject): - return False - - if not hasattr(obj, 'Shape'): - return False - - if not hasattr(obj.Shape, 'Solids'): - return False - - if len(obj.Shape.Solids) == 0: - return False - - return True diff --git a/freecad_workbench/freecad/robossembler/cad_generation/main.py b/freecad_workbench/freecad/robossembler/cad_generation/main.py deleted file mode 100644 index 73859f1..0000000 --- a/freecad_workbench/freecad/robossembler/cad_generation/main.py +++ /dev/null @@ -1,32 +0,0 @@ -import FreeCAD as App -from helper.file_system_repository import FileSystemRepository -from scenarios.robossembler_freecad_export_scenari import ( - RobossemblerFreeCadExportScenario, -) - - -import FreeCADGui as Gui - - -import FreeCAD as App - -import os - - -def main(): - try: - print(os.path.join(os.path.dirname(__file__)) + "/env.json") - env = FileSystemRepository.readJSON( - os.path.join(os.path.dirname(__file__)) + "/env.json" - ) - App.openDocument(env.get("cadFilePath")) - RobossemblerFreeCadExportScenario.call(env.get("outPath")) - App.closeDocument(App.ActiveDocument.Name) - freecadQTWindow = Gui.getMainWindow() - freecadQTWindow.close() - except ValueError: - freecadQTWindow = Gui.getMainWindow() - freecadQTWindow.close() - - -main() diff --git a/freecad_workbench/freecad/robossembler/cad_generation/model/files_generator.py b/freecad_workbench/freecad/robossembler/cad_generation/model/files_generator.py deleted file mode 100644 index 68b4a0b..0000000 --- a/freecad_workbench/freecad/robossembler/cad_generation/model/files_generator.py +++ /dev/null @@ -1,13 +0,0 @@ -from enum import Enum - - -class FilesGenerator(Enum): - DETAIL = 'detail.json' - ASSEMBLY = 'assembly.json' - - -class FolderGenerator(Enum): - MESHES = 'meshes' - ASSETS = 'assets' - SDF = 'sdf' - ASSEMBlY = 'assembly' diff --git a/freecad_workbench/freecad/robossembler/cad_generation/model/geometry_part.py b/freecad_workbench/freecad/robossembler/cad_generation/model/geometry_part.py deleted file mode 100644 index f63f055..0000000 --- a/freecad_workbench/freecad/robossembler/cad_generation/model/geometry_part.py +++ /dev/null @@ -1,86 +0,0 @@ -from typing import Any, TypeVar, Type, cast - - -T = TypeVar("T") - - -def from_float(x: Any) -> float: - assert isinstance(x, (float, int)) and not isinstance(x, bool) - return float(x) - - -def to_float(x: Any) -> float: - assert isinstance(x, float) - return x - - -def to_class(c: Type[T], x: Any) -> dict: - assert isinstance(x, c) - return cast(Any, x).to_dict() - - -class Axis: - x: float - y: float - z: float - - def __init__(self, x: float, y: float, z: float) -> None: - self.x = x - self.y = y - self.z = z - - @staticmethod - def from_dict(obj: Any) -> 'Axis': - assert isinstance(obj, dict) - x = from_float(obj.get("x")) - y = from_float(obj.get("y")) - z = from_float(obj.get("z")) - return Axis(x, y, z) - - def to_dict(self) -> dict: - result: dict = {} - result["x"] = to_float(self.x) - result["y"] = to_float(self.y) - result["z"] = to_float(self.z) - return result - - -class GeometryPart: - euler: Axis - position: Axis - rotation: Axis - center: Axis - - def __init__(self, euler: Axis, position: Axis, rotation: Axis, center: Axis) -> None: - self.euler = euler - self.position = position - self.rotation = rotation - self.center = center - - @staticmethod - def from_dict(obj: Any) -> 'GeometryPart': - assert isinstance(obj, dict) - euler = Axis.from_dict(obj.get("euler")) - position = Axis.from_dict(obj.get("position")) - rotation = Axis.from_dict(obj.get("rotation")) - center = Axis.from_dict(obj.get("center")) - return GeometryPart(euler, position, rotation, center) - - def to_dict(self) -> dict: - result: dict = {} - result["euler"] = to_class(Axis, self.euler) - result["position"] = to_class(Axis, self.position) - result["rotation"] = to_class(Axis, self.rotation) - result["center"] = to_class(Axis, self.center) - return result - - def toJson(self) -> str: - return str(self.to_dict()).replace('\'', '"') - - -def geometry_part_from_dict(s: Any) -> GeometryPart: - return GeometryPart.from_dict(s) - - -def geometry_part_to_dict(x: GeometryPart) -> Any: - return to_class(GeometryPart, x) diff --git a/freecad_workbench/freecad/robossembler/cad_generation/model/join_mesh_model.py b/freecad_workbench/freecad/robossembler/cad_generation/model/join_mesh_model.py deleted file mode 100644 index 52ca96b..0000000 --- a/freecad_workbench/freecad/robossembler/cad_generation/model/join_mesh_model.py +++ /dev/null @@ -1,33 +0,0 @@ -import FreeCAD -import Mesh -import FreeCAD as App -from model.mesh_part_model import MeshPartModel - - -class JoinMeshModel: - id = None - mesh = None - - def __init__(self, meshesPartModels: list['MeshPartModel']) -> None: - meshes = [] - import Mesh - from random import randrange - for el in meshesPartModels: - meshes.append(el.mesh.Mesh) - - self.id = 'MergedMesh' + str(randrange(1000000)) - document = App.ActiveDocument - merged_mesh = Mesh.Mesh() - for el in meshes: - merged_mesh.addMesh(el) - - new_obj = App.activeDocument().addObject("Mesh::Feature", self.id) - new_obj.Mesh = merged_mesh - new_obj.ViewObject.DisplayMode = "Flat Lines" # Set display mode to flat lines - self.mesh = new_obj - - def remove(self): - try: - App.ActiveDocument.removeObject(self.id) - except Exception as e: - print(e) diff --git a/freecad_workbench/freecad/robossembler/cad_generation/model/mesh_part_model.py b/freecad_workbench/freecad/robossembler/cad_generation/model/mesh_part_model.py deleted file mode 100644 index dc77871..0000000 --- a/freecad_workbench/freecad/robossembler/cad_generation/model/mesh_part_model.py +++ /dev/null @@ -1,32 +0,0 @@ -import FreeCAD as App -import uuid -import Mesh -import Part -# import PartGui -import MeshPart - - -class MeshPartModel: - id = None - mesh = None - - def __init__(self, part) -> None: - try: - from random import randrange - self.id = 'mesh' + str(randrange(1000000)) - document = App.ActiveDocument - mesh = document.addObject("Mesh::Feature", self.id) - shape = Part.getShape(part, "") - mesh.Mesh = MeshPart.meshFromShape( - Shape=shape, LinearDeflection=20, AngularDeflection=0.1, Relative=False) - mesh.Label = self.id - self.mesh = mesh - except Exception as e: - print(e) - pass - - def remove(self): - try: - App.ActiveDocument.removeObject(self.mesh.Label) - except Exception as e: - print(e) diff --git a/freecad_workbench/freecad/robossembler/cad_generation/model/robosembler_assets.py b/freecad_workbench/freecad/robossembler/cad_generation/model/robosembler_assets.py deleted file mode 100644 index c8e38b9..0000000 --- a/freecad_workbench/freecad/robossembler/cad_generation/model/robosembler_assets.py +++ /dev/null @@ -1,141 +0,0 @@ -from dataclasses import dataclass -from typing import Any, List, TypeVar, Callable, Type, cast - - -T = TypeVar("T") - - -def from_str(x: Any) -> str: - assert isinstance(x, str) - return x - - -def from_list(f: Callable[[Any], T], x: Any) -> List[T]: - assert isinstance(x, list) - return [f(y) for y in x] - - -def to_class(c: Type[T], x: Any) -> dict: - assert isinstance(x, c) - return cast(Any, x).to_dict() - - -@dataclass -class Asset: - name: str - ixx: str - ixy: str - ixz: str - iyy: str - izz: str - mass: str - posX: str - posY: str - posZ: str - eulerX: str - eulerY: str - eulerZ: str - iyz: str - meshPath: str - friction: str - centerMassX: str - centerMassY: str - centerMassZ: str - - @staticmethod - def from_dict(obj: Any) -> "Asset": - assert isinstance(obj, dict) - name = from_str(obj.get("name")) - ixx = from_str(obj.get("ixx")) - ixy = from_str(obj.get("ixy")) - ixz = from_str(obj.get("ixz")) - iyy = from_str(obj.get("iyy")) - izz = from_str(obj.get("izz")) - mass = from_str(obj.get("mass")) - posX = from_str(obj.get("posX")) - posY = from_str(obj.get("posY")) - posZ = from_str(obj.get("posZ")) - eulerX = from_str(obj.get("eulerX")) - eulerY = from_str(obj.get("eulerY")) - eulerZ = from_str(obj.get("eulerZ")) - iyz = from_str(obj.get("iyz")) - meshPath = from_str(obj.get("meshPath")) - friction = from_str(obj.get("friction")) - centerMassX = from_str(obj.get("centerMassX")) - centerMassY = from_str(obj.get("centerMassY")) - centerMassZ = from_str(obj.get("centerMassZ")) - return Asset( - name, - ixx, - ixy, - ixz, - iyy, - izz, - mass, - posX, - posY, - posZ, - eulerX, - eulerY, - eulerZ, - iyz, - meshPath, - friction, - centerMassX, - centerMassY, - centerMassZ, - ) - - def to_dict(self) -> dict: - result: dict = {} - result["name"] = from_str(self.name) - result["ixx"] = from_str(self.ixx) - result["ixy"] = from_str(self.ixy) - result["ixz"] = from_str(self.ixz) - result["iyy"] = from_str(self.iyy) - result["izz"] = from_str(self.izz) - result["mass"] = from_str(self.mass) - result["posX"] = from_str(self.posX) - result["posY"] = from_str(self.posY) - result["posZ"] = from_str(self.posZ) - result["eulerX"] = from_str(self.eulerX) - result["eulerY"] = from_str(self.eulerY) - result["eulerZ"] = from_str(self.eulerZ) - result["iyz"] = from_str(self.iyz) - result["meshPath"] = from_str(self.meshPath) - result["friction"] = from_str(self.friction) - result["centerMassX"] = from_str(self.centerMassX) - result["centerMassY"] = from_str(self.centerMassY) - result["centerMassZ"] = from_str(self.centerMassZ) - return result - - -@dataclass -class RobossemblerAssets: - assets: List[Asset] - instances: List[Any] - - @staticmethod - def from_dict(obj: Any) -> "RobossemblerAssets": - assert isinstance(obj, dict) - assets = from_list(Asset.from_dict, obj.get("assets")) - instances = from_list(lambda x: x, obj.get("instances")) - return RobossemblerAssets(assets, instances) - - def to_dict(self) -> dict: - result: dict = {} - result["assets"] = from_list(lambda x: to_class(Asset, x), self.assets) - result["instances"] = from_list(lambda x: x, self.instances) - return result - - def toJson(self) -> str: - print(self.to_dict()) - return str(self.to_dict()).replace("'", '"') - - -def RobossemblerAssetsfromdict(s: Any) -> RobossemblerAssets: - return RobossemblerAssets.from_dict(s) - - -def RobossemblerAssetstodict(x: RobossemblerAssets) -> Any: - return to_class(RobossemblerAssets, x) diff --git a/freecad_workbench/freecad/robossembler/cad_generation/model/sdf_geometry_model.py b/freecad_workbench/freecad/robossembler/cad_generation/model/sdf_geometry_model.py deleted file mode 100644 index 86a6d89..0000000 --- a/freecad_workbench/freecad/robossembler/cad_generation/model/sdf_geometry_model.py +++ /dev/null @@ -1,158 +0,0 @@ -import json - - -def from_str(x): - assert isinstance(x, str) - return x - - -def from_none(x): - assert x is None - return x - - -def from_union(fs, x): - for f in fs: - try: - return f(x) - except: - pass - assert False - - -def to_class(c, x): - assert isinstance(x, c) - return x.to_dict() - - -class SdfGeometryModel: - def __init__( - self, - name, - ixx, - ixy, - ixz, - iyy, - izz, - mass, - posX, - posY, - posZ, - eulerX, - eulerY, - eulerZ, - iyz, - meshPath, - friction, - centerMassX, - centerMassY, - centerMassZ, - ): - self.name = name - self.ixx = ixx - self.ixy = ixy - self.ixz = ixz - self.iyy = iyy - self.izz = izz - self.mass = mass - self.posX = posX - self.posY = posY - self.posZ = posZ - self.eulerX = eulerX - self.eulerY = eulerY - self.eulerZ = eulerZ - self.iyz = iyz - self.meshPath = meshPath - self.friction = friction - self.centerMassX = centerMassX - self.centerMassY = centerMassY - self.centerMassZ = centerMassZ - - @staticmethod - def from_dict(obj): - assert isinstance(obj, dict) - name = from_union([from_str, from_none], obj.get("name")) - ixx = from_union([from_str, from_none], obj.get("ixx")) - ixy = from_union([from_str, from_none], obj.get("ixy")) - ixz = from_union([from_str, from_none], obj.get("ixz")) - iyy = from_union([from_str, from_none], obj.get("iyy")) - iyz = from_union([from_str, from_none], obj.get("iyz")) - izz = from_union([from_str, from_none], obj.get("izz")) - mass = from_union([from_str, from_none], obj.get("mass")) - posX = from_union([from_str, from_none], obj.get("posX")) - posY = from_union([from_str, from_none], obj.get("posY")) - posZ = from_union([from_str, from_none], obj.get("posZ")) - eulerX = from_union([from_str, from_none], obj.get("eulerX")) - eulerY = from_union([from_str, from_none], obj.get("eulerY")) - eulerZ = from_union([from_str, from_none], obj.get("eulerZ")) - meshPath = from_union([from_str, from_none], obj.get("meshPath")) - friction = from_union([from_str, from_none], obj.get("friction")) - centerMassX = from_union([from_str, from_none], obj.get("centerMassX")) - centerMassY = from_union([from_str, from_none], obj.get("centerMassY")) - centerMassZ = from_union([from_str, from_none], obj.get("centerMassZ")) - return SdfGeometryModel( - name, - ixx, - ixy, - ixz, - iyy, - izz, - mass, - posX, - posY, - posZ, - eulerX, - eulerY, - eulerZ, - iyz, - meshPath, - friction, - centerMassX, - centerMassY, - centerMassZ, - ) - - def to_dict(self): - result = {} - if self.name is not None: - result["name"] = from_union([from_str, from_none], self.name) - if self.ixx is not None: - result["ixx"] = from_union([from_str, from_none], self.ixx) - if self.ixy is not None: - result["ixy"] = from_union([from_str, from_none], self.ixy) - if self.ixz is not None: - result["ixz"] = from_union([from_str, from_none], self.ixz) - if self.iyy is not None: - result["iyy"] = from_union([from_str, from_none], self.iyy) - if self.izz is not None: - result["izz"] = from_union([from_str, from_none], self.izz) - if self.mass is not None: - result["mass"] = from_union([from_str, from_none], self.mass) - if self.posX is not None: - result["posX"] = from_union([from_str, from_none], self.posX) - if self.posY is not None: - result["posY"] = from_union([from_str, from_none], self.posY) - if self.posZ is not None: - result["posZ"] = from_union([from_str, from_none], self.posZ) - if self.eulerX is not None: - result["eulerX"] = from_union([from_str, from_none], self.eulerX) - if self.eulerY is not None: - result["eulerY"] = from_union([from_str, from_none], self.eulerY) - if self.eulerZ is not None: - result["eulerZ"] = from_union([from_str, from_none], self.eulerZ) - if self.iyz is not None: - result["iyz"] = from_union([from_str, from_none], self.iyz) - if self.meshPath is not None: - result["meshPath"] = from_union([from_str, from_none], self.meshPath) - if self.friction is not None: - result["friction"] = from_union([from_str, from_none], self.eulerZ) - if self.centerMassX is not None: - result["centerMassX"] = from_union([from_str, from_none], self.centerMassX) - if self.centerMassY is not None: - result["centerMassY"] = from_union([from_str, from_none], self.centerMassY) - if self.centerMassZ is not None: - result["centerMassZ"] = from_union([from_str, from_none], self.centerMassZ) - return result - - def toJSON(self) -> str: - return str(self.to_dict()).replace("'", '"') diff --git a/freecad_workbench/freecad/robossembler/cad_generation/model/simple_copy_part_model.py b/freecad_workbench/freecad/robossembler/cad_generation/model/simple_copy_part_model.py deleted file mode 100644 index 05c54f0..0000000 --- a/freecad_workbench/freecad/robossembler/cad_generation/model/simple_copy_part_model.py +++ /dev/null @@ -1,30 +0,0 @@ -import FreeCAD as App -import Part - - -class SimpleCopyPartModel: - id = None - copyLink = None - label = None - part = None - - def getPart(self): - return self.part - - def __init__(self, part) -> None: - try: - from random import randrange - self.id = str(randrange(1000000)) - childObj = part - __shape = Part.getShape( - childObj, '', needSubElement=False, refine=False) - obj = App.ActiveDocument.addObject('Part::Feature', self.id) - obj.Shape = __shape - self.part = obj - self.label = obj.Label - App.ActiveDocument.recompute() - except Exception as e: - print(e) - - def remove(self): - App.ActiveDocument.removeObject(self.label) diff --git a/freecad_workbench/freecad/robossembler/cad_generation/scenarios/robossembler_freecad_export_scenari.py b/freecad_workbench/freecad/robossembler/cad_generation/scenarios/robossembler_freecad_export_scenari.py deleted file mode 100644 index b08f050..0000000 --- a/freecad_workbench/freecad/robossembler/cad_generation/scenarios/robossembler_freecad_export_scenari.py +++ /dev/null @@ -1,40 +0,0 @@ -from model.robosembler_assets import RobossemblerAssets -from usecases.export_assembly_them_all_usecase import ExportAssemblyThemAllUseCase -import FreeCAD -from usecases.export_usecase import EXPORT_TYPES, ExportUseCase -from usecases.get_sdf_geometry_usecase import GeometryUseCase -from usecases.assembly_parse_usecase import AssemblyParseUseCase -from model.files_generator import FolderGenerator -from helper.file_system_repository import FileSystemRepository -import os -import json - - -class RobossemblerFreeCadExportScenario: - def call(path): - directory = path - - __objs__ = FreeCAD.ActiveDocument.RootObjects - directoryExport = directory + "/" - FileSystemRepository.deletingOldAndCreatingNewFolder( - directoryExport + FolderGenerator.MESHES.value - ) - - RobossemblerFreeCadExportScenario.geometry(directory) - ExportAssemblyThemAllUseCase().call(directoryExport) - return True - - def geometry(outPutsPath: str): - exportUseCase = ExportUseCase.call(outPutsPath, EXPORT_TYPES.OBJ) - # for el in GeometryUseCase().call(exportUseCase): - # FileSystemRepository.writeFile(el.toJSON(), outPutsPath + '/' + FolderGenerator.ASSETS.value + '/', el.name + '.json',) - - assets = [] - for el in GeometryUseCase().call(exportUseCase): - assets.append(el) - robossemblerAssets = RobossemblerAssets(assets=assets, instances=[]).toJson() - FileSystemRepository.writeFile( - robossemblerAssets, - outPutsPath, - "robossembler_assets.json", - ) diff --git a/freecad_workbench/freecad/robossembler/cad_generation/usecases/asm4parser_usecase.py b/freecad_workbench/freecad/robossembler/cad_generation/usecases/asm4parser_usecase.py deleted file mode 100644 index f732d1b..0000000 --- a/freecad_workbench/freecad/robossembler/cad_generation/usecases/asm4parser_usecase.py +++ /dev/null @@ -1,53 +0,0 @@ -import FreeCAD as App - -class Asm4StructureParseUseCase: - _parts = [] - _label = [] - - def getSubPartsLabel(self, group): - groupLabel = [] - for el in group: - if str(el) == '': - groupLabel.append(el.Label) - return groupLabel - - def parseLabel(self, nextGroup, label, level=2, nextGroupParse=0): - if nextGroup.__len__() == nextGroupParse: - return - else: - groupParts = [] - - for el in nextGroup: - if str(el) == '': - groupParts.append(el) - - for el in groupParts: - if str(el) == '': - label.append({ - "level": level, - "attachedTo": el.AttachedTo.split('#'), - "label": el.Label, - "axis": self.getSubPartsLabel(el.Group) - }) - - def initParse(self): - - model = App.ActiveDocument.RootObjects[1] - self._label.append({ - "level": 1, - "attachedTo": "Parent Assembly", - "label": model.Label, - "axis": self.getSubPartsLabel(model.Group) - }) - for parent in model.Group: - if str(parent) == '': - self._label.append({ - "level": 1, - "attachedTo": parent.AttachedTo.split('#'), - "label": parent.Label, - "axis": self.getSubPartsLabel(parent.Group) - }) - print(self._label) - - - \ No newline at end of file diff --git a/freecad_workbench/freecad/robossembler/cad_generation/usecases/assembly_parse_usecase.py b/freecad_workbench/freecad/robossembler/cad_generation/usecases/assembly_parse_usecase.py deleted file mode 100644 index e3b4e0d..0000000 --- a/freecad_workbench/freecad/robossembler/cad_generation/usecases/assembly_parse_usecase.py +++ /dev/null @@ -1,58 +0,0 @@ -import FreeCAD as App -def is_object_solid(obj): - """If obj is solid return True""" - if not isinstance(obj, App.DocumentObject): - return False - if hasattr(obj, 'Group'): - return False - - if not hasattr(obj, 'Shape'): - return False - # if not hasattr(obj.Shape, 'Mass'): - # return False - if not hasattr(obj.Shape, 'Solids'): - return False - - if len(obj.Shape.Solids) == 0: - return False - - return True - - -class AssemblyParseUseCase: - _parts = [] - - _asm = [] - - def getAsm(self): - return self._asm - - def __init__(self) -> None: - if (self._asm.__len__() == 0): - self.initParse() - pass - - def initParse(self): - for el in App.ActiveDocument.Objects: - if (is_object_solid(el)): - self._asm.append(el.Label) - - def toJson(self): - return str(self._asm).replace('\'', "\"") - - def getSubPartsLink(self, group): - groupLink = {} - for el in group: - if (is_object_solid(el)): - if str(el.Shape).find('Solid') != -1: - if groupLink.get(el.Label) == None: - groupLink[el.Label] = [] - for i in el.Group: - if str(i).find('Pad') != -1: - groupLink[el.Label].append(i) - if groupLink.__len__() == 0: - return None - return groupLink - - def getLinkedProperty(self): - return self._asm diff --git a/freecad_workbench/freecad/robossembler/cad_generation/usecases/export_assembly_them_all_usecase.py b/freecad_workbench/freecad/robossembler/cad_generation/usecases/export_assembly_them_all_usecase.py deleted file mode 100644 index 837059a..0000000 --- a/freecad_workbench/freecad/robossembler/cad_generation/usecases/export_assembly_them_all_usecase.py +++ /dev/null @@ -1,118 +0,0 @@ -from typing import List -import FreeCAD as App -import Part -from model.join_mesh_model import JoinMeshModel -from model.mesh_part_model import MeshPartModel -from helper.file_system_repository import FileSystemRepository -from helper.is_solid import is_object_solid -from model.simple_copy_part_model import SimpleCopyPartModel -from model.files_generator import FolderGenerator -from usecases.assembly_parse_usecase import AssemblyParseUseCase -import os -import json - - -class ExportAssemblyThemAllUseCase: - def call(self, path): - assembly = AssemblyParseUseCase().getAsm() - asmStructure = {} - inc = 0 - for el in assembly: - if inc != 0: - asmStructure[inc] = {"child": el, "parents": assembly[0:inc]} - inc += 1 - objectsFreeCad = App.ActiveDocument.Objects - asmSolids = {} - for k, v in asmStructure.items(): - assemblyParentList = v["parents"] - assemblyChild = v["child"] - for el in assemblyParentList: - for solid in objectsFreeCad: - if el == solid.Label: - if asmSolids.get(k) is None: - asmSolids[k] = { - "parents": [], - "child": list( - filter( - lambda x: x.Label == assemblyChild, - objectsFreeCad, - ) - )[0], - } - - asmSolids[k]["parents"].append(solid) - - inc = 0 - for k, v in asmSolids.items(): - geometry = {"0": [], "1": []} - if k != 0: - App.activeDocument().addObject("Part::Compound", "Compound") - - copyLinks = list(map(lambda el: SimpleCopyPartModel(el), v["parents"])) - - if copyLinks != None: - App.activeDocument().Compound.Links = list( - map(lambda el: el.getPart(), copyLinks) - ) - - object = App.activeDocument().getObject("Compound") - boundBox = object.Shape.BoundBox - geometry["0"].append(boundBox.XMax) - geometry["0"].append(boundBox.YMax) - geometry["0"].append(boundBox.ZMax) - - os.makedirs( - path + FolderGenerator.ASSEMBlY.value + "/" + "0000" + str(k) - ) - boundBoxChild = v["child"].Shape.BoundBox - geometry["1"].append(boundBoxChild.XMax) - geometry["1"].append(boundBoxChild.YMax) - geometry["1"].append(boundBoxChild.ZMax) - meshParents = [] - - for el in v["parents"]: - meshParents.append(MeshPartModel(el)) - joinMesh = JoinMeshModel(meshParents) - for el in meshParents: - el.remove() - import importOBJ - - importOBJ.export( - joinMesh.mesh, - path - + FolderGenerator.ASSEMBlY.value - + "/" - + "0000" - + str(k) - + "/" - + str(1) - + ".obj", - ) - joinMesh.remove() - importOBJ.export( - v["child"], - path - + FolderGenerator.ASSEMBlY.value - + "/" - + "0000" - + str(k) - + "/" - + str(0) - + ".obj", - ) - FileSystemRepository.writeFile( - json.dumps(geometry), - path - + FolderGenerator.ASSEMBlY.value - + "/" - + "0000" - + str(k) - + "/", - "translation.json", - ) - - App.ActiveDocument.removeObject("Compound") - for el in copyLinks: - el.remove() - App.activeDocument().recompute() - inc += 1 diff --git a/freecad_workbench/freecad/robossembler/cad_generation/usecases/export_usecase.py b/freecad_workbench/freecad/robossembler/cad_generation/usecases/export_usecase.py deleted file mode 100644 index abdc92b..0000000 --- a/freecad_workbench/freecad/robossembler/cad_generation/usecases/export_usecase.py +++ /dev/null @@ -1,35 +0,0 @@ -# import importDAE -import Mesh -import FreeCAD as App -from model.files_generator import FolderGenerator -from helper.is_solid import is_object_solid -from enum import Enum - - -class EXPORT_TYPES(Enum): - STL = "STL" - DAO = "DAO" - OBJ = "OBJ" - - -class ExportUseCase: - def call(path: str, type: EXPORT_TYPES): - meshes = {} - for el in App.ActiveDocument.Objects: - if is_object_solid(el): - match type.value: - case EXPORT_TYPES.OBJ.value: - import importOBJ - - importOBJ.export( - [el], - path - + FolderGenerator.MESHES.value - + "/" - + el.Label - + ".obj", - ) - meshes[el.Label] = ( - "/" + FolderGenerator.MESHES.value + "/" + el.Label + ".obj" - ) - return meshes diff --git a/freecad_workbench/freecad/robossembler/cad_generation/usecases/geometry_usecase.py b/freecad_workbench/freecad/robossembler/cad_generation/usecases/geometry_usecase.py deleted file mode 100644 index 13ebfd2..0000000 --- a/freecad_workbench/freecad/robossembler/cad_generation/usecases/geometry_usecase.py +++ /dev/null @@ -1,58 +0,0 @@ - -import FreeCAD as App -from helper.is_solid import is_object_solid - - -class GeometryUseCase: - def call() -> dict: - labels = [] - Error = False - for el in App.ActiveDocument.Objects: - try: - - if is_object_solid(el): - labels.append(el.Label) - - geometry = { - "euler": { - "x": None, - "y": None, - "z": None - }, - "position": { - "x": None, - "y": None, - "z": None - }, - "rotation": { - "x": None, - "y": None, - "z": None - }, - "center": { - "x": None, - "y": None, - "z": None - }, - - } - - boundBox = el.Shape.BoundBox - geometry["center"]["x"] = boundBox.Center.x - geometry["center"]["y"] = boundBox.Center.y - geometry["center"]["z"] = boundBox.Center.z - geometry["position"]['x'] = boundBox.XMax - geometry["position"]['y'] = boundBox.YMax - geometry["position"]['z'] = boundBox.ZMax - rotation = el.Placement.Rotation - geometry["rotation"]['x'] = rotation.Axis.z - geometry["rotation"]['y'] = rotation.Axis.y - geometry["rotation"]['z'] = rotation.Axis.z - euler = el.Placement.Rotation.toEuler() - geometry["euler"]['x'] = euler[0] - geometry["euler"]['y'] = euler[1] - geometry["euler"]['z'] = euler[2] - except Exception as e: - print(e) - # App.Console.PrintMessage("Clicked on position: ("+str(pos[0])+", "+str(pos[1])+")\n") - return {"geometry": geometry, "labels": labels, "label": el.Label} diff --git a/freecad_workbench/freecad/robossembler/cad_generation/usecases/get_sdf_geometry_usecase.py b/freecad_workbench/freecad/robossembler/cad_generation/usecases/get_sdf_geometry_usecase.py deleted file mode 100644 index f3b9770..0000000 --- a/freecad_workbench/freecad/robossembler/cad_generation/usecases/get_sdf_geometry_usecase.py +++ /dev/null @@ -1,74 +0,0 @@ -import FreeCAD as App -from model.robosembler_assets import Asset -from model.sdf_geometry_model import SdfGeometryModel - -from helper.is_solid import is_object_solid - - -class GeometryUseCase: - ShapePropertyCheck = [ - "Mass", - "MatrixOfInertia", - "Placement", - ] - PartPropertyCheck = ["Shape"] - - def call(self, stlPaths: dict) -> list[Asset]: - materialSolid = {} - for el in App.ActiveDocument.Objects: - if str(el) == "": - friction = el.Material.get("SlidingFriction") - for i in el.References: - materialSolid[i[0].Label] = friction - geometry = [] - try: - for el in App.ActiveDocument.Objects: - if is_object_solid(el): - mass = el.Shape.Mass - inertia = el.Shape.MatrixOfInertia - pos = el.Shape.Placement - inertia = el.Shape.MatrixOfInertia - name = el.Label - delimiter = 1000000 - ixx = str(inertia.A11 / delimiter) - ixy = str(inertia.A12 / delimiter) - ixz = str(inertia.A13 / delimiter) - iyy = str(inertia.A22 / delimiter) - iyz = str(inertia.A23 / delimiter) - izz = str(inertia.A33 / delimiter) - massSDF = str(mass / delimiter) - posX = str(pos.Base[0] / delimiter) - posY = str(pos.Base[1] / delimiter) - posZ = str(pos.Base[2] / delimiter) - eulerX = str(pos.Rotation.toEuler()[0]) - eulerY = str(pos.Rotation.toEuler()[1]) - eulerZ = str(pos.Rotation.toEuler()[2]) - centerMassX = str(el.Shape.CenterOfMass[0]) - centerMassY = str(el.Shape.CenterOfMass[1]) - centerMassZ = str(el.Shape.CenterOfMass[2]) - geometry.append( - Asset( - meshPath=stlPaths.get(el.Label), - name=name, - ixx=ixx, - ixz=ixz, - ixy=ixy, - iyy=iyy, - iyz=iyz, - izz=izz, - mass=massSDF, - posX=posX, - posY=posY, - posZ=posZ, - eulerX=eulerX, - eulerY=eulerY, - eulerZ=eulerZ, - friction=materialSolid.get(el.Label) or "", - centerMassX=centerMassX, - centerMassY=centerMassY, - centerMassZ=centerMassZ, - ) - ) - except Exception as e: - print(e) - return geometry diff --git a/freecad_workbench/freecad/robossembler/cad_stability_check/.gitignore b/freecad_workbench/freecad/robossembler/cad_stability_check/.gitignore deleted file mode 100644 index e482277..0000000 --- a/freecad_workbench/freecad/robossembler/cad_stability_check/.gitignore +++ /dev/null @@ -1,96 +0,0 @@ -# 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 - -# Unit test / coverage reports -htmlcov/ -.tox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*,cover -.hypothesis/ - -# Translations -*.mo -*.pot - -# Django stuff: -*.log -local_settings.py - -# Flask stuff: -instance/ -.webassets-cache - -# Scrapy stuff: -.scrapy - -# Sphinx documentation -docs/_build/ - -# PyBuilder -target/ - -# Jupyter Notebook -.ipynb_checkpoints - -# pyenv -.python-version - -# celery beat schedule file -celerybeat-schedule - -# SageMath parsed files -*.sage.py - -# dotenv -.env - -# virtualenv -.venv -venv/ -ENV/ - -# Spyder project settings -.spyderproject - -# Rope project settings -.ropeproject -env.json -out/ \ No newline at end of file diff --git a/freecad_workbench/freecad/robossembler/cad_stability_check/main.py b/freecad_workbench/freecad/robossembler/cad_stability_check/main.py deleted file mode 100644 index f5d0f1f..0000000 --- a/freecad_workbench/freecad/robossembler/cad_stability_check/main.py +++ /dev/null @@ -1,461 +0,0 @@ -# Алгоритм генерации графа с помощью оценки стабильности подсборок в физическом движке PyBullet -from typing import Any, TypeVar, Type, cast -import FreeCAD as App -import json -import importOBJ -import Draft -import os -import Part -import numpy as np -from typing import TypeAlias -import FreeCADGui as Gui - -ISequencesUnion: TypeAlias = dict[str : dict[str : list[str]]] - - -def importObjAtPath(path: str, inc: int): - try: - importOBJ.insert("" + path, App.ActiveDocument.Label) - - mesh = App.ActiveDocument.Objects[inc] - shape = Part.Shape() - shape.makeShapeFromMesh(mesh.Mesh.Topology, 0.05) - solid = Part.makeSolid(shape) - - Part.show(solid) - - App.ActiveDocument.Objects[inc + 1].Label = App.ActiveDocument.Objects[inc].Name - App.ActiveDocument.removeObject(App.ActiveDocument.Objects[inc].Name) - return App.ActiveDocument.Objects[inc] - except: - print("path") - print(path) - print("inc") - print(inc) - - -T = TypeVar("T") - - -def from_float(x: Any) -> float: - assert isinstance(x, (float, int)) and not isinstance(x, bool) - return float(x) - - -def to_float(x: Any) -> float: - assert isinstance(x, float) - return x - - -def from_str(x: Any) -> str: - assert isinstance(x, str) - return x - - -def to_class(c: Type[T], x: Any) -> dict: - assert isinstance(x, c) - return cast(Any, x).to_dict() - - -def euler_to_quaternion(yaw, pitch, roll): - qx = np.sin(roll / 2) * np.cos(pitch / 2) * np.cos(yaw / 2) - np.cos( - roll / 2 - ) * np.sin(pitch / 2) * np.sin(yaw / 2) - qy = np.cos(roll / 2) * np.sin(pitch / 2) * np.cos(yaw / 2) + np.sin( - roll / 2 - ) * np.cos(pitch / 2) * np.sin(yaw / 2) - qz = np.cos(roll / 2) * np.cos(pitch / 2) * np.sin(yaw / 2) - np.sin( - roll / 2 - ) * np.sin(pitch / 2) * np.cos(yaw / 2) - qw = np.cos(roll / 2) * np.cos(pitch / 2) * np.cos(yaw / 2) + np.sin( - roll / 2 - ) * np.sin(pitch / 2) * np.sin(yaw / 2) - - return [qx, qy, qz, qw] - - -class Coords: - x: float - y: float - z: float - - def __init__(self, x: float, y: float, z: float) -> None: - self.x = x - self.y = y - self.z = z - - @staticmethod - def from_dict(obj: Any) -> "Coords": - assert isinstance(obj, dict) - x = from_float(obj.get("x")) - y = from_float(obj.get("y")) - z = from_float(obj.get("z")) - return Coords(x, y, z) - - def to_dict(self) -> dict: - result: dict = {} - result["x"] = to_float(self.x) - result["y"] = to_float(self.y) - result["z"] = to_float(self.z) - return result - - def vector(self): - return App.Vector(self.x, self.y, self.z) - - -class MotionResultModel: - id: str - quaternion: Coords - position: Coords - - def __init__(self, id: str, quaternion: Coords, position: Coords) -> None: - self.id = id - self.quaternion = quaternion - self.position = position - - @staticmethod - def from_dict(obj: Any) -> "MotionResultModel": - id = from_str(obj.get("id")) - quaternion = Coords.from_dict(obj.get("quaternion")) - position = Coords.from_dict(obj.get("position")) - return MotionResultModel(id, quaternion, position) - - def to_dict(self) -> dict: - result: dict = {} - result["id"] = from_str(self.id) - result["quaternion"] = to_class(Coords, self.quaternion) - result["position"] = to_class(Coords, self.position) - return result - - -class SequencesEvaluation: - sequences: ISequencesUnion - assemblyDir: str - result: dict = {} - - def __init__(self, sequences, assemblyDir) -> None: - self.sequences = sequences - self.assemblyDir = assemblyDir - pass - - def assemblyComputed(self): - isOk = True - for sequenceNumber, v in self.sequences.items(): - for assemblyNumber, assemblySequenced in v.items(): - if isOk: - # sequenceNumber += 1 - isOk = False - self.comptedAssembly( - assemblySequenced, sequenceNumber, assemblyNumber - ) - - pass - - def comptedAssembly( - self, assembly: list[str], sequenceNumber: int, assemblyNumber: int - ): - assemblyParts = [] - for counter in range(len(assembly)): - importObjAtPath( - self.assemblyDir + "generation/meshes/" + assembly[counter] + ".obj", - counter, - ) - assemblyParts.append( - {"part": App.ActiveDocument.Objects[counter], "name": assembly[counter]} - ) - - motionResult = json.loads( - ( - open( - self.assemblyDir - + "stability" - + "/" - + str(sequenceNumber + 1) - + "/" - + str(assemblyNumber) - + "/" - + "motion_result.json" - ) - ).read() - ) - - simulatorMotionResults: list["MotionResultModel"] = [] - for _k, v in motionResult.items(): - print(v) - simulatorMotionResults.append(MotionResultModel.from_dict(v)) - - for el in simulatorMotionResults: - for e in assemblyParts: - # сопоставляем детали - if el.id == e.get("name"): - # вычисляем центр детали для перемещения - center = e.get("part").Shape.CenterOfMass - # получаем центр деталей из симуляции - new_center = App.Vector(el.position.vector()) - - # вычисляем вектор смещения - offset = new_center - center - # перемещаем деталь на вектор смещения - e.get("part").Placement.Base += offset - - # # импортируем меш связанный с зоной обьекта - zonePart = importObjAtPath( - self.assemblyDir - + "stability/zones/meshes/zone_sub_assembly" - + str(assembly.__len__() - 1) - + ".obj", - len(App.ActiveDocument.Objects), - ) - # # получаем координаты зоны относительно детали за которой закреплена зона - - coords = json.loads( - ( - open( - self.assemblyDir - + "stability/zones/sub_assembly_coords_" - + str(assemblyNumber - 1) - + ".json" - ) - ).read() - ) - assemblyCounter = len(assemblyParts) - detailWhichZoneBindings = assemblyParts[assemblyCounter - 2].get("part") - - detailStabilityComputed = assemblyParts[assemblyCounter - 1].get("part") - relativeCoordinates = coords.get("relativeCoordinates") - - relativeEuler = coords.get("relativeEuler") - - specificEuler = { - "yaw": detailWhichZoneBindings.Placement.Rotation.toEuler()[0] - - relativeEuler.get("yaw"), - "pitch": detailWhichZoneBindings.Placement.Rotation.toEuler()[1] - - relativeEuler.get("pitch"), - "roll": detailWhichZoneBindings.Placement.Rotation.toEuler()[2] - - relativeEuler.get("roll"), - } - quaternion = euler_to_quaternion( - specificEuler.get("yaw"), - specificEuler.get("pitch"), - specificEuler.get("roll"), - ) - rotation = App.Rotation( - quaternion[0], quaternion[1], quaternion[2], quaternion[3] - ) - - detailStabilityComputed.Placement.Rotation = rotation - centerVector = detailWhichZoneBindings.Shape.CenterOfMass - vector = App.Vector( - relativeCoordinates.get("x"), - relativeCoordinates.get("y"), - relativeCoordinates.get("z"), - ) - print(vector) - # TODO - current_center = zonePart.Shape.CenterOfMass - move_vector = App.Vector(centerVector + vector) - current_center - zonePart.Placement.move(move_vector) - - computedStabilityResult = computedStability(zonePart, detailStabilityComputed) - - if sequenceNumber not in self.result.keys(): - self.result[sequenceNumber] = [] - - self.result[sequenceNumber].append( - {str(assemblyNumber): assembly, "result": computedStabilityResult} - ) - # for part in App.ActiveDocument.Objects: - # App.ActiveDocument.removeObject(part.Name) - - -def get_part_center(part): - shape = None - if not hasattr(part, "Shape"): - shape = part.Mesh - if hasattr(part, "Shape"): - shape = part.Shape - - center = shape.BoundBox.Center - return App.Vector(center[0], center[1], center[2]) - - -def move_second_part_to_match_center(first_part, second_part): - first_center = get_part_center(first_part) - second_center = get_part_center(second_part) - offset = first_center - second_center - second_part.Placement.move(offset) - - -def create(part): - clone = Draft.make_clone([part], forcedraft=True) - - clone.Scale = App.Vector(1.30, 1.30, 1.30) - clone_corr = ( - App.Vector(0.4476673941774023, -2.109332894191716, -0.5918687740295264) - - clone.Placement.Base - ).scale(*App.Vector(-0.25, -0.25, -0.25)) - clone.Placement.move(clone_corr) - App.ActiveDocument.recompute() - - return clone - - -def getFullPathObj(assemblyFolder: str, name: str): - return assemblyFolder + "sdf/meshes/" + name + ".obj" - - -def computedStability(refElement, childElement): - rootElement = childElement.Shape.BoundBox - # Создание обьекта на котором делается операция пересечения - App.activeDocument().addObject("Part::MultiCommon", "Common") - App.activeDocument().Common.Shapes = [ - refElement, - childElement, - ] - App.ActiveDocument.getObject("Common").ViewObject.ShapeColor = getattr( - App.ActiveDocument.getObject(refElement.Name).getLinkedObject(True).ViewObject, - "ShapeColor", - App.ActiveDocument.getObject("Common").ViewObject.ShapeColor, - ) - App.ActiveDocument.getObject("Common").ViewObject.DisplayMode = getattr( - App.ActiveDocument.getObject(childElement.Name) - .getLinkedObject(True) - .ViewObject, - "DisplayMode", - App.ActiveDocument.getObject("Common").ViewObject.DisplayMode, - ) - App.ActiveDocument.recompute() - obj = App.ActiveDocument.getObjectsByLabel("Common")[0] - - shp = obj.Shape - bbox = shp.BoundBox - # Если после операции пересечения зона обьекта совпадает с зоной тестируемого обьекта то тест прошел успешно - if ( - bbox.XLength == rootElement.XLength - and bbox.YLength == rootElement.YLength - and rootElement.ZLength == bbox.ZLength - ): - return True - return False - - -def autoStabilityZoneComputed(stepFilesPaths: list[str], directoryStableZonesPath: str): - cadObjects = [] - for count in range(len(stepFilesPaths)): - importObjAtPath(stepFilesPaths[count], count) - cadObjects.append(App.ActiveDocument.Objects[count]) - - assemblesBindings = [] - - for increment in range(len(cadObjects)): - if increment != 0: - detailForEvaluationZ = cadObjects[increment] - zoneBindingDetailZ = cadObjects[increment - 1] - assemblesBindings.append( - { - "zoneBindingDetail": detailForEvaluationZ, - "detailForEvaluation": zoneBindingDetailZ, - "relativeCoordinates": None, - "zonePart": None, - } - ) - for increment in range(len(assemblesBindings)): - el = assemblesBindings[increment] - - zoneBindingDetail = el.get("zoneBindingDetail") - zoneBindingDetailCenterVector = zoneBindingDetail.Shape.CenterOfMass - zoneDetail = create(el.get("detailForEvaluation")) - move_second_part_to_match_center(el.get("zoneBindingDetail"), zoneDetail) - zoneDetail.Label = "zone_sub_assembly" + str(increment + 1) - - zoneDetail.ViewObject.ShapeColor = (0.40, 0.74, 0.71) - zoneDetail.ViewObject.Transparency = 50 - zoneDetailCenterVector = el.get("detailForEvaluation").Shape.CenterOfMass - - el["relativeCoordinates"] = { - "x": zoneBindingDetailCenterVector.x - zoneDetailCenterVector.x, - "y": zoneBindingDetailCenterVector.y - zoneDetailCenterVector.y, - "z": zoneBindingDetailCenterVector.z - zoneDetailCenterVector.z, - } - - el["relativeEuler"] = { - "yaw": zoneBindingDetail.Placement.Rotation.toEuler()[0] - - el.get("detailForEvaluation").Placement.Rotation.toEuler()[0], - "pitch": zoneBindingDetail.Placement.Rotation.toEuler()[1] - - el.get("detailForEvaluation").Placement.Rotation.toEuler()[1], - "roll": zoneBindingDetail.Placement.Rotation.toEuler()[2] - - el.get("detailForEvaluation").Placement.Rotation.toEuler()[2], - } - el["zonePart"] = zoneDetail - - meshesPath = directoryStableZonesPath + "meshes/" - if not os.path.exists(directoryStableZonesPath): - os.makedirs(directoryStableZonesPath) - if not os.path.exists(meshesPath): - os.makedirs(meshesPath) - zonesSaved = {} - for counter in range(len(assemblesBindings)): - zoneComputed = assemblesBindings[counter] - mesh = zoneComputed.get("zonePart") - zonesSavePath = meshesPath + mesh.Label + ".obj" - importOBJ.export([mesh], zonesSavePath) - zonesSaved[mesh.Label] = "meshes/" + mesh.Label + ".obj" - for counter in range(len(assemblesBindings)): - el = assemblesBindings[counter] - savePath = zonesSaved[el.get("zonePart").Label] - el["zonePart"] = savePath - el["detailForEvaluation"] = el["detailForEvaluation"].Label - el["zoneBindingDetail"] = el["zoneBindingDetail"].Label - - json_result = json.dumps(el) - - file_to_open = ( - directoryStableZonesPath + "sub_assembly_coords_" + str(counter) + ".json" - ) - - f = open( - file_to_open, - "w", - ) - - f.write(json_result) - f.close() - - -def main(): - App.newDocument() - env = json.loads((open("./env.json")).read()) - - assemblyDir = env.get("aspPath") - sequencesJSON = json.loads((open(assemblyDir + "sequences.json")).read()) - directoryStableZones = assemblyDir + "stability/zones/" - - sequences = sequencesJSON.get("sequences") - stepStructure = json.loads((open(assemblyDir + "step-structure.json")).read()) - - stepFilesPaths = [] - for step in stepStructure: - stepFilesPaths.append(assemblyDir + "generation/meshes/" + step + ".obj") - if not os.path.exists(directoryStableZones): - print("Zones not found automatic calculation started") - autoStabilityZoneComputed(stepFilesPaths, directoryStableZones) - - sequencesJoin = {} - - for arrayCounter in range(len(sequences)): - for indexCounter in range(len(sequences[arrayCounter])): - if indexCounter != 0: - if sequencesJoin.get(arrayCounter) == None: - sequencesJoin[arrayCounter] = { - indexCounter: sequences[arrayCounter][0 : indexCounter + 1] - } - else: - sequencesJoin[arrayCounter][indexCounter] = sequences[arrayCounter][ - 0 : indexCounter + 1 - ] - - seqEvaluation = SequencesEvaluation(sequencesJoin, assemblyDir) - seqEvaluation.assemblyComputed() - - -main() diff --git a/freecad_workbench/freecad/robossembler/cad_stability_input/.gitignore b/freecad_workbench/freecad/robossembler/cad_stability_input/.gitignore deleted file mode 100644 index 2b2f40c..0000000 --- a/freecad_workbench/freecad/robossembler/cad_stability_input/.gitignore +++ /dev/null @@ -1,95 +0,0 @@ -# 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 - -# Unit test / coverage reports -htmlcov/ -.tox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*,cover -.hypothesis/ - -# Translations -*.mo -*.pot - -# Django stuff: -*.log -local_settings.py - -# Flask stuff: -instance/ -.webassets-cache - -# Scrapy stuff: -.scrapy - -# Sphinx documentation -docs/_build/ - -# PyBuilder -target/ - -# Jupyter Notebook -.ipynb_checkpoints - -# pyenv -.python-version - -# celery beat schedule file -celerybeat-schedule - -# SageMath parsed files -*.sage.py - -# dotenv -.env - -# virtualenv -.venv -venv/ -ENV/ - -# Spyder project settings -.spyderproject - -# Rope project settings -.ropeproject -env.json \ No newline at end of file diff --git a/freecad_workbench/freecad/robossembler/cad_stability_input/LICENSE b/freecad_workbench/freecad/robossembler/cad_stability_input/LICENSE deleted file mode 100644 index 5f2dd7f..0000000 --- a/freecad_workbench/freecad/robossembler/cad_stability_input/LICENSE +++ /dev/null @@ -1,505 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -(This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.) - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -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 this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -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 -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser 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 Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "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 -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY 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 -LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Libraries - - If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms of the -ordinary General Public License). - - To apply these terms, attach the following notices to the library. It is -safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least the -"copyright" line and a pointer to where the full notice is found. - - {description} - Copyright (C) {year} {fullname} - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 - USA - -Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the library, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James Random - Hacker. - - {signature of Ty Coon}, 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! - diff --git a/freecad_workbench/freecad/robossembler/cad_stability_input/README.md b/freecad_workbench/freecad/robossembler/cad_stability_input/README.md deleted file mode 100644 index e69de29..0000000 diff --git a/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/.gitignore b/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/.gitignore deleted file mode 100644 index 2b2f40c..0000000 --- a/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/.gitignore +++ /dev/null @@ -1,95 +0,0 @@ -# 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 - -# Unit test / coverage reports -htmlcov/ -.tox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*,cover -.hypothesis/ - -# Translations -*.mo -*.pot - -# Django stuff: -*.log -local_settings.py - -# Flask stuff: -instance/ -.webassets-cache - -# Scrapy stuff: -.scrapy - -# Sphinx documentation -docs/_build/ - -# PyBuilder -target/ - -# Jupyter Notebook -.ipynb_checkpoints - -# pyenv -.python-version - -# celery beat schedule file -celerybeat-schedule - -# SageMath parsed files -*.sage.py - -# dotenv -.env - -# virtualenv -.venv -venv/ -ENV/ - -# Spyder project settings -.spyderproject - -# Rope project settings -.ropeproject -env.json \ No newline at end of file diff --git a/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/LICENSE b/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/LICENSE deleted file mode 100644 index 5f2dd7f..0000000 --- a/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/LICENSE +++ /dev/null @@ -1,505 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -(This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.) - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -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 this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -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 -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser 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 Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "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 -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY 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 -LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Libraries - - If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms of the -ordinary General Public License). - - To apply these terms, attach the following notices to the library. It is -safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least the -"copyright" line and a pointer to where the full notice is found. - - {description} - Copyright (C) {year} {fullname} - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 - USA - -Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the library, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James Random - Hacker. - - {signature of Ty Coon}, 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! - diff --git a/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/README.md b/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/README.md deleted file mode 100644 index e69de29..0000000 diff --git a/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/gui/__init__.py b/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/gui/__init__.py deleted file mode 100644 index f80dcdc..0000000 --- a/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/gui/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -import os -from .version import __version__ - -ICONPATH = os.path.join(os.path.dirname(__file__), "resources") diff --git a/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/gui/init_gui.py b/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/gui/init_gui.py deleted file mode 100644 index 65c0bdb..0000000 --- a/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/gui/init_gui.py +++ /dev/null @@ -1,89 +0,0 @@ -import os -import FreeCADGui as Gui -import FreeCAD as App -from PySide.QtCore import QT_TRANSLATE_NOOP -import shutil -ICONPATH = os.path.join(os.path.dirname(__file__), "resources") -zone = "StabilityZone" -import requests -import importOBJ - - -class AddStabilityZone: - def __init__(self): - pass - - def GetResources(self): - return {'Pixmap': os.path.join(ICONPATH, "stability_zone.svg"), - 'Accel': "Ctrl+A", - 'MenuText': QT_TRANSLATE_NOOP("My_Command", "My Command"), - 'ToolTip': QT_TRANSLATE_NOOP("My_Command", "Runs my command in the active document")} - - def Activated(self): - App.ActiveDocument.addObject("Part::Box", "Box") - App.ActiveDocument.ActiveObject.Label = zone - selected_object = App.ActiveDocument.getObjectsByLabel(zone)[0] - selected_object.ViewObject.Transparency = 50 - selected_object.ViewObject.ShapeColor = (0.15, 0.80, 0.50) - pass - - def IsActive(self): - return True - - -class SyncServer: - - httpURL = None - def __init__(self, httpURL): - self.httpURL = httpURL - - - def GetResources(self): - return {'Pixmap': os.path.join(ICONPATH, "server_sync.svg"), - 'Accel': "Ctrl+A", - 'MenuText': QT_TRANSLATE_NOOP("My_Command", "My Command"), - 'ToolTip': QT_TRANSLATE_NOOP("My_Command", "Runs my command in the active document")} - - def Activated(self): - StabilityZone = App.ActiveDocument.getObjectsByLabel(zone) - dir_path = os.path.dirname(os.path.realpath(__file__)) - dir_out = dir_path + '/out/' - if not os.path.exists(dir_out): - os.makedirs(dir_out) - importOBJ.export(StabilityZone, u"" + dir_out + 'StabilityZone.obj') - shutil.make_archive(dir_out + '/' + 'geometry', 'zip',) - zipArch = dir_out + 'geometry.zip' - requests.post(url=self.httpURL, files={'zip': open(zipArch, "rb")}) - shutil.rmtree(dir_out) - pass - - def IsActive(self): - return True - - -class StabilityWorkbench(Gui.Workbench): - - MenuText = "stability workbench" - ToolTip = "a simple template workbench" - Icon = os.path.join(ICONPATH, "template_resource.svg") - toolbox = ['AddStabilityZone', 'SyncServer'] - httpURL = None - def __init__(self,httpURL): - self.httpURL = httpURL - - - def GetClassName(self): - return "Gui::PythonWorkbench" - - def Initialize(self): - Gui.addCommand('AddStabilityZone', AddStabilityZone()) - Gui.addCommand('SyncServer', SyncServer( - self.httpURL)) - self.appendToolbar("Tools", self.toolbox) - self.appendMenu("Tools", self.toolbox) - - def Activated(self): - pass - - def Deactivated(self): - pass diff --git a/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/gui/resources/server_sync.svg b/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/gui/resources/server_sync.svg deleted file mode 100644 index da595a2..0000000 --- a/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/gui/resources/server_sync.svg +++ /dev/null @@ -1,134 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - diff --git a/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/gui/resources/stability_zone.svg b/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/gui/resources/stability_zone.svg deleted file mode 100644 index 3f7686a..0000000 --- a/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/gui/resources/stability_zone.svg +++ /dev/null @@ -1,142 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - diff --git a/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/gui/resources/template_resource.svg b/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/gui/resources/template_resource.svg deleted file mode 100644 index 509be26..0000000 --- a/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/gui/resources/template_resource.svg +++ /dev/null @@ -1,166 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - T - diff --git a/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/gui/version.py b/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/gui/version.py deleted file mode 100644 index 3486632..0000000 --- a/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/gui/version.py +++ /dev/null @@ -1 +0,0 @@ -__version__ = "0.8.1" \ No newline at end of file diff --git a/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/main.py b/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/main.py deleted file mode 100644 index e0bb99d..0000000 --- a/freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/main.py +++ /dev/null @@ -1,47 +0,0 @@ -import os -import FreeCADGui as Gui -import FreeCAD as App -from gui.init_gui import StabilityWorkbench -import json - - -def importObjAtPath(path: str): - import importOBJ - importOBJ.insert(u"" + path, App.ActiveDocument.Label) - - pass - - -def getFullPathObj(assemblyFolder: str, name: str): - return assemblyFolder + 'sdf/meshes/' + name + '.obj' - - -def main(): - App.newDocument() - env = json.loads((open('./env.json')).read()) - assemblyFolder = env.get('assemblyFolder') - assemblyStructure = json.loads( - (open(assemblyFolder + 'step-structure.json')).read()) - assemblyNumber = int(env.get('buildNumber')) - 1 - activeDetail = assemblyStructure[assemblyNumber] - - subassemblyNotParticipatingInMarkup = assemblyStructure[0:assemblyNumber - 1] - detailOfTheMarkingZoneOfWhich = assemblyStructure[assemblyNumber - 1] - importObjAtPath(getFullPathObj(assemblyFolder, activeDetail)) - importObjAtPath(getFullPathObj( - assemblyFolder, detailOfTheMarkingZoneOfWhich)) - meshMark = App.ActiveDocument.Objects[0] - meshDetailOfTheMarkZone = App.ActiveDocument.Objects[1] - meshMark.ViewObject.ShapeColor = (0.31, 0.77, 0.87) - meshDetailOfTheMarkZone.ViewObject.ShapeColor = (0.68, 0.66, 0.95) - for el in list(map(lambda el: getFullPathObj(assemblyFolder, el), subassemblyNotParticipatingInMarkup)): - importObjAtPath(el) - for el in App.ActiveDocument.Objects[2:App.ActiveDocument.Objects.__len__()]: - el.ViewObject.ShapeColor = (0.32, 0.05, 0.38) - Gui.SendMsgToActiveView("ViewSelection") - - Gui.addWorkbench(StabilityWorkbench(env.get('resultURL'))) - Gui.activateWorkbench("StabilityWorkbench") - - -main() diff --git a/freecad_workbench/freecad/robossembler/cad_stability_input/gui/__init__.py b/freecad_workbench/freecad/robossembler/cad_stability_input/gui/__init__.py deleted file mode 100644 index f80dcdc..0000000 --- a/freecad_workbench/freecad/robossembler/cad_stability_input/gui/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -import os -from .version import __version__ - -ICONPATH = os.path.join(os.path.dirname(__file__), "resources") diff --git a/freecad_workbench/freecad/robossembler/cad_stability_input/gui/init_gui.py b/freecad_workbench/freecad/robossembler/cad_stability_input/gui/init_gui.py deleted file mode 100644 index 65c0bdb..0000000 --- a/freecad_workbench/freecad/robossembler/cad_stability_input/gui/init_gui.py +++ /dev/null @@ -1,89 +0,0 @@ -import os -import FreeCADGui as Gui -import FreeCAD as App -from PySide.QtCore import QT_TRANSLATE_NOOP -import shutil -ICONPATH = os.path.join(os.path.dirname(__file__), "resources") -zone = "StabilityZone" -import requests -import importOBJ - - -class AddStabilityZone: - def __init__(self): - pass - - def GetResources(self): - return {'Pixmap': os.path.join(ICONPATH, "stability_zone.svg"), - 'Accel': "Ctrl+A", - 'MenuText': QT_TRANSLATE_NOOP("My_Command", "My Command"), - 'ToolTip': QT_TRANSLATE_NOOP("My_Command", "Runs my command in the active document")} - - def Activated(self): - App.ActiveDocument.addObject("Part::Box", "Box") - App.ActiveDocument.ActiveObject.Label = zone - selected_object = App.ActiveDocument.getObjectsByLabel(zone)[0] - selected_object.ViewObject.Transparency = 50 - selected_object.ViewObject.ShapeColor = (0.15, 0.80, 0.50) - pass - - def IsActive(self): - return True - - -class SyncServer: - - httpURL = None - def __init__(self, httpURL): - self.httpURL = httpURL - - - def GetResources(self): - return {'Pixmap': os.path.join(ICONPATH, "server_sync.svg"), - 'Accel': "Ctrl+A", - 'MenuText': QT_TRANSLATE_NOOP("My_Command", "My Command"), - 'ToolTip': QT_TRANSLATE_NOOP("My_Command", "Runs my command in the active document")} - - def Activated(self): - StabilityZone = App.ActiveDocument.getObjectsByLabel(zone) - dir_path = os.path.dirname(os.path.realpath(__file__)) - dir_out = dir_path + '/out/' - if not os.path.exists(dir_out): - os.makedirs(dir_out) - importOBJ.export(StabilityZone, u"" + dir_out + 'StabilityZone.obj') - shutil.make_archive(dir_out + '/' + 'geometry', 'zip',) - zipArch = dir_out + 'geometry.zip' - requests.post(url=self.httpURL, files={'zip': open(zipArch, "rb")}) - shutil.rmtree(dir_out) - pass - - def IsActive(self): - return True - - -class StabilityWorkbench(Gui.Workbench): - - MenuText = "stability workbench" - ToolTip = "a simple template workbench" - Icon = os.path.join(ICONPATH, "template_resource.svg") - toolbox = ['AddStabilityZone', 'SyncServer'] - httpURL = None - def __init__(self,httpURL): - self.httpURL = httpURL - - - def GetClassName(self): - return "Gui::PythonWorkbench" - - def Initialize(self): - Gui.addCommand('AddStabilityZone', AddStabilityZone()) - Gui.addCommand('SyncServer', SyncServer( - self.httpURL)) - self.appendToolbar("Tools", self.toolbox) - self.appendMenu("Tools", self.toolbox) - - def Activated(self): - pass - - def Deactivated(self): - pass diff --git a/freecad_workbench/freecad/robossembler/cad_stability_input/gui/resources/server_sync.svg b/freecad_workbench/freecad/robossembler/cad_stability_input/gui/resources/server_sync.svg deleted file mode 100644 index da595a2..0000000 --- a/freecad_workbench/freecad/robossembler/cad_stability_input/gui/resources/server_sync.svg +++ /dev/null @@ -1,134 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - diff --git a/freecad_workbench/freecad/robossembler/cad_stability_input/gui/resources/stability_zone.svg b/freecad_workbench/freecad/robossembler/cad_stability_input/gui/resources/stability_zone.svg deleted file mode 100644 index 3f7686a..0000000 --- a/freecad_workbench/freecad/robossembler/cad_stability_input/gui/resources/stability_zone.svg +++ /dev/null @@ -1,142 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - diff --git a/freecad_workbench/freecad/robossembler/cad_stability_input/gui/resources/template_resource.svg b/freecad_workbench/freecad/robossembler/cad_stability_input/gui/resources/template_resource.svg deleted file mode 100644 index 509be26..0000000 --- a/freecad_workbench/freecad/robossembler/cad_stability_input/gui/resources/template_resource.svg +++ /dev/null @@ -1,166 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - T - diff --git a/freecad_workbench/freecad/robossembler/cad_stability_input/gui/version.py b/freecad_workbench/freecad/robossembler/cad_stability_input/gui/version.py deleted file mode 100644 index 3486632..0000000 --- a/freecad_workbench/freecad/robossembler/cad_stability_input/gui/version.py +++ /dev/null @@ -1 +0,0 @@ -__version__ = "0.8.1" \ No newline at end of file diff --git a/freecad_workbench/freecad/robossembler/cad_stability_input/main.py b/freecad_workbench/freecad/robossembler/cad_stability_input/main.py deleted file mode 100644 index e0bb99d..0000000 --- a/freecad_workbench/freecad/robossembler/cad_stability_input/main.py +++ /dev/null @@ -1,47 +0,0 @@ -import os -import FreeCADGui as Gui -import FreeCAD as App -from gui.init_gui import StabilityWorkbench -import json - - -def importObjAtPath(path: str): - import importOBJ - importOBJ.insert(u"" + path, App.ActiveDocument.Label) - - pass - - -def getFullPathObj(assemblyFolder: str, name: str): - return assemblyFolder + 'sdf/meshes/' + name + '.obj' - - -def main(): - App.newDocument() - env = json.loads((open('./env.json')).read()) - assemblyFolder = env.get('assemblyFolder') - assemblyStructure = json.loads( - (open(assemblyFolder + 'step-structure.json')).read()) - assemblyNumber = int(env.get('buildNumber')) - 1 - activeDetail = assemblyStructure[assemblyNumber] - - subassemblyNotParticipatingInMarkup = assemblyStructure[0:assemblyNumber - 1] - detailOfTheMarkingZoneOfWhich = assemblyStructure[assemblyNumber - 1] - importObjAtPath(getFullPathObj(assemblyFolder, activeDetail)) - importObjAtPath(getFullPathObj( - assemblyFolder, detailOfTheMarkingZoneOfWhich)) - meshMark = App.ActiveDocument.Objects[0] - meshDetailOfTheMarkZone = App.ActiveDocument.Objects[1] - meshMark.ViewObject.ShapeColor = (0.31, 0.77, 0.87) - meshDetailOfTheMarkZone.ViewObject.ShapeColor = (0.68, 0.66, 0.95) - for el in list(map(lambda el: getFullPathObj(assemblyFolder, el), subassemblyNotParticipatingInMarkup)): - importObjAtPath(el) - for el in App.ActiveDocument.Objects[2:App.ActiveDocument.Objects.__len__()]: - el.ViewObject.ShapeColor = (0.32, 0.05, 0.38) - Gui.SendMsgToActiveView("ViewSelection") - - Gui.addWorkbench(StabilityWorkbench(env.get('resultURL'))) - Gui.activateWorkbench("StabilityWorkbench") - - -main() diff --git a/freecad_workbench/freecad/robossembler/chekingEntities.py b/freecad_workbench/freecad/robossembler/chekingEntities.py deleted file mode 100644 index 50dff73..0000000 --- a/freecad_workbench/freecad/robossembler/chekingEntities.py +++ /dev/null @@ -1,27 +0,0 @@ -import FreeCAD - -# Функция для получения списка всех объектов с заданным свойством -def get_objects_with_property(property_name, property_value): - result = [] - for obj in FreeCAD.ActiveDocument.Objects: - if hasattr(obj, "PropertiesList") and property_name in obj.PropertiesList: - if obj.getPropertyByName(property_name) == property_value: - result.append(obj) - return result - -# Получение списка всех объектов с названием тела в свойстве -bodies = get_objects_with_property("BodyName", "Body") - -# Получение списка всех объектов -all_objects = FreeCAD.ActiveDocument.Objects - -# Поиск и вывод тел, у которых нет связанных вспомогательных объектов -for body in bodies: - linked_objects = [] - for obj in all_objects: - if obj.hasLinkOf(body): - linked_objects.append(obj.Name) - if not linked_objects: - print(f"Тело без связанных объектов: {body.Name}") - - diff --git a/freecad_workbench/freecad/robossembler/constraints_operator.py b/freecad_workbench/freecad/robossembler/constraints_operator.py deleted file mode 100644 index 0006731..0000000 --- a/freecad_workbench/freecad/robossembler/constraints_operator.py +++ /dev/null @@ -1,141 +0,0 @@ -import FreeCAD as App -import json -import os - - - - -def has_active_document(): - doc = App.activeDocument() - if not doc: - App.Console.PrintError("Нет активного документа в FreeCAD.\n") - return False - return True - -def get_assembly_settings_folder(): - if not has_active_document(): - return False - - doc = App.activeDocument() - assembly_settings_folder = None - for obj in doc.Objects: - if obj.Name == "Assembly_Settings": - assembly_settings_folder = obj - break - if not assembly_settings_folder: - assembly_settings_folder = doc.addObject("App::DocumentObjectGroup", "Assembly_Settings") - - return assembly_settings_folder - - - - - -#Создаем объект, описывающий крепежные элементы -#Стоит отметить, что структура крепежа может быть сложнее, чем просто винт. В будущем стоит придумать, как отразить эту структуру, если это необходимо - -def create_fastener_set(): - doc = App.activeDocument() - assembly_settings_folder = get_assembly_settings_folder() - - fastener_set = doc.addObject("Part::FeaturePython", "Fastener_Set") - fastener_set.addProperty("App::PropertyString", "Type", 'Asm_Settings').Type = 'fastener_set' - fastener_set.addProperty("App::PropertyLink", "Parent", 'Asm_Settings') - fastener_set.addProperty("App::PropertyLink", "Child", 'Asm_Settings') - fastener_set.addProperty("App::PropertyLinkList", "Fasteners", 'Asm_Settings') - - assembly_settings_folder.addObject(fastener_set) - - -#Жесткая последовательность для двух деталей -def create_assembly_sequence(): - doc = App.activeDocument() - assembly_settings_folder = get_assembly_settings_folder() - - assembly_sequence = doc.addObject("Part::FeaturePython", "Assembly_Sequence") - assembly_sequence.addProperty("App::PropertyString", "Type", 'Asm_Settings').Type = 'asm_sequence' - assembly_sequence.addProperty("App::PropertyLink", "Parent", 'Asm_Settings') - assembly_sequence.addProperty("App::PropertyLink", "Child", 'Asm_Settings') - - assembly_settings_folder.addObject(assembly_sequence) - - - -#Допустимый зазор для группы элементов, при котором будут распознаваться контакты с окружающими деталями -def create_clearance_constraint(max_clearance = 1.0): - doc = App.activeDocument() - assembly_settings_folder = get_assembly_settings_folder() - - - clearance_constraint = doc.addObject("Part::FeaturePython", "Clearance_Constraint") - clearance_constraint.addProperty("App::PropertyLinkList", "PartName", 'Asm_Settings') - clearance_constraint.addProperty("App::PropertyString", "Type", 'Asm_Settings').Type = 'clearance' - clearance_constraint.addProperty("App::PropertyFloat", "MaxClearance", 'Asm_Settings').MaxClearance = max_clearance - - assembly_settings_folder.addObject(clearance_constraint) - -def create_assembly_parameters(): - doc = App.activeDocument() - assembly_settings_folder = get_assembly_settings_folder() - - assembly_parameters = doc.addObject("Part::FeaturePython", "Assembly_Parameters") - assembly_parameters.addProperty("App::PropertyFloat", "Subassembly_Size", 'Asm_Settings') - assembly_parameters.addProperty("App::PropertyLink", "Subassembly_Mass", 'Asm_Settings') - assembly_parameters.addProperty("App::PropertyBool", "Materials_Together", 'Asm_Settings') - assembly_parameters.addProperty("App::PropertyFloat", "Total_Clearance") - - assembly_settings_folder.addObject(assembly_parameters) - - - -#экспорт всех заданных настроек в общий файл json -def export_assembly_settings(): - doc = App.activeDocument() - if not doc: - return - - assembly_settings_folder = None - for obj in doc.Objects: - if obj.Name == "Assembly_Settings": - assembly_settings_folder = obj - break - - if not assembly_settings_folder: - return - - data = [] - for obj in assembly_settings_folder.Group: - if hasattr(obj, "Type"): - obj_dict = {"Name": obj.Name} - if obj.Type == "fastener_set": - fasteners = [part.Label for part in obj.Fasteners] - obj_dict.update({ - "Type": "fastener_set", - "Parent": obj.Parent.Label, - "Child": obj.Child.Label, - "Fasteners": fasteners - }) - elif obj.Type == "asm_sequence": - obj_dict.update({ - "Type": "asm_sequence", - "Parent": obj.Parent.Label, - "Child": obj.Child.Label - }) - elif obj.Type == "clearance": - partnames = [part.Label for part in obj.PartName] - obj_dict.update({ - "Type": "clearance", - "PartName": partnames, - "MaxClearance": obj.MaxClearance - }) - data.append(obj_dict) - - save_dir = os.path.dirname(doc.FileName) - save_path = os.path.join(save_dir, "assembly_settings_" + App.ActiveDocument.Label + ".json") - with open(save_path, "w") as f: - json.dump(data, f, indent=4) - -# create_fastener_set() -# create_assembly_sequence() -# create_clearance_constraint() -# export_assembly_settings() \ No newline at end of file diff --git a/freecad_workbench/freecad/robossembler/export_entities.py b/freecad_workbench/freecad/robossembler/export_entities.py deleted file mode 100644 index dee9aee..0000000 --- a/freecad_workbench/freecad/robossembler/export_entities.py +++ /dev/null @@ -1,51 +0,0 @@ -import os -import json -import FreeCAD -import Tools - -def export_coordinate_systems(): - # Получение активного документа FreeCAD - doc = FreeCAD.ActiveDocument - if not doc: - raise ValueError("Нет активного документа FreeCAD.") - - # Получение имени активного документа - doc_name = doc.Name - - - # Получение пути к папке и имя файла активного документа - folder_path, file_name = os.path.split(doc.FileName) - - # Создание папки для экспорта, если она не существует - output_folder = os.path.join(folder_path, 'entities') - if not os.path.exists(output_folder): - os.makedirs(output_folder) - - - - # Создание копии активного документа - # надо сохраняться, а не копироваться - - doc.save() - - - - # Получение списка объектов документа - objects = doc.Objects - - # Обход объектов для сохранения локальных систем координат - for obj in objects: - if obj.TypeId == 'PartDesign::CoordinateSystem': - - partprops = Tools.getLocalPartProps(obj) - - - output_file_path = os.path.join(output_folder, f"{obj.Label}.json") - with open(output_file_path, "w", encoding="utf8") as propfile: - json.dump(partprops, propfile, indent=1, separators=(',', ': ')) - - - print("Экспорт обьектов завершен.") - -# export_coordinate_systems() - diff --git a/freecad_workbench/freecad/robossembler/freecad_to_json.py b/freecad_workbench/freecad/robossembler/freecad_to_json.py deleted file mode 100644 index daf4ab3..0000000 --- a/freecad_workbench/freecad/robossembler/freecad_to_json.py +++ /dev/null @@ -1,175 +0,0 @@ -''' -DESCRIPTION. -- Reads a FreeCAD .FCStd file. -- Set tesselation parts to mesh. -- Return scene as JSON dictionary. -''' - -import json -import FreeCAD -import Part -import Mesh -import MeshPart -import logging -import math -from freecad.robossembler.utils.is_object_solid import is_object_solid -from freecad.robossembler.utils.processor import process_file -from freecad.robossembler.utils.custom_parser import CustomArgumentParser - -logger = logging.getLogger(__name__) - - -def freecad_to_json(**kwargs): - ''' Reads a FreeCAD .FCStd file and return json assembly. ''' - - scene = {} - js_objs = {} - - doc = FreeCAD.open(kwargs['fcstd_path']) - docname = doc.Name - - # collect all materials - fem_mats = [] - for fem_mat in doc.Objects: - if fem_mat.isDerivedFrom('App::MaterialObjectPython'): - fem_mats.append(fem_mat) - - for obj in doc.Objects: - js_obj = {} - - if kwargs['skiphidden']: - if not obj.Visibility: - continue - - if obj.isDerivedFrom('PartDesign::CoordinateSystem'): - js_obj['type'] = 'LCS' - - elif obj.isDerivedFrom('Part::Feature'): - js_obj['type'] = 'PART' - # filter for nonsolids - - if is_object_solid(obj) or hasattr(obj, kwargs['property_forse_nonsolid']): - # create mesh from shape - shape = obj.Shape - shape = obj.Shape.copy() - shape.Placement = obj.Placement.inverse().multiply(shape.Placement) - meshfromshape = doc.addObject('Mesh::Feature', 'Mesh') - if kwargs['tesselation_method'] == 'Standard': - meshfromshape.Mesh = MeshPart.meshFromShape( - Shape=shape, - LinearDeflection=kwargs['linear_deflection'], - AngularDeflection=math.radians(kwargs['angular_deflection']), - Relative=False) - elif kwargs['tesselation_method'] == 'FEM': - meshfromshape.Mesh = MeshPart.meshFromShape( - Shape=shape, - MaxLength=kwargs['fem_size']) - else: - raise TypeError('Wrong tesselation method! ' - 'Standard and FEM methods are supported only!') - - t = meshfromshape.Mesh.Topology - verts = [[v.x, v.y, v.z] for v in t[0]] - faces = t[1] - js_obj['mesh'] = (verts, faces) - - # one material for the whole object - for fem_mat in fem_mats: - for ref in fem_mat.References: - if ref[0].Label == obj.Label: - js_obj['material'] = fem_mat.Material - - # skip for other object's types - else: - continue - - js_obj['fc_location'] = tuple(obj.Placement.Base) - js_obj['fc_rotation'] = obj.Placement.Rotation.Q - - # construct assembly hierarchy - obj_parent = obj.getParentGeoFeatureGroup() - obj_child_name = None - parents = {} - deep_index = 0 - while obj_parent: - parent = {} - parent['fc_location'] = tuple(obj_parent.Placement.Base) - parent['fc_rotation'] = obj_parent.Placement.Rotation.Q - obj_child_name = obj_parent.Label - obj_parent = obj_parent.getParentGeoFeatureGroup() - if obj_parent: - parent['parent'] = obj_parent.Label - else: - parent['parent'] = None - parents[obj_child_name] = parent - parent['deep_index'] = deep_index - deep_index += 1 - js_obj['hierarchy'] = parents - - js_objs[obj.Label] = js_obj - - FreeCAD.closeDocument(docname) - - scene[kwargs['fcstd_path']] = js_objs - - logger.info('Passed %s objects without errors', len(js_objs)) - - print(json.dumps(scene)) - - -# to run script via FreeCADCmd -parser = CustomArgumentParser() -parser.add_argument( - '--fcstd_path', - type=str, - help='Path to source FreeCAD scene', - required=True -) -parser.add_argument( - '--tesselation_method', - type=str, - help='Select tesselation method: Standard or FEM.', - default='Standard', - required=False -) -parser.add_argument( - '--linear_deflection', - type=float, - help='Max linear distance error', - default=0.1, - required=False -) -parser.add_argument( - '--angular_deflection', - type=float, - help='Max angular distance error', - default=20.0, - required=False -) -parser.add_argument( - '--fem_size', - type=float, - help='For FEM method only! Finite element size in mm', - default=50.0, - required=False -) -parser.add_argument( - '--skiphidden', - type=bool, - help='Skip processing for hidden FreeCAD objects', - default=True, - required=False -) -parser.add_argument( - '--property_forse_nonsolid', - type=str, - help='FreeCAD property to enable processing for nonsolid objects', - default='Robossembler_NonSolid', - required=False -) - -fc_kwargs = vars(parser.parse_known_args()[0]) - -freecad_to_json(**fc_kwargs) - -logger.info('FreeCAD scene passed!') diff --git a/freecad_workbench/freecad/robossembler/geometric_feasibility_predicate/README.MD b/freecad_workbench/freecad/robossembler/geometric_feasibility_predicate/README.MD deleted file mode 100644 index 60daaf6..0000000 --- a/freecad_workbench/freecad/robossembler/geometric_feasibility_predicate/README.MD +++ /dev/null @@ -1,2 +0,0 @@ -/Users/idontsudo/Desktop/FreeCAD.app/Contents/MacOS/FreeCAD -freecadcmd main.py \ No newline at end of file diff --git a/freecad_workbench/freecad/robossembler/geometric_feasibility_predicate/env.json b/freecad_workbench/freecad/robossembler/geometric_feasibility_predicate/env.json deleted file mode 100644 index 0780dea..0000000 --- a/freecad_workbench/freecad/robossembler/geometric_feasibility_predicate/env.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "cadFilePath": "path/to/file", - "outPath": "out/path", - "objectIndentation": 0 -} diff --git a/freecad_workbench/freecad/robossembler/geometric_feasibility_predicate/geometry_usecase.py b/freecad_workbench/freecad/robossembler/geometric_feasibility_predicate/geometry_usecase.py deleted file mode 100644 index 3807ad5..0000000 --- a/freecad_workbench/freecad/robossembler/geometric_feasibility_predicate/geometry_usecase.py +++ /dev/null @@ -1,63 +0,0 @@ -import FreeCAD as App -import FreeCAD.Console as Console - -class GeometryUseCase: - def __init__(self, document): - self.document = document - - def is_valid_geometry(self, obj): - return hasattr(obj, "Shape") and obj.Shape.Volume is not None - - def create_intersection_matrix(self): - bodies = [obj for obj in self.document.Objects if self.is_valid_geometry(obj)] - num_bodies = len(bodies) - intersection_matrix = [[False for _ in range(num_bodies)] for _ in range(num_bodies)] - - for i in range(num_bodies): - for j in range(i + 1, num_bodies): - body1 = bodies[i] - body2 = bodies[j] - - if body1.Shape.common(body2.Shape).Volume > 0: - intersection_matrix[i][j] = True - intersection_matrix[j][i] = True - - if not hasattr(body1, "AllowIntersections") or not hasattr(body2, "AllowIntersections"): - Console.PrintWarning( - f"Пересечение между '{body1.Name}' и '{body2.Name}' без разрешения.\n" - ) - - return intersection_matrix - - def create_contact_matrix(self): - bodies = [obj for obj in self.document.Objects if self.is_valid_geometry(obj)] - num_bodies = len(bodies) - contact_matrix = [[False for _ in range(num_bodies)] for _ in range(num_bodies)] - - for i in range(num_bodies): - for j in range(i + 1, num_bodies): - body1 = bodies[i] - body2 = bodies[j] - - if body1.Shape.common(body2.Shape).SurfaceArea > 0: - contact_matrix[i][j] = True - contact_matrix[j][i] = True - - return contact_matrix - - -doc = App.ActiveDocument -if doc is None: - Console.PrintError("Нет активного документа в FreeCAD.\n") -else: - use_case = GeometryUseCase(doc) - - intersection_matrix = use_case.create_intersection_matrix() - Console.PrintMessage("Матрица пересечений:\n") - for row in intersection_matrix: - Console.PrintMessage(f"{row}\n") - - contact_matrix = use_case.create_contact_matrix() - Console.PrintMessage("Матрица контактов:\n") - for row in contact_matrix: - Console.PrintMessage(f"{row}\n") diff --git a/freecad_workbench/freecad/robossembler/geometric_feasibility_predicate/main.py b/freecad_workbench/freecad/robossembler/geometric_feasibility_predicate/main.py deleted file mode 100644 index 888c6ec..0000000 --- a/freecad_workbench/freecad/robossembler/geometric_feasibility_predicate/main.py +++ /dev/null @@ -1,775 +0,0 @@ -import FreeCAD as App -import uuid -import os -import json -from typing import List, Dict, Any, TypeVar, Callable, Type, cast -from itertools import repeat - - -class CoreList(List): - # the list contains only True - def onlyTrue(self) -> bool: - print(self) - for el in self: - if el is not True: - return False - return True - - -def isInListRange(listIn, index): - try: - listIn[index] - return False - except: - return True - - -class AllSequences: - all_sequences = None - adj_matrix = None - topologyIds = None - adj_matrix_names = None - - def __init__(self, adj_matrix) -> None: - self.adj_matrix = adj_matrix - self.all_possible_sequences(self.adj_matrix) - self.matrix_by_name() - pass - - def matrix_by_name(self): - result = self.all_sequences - inc = 0 - for matrix in self.all_sequences: - for index in range(len(matrix)): - result[inc][index] = list( - filter( - lambda el: el.get("number") == matrix[index] + 1, - self.topologyIds, - ) - )[0].get("name") - inc += 1 - self.adj_matrix_names = result - pass - - def find_all_sequences(self, adj_matrix): - sequences = [] - num_vertices = len(adj_matrix) - - def dfs(vertex, sequence): - sequence.append(vertex) - - if len(sequence) == num_vertices: - sequences.append(sequence) - return - - for i in range(num_vertices): - if adj_matrix[vertex][i] == 1 and i not in sequence: - dfs(i, sequence.copy()) - - for i in range(num_vertices): - dfs(i, []) - - self.all_sequences = sequences - - def findId(self, listMatrix, id): - def filter_odd_num(in_num): - if in_num["name"] == id: - return True - else: - return False - - return list(filter(filter_odd_num, listMatrix))[0]["number"] - - def iter_paths(self, adj, min_length=6, path=None): - if not path: - for start_node in range(len(adj)): - yield from self.iter_paths(adj, min_length, [start_node]) - else: - if len(path) >= min_length: - yield path - if path[-1] in path[:-1]: - return - current_node = path[-1] - for next_node in range(len(adj[current_node])): - if adj[current_node][next_node] == 1: - yield from self.iter_paths(adj, min_length, path + [next_node]) - - def allUnique(self, x): - seen = set() - return not any(i in seen or seen.add(i) for i in x) - - def all_possible_sequences(self, matrix): - topologyIds = [] - topologyMatrixNumber = {} - inc = 0 - for k, v in matrix.items(): - inc += 1 - topologyIds.append({"name": k, "number": inc}) - inc = 0 - for k, v in matrix.items(): - inc += 1 - topologyMatrixNumber[inc] = list( - map(lambda el: self.findId(topologyIds, el), v) - ) - self.topologyIds = topologyIds - adj = [] - matrixSize = matrix.keys().__len__() - inc = 0 - for k, v in topologyMatrixNumber.items(): - adj.append(list(repeat(0, matrixSize))) - for el in v: - adj[inc][el - 1] = 1 - inc += 1 - return self.find_all_sequences(adj) - - -class VectorModel: - x: float - y: float - z: float - - def __init__(self, cadVector) -> None: - self.x = cadVector[0] - self.y = cadVector[1] - self.z = cadVector[2] - pass - - def toFreeCadVector(self): - return App.Vector(self.x, self.y, self.z) - - -class FreeCadRepository: - _solids = [] - - def isAllObjectsSolids(self) -> List[str]: - result = [] - for part in App.ActiveDocument.Objects: - if self.is_object_solid(part) is False: - result.append(part.Label) - return result - - def objectSetPosition(self, solid, cadVector): - solid.Placement.Base = cadVector - pass - - def objectGetPosition(self, solid) -> VectorModel: - return VectorModel(cadVector=solid.Placement.Base) - - def isObjectIntersections(self, part) -> bool: - for solid in self.getAllSolids(): - if solid.Label != part.Label: - collisionResult: int = int(part.Shape.distToShape(solid.Shape)[0]) - if collisionResult == 0: - return True - return False - - def objectHasTouches(self, part, objectIndentation: float) -> List[str]: - positionVector = self.objectGetPosition(part) - result = CoreList() - result.append(self.isObjectIntersections(part=part)) - - if objectIndentation != 0 and objectIndentation != None: - result.append( - self.axis_movement_and_intersections_observer( - positionVector=positionVector, - alongAxis="x", - objectIndentation=objectIndentation, - part=part, - ) - ) - result.append( - self.axis_movement_and_intersections_observer( - positionVector=positionVector, - alongAxis="y", - objectIndentation=objectIndentation, - part=part, - ) - ) - result.append( - self.axis_movement_and_intersections_observer( - positionVector=positionVector, - alongAxis="z", - objectIndentation=objectIndentation, - part=part, - ) - ) - - return result.onlyTrue() - - def axis_movement_and_intersections_observer( - self, - positionVector: VectorModel, - alongAxis: str, - objectIndentation: float, - part, - ) -> bool: - # UP - positionVector.__setattr__( - alongAxis, positionVector.__getattribute__(alongAxis) + objectIndentation - ) - self.objectSetPosition(part, positionVector.toFreeCadVector()) - result = self.isObjectIntersections(part=part) - if result: - return True - # DOWN - positionVector.__setattr__( - alongAxis, positionVector.__getattribute__(alongAxis) - objectIndentation - ) - positionVector.__setattr__( - alongAxis, positionVector.__getattribute__(alongAxis) - objectIndentation - ) - result = self.isObjectIntersections(part=part) - if result: - return True - self.isObjectIntersections(part=part) - # ROLLBACK - positionVector.__setattr__( - alongAxis, positionVector.__getattribute__(alongAxis) + objectIndentation - ) - self.objectSetPosition(part, positionVector.toFreeCadVector()) - return False - - def getAllSolids(self): - if self._solids.__len__() == 0: - for part in App.ActiveDocument.Objects: - if self.is_object_solid(part): - self._solids.append(part) - - return self._solids - - def is_object_solid(self, obj): - if not isinstance(obj, App.DocumentObject): - return False - if hasattr(obj, "Group"): - return False - - if not hasattr(obj, "Shape"): - return False - if not hasattr(obj.Shape, "Solids"): - return False - - if len(obj.Shape.Solids) == 0: - return False - - return True - - -T = TypeVar("T") - - -def from_list(f: Callable[[Any], T], x: Any) -> List[T]: - assert isinstance(x, list) - return [f(y) for y in x] - - -def from_str(x: Any) -> str: - assert isinstance(x, str) - return x - - -def from_dict(f: Callable[[Any], T], x: Any) -> Dict[str, T]: - assert isinstance(x, dict) - return {k: f(v) for (k, v) in x.items()} - - -def to_class(c: Type[T], x: Any) -> dict: - assert isinstance(x, c) - return cast(Any, x).to_dict() - - -# Вспомогательный класс который делает генрацию JSON на основе пайтон обьектов - - -class AdjacencyMatrix: - matrixError: Dict[str, str] = {} - all_parts: List[str] - first_detail: str - matrix: Dict[str, List[str]] - - def __init__( - self, all_parts: List[str], first_detail: str, matrix: Dict[str, List[str]] - ) -> None: - self.all_parts = all_parts - self.first_detail = first_detail - self.matrix = matrix - self.validateMatrix() - - def whatPlaceLeadingPartIndex(self): - i = 0 - for el in self.matrix: - if el == self.first_detail: - return i - i = +1 - - def validateMatrix(self): - for el in self.all_parts: - if self.matrix.get(el) == None: - self.matrixError[el] = "Not found adjacency " + el - - @staticmethod - def from_dict(obj: Any) -> "AdjacencyMatrix": - assert isinstance(obj, dict) - all_pars = from_list(from_str, obj.get("allParts")) - first_detail = from_str(obj.get("firstDetail")) - matrix = from_dict(lambda x: from_list(from_str, x), obj.get("matrix")) - - return AdjacencyMatrix(all_pars, first_detail, matrix) - - def to_dict(self) -> dict: - result: dict = {} - result["allParts"] = from_list(from_str, self.all_parts) - result["firstDetail"] = from_str(self.first_detail) - result["matrix"] = from_dict(lambda x: from_list(from_str, x), self.matrix) - if self.matrixError.values().__len__() == 0: - result["matrixError"] = None - else: - result["matrixError"] = self.matrixError - return result - - def getDictMatrix(self) -> dict: - result = {} - - for k, v in self.matrix.items(): - result[k] = {} - for el in v: - result[k][el] = el - - return result - - -def adjacency_matrix_from_dict(s: Any) -> AdjacencyMatrix: - return AdjacencyMatrix.from_dict(s) - - -def adjacency_matrix_to_dict(x: AdjacencyMatrix) -> Any: - return to_class(AdjacencyMatrix, x) - - -# Вспомогательный класс для работы с Freecad - - -class FreeCadMetaModel(object): - def __init__(self, label, vertex) -> None: - self.label = label - self.vertex = vertex - - -collision_squares_labels = [] - - -class MeshGeometryCoordinateModel(object): - # Получение геометрии мешей - def __init__( - self, - x, - y, - z, - label, - ): - self.x = x - self.y = y - self.z = z - self.label = label - self.cadLabel = "" - - def initializePrimitivesByCoordinate(self, detailSquares): - uuidDoc = str(uuid.uuid1()) - App.ActiveDocument.addObject("Part::Box", "Box") - App.ActiveDocument.ActiveObject.Label = uuidDoc - App.ActiveDocument.recompute() - part = App.ActiveDocument.getObjectsByLabel(uuidDoc)[0] - collision_squares_labels.append(uuidDoc) - part.Width = 2 - part.Height = 2 - part.Length = 2 - part.Placement = App.Placement( - App.Vector(self.x - 1, self.y - 1, self.z - 1), - App.Rotation(App.Vector(0.00, 0.00, 1.00), 0.00), - ) - if detailSquares.get(self.label) is None: - detailSquares[self.label] = [] - detailSquares[self.label].append(self) - self.cadLabel = uuidDoc - App.ActiveDocument.recompute() - - -class FS: - def readJSON(path: str): - return json.loads((open(path)).read()) - - def writeFile(data, filePath, fileName): - file_to_open = filePath + fileName - - f = open(file_to_open, "w", encoding="utf8") - - f.write(data) - - def readFile(path: str): - return open(path).read() - - def readFilesTypeFolder(pathFolder: str, fileType=".json"): - filesJson = list( - filter( - lambda x: x[-fileType.__len__() :] == fileType, os.listdir(pathFolder) - ) - ) - return filesJson - - -class GetAllPartsLabelsUseCase: - # Получение всех названий деталей - def call(self): - parts = [] - for part in FreeCadRepository().getAllSolids(): - parts.append(part.Label) - return parts - - -def isUnique(array, element): - for i in array: - if i == element: - return False - - return True - - -class GetCollisionAtPrimitiveUseCase(object): - # Получение колизий примитивов - def call(self, freeCadMetaModels, detailSquares) -> Dict[str, List[str]]: - matrix: Dict[str, List[str]] = {} - for model in freeCadMetaModels: - activePart = App.ActiveDocument.getObjectsByLabel(model.label)[0] - for key in detailSquares: - if model.label != key: - for renderPrimitive in detailSquares[key]: - primitivePart = App.ActiveDocument.getObjectsByLabel( - renderPrimitive.cadLabel - )[0] - collisionResult: int = int( - activePart.Shape.distToShape(primitivePart.Shape)[0] - ) - if collisionResult == 0: - if matrix.get(model.label) == None: - matrix[model.label] = [renderPrimitive.label] - else: - if isUnique(matrix[model.label], renderPrimitive.label): - matrix[model.label].append(renderPrimitive.label) - return matrix - - -class GetFirstDetailUseCase: - # Получение первой детали - def call(self): - return FreeCadRepository().getAllSolids()[0].Label - - -class GetPartPrimitiveCoordinatesUseCase(object): - # Получение координат примитивов - def call(self, freeCadMetaModels): - meshCoordinates: list[MeshGeometryCoordinateModel] = [] - for model in freeCadMetaModels: - vertexesDetail = model.vertex - labelDetail = model.label - for coords in vertexesDetail: - detailVertex = MeshGeometryCoordinateModel( - coords.X, - coords.Y, - coords.Z, - labelDetail, - ) - meshCoordinates.append(detailVertex) - - return meshCoordinates - - -class InitPartsParseUseCase: - # Инициализация парсинга - def call(self): - product_details = [] - for part in FreeCadRepository().getAllSolids(): - if part is not None: - model = FreeCadMetaModel(part.Label, part.Shape.Vertexes) - if model is not None: - product_details.append(model) - return product_details - - -class RenderPrimitiveUseCase(object): - # Рендеринг премитивов - def call( - self, meshModels: list[MeshGeometryCoordinateModel], detailSquares - ) -> None: - for mesh in meshModels: - mesh.initializePrimitivesByCoordinate(detailSquares) - - -class ClearWorkSpaceDocumentUseCase(object): - # Очистка рабочего простарнства - def call(self, detailSquares): - for key in detailSquares: - for renderPrimitive in detailSquares[key]: - primitivePart = App.ActiveDocument.getObjectsByLabel( - renderPrimitive.cadLabel - )[0] - App.ActiveDocument.removeObject(primitivePart.Name) - - -class RenderPrimitivesScenario(object): - def __init__( - self, - initPartsParseUseCase: InitPartsParseUseCase, - getPartPrimitiveCoordinatesUseCase: GetPartPrimitiveCoordinatesUseCase, - renderPrimitiveUseCase: RenderPrimitiveUseCase, - getCollisionAtPrimitives: GetCollisionAtPrimitiveUseCase, - clearWorkSpaceDocument: ClearWorkSpaceDocumentUseCase, - ) -> None: - self.initPartsParseUseCase = initPartsParseUseCase - self.getPartPrimitiveCoordinatesUseCase = getPartPrimitiveCoordinatesUseCase - self.renderPrimitiveUseCase = renderPrimitiveUseCase - self.getCollisionAtPrimitives = getCollisionAtPrimitives - self.clearWorkSpaceDocument = clearWorkSpaceDocument - - def call(self) -> None: - meshCoordinates = [] - detailSquares = {} - parts = self.initPartsParseUseCase.call() - meshCoordinates = self.getPartPrimitiveCoordinatesUseCase.call(parts) - self.renderPrimitiveUseCase.call(meshCoordinates, detailSquares) - matrix = self.getCollisionAtPrimitives.call(parts, detailSquares) - self.clearWorkSpaceDocument.call(detailSquares) - return matrix - - -class ClearWorkSpaceDocumentUseCase(object): - # Очистака рабочего пространства - def call(self, detailSquares): - for key in detailSquares: - for renderPrimitive in detailSquares[key]: - primitivePart = App.ActiveDocument.getObjectsByLabel( - renderPrimitive.cadLabel - )[0] - App.ActiveDocument.removeObject(primitivePart.Name) - - -class CadAdjacencyMatrix: - # Матрица основанная на соприкосновении примитива с обьектами - def primitiveMatrix(self): - # Получение матрицы - matrix = RenderPrimitivesScenario( - InitPartsParseUseCase(), - GetPartPrimitiveCoordinatesUseCase(), - RenderPrimitiveUseCase(), - GetCollisionAtPrimitiveUseCase(), - ClearWorkSpaceDocumentUseCase(), - ).call() - return AdjacencyMatrix( - all_parts=GetAllPartsLabelsUseCase().call(), - first_detail=GetFirstDetailUseCase().call(), - matrix=matrix, - ) - - # Матрица основанная на соприкосновении обьектов - - def matrixBySurfaces(self): - matrix = {} - for part in FreeCadRepository().getAllSolids(): - matrix[part.Label] = [] - for nextPart in FreeCadRepository().getAllSolids(): - if part.Label != nextPart.Label: - # Вычисление соприконсоновения площади деталей - collisionResult: int = int( - part.Shape.distToShape(nextPart.Shape)[0] - ) - print(collisionResult) - print("collisionResult") - if collisionResult == 0: - matrix[part.Label].append(nextPart.Label) - - return AdjacencyMatrix( - all_parts=GetAllPartsLabelsUseCase().call(), - first_detail=GetFirstDetailUseCase().call(), - matrix=matrix, - ) - - -def reduce(function, iterable, initializer=None): - it = iter(iterable) - if initializer is None: - value = next(it) - else: - value = initializer - for element in it: - value = function(value, element) - return value - - -def to_ascii_hash(text): - ascii_values = [ord(character) for character in text] - return reduce(lambda x, y: x + y, ascii_values) - - -def matrixGetUniqueContact(matrix): - detailsToCheck = [] - detailsHashCheck = {} - for k, v in matrix.items(): - for el in v: - if el != k: - hash = to_ascii_hash(k + el) - if detailsHashCheck.get(hash) == None: - detailsHashCheck[hash] = hash - detailsToCheck.append({"child": el, "parent": k}) - return detailsToCheck - - -class IntersectionComputedUseCase: - def call(parts): - App.activeDocument().addObject("Part::MultiCommon", "Common") - App.activeDocument().Common.Shapes = [parts[0], parts[1]] - App.activeDocument().getObject("Common").ViewObject.ShapeColor = getattr( - parts[0].getLinkedObject(True).ViewObject, - "ShapeColor", - App.activeDocument().getObject("Common").ViewObject.ShapeColor, - ) - App.activeDocument().getObject("Common").ViewObject.DisplayMode = getattr( - parts[0].getLinkedObject(True).ViewObject, - "DisplayMode", - App.activeDocument().getObject("Common").ViewObject.DisplayMode, - ) - App.ActiveDocument.recompute() - area = App.activeDocument().getObject("Common").Shape.Area - App.ActiveDocument.removeObject("Common") - return area - - -class ErrorStringModel: - def __init__(self, error: str) -> None: - self.error = error - pass - - error: str - - def toString(self) -> str: - return json.dumps( - { - "error": self.error, - }, - ensure_ascii=False, - indent=4, - ) - - -class IsAllObjectSolidsCheckUseCase: - def call() -> ErrorStringModel: - result = FreeCadRepository().isAllObjectsSolids() - if result.__len__() == 0: - return None - - return ErrorStringModel(error="Is not solid objects: " + ",".join(result)) - - -class CheckObjectHasTouchesUseCase: - def call(objectIndentation: float) -> ErrorStringModel: - result = [] - for part in FreeCadRepository().getAllSolids(): - if ( - FreeCadRepository().objectHasTouches( - part=part, objectIndentation=objectIndentation - ) - is False - ): - result.append(part.Label) - if result.__len__() == 0: - return None - return ErrorStringModel( - error="Solids bodies have no recounts: " + ",".join(result) - ) - - -class CheckCadIntersectionObjects: - report = [] - - def call() -> bool: - FreeCadRepository().getAllSolids() - return False - - -class ExitFreeCadUseCase: - def call(): - import FreeCADGui as Gui - - freecadQTWindow = Gui.getMainWindow() - freecadQTWindow.close() - - -# class CheckValidIntersectionUseCase: -# def call() -> ErrorStringModel: -# for part in FreeCadRepository().getAllSolids(): -# print(part) -# FreeCadRepository().obj -# pass - - - -def main(): - env = FS.readJSON("env.json") - cadFilePath = str(env["cadFilePath"]) - outPath = str(env["outPath"]) - objectIndentation = float(env["objectIndentation"]) - - if cadFilePath == None: - return TypeError("CadFile not found env.json") - App.open("" + cadFilePath) - - # isAllObjectSolidsCheckUseCase = IsAllObjectSolidsCheckUseCase.call() - - # if isAllObjectSolidsCheckUseCase != None: - # FS.writeFile(isAllObjectSolidsCheckUseCase.toString(), outPath, 'error.json') - # ExitFreeCadUseCase.call() - # return - - # checkObjectHasTouchesUseCase = CheckObjectHasTouchesUseCase.call(objectIndentation) - - # if checkObjectHasTouchesUseCase != None: - # FS.writeFile(checkObjectHasTouchesUseCase.toString(), outPath, 'error.json') - # ExitFreeCadUseCase.call() - # return - - topologyMatrix = CadAdjacencyMatrix().matrixBySurfaces() - import json - - sequences = json.dumps( - {"sequences": AllSequences(topologyMatrix.matrix).adj_matrix_names}, - ensure_ascii=False, - indent=4, - ) - matrix = topologyMatrix.matrix - contacts = matrixGetUniqueContact(matrix) - intersection_geometry = {"status": True, "recalculations": None} - for el in contacts: - child = App.ActiveDocument.getObjectsByLabel(el.get("child"))[0] - parent = App.ActiveDocument.getObjectsByLabel(el.get("parent"))[0] - area = IntersectionComputedUseCase.call([child, parent]) - if area != 0.0: - if intersection_geometry.get("recalculations") == None: - intersection_geometry["status"] = False - intersection_geometry["recalculations"] = [] - intersection_geometry["recalculations"].append( - {"area": area, "connect": el.get("child") + " " + el.get("parent")} - ) - - FS.writeFile( - json.dumps(intersection_geometry, ensure_ascii=False, indent=4), - outPath, - "intersection_geometry.json", - ) - FS.writeFile(sequences, outPath, "sequences.json") - - FS.writeFile( - json.dumps(topologyMatrix.to_dict(), ensure_ascii=False, indent=4), - outPath, - "adjacency_matrix.json", - ) - ExitFreeCadUseCase.call() - - -#main() diff --git a/freecad_workbench/freecad/robossembler/get_sequences.py b/freecad_workbench/freecad/robossembler/get_sequences.py deleted file mode 100644 index 7d268bf..0000000 --- a/freecad_workbench/freecad/robossembler/get_sequences.py +++ /dev/null @@ -1,61 +0,0 @@ -import json -import networkx as nx - -def load_data(file_path): - with open(file_path, 'r') as file: - return json.load(file) - -def create_graph(data): - G = nx.Graph() - for part in data['allParts']: - G.add_node(part) - for part, connections in data['matrix'].items(): - for connected_part in connections: - G.add_edge(part, connected_part) - return G - -def find_leaf_nodes(graph, central_node): - leaf_nodes = [] - for node in graph.nodes: - if node != central_node and graph.degree(node) == 1: - leaf_nodes.append(node) - return leaf_nodes - -def find_all_paths(graph, start_node, end_node): - try: - return list(nx.all_simple_paths(graph, start_node, end_node)) - except nx.NetworkXNoPath: - return [] - -def load_constraints(file_path): - with open(file_path, 'r') as file: - return json.load(file) - -def is_valid_sequence(sequence, constraints): - for constraint in constraints: - if constraint[0] in sequence and constraint[1] in sequence: - if sequence.index(constraint[0]) > sequence.index(constraint[1]): - return False - return True - -def save_sequences(sequences, file_path): - with open(file_path, 'w') as file: - json.dump(sequences, file, indent=4) - -data = load_data('adjacency_matrix.json') -constraints = load_constraints('constraints.json') -all_parts = data['allParts'] -graph = create_graph(data) -first_detail = data['firstDetail'] -leaf_nodes = find_leaf_nodes(graph, first_detail) - -all_sequences = [] -for leaf in leaf_nodes: - paths = find_all_paths(graph, leaf, first_detail) - for path in paths: - if set(path) == set(all_parts) and is_valid_sequence(path, constraints): - all_sequences.append(path) - -save_sequences(all_sequences, 'valid_sequences.json') - -print(f"Найдено {len(all_sequences)} допустимых последовательностей сборки.") diff --git a/freecad_workbench/freecad/robossembler/graph_visualisation.py b/freecad_workbench/freecad/robossembler/graph_visualisation.py deleted file mode 100644 index 9baf51c..0000000 --- a/freecad_workbench/freecad/robossembler/graph_visualisation.py +++ /dev/null @@ -1,26 +0,0 @@ -import json -import networkx as nx -import matplotlib.pyplot as plt - -# Загружаем данные из файла -with open('adjacency_matrix.json', 'r') as file: - data = json.load(file) - -# Создаем пустой граф -G = nx.Graph() - -# Добавляем узлы -for part in data['allParts']: - G.add_node(part) - -# Добавляем ребра -for part, connections in data['matrix'].items(): - for connected_part in connections: - G.add_edge(part, connected_part) - -# Визуализируем граф -plt.figure(figsize=(10, 8)) -pos = nx.spring_layout(G) -nx.draw(G, pos, with_labels=True, node_size=100, node_color='lightblue', font_size=10, font_weight='bold', edge_color='gray') -plt.title('Graph of Part Connections') -plt.show() diff --git a/freecad_workbench/freecad/robossembler/helper/fs.py b/freecad_workbench/freecad/robossembler/helper/fs.py deleted file mode 100644 index 9068e9a..0000000 --- a/freecad_workbench/freecad/robossembler/helper/fs.py +++ /dev/null @@ -1,14 +0,0 @@ -import os -import json - - -class FS: - def readJSON(path: str): - return json.loads((open(path)).read()) - - def writeFile(data, filePath, fileName): - file_to_open = filePath + fileName - - f = open(file_to_open, 'w', ) - - f.write(data) diff --git a/freecad_workbench/freecad/robossembler/helper/is_solid.py b/freecad_workbench/freecad/robossembler/helper/is_solid.py deleted file mode 100644 index 431c814..0000000 --- a/freecad_workbench/freecad/robossembler/helper/is_solid.py +++ /dev/null @@ -1,18 +0,0 @@ -import FreeCAD - - -def is_object_solid(obj): - """If obj is solid return True""" - if not isinstance(obj, FreeCAD.DocumentObject): - return False - - if not hasattr(obj, 'Shape'): - return False - - if not hasattr(obj.Shape, 'Solids'): - return False - - if len(obj.Shape.Solids) == 0: - return False - - return True diff --git a/freecad_workbench/freecad/robossembler/init_gui.py b/freecad_workbench/freecad/robossembler/init_gui.py deleted file mode 100644 index 2e857fd..0000000 --- a/freecad_workbench/freecad/robossembler/init_gui.py +++ /dev/null @@ -1,95 +0,0 @@ -import os -import FreeCADGui as Gui -import FreeCAD as App - -from .TranslateUtils import translate -from . import ICONPATH, TRANSLATIONSPATH, Frames -from .version import __version__ - -__title__='Robossembler Workbench' -__author__ = 'brothermechanic, Mark Voltov, IDONTSUDO, Igor Brylyov' -__copyright__ = 'Copyright (c) 2023 brothermechanic' -__license__ = 'GPL-2.1' -__email__ = 'brothermechanic@gmail.com, ius.mark.alex@gmail.com' -__url__ = ["https://robossembler.org"] -__status__ = 'development' - - -class Robossembler(Gui.Workbench): - """ - class which gets initiated at startup of the gui - """ - MenuText = "Robossembler" # translate("cool", "Robossembler") - ToolTip = "Robossembler Workbench" # translate("cool", "a simple Robossembler") - Icon = os.path.join(ICONPATH, "robossembler.svg") - toolbox = [] - - def GetClassName(self): - return "Gui::PythonWorkbench" - - def Initialize(self): - """ - This function is called at the first activation of the workbench. - here is the place to import all the commands - """ - # Add translations path - Gui.addLanguagePath(TRANSLATIONSPATH) - Gui.updateLocale() - - self.framecommands = [ - "BoMGeneration", - "FrameCommand", - "SelectedPartFrameCommand", - "AllPartFramesCommand", - "FeatureFrameCommand" - ] - self.toolcommands = [ - "ExportPlacementAndPropertiesCommand", - "Export_Entities", - "ExportGazeboModels", - "InsertGraspPose", - "Validate_Project", - "Publish_Project" - ] - self.asmcommands = [ - "Create Assembly Parameters", - "Create Fastener Set", - "Create Assembly Sequence", - "Export Assembly Settings", - "Compute Assembly Sequence", - # "Create Assembly Layers", - "Create Structure Graph", - "Create Assembly Graph" - - ] - - self.appendToolbar(f"{__class__.__name__} Frames", self.framecommands) - self.appendToolbar(f"{__class__.__name__} Tools", self.toolcommands) - self.appendToolbar(f"{__class__.__name__} Assembly Setup", self.asmcommands) - - App.Console.PrintMessage(translate("Console", - "Switching to robossembler") + "\n") - - App.Console.PrintMessage(translate("Console", - "Switching to robossembler") + "\n") - - # self.appendToolbar(translate("Toolbar", "Tools"), self.toolbox) - # self.appendMenu(translate("Menu", "Tools"), self.toolbox) - - def Activated(self): - ''' - code which should be computed when a user switch to this workbench - ''' - pass - - def Deactivated(self): - ''' - code which should be computed when this workbench is deactivated - ''' - pass - - def ContextMenu(self, recipient): - """This is execcuted whenever the user right-clicks on screen.""" - pass - -Gui.addWorkbench(Robossembler()) diff --git a/freecad_workbench/freecad/robossembler/markup_entities.py b/freecad_workbench/freecad/robossembler/markup_entities.py deleted file mode 100644 index cddf266..0000000 --- a/freecad_workbench/freecad/robossembler/markup_entities.py +++ /dev/null @@ -1,162 +0,0 @@ -import FreeCAD as App -import FreeCADGui as Gui - -doc = App.ActiveDocument - -print('lcs - локальная система координат') -print('grip - позиция захвата') -print('area - плоскость') -print('vol - зона') -print('joint - соединение') -entityType = input('Введите тип получаемого обьекта') - -def create(entityType): - - if entityType == 'grip': - print('задайте начальную точку захватной зоны. ') - print('Учтите, что ось X должна быть направлена вдоль направления раскрытия пальцев') - print('Ось Z должна быть направлена в противоположную сторону от направления кончика пальца захвата') - objname = input('Введите название начальной точки' + "\n") - obj = doc.getObject(objname) - - - poseGenerator(obj) - - - - elif entityType == 'area': - print('задайте плоскость') - objname = input('Введите название плоскости'+ "\n") - obj = doc.getObject(objname) - - areaProps(obj) - - elif entityType == 'vol': - print('задайте обьем') - objname = input('Введите название обьема'+ "\n") - obj = doc.getObject(objname) - - volProps(obj) - - elif entityType == 'joint': - print('Задайте позицию соединения') - objname = input('Введите название соединения'+ "\n") - part1 = input('укажите название первой детали'+ "\n") - part2 = input('укажите название второй детали'+ "\n") - - jointGenerator(objname, part1, part2) - - obj.addProperty("App::PropertyString", "Type").Type = entityType - - - -## заглушки функций на случай, если что-то придумаю полезное для них - - -def areaProps(area): - #здесь нужно отметить свойства зоны - #в принципе, Placement и размеры тут есть, больше ничего особо не нужно - #добавить характеристику entityType - - print(area.Label) - -def volProps(vol): - #желательно указать координаты, габариты, позицию привязки - #но думаю, что это все уже есть - print(vol.Label) - - -def jointGenerator(jointName, part1, part2): - - #получаем относительные координаты для первой детали и для второй детали - #создаем две сущности - точка входа и точка выхода (??????) - #в работе сейчас - print(jointName.Label) - print(part1.Label) - print(part2.Label) - - - - - - - -# Эта функция работает нормально - - -def poseGenerator(lcs): - - box = doc.addObject("Part::Box", "gripSpace") - box.Length = 62 #раскрытие - box.Width = 10 #ширина пальца - box.Height = 40 #глубина - - box.Placement = lcs.Placement - - - #есть смысл создавать привязку прямо здесь же. благодаря параметризации, при подстройке куба все точки сместятся как надо - gripPose = App.ActiveDocument.addObject('PartDesign::CoordinateSystem', 'GripPose') - gripPose.Support = box - gripPose.positionBySupport() - gripPose.MapMode = 'ObjectXY' - gripPose.AttachmentOffset.Base = [str(box.Label) + '.Length' + '/2', str(box.Label) + '.Length'+ '/2', 0] #здесь должна быть активная привязка, не просто значения координат - - gripPose.addProperty("App::PropertyFloat", "GripOpen") - gripPose.addProperty("App::PropertyFloat", "GripDepth") - gripPose.addProperty("App::PropertyFloat", "GripWidth") - gripPose.setExpression('GripDepth', str(box.Label) + '.Height') - gripPose.setExpression('GripOpen', str(box.Label) + '.Length') - gripPose.setExpression('GripWidth', str(box.Label) + '.Width') - - - - - - #нужно создавать внутри Part, а не внутри главного документа. сбиваются привязки !!! - - - print('Установите захватную зону вручную, растянув обьект GripSpace') - doc.recompute() - - -#теперь нужно производить экспорт -#он делается через Tools.py или через импорт-экспорт - - -create(entityType) - - - - -### getObjectInfo работает - - -def getFaceInfo(face): - if face: - App.Console.PrintMessage(f"Информация о грани: {face}\n") - - # Получите позицию (Base) и ориентацию (Rotation) грани в глобальных координатах - placement = face.Placement - position = App.Vector(placement.Base) - orientation = App.Rotation(placement.Rotation) - - App.Console.PrintMessage(f"Позиция грани: {position}\n") - App.Console.PrintMessage(f"Ориентация грани: {orientation}\n") - -def getObjectInfo(): - selection = Gui.Selection.getSelectionEx() - if selection: - selected_object = selection[0].Object - if selected_object: - subelement_name = selection[0].SubElementNames[0] - if "Face" in subelement_name: - face = selected_object.Shape.Faces[int(subelement_name.split("Face")[1])] - getFaceInfo(face) - else: - App.Console.PrintError("Выберите грань, а не тело или другой элемент\n") - else: - App.Console.PrintError("Объект не найден\n") - else: - App.Console.PrintError("Не выбраны объекты\n") - -getObjectInfo() \ No newline at end of file diff --git a/freecad_workbench/freecad/robossembler/pddl/Printer.FCStd b/freecad_workbench/freecad/robossembler/pddl/Printer.FCStd deleted file mode 100644 index b819cd5..0000000 Binary files a/freecad_workbench/freecad/robossembler/pddl/Printer.FCStd and /dev/null differ diff --git a/freecad_workbench/freecad/robossembler/pddl/domain.pddl b/freecad_workbench/freecad/robossembler/pddl/domain.pddl deleted file mode 100644 index 044c805..0000000 --- a/freecad_workbench/freecad/robossembler/pddl/domain.pddl +++ /dev/null @@ -1,97 +0,0 @@ -(define (domain Printer) - -(:requirements :strips :typing :fluents :durative-actions) -(:types - printer workspace - zone - part - arm - assembly - human - filament -) - (:predicates - (arm_available ?a - arm) - (part_at ?p - part ?z - zone) - (printer_ready ?p - printer) - (printer_checked ?p - printer) - (printer_at_work ?p - printer) - (part_of ?part - part ?whole - assembly) - (assembly_order ?prev ?next - assembly) - (assembled ?whole - assembly ?z - zone) - (observer_free ?h - human) - (filament_at ?f - filament ?z - zone) - ) - (:functions - ) -(:durative-action print - :parameters ( ?p - part ?pr - printer ) - :duration ( = ?duration 20) - :condition (and - (at start(printer_ready ?pr)) - ) - :effect (and - (at start (not (printer_ready ?pr))) - (at start (printer_at_work ?pr )) - (at end(part_at ?p ?pr)) - (at end (not (printer_at_work ?pr ))) -) - ) -(:durative-action remove - :parameters ( ?p - part ?pr - printer ?z - zone ?a - arm ) - :duration ( = ?duration 1) - :condition (and - (at start (part_at ?p ?pr)) - (at start (arm_available ?a)) - ) - :effect (and - (at start (not (arm_available ?a))) - (at end (part_at ?p ?z)) - (at end (arm_available ?a)) - (at end (printer_ready ?pr)) -) - ) -(:durative-action assemble - :parameters ( ?p - part ?prev ?next - assembly ?z - zone ?arm - arm ?w - workspace ) - :duration ( = ?duration 5) - :condition (and - (at start (assembled ?prev ?w)) - (at start (part_at ?p ?w)) - (at start (part_of ?p ?next)) - (at start (arm_available ?arm)) - (at start (assembly_order ?prev ?next)) - ) - :effect (and - (at start (not (arm_available ?arm))) - (at end (not (part_at ?p ?w))) - (at end (arm_available ?arm)) - (at end (assembled ?next ?w)) -) - ) -(:durative-action printer_check - :parameters ( ?p - printer ?h - human ) - :duration ( = ?duration 1) - :condition (and - (at start ( observer_free ?h )) - ) - :effect (and - (at start (not (observer_free ?h))) - (at end (observer_free ?h)) - (at end (printer_checked ?p)) -) - ) -(:durative-action printer_filament_load - :parameters ( ?p - printer ?h - human ?f - filament ?z - zone ) - :duration ( = ?duration 5) - :condition (and - (at start (printer_checked ?p)) - (at start (observer_free ?h)) - (at start (filament_at ?f ?z)) - ) - :effect (and - (at start (not(observer_free ?h))) - (at end (observer_free ?h)) - (at end (printer_ready ?p)) - (at end (not (filament_at ?f ?z))) -) - ) - ) diff --git a/freecad_workbench/freecad/robossembler/pddl/freecad2pddl.py b/freecad_workbench/freecad/robossembler/pddl/freecad2pddl.py deleted file mode 100644 index eb4cbc5..0000000 --- a/freecad_workbench/freecad/robossembler/pddl/freecad2pddl.py +++ /dev/null @@ -1,181 +0,0 @@ -import FreeCAD as App -import FreeCADGui as Gui - - - - - -#функции для создания обьектов PDDL - -def add_types(): - doc = App.ActiveDocument - types = doc.addObject('App::FeaturePython', 'Types') - types.addProperty("App::PropertyString", 'PDDL', 'PDDL').PDDL = 'PDDL' - types.addProperty("App::PropertyString", 'Type', 'PDDL').Type = 'Types' - types.addProperty("App::PropertyStringList", 'Types', 'PDDL') - - print('Types of objects added successfully') - return(types) -#слишком много types - -def add_parameters(): - doc = App.ActiveDocument - params = doc.addObject('App::FeaturePython', 'Parameters') - params.addProperty("App::PropertyString", 'PDDL', 'PDDL').PDDL = 'PDDL' - params.addProperty("App::PropertyString", 'Type', 'PDDL').Type = 'Parameters' - params.addProperty('App::PropertyPythonObject', 'Parameters','PDDl') - - print('Domain parameters added successfully') - return(params) - -def add_action(): - doc = App.ActiveDocument - - name = input('Название действия:') - action = doc.addObject('App::FeaturePython', str(name)) - action.addProperty("App::PropertyString", 'PDDL', 'PDDL').PDDL = 'PDDL' - action.addProperty("App::PropertyString", 'Type', 'PDDL').Type = 'Action' - action.addProperty("App::PropertyStringList", 'Parameters', 'PDDL') - action.addProperty("App::PropertyStringList", 'Conditions', 'PDDL') - action.addProperty("App::PropertyStringList", 'Effects', 'PDDL') - sortEntity(action) - print('Action ' + name + 'added successfully') - return(action) - - -def add_predicate(): - doc = App.ActiveDocument - - name = input('Название предиката:') - parms = input('Переменные') - predicate = doc.addObject('App::FeaturePython', str(name)) - predicate.addProperty("App::PropertyString", 'PDDL', 'PDDL').PDDL = 'PDDL' - predicate.addProperty("App::PropertyString", 'Type', 'PDDL').Type = 'Predicate' - # predicate.addProperty("App::PropertyStringList", 'Name', 'PDDL') - predicate.addProperty("App::PropertyStringList", 'Parameters', 'PDDL').Parameters = parms - sortEntity(predicate) - print('Predicate ' + name + 'added successfully') - return(predicate) - - -def add_durative_action(): - doc = App.ActiveDocument - name = input('Название действия:') - action = doc.addObject('App::FeaturePython', str(name)) - action.addProperty("App::PropertyString", 'PDDL', 'PDDL').PDDL = 'PDDL' - action.addProperty("App::PropertyString", 'Type', 'PDDL').Type = 'DurativeAction' - action.addProperty("App::PropertyStringList", 'Parameters', 'PDDL') - action.addProperty("App::PropertyStringList", 'Conditions', 'PDDL') - action.addProperty("App::PropertyStringList", 'Effects', 'PDDL') - action.addProperty('App::PropertyString', 'Duration', 'PDDL') - sortEntity(action) - print('Durative Action ' + name + ' added successfully') - return(action) - - - - -def export_to_file(): - filename = App.ActiveDocument.Name - file_path = App.ActiveDocument.FileName.rsplit("/", 1)[0] + filename + '_domain.pddl' - - doc = App.ActiveDocument - objs = doc.Objects - with open(file_path, 'w') as f: - f.write('(define (domain '+ filename +')\n \n') - f.write('(:requirements :strips :typing :fluents :durative-actions)\n') - - # Типы обьектов - types = doc.getObjectsByLabel('Types')[0] - f.write('(:types \n') - - for obj_type in types.Types: - f.write(' ' + obj_type + ' \n') - f.write(')\n') - - # предикаты - f.write(' (:predicates\n') - for obj in objs: - if hasattr(obj, 'PDDL') and hasattr(obj, 'Type') and obj.Type == 'Predicate': - f.write(' ('+ obj.Label) - for params in obj.Parameters: - f.write(' ' + params) - f.write(')\n') - f.write(' )\n') - - # функции - f.write(' (:functions\n') - f.write(' )\n') - - #действия: - for obj in objs: - if hasattr(obj, 'PDDL') and hasattr(obj, 'Type') and obj.Type == 'Action': - f.write('(:action ' + obj.Label + '\n') - f.write(' :parameters (') - for params in obj.Parameters: - f.write('' + params + ' ') - f.write(')\n') - f.write(' :condition (and \n') - - for condition in obj.Conditions: - f.write(' (' + condition + ') \n') - - f.write(' )\n') - - f.write(' :effect (and \n') - - for effect in obj.Effects: - f.write(' (' + effect + ') \n') - # f.write(' ') - f.write(')\n') - - f.write(' )\n') - - # длительные действия: - for obj in objs: - if hasattr(obj, 'PDDL') and hasattr(obj, 'Type') and obj.Type == 'DurativeAction': - f.write('(:durative-action ' + obj.Label + '\n') - f.write(' :parameters (') - for params in obj.Parameters: - f.write(' ' + params ) - f.write(' )\n') - f.write(' :duration ( = ?duration '+ str(obj.Duration) +')\n') - f.write(' :condition (and \n') - - for condition in obj.Conditions: - f.write(' (' + condition + ') \n') - # f.write(') ') - # f.write(')\n') - f.write(' )\n') - - f.write(' :effect (and \n') - - for effect in obj.Effects: - f.write(' (' + effect + ') \n') - # f.write(' ') - f.write(')\n') - - f.write(' )\n') - - - - f.write(' )\n') - - - -def sortEntity(object): - doc = App.ActiveDocument - - - if len(doc.getObjectsByLabel(object.Type)) == 0: - pddl_group = doc.addObject("App::DocumentObjectGroup", object.Type) - else: - pddl_group = doc.getObjectsByLabel(object.Type)[0] - pddl_group.addObject(object) - - - - Gui.updateGui() - - - diff --git a/freecad_workbench/freecad/robossembler/pddl/insertion_vector_predicate/.gitignore b/freecad_workbench/freecad/robossembler/pddl/insertion_vector_predicate/.gitignore deleted file mode 100644 index 4a47d9e..0000000 --- a/freecad_workbench/freecad/robossembler/pddl/insertion_vector_predicate/.gitignore +++ /dev/null @@ -1,116 +0,0 @@ -# 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 - -# Unit test / coverage reports -htmlcov/ -.tox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*.cover -.hypothesis/ - -# Translations -*.mo -*.pot - -# Django stuff: -*.log -local_settings.py - -# Flask stuff: -instance/ -.webassets-cache - -# Scrapy stuff: -.scrapy - -# Sphinx documentation -docs/_build/ - -# PyBuilder -target/ - -# Jupyter Notebook -.ipynb_checkpoints - -# pyenv -.python-version - -# celery beat schedule file -celerybeat-schedule - -# SageMath parsed files -*.sage.py - -# dotenv -.env - -# virtualenv -.venv -venv/ -ENV/ - -# Spyder project settings -.spyderproject -.spyproject - -# Rope project settings -.ropeproject - -# mkdocs documentation -/site - -# mypy -.mypy_cache/ - -# blender backup files -*.blend1 -install_plugin_cad.sh -.vscode -.DS_Store - -# emacs backup files -~* -*~ -*# -.#* -\#*\# -out/ -/env.json \ No newline at end of file diff --git a/freecad_workbench/freecad/robossembler/pddl/insertion_vector_predicate/README.md b/freecad_workbench/freecad/robossembler/pddl/insertion_vector_predicate/README.md deleted file mode 100644 index 24d4b44..0000000 --- a/freecad_workbench/freecad/robossembler/pddl/insertion_vector_predicate/README.md +++ /dev/null @@ -1,33 +0,0 @@ -# Start dev -create env.json - -```json -{ - "cadDoc":"CAD_DOC_PATH_REPLACE", - "sequences":"SEQUENCES_PATH_REPLACE", - "aspDir":"ASP_DIR_REPLACE" -} -``` -# Command generation assets -freecad generate.py - -# Command generation insertion vectors - -git submodule update --init -conda env create -f assembly/environment.yml -conda activate assembly -python assembly/simulation/setup.py install -sudo apt-get install libgl1-mesa-dev xorg-dev -python3 main.py - - - -# Последовательность действий - -1. cad_generation main.py - 1. в env json прописываем пути -2. geometric_feasibility_predicate main.py - 1. в env json прописываем пути - -3. insertion vector predicate main.py #исправить пути к моделям в main.py -4. результат : траектории вставки \ No newline at end of file diff --git a/freecad_workbench/freecad/robossembler/pddl/insertion_vector_predicate/assembly b/freecad_workbench/freecad/robossembler/pddl/insertion_vector_predicate/assembly deleted file mode 160000 index 395ee5b..0000000 --- a/freecad_workbench/freecad/robossembler/pddl/insertion_vector_predicate/assembly +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 395ee5b638ccaa0cbe5b48101655560e49365195 diff --git a/freecad_workbench/freecad/robossembler/pddl/insertion_vector_predicate/generate.py b/freecad_workbench/freecad/robossembler/pddl/insertion_vector_predicate/generate.py deleted file mode 100644 index c08adb3..0000000 --- a/freecad_workbench/freecad/robossembler/pddl/insertion_vector_predicate/generate.py +++ /dev/null @@ -1,205 +0,0 @@ - - -from typing import List -import FreeCAD as App -import Part -import Mesh -import Part -import MeshPart -import os -import json -import FreeCADGui as Gui - -class FS: - def readJSON(path: str): - return json.loads((open(path)).read()) - - def writeFile(data, filePath, fileName): - file_to_open = filePath + fileName - - f = open(file_to_open, 'w', encoding='utf-8', - errors='ignore') - f.write(data) - f.close() - def createFolder(path: str): - if (not os.path.exists(path)): - return os.mkdir(path) - - - -class SimpleCopyPartModel: - id = None - copyLink = None - label = None - part = None - - def getPart(self): - return self.part - - def __init__(self, part) -> None: - try: - from random import randrange - self.id = str(randrange(1000000)) - childObj = part - print(part) - __shape = Part.getShape( - childObj, '', needSubElement=False, refine=False) - obj = App.ActiveDocument.addObject('Part::Feature', self.id) - obj.Shape = __shape - self.part = obj - self.label = obj.Label - App.ActiveDocument.recompute() - except Exception as e: - print(e) - - def remove(self): - App.ActiveDocument.removeObject(self.label) - -class MeshPartModel: - id = None - mesh = None - - def __init__(self, part) -> None: - try: - from random import randrange - self.id = 'mesh' + str(randrange(1000000)) - document = App.ActiveDocument - mesh = document.addObject("Mesh::Feature", self.id) - shape = Part.getShape(part, "") - mesh.Mesh = MeshPart.meshFromShape( - Shape=shape, LinearDeflection=20, AngularDeflection=0.1, Relative=False) - mesh.Label = self.id - self.mesh = mesh - except Exception as e: - print(e) - pass - - def remove(self): - try: - App.ActiveDocument.removeObject(self.mesh.Label) - except Exception as e: - print(e) - - - -class JoinMeshModel: - id = None - mesh = None - - def __init__(self, meshesPartModels: list['MeshPartModel']) -> None: - meshes = [] - from random import randrange - for el in meshesPartModels: - meshes.append(el.mesh.Mesh) - - self.id = 'MergedMesh' + str(randrange(1000000)) - doc = App.ActiveDocument - merged_mesh = Mesh.Mesh() - for el in meshes: - merged_mesh.addMesh(el) - - new_obj = doc.addObject("Mesh::Feature", self.id) - new_obj.Mesh = merged_mesh - new_obj.ViewObject.DisplayMode = "Flat Lines" - self.mesh = new_obj - - def remove(self): - try: - App.ActiveDocument.removeObject(self.id) - except Exception as e: - print(e) - - -class ExportAssemblyThemAllUseCase: - - def call(self, path:str, assemblys:list[str]): - assembly = assemblys - asmStructure = {} - inc = 0 - for el in assembly: - if (inc != 0): - asmStructure[inc] = { - "child": el, - "parents": assembly[0:inc] - } - inc += 1 - objectsFreeCad = App.ActiveDocument.Objects - asmSolids = {} - for k, v in asmStructure.items(): - assemblyParentList = v['parents'] - assemblyChild = v['child'] - for el in assemblyParentList: - for solid in objectsFreeCad: - if (el == solid.Label): - if (asmSolids.get(k) is None): - - asmSolids[k] = {'parents': [], 'child': list( - filter(lambda x: x.Label == assemblyChild, objectsFreeCad))[0]} - - asmSolids[k]['parents'].append(solid) - - inc = 0 - for k, v in asmSolids.items(): - geometry = {"0": [], "1": []} - if (k != 0): - App.activeDocument().addObject("Part::Compound", "Compound") - - copyLinks = list( - map(lambda el: SimpleCopyPartModel(el), v['parents'])) - - if copyLinks != None: - App.activeDocument().Compound.Links = list( - map(lambda el: el.getPart(), copyLinks)) - - object = App.activeDocument().getObject('Compound') - boundBox = object.Shape.BoundBox - geometry['0'].append(boundBox.XMax) - geometry['0'].append(boundBox.YMax) - geometry['0'].append(boundBox.ZMax) - - boundBoxChild = v['child'].Shape.BoundBox - geometry['1'].append(boundBoxChild.XMax) - geometry['1'].append(boundBoxChild.YMax) - geometry['1'].append(boundBoxChild.ZMax) - meshParents = [] - - for el in v['parents']: - meshParents.append(MeshPartModel(el)) - joinMesh = JoinMeshModel(meshParents) - for el in meshParents: - el.remove() - import importOBJ - importOBJ.export(joinMesh.mesh, path + str(1) + '.obj') - joinMesh.remove() - importOBJ.export(v['child'], path + str(0) + '.obj') - FS.writeFile(json.dumps(geometry), path, 'translation.json') - - App.ActiveDocument.removeObject("Compound") - for el in copyLinks: - el.remove() - App.activeDocument().recompute() - inc += 1 - -def main(): - - env = FS.readJSON('./env.json') - env.get('cadDoc') - aspDir = env.get('aspDir') - sequences = FS.readJSON(env.get('sequences')).get('sequences') - App.openDocument(env.get('cadDoc')) - for sequencyNumber in range(len(sequences)): - FS.createFolder(aspDir + 'assemblys/') - mainFolder = aspDir + 'assemblys/' + str(sequencyNumber) + '/' - FS.createFolder(mainFolder) - for subSequenceNumber in range(len(sequences[sequencyNumber])): - if(subSequenceNumber != 0): - subFolder = aspDir + 'assemblys/' + \ - str(sequencyNumber) + '/' + str(subSequenceNumber) + '/' - - FS.createFolder(subFolder) - ExportAssemblyThemAllUseCase().call(path=subFolder,assemblys=sequences[sequencyNumber][0:subSequenceNumber+1]) - - App.closeDocument(App.ActiveDocument.Name) - freecadQTWindow = Gui.getMainWindow() - freecadQTWindow.close() -main() \ No newline at end of file diff --git a/freecad_workbench/freecad/robossembler/pddl/insertion_vector_predicate/main.py b/freecad_workbench/freecad/robossembler/pddl/insertion_vector_predicate/main.py deleted file mode 100644 index b2fd134..0000000 --- a/freecad_workbench/freecad/robossembler/pddl/insertion_vector_predicate/main.py +++ /dev/null @@ -1,174 +0,0 @@ -import os -import sys - -project_base_dir = os.path.abspath(os.path.join( - os.path.dirname(os.path.abspath(__file__)), './')) + '/assembly/' - - -sys.path.append(project_base_dir) -sys.path.append(project_base_dir + '/baselines/') -sys.path.append(project_base_dir + '/assets/') - -from scipy.spatial.transform import Rotation -import shutil -from spatialmath import * -from spatialmath.base import * -from assembly.assets.process_mesh import process_mesh -from assembly.examples.run_joint_plan import get_planner -from assembly.baselines.run_joint_plan import PyPlanner -from assembly.assets.subdivide import subdivide_to_size -import numpy as np -import json -import trimesh - -import re -def merge_meshes(meshes): - # Создание пустого меша - merged_mesh = trimesh.Trimesh() - - # Объединение каждого меша в один - for mesh in meshes: - merged_mesh = trimesh.util.concatenate( - [merged_mesh, trimesh.load(mesh)]) - i = True - while i: - if merged_mesh.fill_holes(): - i = False - - - - - - return merged_mesh - - -os.environ['OMP_NUM_THREADS'] = '1' - - - -class FS: - def readJSON(path: str): - return json.loads((open(path)).read()) - - def writeFile(data, filePath, fileName): - - file_to_open = filePath + fileName - - f = open(file_to_open, 'w', ) - - f.write(data) - - def readFile(path: str): - return open(path).read() - - def readFilesTypeFolder(pathFolder: str, fileType='.json'): - return os.listdir(pathFolder) - - def readFolder(pathFolder: str): - return list(map(lambda el: pathFolder + '/' + el, os.listdir(pathFolder))) - - def createFolder(path: str): - if (not os.path.exists(path)): - return os.mkdir(path) - - -def listGetFirstValue(iterable, default=False, pred=None): - return next(filter(pred, iterable), default) - - -def filterModels(filterModels, filterModelsDescription): - models = [] - for el in filterModelsDescription: - models.append(listGetFirstValue( - filterModels, None, lambda x: x.name == el)) - return models - - -# mesh1 = trimesh.load('/Users/idontsudo/framework/asp/out/sdf-generation/meshes/Cube.obj') -# mesh2 = trimesh.load('/Users/idontsudo/framework/asp/out/sdf-generation/meshes/Cube001.obj') - - -# # Объединение мешей -# merged_mesh = merge_meshes([mesh1, mesh2]) - -# # Сохранение объединенного меша в файл -# merged_mesh.export('merged.obj') -def main(): - # from argparse import ArgumentParser - # parser = ArgumentParser() - # parser.add_argument('--asp-path', type=str, required=True) - # args = parser.parse_args() - # aspDir = args.asp_dir - - # # Коректировка пути до папки с генерацией ASP - # if (aspDir == None): - # args.print_helper() - # if (aspDir[aspDir.__len__() - 1] != '/'): - # aspDir += '/' - aspDir = "/home/markvoltov/GitProjects/framework/test_models/" - sequences = FS.readJSON(aspDir + 'sequences.json').get('sequences') - - assemblyDirNormalize = [] - for el in FS.readFolder(aspDir + 'assemblys'): - for e in FS.readFolder(el): - try: - # Пост обработка .obj обьектов - process_mesh(source_dir=e, target_dir=e + - '/process/', subdivide=e, verbose=True) - assemblyDirNormalize.append(e + '/process/') - except Exception as e: - print('ERRROR:') - print(e) - - - print(assemblyDirNormalize) - for el in assemblyDirNormalize: - asset_folder = os.path.join(project_base_dir, aspDir) - assembly_dir = os.path.join(asset_folder, el) - planner = get_planner('bfs')(assembly_dir, assembly_dir, 0, [ - 1], False, 'sdf', 0.05, 0.01, 100, 100, True) - - # Планирование пути - status, t_plan, path = planner.plan( - 120, seed=1, return_path=True, render=False, record_path=None - ) - coords = [] - - for k in path: - seMatrix = SE3(k) - euler = seMatrix.eul() - coord = seMatrix.A[0:3, 3] - rot = Rotation.from_euler('xyz', euler, degrees=True).as_quat() - coords.append({'quadrelion': [rot[0], rot[1], rot[2], rot[3]], 'xyz': [ - coord[0], coord[1], coord[2]], 'euler': [euler[0], euler[1], euler[2]]}) - # Запись пути в кортеж - planingObject = { - "time": t_plan, - "insertion_path": coords, - "status": status, - } - # Запись результата планирования - FS.writeFile(json.dumps(planingObject), - el[0:el.__len__() - 8], 'insertion_path.json') - - try: - planner = PyPlanner(assembly_dir, 'process', still_ids=[1],) - status, t_plan, path = planner.plan( - planner_name='rrt', - step_size=None, - max_time=None, - seed=1, - return_path=True, - simplify=False, - render=False - ) - - print(f'Status: {status}, planning time: {t_plan}') - - if args.save_dir is not None: - planner.save_path(path, args.save_dir, args.n_save_state) - except Exception as e: - print(e) - - -main() diff --git a/freecad_workbench/freecad/robossembler/pddl/insertion_vector_predicate/requirements.txt b/freecad_workbench/freecad/robossembler/pddl/insertion_vector_predicate/requirements.txt deleted file mode 100644 index 9f14b84..0000000 --- a/freecad_workbench/freecad/robossembler/pddl/insertion_vector_predicate/requirements.txt +++ /dev/null @@ -1,3 +0,0 @@ -spatialmath-python -scipy -uuid \ No newline at end of file diff --git a/freecad_workbench/freecad/robossembler/pddl/my_problem.pddl b/freecad_workbench/freecad/robossembler/pddl/my_problem.pddl deleted file mode 100644 index 56ae618..0000000 --- a/freecad_workbench/freecad/robossembler/pddl/my_problem.pddl +++ /dev/null @@ -1,69 +0,0 @@ -(define (problem my_problem) -(:domain roboarm) -(:objects - ur_manipulator_gripper - arm - printer - printer - world - zone - box1 box2 box3 box4 box5 box6 - part - asm0 asm1 asm2 asm3 asm4 asm5 asm6 - assembly -) - -(:init - not(part_at box1 world) - not(part_at box2 world) - not(part_at box3 world) - not(part_at box4 world) - not(part_at box5 world) - not(part_at box6 world) - (part_of box1 asm1) - (part_of box2 asm2) - (part_of box3 asm3) - (part_of box4 asm4) - (part_of box5 asm5) - (part_of box6 asm6) - (assembly_order asm0 asm1) - (assembly_order asm1 asm2) - (assembly_order asm2 asm3) - (assembly_order asm3 asm4) - (assembly_order asm4 asm5) - (assembly_order asm5 asm6) - - (printer_available printer) - (arm_available ur_manipulator_gripper) - (assembly_at asm0 world) - (assembled asm0) -) - -(:goal (and - (assembled asm6) -)) -) - -; нужно указать желаемое конечное состояние -; (эффект в конце действия) -; в нашем случае, допустим, будет asm6 -; чтобы включить принтер в процесс, у нас должны спавниться детали - -; будет что-то типа (not part_at box1 workzone) - -; и action print -; начальные условия: not part_at box workzone -; принтер доступен -; в ходе дела парт печатается, принтер не доступен -; в конце - принтер доступен, деталь в зоне - -; нужно в генераторе добавить поддержку условий at start и at end -; но пока что это можно прописать текстом - - -; предикаты - -; рука доступна - рука -; сборка в зоне - сборка зона -; деталь часть сборки - деталь сборка -; собрана - сборка -; сборочный порядок - предсборка следсборка - -; + -; деталь в зоне - деталь зона -; принтер доступен - принтер - diff --git a/freecad_workbench/freecad/robossembler/pddl/printETA.py b/freecad_workbench/freecad/robossembler/pddl/printETA.py deleted file mode 100644 index 554fb15..0000000 --- a/freecad_workbench/freecad/robossembler/pddl/printETA.py +++ /dev/null @@ -1,98 +0,0 @@ - -import os -import subprocess -import time - -import FreeCAD -import Mesh - - -import gcoder - - -def export_to_stl(doc, output_dir): - objects = doc.Objects - - for obj in objects: - if isinstance(obj, Part.Feature): - stl_path = os.path.join(output_dir, obj.Label + ".stl") - mesh = obj.Shape.tessellate(0.1) - - # Создаем меш из геометрии объекта - mesh_obj = Mesh.Mesh(mesh) - - # Проверяем, что меш содержит данные - if len(mesh_obj.Points) > 0: - # Экспортируем меш в формат STL - mesh_obj.write(stl_path) - - -def create_gcode(stl_dir, output_dir): - stl_files = [f for f in os.listdir(stl_dir) if f.endswith(".stl")] - - for stl_file in stl_files: - stl_path = os.path.join(stl_dir, stl_file) - - gcode_file = stl_file.replace(".stl", ".gcode") - gcode_path = os.path.join(output_dir, gcode_file) - - # Команда для запуска Slic3r (в Ubuntu используется slic3r-пакет) - cmd = ["slic3r", "--load", "/home/mark-voltov/my_config.ini", "-o", gcode_path, stl_path] - - # Запускаем Slic3r - subprocess.run(cmd) - -def get_print_duration(gcode_dir): - - gcoder.G - gcode_files = [f for f in os.listdir(gcode_dir) if f.endswith(".gcode")] - - total_duration = 0 - - for gcode_file in gcode_files: - gcode_path = os.path.join(gcode_dir, gcode_file) - - with open(gcode_path, "r") as file: - lines = file.readlines() - - for line in lines: - if line.startswith("; estimated printing time"): - duration = float(line.split(":")[1].strip()) * 60 - total_duration += duration - break - - return total_duration - - -file_location = App.ActiveDocument.FileName -file_name = os.path.basename(file_location ) #eds_report.csv -location = os.path.dirname(file_location ) - - -# Путь к документу FreeCAD -doc_path = file_location - -# Каталог для сохранения STL-файлов -stl_dir = location + '/stl' - -# Каталог для сохранения G-code файлов -gcode_dir = location + '/gcode' - -# Открываем документ FreeCAD -doc = FreeCAD.open(doc_path) - -# Экспортируем модель в файлы STL -export_to_stl(doc, stl_dir) -print("STL файлы успешно созданы.") - -# Создаем G-code файлы с помощью Slic3r -create_gcode(stl_dir, gcode_dir) -print("G-code файлы успешно созданы.") - -# Получаем оценочную длительность печати -print_duration = get_print_duration(gcode_dir) -print("Оценочная длительность печати: {} секунд.".format(print_duration)) - -# Закрываем документ FreeCAD -FreeCAD.closeDocument(doc) - diff --git a/freecad_workbench/freecad/robossembler/pddl/problem.pddl b/freecad_workbench/freecad/robossembler/pddl/problem.pddl deleted file mode 100644 index 98b2207..0000000 --- a/freecad_workbench/freecad/robossembler/pddl/problem.pddl +++ /dev/null @@ -1,127 +0,0 @@ -(define (problem p1) -(:domain robossembler) -(:objects - ;; information from Scene - rasmt - arm - printer1 printer2 printer3 - printer - workspace1 - workspace - worker - human - filament1 filament2 filament3 - filament - ;; information from CAD - pad009003002002 pad009003002003 pad009003002005 pad009003002011 fusion004003 o_2_a001 o_2_m001 o_3_m001 o_3_a001 pad009003002008 fusion005 o_4_m001 o_5_m001 o_5_a001 o_4_a001 fusion006 r_a001 r_m001 r_l001 synfix synfix001 fusion fusion001 synfix002 fusion002 synfix003 fusion007 pad009003002012 pad001 pocket pad002 fusion008 fusion009 bearing_dgsr_6006_001 bearing_dgsr_6006_002 bearing_dgsr_6006_003 bearing_dgsr_6005_ bearing_dgsr_6005_001 bearing_dgsr_6005_002 bearing_dgsr_6005_003 bearing_dgsr_6005_004 pad003 pocket001 - part - subasm00 subasm0 subasm1 subasm2 subasm3 subasm4 subasm5 subasm6 subasm7 subasm8 subasm9 subasm10 subasm11 subasm12 subasm13 subasm14 subasm15 subasm16 subasm17 subasm18 subasm19 subasm20 subasm21 subasm22 subasm23 subasm24 subasm25 subasm26 subasm27 subasm28 subasm29 subasm30 subasm31 subasm32 subasm33 subasm34 subasm35 subasm36 subasm37 subasm38 subasm39 subasm40 subasm41 subasm42 - assembly -) -(:init - ;; information from Scene - - (observer_free worker) - ; (not(printer_ready printer1)) - - ; (printer_ready printer2) - ; (printer_ready printer3) - (filament_at filament1 workspace1) - (filament_at filament2 workspace1) - (filament_at filament3 workspace1) - - - (arm_available rasmt) - ;; information from CAD - (assembled subasm00 workspace1) - - - - -(part_of pad009003002002 subasm0) - (part_of pad009003002003 subasm1) - (part_of pad009003002005 subasm2) - (part_of pad009003002011 subasm3) - (part_of fusion004003 subasm4) - (part_of o_2_a001 subasm5) - (part_of o_2_m001 subasm6) - (part_of o_3_m001 subasm7) - (part_of o_3_a001 subasm8) - (part_of pad009003002008 subasm9) - (part_of fusion005 subasm10) - (part_of o_4_m001 subasm11) - (part_of o_5_m001 subasm12) - (part_of o_5_a001 subasm13) - (part_of o_4_a001 subasm14) - (part_of fusion006 subasm15) - (part_of r_a001 subasm16) - (part_of r_m001 subasm17) - (part_of r_l001 subasm18) - (part_of synfix subasm19) - (part_of synfix001 subasm20) - (part_of fusion subasm21) - (part_of fusion001 subasm22) - (part_of synfix002 subasm23) - (part_of fusion002 subasm24) - (part_of synfix003 subasm25) - (part_of fusion007 subasm26) - (part_of pad009003002012 subasm27) - (part_of pad001 subasm28) - (part_of pocket subasm29) - (part_of pad002 subasm30) - (part_of fusion008 subasm31) - (part_of fusion009 subasm32) - (part_of bearing_dgsr_6006_001 subasm33) - (part_of bearing_dgsr_6006_002 subasm34) - (part_of bearing_dgsr_6006_003 subasm35) - (part_of bearing_dgsr_6005_ subasm36) - (part_of bearing_dgsr_6005_001 subasm37) - (part_of bearing_dgsr_6005_002 subasm38) - (part_of bearing_dgsr_6005_003 subasm39) - (part_of bearing_dgsr_6005_004 subasm40) - (part_of pad003 subasm41) - (part_of pocket001 subasm42) - - (assembly_order subasm00 subasm0) - (assembly_order subasm0 subasm1) - (assembly_order subasm1 subasm2) - (assembly_order subasm2 subasm3) - (assembly_order subasm3 subasm4) - (assembly_order subasm4 subasm5) - (assembly_order subasm5 subasm6) - (assembly_order subasm6 subasm7) - (assembly_order subasm7 subasm8) - (assembly_order subasm8 subasm9) - (assembly_order subasm9 subasm10) - (assembly_order subasm10 subasm11) - (assembly_order subasm11 subasm12) - (assembly_order subasm12 subasm13) - (assembly_order subasm13 subasm14) - (assembly_order subasm14 subasm15) - (assembly_order subasm15 subasm16) - (assembly_order subasm16 subasm17) - (assembly_order subasm17 subasm18) - (assembly_order subasm18 subasm19) - (assembly_order subasm19 subasm20) - (assembly_order subasm20 subasm21) - (assembly_order subasm21 subasm22) - (assembly_order subasm22 subasm23) - (assembly_order subasm23 subasm24) - (assembly_order subasm24 subasm25) - (assembly_order subasm25 subasm26) - (assembly_order subasm26 subasm27) - (assembly_order subasm27 subasm28) - (assembly_order subasm28 subasm29) - (assembly_order subasm29 subasm30) - (assembly_order subasm30 subasm31) - (assembly_order subasm31 subasm32) - (assembly_order subasm32 subasm33) - (assembly_order subasm33 subasm34) - (assembly_order subasm34 subasm35) - (assembly_order subasm35 subasm36) - (assembly_order subasm36 subasm37) - (assembly_order subasm37 subasm38) - (assembly_order subasm38 subasm39) - (assembly_order subasm39 subasm40) - (assembly_order subasm40 subasm41) - (assembly_order subasm41 subasm42) -) -(:goal (and - ;; information from CAD - (assembled subasm42 workspace1) - ) -) -) diff --git a/freecad_workbench/freecad/robossembler/pose_generator.py b/freecad_workbench/freecad/robossembler/pose_generator.py deleted file mode 100644 index ad51a2f..0000000 --- a/freecad_workbench/freecad/robossembler/pose_generator.py +++ /dev/null @@ -1,53 +0,0 @@ -import FreeCAD as App -import FreeCADGui as Gui - -# App.newDocument() -doc = App.ActiveDocument - - -print('задайте начальную точку захватной зоны. ') -print('Учтите, что ось X должна быть направлена вдоль направления раскрытия пальцев') -print('Ось Z должна быть направлена в противоположную сторону от направления кончика пальца захвата') -lcsname = input('Введите название начальной точки' + "\n") - -lcs = doc.getObject(lcsname) - -def poseGenerator(lcs): - - box = doc.addObject("Part::Box", "gripSpace") - box.Length = 62 #раскрытие - box.Width = 10 #ширина пальца - box.Height = 40 #глубина - - box.Placement = lcs.Placement - #box.Transparency = 80 #не работает, хз почему - - - - #есть смысл создавать привязку прямо здесь же. благодаря параметризации, при подстройке куба все точки сместятся как надо - gripPose = App.ActiveDocument.addObject('PartDesign::CoordinateSystem', 'GripPose') - gripPose.Support = box - gripPose.MapMode = 'ObjectXY' - gripPose.AttachmentOffset.Base = [box.Length/2, box.Width/2, 0] #здесь должна быть активная привязка, не просто значения координат - - gripPose.addProperty("App::PropertyFloat", "GripOpen") - gripPose.addProperty("App::PropertyFloat", "GripDepth") - gripPose.addProperty("App::PropertyFloat", "GripWidth") - gripPose.GripOpen = box.Length.Value - gripPose.GripWidth = box.Width.Value - gripPose.GripDepth = box.Height.Value - - - - - #нужно создавать обьект внутри Part, а не внутри главного документа. сбиваются привязки !!! - - - print('Установите захватную зону вручную, растянув обьект GripSpace') - doc.recompute() - - #вроде как работает - - -poseGenerator(lcs) - diff --git a/freecad_workbench/freecad/robossembler/project_validator.py b/freecad_workbench/freecad/robossembler/project_validator.py deleted file mode 100644 index e9913f1..0000000 --- a/freecad_workbench/freecad/robossembler/project_validator.py +++ /dev/null @@ -1,184 +0,0 @@ -import FreeCAD as App -import unicodedata -import numpy as np -from .helper.is_solid import is_object_solid - -## Программа, содержащая все проверки активного проекта FreeCAD в соответствии с issue#149 - -doc = App.ActiveDocument -Console = App.Console - - -#========== Проверка имен =============== -class FormalValidator: - def __init__(self, document): - self.document = document - - def is_unicode_safe(self, name): - normalized_name = unicodedata.normalize('NFKD', name).encode('ASCII', 'ignore').decode() - return name == normalized_name - - def fix_invalid_names(self): - for obj in self.document.Objects: - if not self.is_unicode_safe(obj.Label): - safe_name = unicodedata.normalize('NFKD', obj.Label).encode('ASCII', 'ignore').decode() - obj.Label = safe_name - self.document.recompute() - - #запуск проверки и исправления имен файлов - def validate(self): - invalid_names = [obj.Label for obj in self.document.Objects if not self.is_unicode_safe(obj.Label)] - if invalid_names: - print("Некорректные имена:") - for name in invalid_names: - print(name) - self.fix_invalid_names() - else: - print("Все имена корректны.") - - -class ModelValidator: - def __init__(self, document): - self.document = document - self.partlist = [obj for obj in self.document.Objects if (is_object_solid(obj) and not obj.TypeId == 'App::Part') ] - self.material_objects = [obj for obj in document.Objects if obj.TypeId == "App::MaterialObjectPython"] - - def get_parts(self): - pass - - - - def validate_geometry(self): - for obj in self.document.Objects: - if hasattr(obj, "Shape") and not is_object_solid(obj): - Console.PrintError(f"Объект '{obj.Name}' не является твердым телом.\n") - - def is_intersecting(self, obj1, obj2): - if obj1.Shape.common(obj2.Shape).Volume > 0.0: - return True - - def has_allow_intersections(self, obj): - if hasattr(obj, 'Base_Allowed_Intersection') and getattr(obj, 'Base_Allowed_Intersection', True): - return True - - def check_bodies_for_intersections(self): - bodies = self.partlist - num_bodies = len(bodies) - - for i in range(num_bodies): - for j in range(i + 1, num_bodies): - body1 = bodies[i] - body2 = bodies[j] - if self.is_intersecting(body1, body2): - if self.has_allow_intersections(body1) or self.has_allow_intersections(body2): - Console.PrintWarning( - f"Тела '{body1.Label}' и '{body2.Label}' ""предусмотренно пересекаются.\n") - else: - Console.PrintError( - f"Тела '{body1.Label}' и '{body2.Label}' ""непредусмотренно пересекаются.\n") - print('V = ' + str(body1.Shape.common(body2.Shape).Volume)) - - - def get_adjacency_matrix(self, padding = 1): - # print(int(padding)) - bodies = self.partlist - num_bodies = len(bodies) - adjacency_matrix = np.zeros((num_bodies, num_bodies), dtype=bool) - - for i in range(num_bodies): - shape1 = bodies[i].Shape - for j in range(i + 1, num_bodies): - shape2 = bodies[j].Shape - - if shape1.common(shape2).Volume > 0: - continue - - distance = shape1.distToShape(shape2) - if distance[0] < padding: - adjacency_matrix[i][j] = 1 - adjacency_matrix[j][i] = 1 - - return adjacency_matrix - - def check_bodies_without_contacts(self): - adjacency_matrix = self.get_adjacency_matrix() - bodies = self.partlist - - isolated_bodies = [] - num_bodies = len(bodies) - - for i in range(num_bodies): - # Проверяем, есть ли у тела касания с другими телами - if not any(adjacency_matrix[i]): - isolated_bodies.append(bodies[i].Label) - - if isolated_bodies: - App.Console.PrintWarning("Следующие тела не касаются других:\n") - for label in isolated_bodies: - App.Console.PrintWarning(f"- {label}\n") - else: - App.Console.PrintMessage("Все тела имеют контакты.\n") - - - def find_material_objects(document): - pass - - - - def check_bodies_with_multiple_materials(self): - material_objects = self.material_objects - material_references = {} - - for material in material_objects: - if hasattr(material, "References"): - for reference in material.References: - if reference in material_references: - material_references[reference].append(material.Label) - else: - material_references[reference] = [material.Label] - - conflicts = {k: v for k, v in material_references.items() if len(v) > 1} - - if conflicts: - App.Console.PrintWarning("Обнаружены конфликты между объектами материалов:\n") - for ref, materials in conflicts.items(): - App.Console.PrintWarning(f"Деталь '{ref[0].Label}' используется в материалах: {', '.join(materials)}\n") - else: - App.Console.PrintMessage("Конфликтов в ссылках материалов не обнаружено.\n") - - def check_bodies_without_material(self): - material_objects = self.material_objects - partlist = self.partlist - referenced_bodies = [] - for material in material_objects: - if hasattr(material, "References"): - for reference in material.References: - referenced_bodies.append(reference[0].Label) - - bodies_without_material = [] - for part in partlist: - if part.Label not in referenced_bodies: - bodies_without_material.append(part.Label) - - if bodies_without_material: - App.Console.PrintWarning("Следующие тела не имеют назначенного материала:\n") - for name in bodies_without_material: - App.Console.PrintWarning(f"- {name}\n") - else: - App.Console.PrintMessage("Все тела имеют назначенные материалы.\n") - - - - def validate(self): - self.validate_geometry() - self.check_bodies_for_intersections() - self.check_bodies_without_contacts() - self.check_bodies_without_material() - self.check_bodies_with_multiple_materials() - -def validate_project(): - doc = App.ActiveDocument - FormalValidator(doc).validate() - ModelValidator(doc).validate() - - diff --git a/freecad_workbench/freecad/robossembler/resources/icons/BoMList.svg b/freecad_workbench/freecad/robossembler/resources/icons/BoMList.svg deleted file mode 100644 index caf5d4f..0000000 --- a/freecad_workbench/freecad/robossembler/resources/icons/BoMList.svg +++ /dev/null @@ -1,72 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - ... - - - - - - Parts - - - - List - - - \ No newline at end of file diff --git a/freecad_workbench/freecad/robossembler/resources/icons/Center.svg b/freecad_workbench/freecad/robossembler/resources/icons/Center.svg deleted file mode 100644 index aeddb82..0000000 --- a/freecad_workbench/freecad/robossembler/resources/icons/Center.svg +++ /dev/null @@ -1,237 +0,0 @@ - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/freecad_workbench/freecad/robossembler/resources/icons/PickedPoint.svg b/freecad_workbench/freecad/robossembler/resources/icons/PickedPoint.svg deleted file mode 100644 index 6e0c4b3..0000000 --- a/freecad_workbench/freecad/robossembler/resources/icons/PickedPoint.svg +++ /dev/null @@ -1,152 +0,0 @@ - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - diff --git a/freecad_workbench/freecad/robossembler/resources/icons/PointOnCenterline.svg b/freecad_workbench/freecad/robossembler/resources/icons/PointOnCenterline.svg deleted file mode 100644 index 501db60..0000000 --- a/freecad_workbench/freecad/robossembler/resources/icons/PointOnCenterline.svg +++ /dev/null @@ -1,275 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/freecad_workbench/freecad/robossembler/resources/icons/PointOnEdge.svg b/freecad_workbench/freecad/robossembler/resources/icons/PointOnEdge.svg deleted file mode 100644 index 0edfb5e..0000000 --- a/freecad_workbench/freecad/robossembler/resources/icons/PointOnEdge.svg +++ /dev/null @@ -1,181 +0,0 @@ - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - diff --git a/freecad_workbench/freecad/robossembler/resources/icons/PointOnSurface.svg b/freecad_workbench/freecad/robossembler/resources/icons/PointOnSurface.svg deleted file mode 100644 index 62c8edc..0000000 --- a/freecad_workbench/freecad/robossembler/resources/icons/PointOnSurface.svg +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - diff --git a/freecad_workbench/freecad/robossembler/resources/icons/addgrasppose.svg b/freecad_workbench/freecad/robossembler/resources/icons/addgrasppose.svg deleted file mode 100644 index 3c74388..0000000 --- a/freecad_workbench/freecad/robossembler/resources/icons/addgrasppose.svg +++ /dev/null @@ -1,16 +0,0 @@ - - - -Created with Fabric.js 4.6.0 - - - - - - - - - - - - \ No newline at end of file diff --git a/freecad_workbench/freecad/robossembler/resources/icons/allpartframes.svg b/freecad_workbench/freecad/robossembler/resources/icons/allpartframes.svg deleted file mode 100644 index 11d63fa..0000000 --- a/freecad_workbench/freecad/robossembler/resources/icons/allpartframes.svg +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - ALL - - - ALL - - - - - - - - - diff --git a/freecad_workbench/freecad/robossembler/resources/icons/allpartgroups.svg b/freecad_workbench/freecad/robossembler/resources/icons/allpartgroups.svg deleted file mode 100644 index c12ed92..0000000 --- a/freecad_workbench/freecad/robossembler/resources/icons/allpartgroups.svg +++ /dev/null @@ -1,141 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/freecad_workbench/freecad/robossembler/resources/icons/assembly.ico b/freecad_workbench/freecad/robossembler/resources/icons/assembly.ico deleted file mode 100644 index 36df58d..0000000 Binary files a/freecad_workbench/freecad/robossembler/resources/icons/assembly.ico and /dev/null differ diff --git a/freecad_workbench/freecad/robossembler/resources/icons/assembly4.svg b/freecad_workbench/freecad/robossembler/resources/icons/assembly4.svg deleted file mode 100644 index ed78093..0000000 --- a/freecad_workbench/freecad/robossembler/resources/icons/assembly4.svg +++ /dev/null @@ -1,411 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - Path-Stock - 2015-07-04 - http://www.freecadweb.org/wiki/index.php?title=Artwork - - - FreeCAD - - - FreeCAD/src/Mod/Path/Gui/Resources/icons/Path-Stock.svg - - - FreeCAD LGPL2+ - - - https://www.gnu.org/copyleft/lesser.html - - - [agryson] Alexander Gryson - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/freecad_workbench/freecad/robossembler/resources/icons/auxDatum.svg b/freecad_workbench/freecad/robossembler/resources/icons/auxDatum.svg deleted file mode 100644 index c1ca8d8..0000000 --- a/freecad_workbench/freecad/robossembler/resources/icons/auxDatum.svg +++ /dev/null @@ -1,240 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - [wmayer] - - - Sketcher_Sketch - 2011-10-10 - http://www.freecadweb.org/wiki/index.php?title=Artwork - - - FreeCAD - - - FreeCAD/src/Mod/Sketcher/Gui/Resources/icons/Sketcher_Sketch.svg - - - FreeCAD LGPL2+ - - - https://www.gnu.org/copyleft/lesser.html - - - [agryson] Alexander Gryson - - - - - - - - - - - - - - - - - - - - - - - diff --git a/freecad_workbench/freecad/robossembler/resources/icons/featureframecreator.svg b/freecad_workbench/freecad/robossembler/resources/icons/featureframecreator.svg deleted file mode 100644 index a5d9ebe..0000000 --- a/freecad_workbench/freecad/robossembler/resources/icons/featureframecreator.svg +++ /dev/null @@ -1,254 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/freecad_workbench/freecad/robossembler/resources/icons/frame.svg b/freecad_workbench/freecad/robossembler/resources/icons/frame.svg deleted file mode 100644 index 6e0c4b3..0000000 --- a/freecad_workbench/freecad/robossembler/resources/icons/frame.svg +++ /dev/null @@ -1,152 +0,0 @@ - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - diff --git a/freecad_workbench/freecad/robossembler/resources/icons/free-icon-export-724827.ico b/freecad_workbench/freecad/robossembler/resources/icons/free-icon-export-724827.ico deleted file mode 100644 index 8101ed1..0000000 Binary files a/freecad_workbench/freecad/robossembler/resources/icons/free-icon-export-724827.ico and /dev/null differ diff --git a/freecad_workbench/freecad/robossembler/resources/icons/free-icon-software-5741483.png b/freecad_workbench/freecad/robossembler/resources/icons/free-icon-software-5741483.png deleted file mode 100644 index 066ccb3..0000000 Binary files a/freecad_workbench/freecad/robossembler/resources/icons/free-icon-software-5741483.png and /dev/null differ diff --git a/freecad_workbench/freecad/robossembler/resources/icons/galternatives.ico b/freecad_workbench/freecad/robossembler/resources/icons/galternatives.ico deleted file mode 100644 index c810ca6..0000000 Binary files a/freecad_workbench/freecad/robossembler/resources/icons/galternatives.ico and /dev/null differ diff --git a/freecad_workbench/freecad/robossembler/resources/icons/gazeboexport.svg b/freecad_workbench/freecad/robossembler/resources/icons/gazeboexport.svg deleted file mode 100644 index 944756d..0000000 --- a/freecad_workbench/freecad/robossembler/resources/icons/gazeboexport.svg +++ /dev/null @@ -1,80 +0,0 @@ - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - diff --git a/freecad_workbench/freecad/robossembler/resources/icons/github_preview.png b/freecad_workbench/freecad/robossembler/resources/icons/github_preview.png deleted file mode 100644 index 3da4e14..0000000 Binary files a/freecad_workbench/freecad/robossembler/resources/icons/github_preview.png and /dev/null differ diff --git a/freecad_workbench/freecad/robossembler/resources/icons/inserttask.svg b/freecad_workbench/freecad/robossembler/resources/icons/inserttask.svg deleted file mode 100644 index bc562cf..0000000 --- a/freecad_workbench/freecad/robossembler/resources/icons/inserttask.svg +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - diff --git a/freecad_workbench/freecad/robossembler/resources/icons/iteration_3316689.ico b/freecad_workbench/freecad/robossembler/resources/icons/iteration_3316689.ico deleted file mode 100644 index 9ed4218..0000000 Binary files a/freecad_workbench/freecad/robossembler/resources/icons/iteration_3316689.ico and /dev/null differ diff --git a/freecad_workbench/freecad/robossembler/resources/icons/partframe.svg b/freecad_workbench/freecad/robossembler/resources/icons/partframe.svg deleted file mode 100644 index 4a7acc5..0000000 --- a/freecad_workbench/freecad/robossembler/resources/icons/partframe.svg +++ /dev/null @@ -1,384 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - [wmayer] - - - Part_ShapeInfo - 2011-10-21 - http://www.freecadweb.org/wiki/index.php?title=Artwork - - - FreeCAD - - - FreeCAD/src/Mod/Part/Gui/Resources/icons/Part_ShapeInfo.svg - - - FreeCAD LGPL2+ - - - https://www.gnu.org/copyleft/lesser.html - - - [agryson] Alexander Gryson - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/freecad_workbench/freecad/robossembler/resources/icons/parttojson.svg b/freecad_workbench/freecad/robossembler/resources/icons/parttojson.svg deleted file mode 100644 index 2531c40..0000000 --- a/freecad_workbench/freecad/robossembler/resources/icons/parttojson.svg +++ /dev/null @@ -1,262 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/freecad_workbench/freecad/robossembler/resources/icons/placetask.svg b/freecad_workbench/freecad/robossembler/resources/icons/placetask.svg deleted file mode 100644 index b99e61b..0000000 --- a/freecad_workbench/freecad/robossembler/resources/icons/placetask.svg +++ /dev/null @@ -1,66 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - Path-BaseGeometry - 2016-05-15 - http://www.freecadweb.org/wiki/index.php?title=Artwork - - - FreeCAD - - - FreeCAD/src/Mod/Path/Gui/Resources/icons/Path-BaseGeometry.svg - - - FreeCAD LGPL2+ - - - https://www.gnu.org/copyleft/lesser.html - - - [agryson] Alexander Gryson - - - - - - - - - - - - - - - diff --git a/freecad_workbench/freecad/robossembler/resources/icons/plasetask.svg b/freecad_workbench/freecad/robossembler/resources/icons/plasetask.svg deleted file mode 100644 index c0ac862..0000000 --- a/freecad_workbench/freecad/robossembler/resources/icons/plasetask.svg +++ /dev/null @@ -1,66 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - Path-BaseGeometry - 2016-05-15 - http://www.freecadweb.org/wiki/index.php?title=Artwork - - - FreeCAD - - - FreeCAD/src/Mod/Path/Gui/Resources/icons/Path-BaseGeometry.svg - - - FreeCAD LGPL2+ - - - https://www.gnu.org/copyleft/lesser.html - - - [agryson] Alexander Gryson - - - - - - - - - - - - - - - diff --git a/freecad_workbench/freecad/robossembler/resources/icons/pngwing.com.ico b/freecad_workbench/freecad/robossembler/resources/icons/pngwing.com.ico deleted file mode 100644 index dcc5a1f..0000000 Binary files a/freecad_workbench/freecad/robossembler/resources/icons/pngwing.com.ico and /dev/null differ diff --git a/freecad_workbench/freecad/robossembler/resources/icons/publish.svg b/freecad_workbench/freecad/robossembler/resources/icons/publish.svg deleted file mode 100644 index 0cb83cd..0000000 --- a/freecad_workbench/freecad/robossembler/resources/icons/publish.svg +++ /dev/null @@ -1,175 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - Openclipart - - - - 2006-11-06T21:15:34 - A not to detailed picture of earth with land masses in dark blue. - https://openclipart.org/detail/1318/blue-earth-by-darkowl - - - darkowl - - - - - earth - geography - globe - glossy - planet - world - - - - - - - - - - - diff --git a/freecad_workbench/freecad/robossembler/resources/icons/robossembler.svg b/freecad_workbench/freecad/robossembler/resources/icons/robossembler.svg deleted file mode 100644 index 509be26..0000000 --- a/freecad_workbench/freecad/robossembler/resources/icons/robossembler.svg +++ /dev/null @@ -1,166 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - T - diff --git a/freecad_workbench/freecad/robossembler/resources/icons/screw26.ico b/freecad_workbench/freecad/robossembler/resources/icons/screw26.ico deleted file mode 100644 index 95d8fcf..0000000 Binary files a/freecad_workbench/freecad/robossembler/resources/icons/screw26.ico and /dev/null differ diff --git a/freecad_workbench/freecad/robossembler/resources/icons/screwtask.svg b/freecad_workbench/freecad/robossembler/resources/icons/screwtask.svg deleted file mode 100644 index f307cc8..0000000 --- a/freecad_workbench/freecad/robossembler/resources/icons/screwtask.svg +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - - - - - image/svg+xml - - - Path-BaseGeometry - 2016-05-15 - http://www.freecadweb.org/wiki/index.php?title=Artwork - - - FreeCAD - - - FreeCAD/src/Mod/Path/Gui/Resources/icons/Path-BaseGeometry.svg - - - FreeCAD LGPL2+ - - - https://www.gnu.org/copyleft/lesser.html - - - [agryson] Alexander Gryson - - - - - - - - - - - - - - - - - - diff --git a/freecad_workbench/freecad/robossembler/resources/icons/taskcreator.svg b/freecad_workbench/freecad/robossembler/resources/icons/taskcreator.svg deleted file mode 100644 index 49c923c..0000000 --- a/freecad_workbench/freecad/robossembler/resources/icons/taskcreator.svg +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - Path-BaseGeometry - 2016-05-15 - http://www.freecadweb.org/wiki/index.php?title=Artwork - - - FreeCAD - - - FreeCAD/src/Mod/Path/Gui/Resources/icons/Path-BaseGeometry.svg - - - FreeCAD LGPL2+ - - - https://www.gnu.org/copyleft/lesser.html - - - [agryson] Alexander Gryson - - - - - - - T - diff --git a/freecad_workbench/freecad/robossembler/resources/translations/update_translation.sh b/freecad_workbench/freecad/robossembler/resources/translations/update_translation.sh deleted file mode 100755 index b4cfaaa..0000000 --- a/freecad_workbench/freecad/robossembler/resources/translations/update_translation.sh +++ /dev/null @@ -1,112 +0,0 @@ -#!/usr/bin/env bash - -# -------------------------------------------------------------------------------------------------- -# -# Update translation files -# -# Supported locales on FreeCAD <2024-01-20, FreeCADGui.supportedLocales(), total=40>: -# {'English': 'en', 'Afrikaans': 'af', 'Arabic': 'ar', 'Basque': 'eu', 'Belarusian': 'be', -# 'Bulgarian': 'bg', 'Catalan': 'ca', 'Chinese Simplified': 'zh-CN', -# 'Chinese Traditional': 'zh-TW', 'Croatian': 'hr', 'Czech': 'cs', 'Dutch': 'nl', -# 'Filipino': 'fil', 'Finnish': 'fi', 'French': 'fr', 'Galician': 'gl', 'Georgian': 'ka', -# 'German': 'de', 'Greek': 'el', 'Hungarian': 'hu', 'Indonesian': 'id', 'Italian': 'it', -# 'Japanese': 'ja', 'Kabyle': 'kab', 'Korean': 'ko', 'Lithuanian': 'lt', 'Norwegian': 'no', -# 'Polish': 'pl', 'Portuguese': 'pt-PT', 'Portuguese, Brazilian': 'pt-BR', 'Romanian': 'ro', -# 'Russian': 'ru', 'Serbian': 'sr', 'Serbian, Latin': 'sr-CS', 'Slovak': 'sk', -# 'Slovenian': 'sl', 'Spanish': 'es-ES', 'Spanish, Argentina': 'es-AR', 'Swedish': 'sv-SE', -# 'Turkish': 'tr', 'Ukrainian': 'uk', 'Valencian': 'val-ES', 'Vietnamese': 'vi'} -# -# NOTE: WORKFLOW -# 0. Install Qt tools -# Debian-based (e.g., Ubuntu): $ sudo apt-get install qttools5-dev-tools pyqt5-dev-tools -# Fedora-based: $ sudo dnf install qt5-linguist qt5-devel -# Arch-based: $ sudo pacman -S qt5-tools python-pyqt5 -# 1. Make the script executable -# $ chmod +x update_translation.sh -# 2. Execute the script passing the locale code as first parameter -# The script has to be executed within the `resources/translations` directory -# Only update the files you're translating! -# $ ./update_translation.sh es-ES -# 3. Do the translation via Qt Linguist and use `File>Release` -# 4. If releasing with the script execute the script passing the locale code as first parameter -# and use '-r' flag next -# $ ./update_translation.sh es-ES -r -# -# -------------------------------------------------------------------------------------------------- - -supported_locales=( - "en" "af" "ar" "eu" "be" "bg" "ca" "zh-CN" "zh-TW" "hr" - "cs" "nl" "fil" "fi" "fr" "gl" "ka" "de" "el" "hu" - "id" "it" "ja" "kab" "ko" "lt" "no" "pl" "pt-PT" "pt-BR" - "ro" "ru" "sr" "es-ES" "es-AR" "sv-SE" "tr" "uk" "val-ES" "vi" -) - -is_locale_supported() { - local locale="$1" - for supported_locale in "${supported_locales[@]}"; do - if [[ "$supported_locale" == "$locale" ]]; then - return 0 - fi - done - return 1 -} - -get_strings() { - # Get translatable strings from ../ui/*.ui Qt Designer files - # lupdate ../ui/*.ui -ts uifiles.ts -no-obsolete - # Get translatable strings from ../../*.py Python files - pylupdate5 ../../*.py -ts pyfiles.ts -verbose -} - -delete_files() { - # Delete files that are no longer needed - # rm uifiles.ts - rm pyfiles.ts - rm -f ${WB}.ts -} - -add_new_locale() { - echo -e "\033[1;33m\n\t<<< Creating '${WB}_${LOCALE}.ts' file >>>\n\033[m" - get_strings - # Join strings from Qt Designer and Python files - # lconvert -i uifiles.ts pyfiles.ts -o ${WB}_${LOCALE}.ts - lconvert -source-language en -target-language $LOCALE \ - -i pyfiles.ts -o ${WB}_${LOCALE}.ts -} - -update_locale() { - echo -e "\033[1;32m\n\t<<< Updating '${WB}_${LOCALE}.ts' file >>>\n\033[m" - get_strings - # Join strings from Qt Designer and Python files - # lconvert -i uifiles.ts pyfiles.ts -o ${WB}.ts - lconvert -i pyfiles.ts -o ${WB}.ts - # Join newly created file with older file ( -no-obsolete) - lconvert -source-language en -target-language $LOCALE \ - -i ${WB}.ts ${WB}_${LOCALE}.ts -o ${WB}_${LOCALE}.ts -} - -release_translation() { - # Release translation (creation of *.qm file from *.ts file) - lrelease ${WB}_${LOCALE}.ts -} - -# Main function ------------------------------------------------------------------------------------ - -WB="robossembler" -LOCALE="$1" - -if is_locale_supported "$LOCALE"; then - if [ "$2" == "-r" ]; then - release_translation - else - if [ ! -f "${WB}_${LOCALE}.ts" ]; then - add_new_locale - else - update_locale - fi - delete_files - fi -else - echo "Verify your language code. Case sensitive." - echo "If it's correct ask a maintainer to add support for your language on FreeCAD." -fi diff --git a/freecad_workbench/freecad/robossembler/resources/translations/workbench_starterkit_es-ES.qm b/freecad_workbench/freecad/robossembler/resources/translations/workbench_starterkit_es-ES.qm deleted file mode 100644 index 0af8899..0000000 Binary files a/freecad_workbench/freecad/robossembler/resources/translations/workbench_starterkit_es-ES.qm and /dev/null differ diff --git a/freecad_workbench/freecad/robossembler/resources/translations/workbench_starterkit_es-ES.ts b/freecad_workbench/freecad/robossembler/resources/translations/workbench_starterkit_es-ES.ts deleted file mode 100644 index 4fb4c6d..0000000 --- a/freecad_workbench/freecad/robossembler/resources/translations/workbench_starterkit_es-ES.ts +++ /dev/null @@ -1,46 +0,0 @@ - - - - - Console - - - Switching to robossembler - Cambiando a entorno de trabajo cool - - - - Run a numpy function: - Ejecutar una función de numpy - - - - Menu - - - Tools - Herramientas - - - - Toolbar - - - Tools - Herramientas - - - - cool - - - template workbench - Entorno de trabajo plantilla - - - - a simple template workbench - Una plantilla simple de entorno de trabajo - - - diff --git a/freecad_workbench/freecad/robossembler/robossembler_FEM_materials/Robossembler_ABS-Dark-Rough.FCMat b/freecad_workbench/freecad/robossembler/robossembler_FEM_materials/Robossembler_ABS-Dark-Rough.FCMat deleted file mode 100644 index 49eb02a..0000000 --- a/freecad_workbench/freecad/robossembler/robossembler_FEM_materials/Robossembler_ABS-Dark-Rough.FCMat +++ /dev/null @@ -1,33 +0,0 @@ -; Robossembler_ABS-Dark-Rough -; (c) 2023 brothermechanic (CC-BY 3.0) - -[General] -Name = Robossembler_ABS-Dark-Rough -Description = Generic ABS material for Robossembler project's pipeline. -Father = Thermoplast - -[Mechanical] -Density = 1060 kg/m^3 -PoissonRatio = 0.37 -UltimateTensileStrength = 38.8 MPa -YieldStrength = 44.1 MPa -YoungsModulus = 2300 MPa - -[Thermal] -SpecificHeat = 2050 J/kg/K -ThermalConductivity = 0.158 W/m/K -ThermalExpansionCoefficient = 0.000093 m/m/K - -[Rendering] -DiffuseColor = (0.1, 0.1, 0.1, 1.0) -EmissiveColor = (0.0, 0.0, 0.0, 1.0) -Shininess = 35 -TexturePath = ~/texture.jpg -Transparency = 0.0 - -[VectorRendering] -ViewColor = (0.0, 0.0, 1.0, 1.0) - -[UserDefined] -usernum = 0.0 -userstr = String diff --git a/freecad_workbench/freecad/robossembler/robossembler_FEM_materials/Robossembler_ABS-Grey-Rough.FCMat b/freecad_workbench/freecad/robossembler/robossembler_FEM_materials/Robossembler_ABS-Grey-Rough.FCMat deleted file mode 100644 index 04ef764..0000000 --- a/freecad_workbench/freecad/robossembler/robossembler_FEM_materials/Robossembler_ABS-Grey-Rough.FCMat +++ /dev/null @@ -1,33 +0,0 @@ -; Robossembler_ABS-Grey-Rough -; (c) 2023 brothermechanic (CC-BY 3.0) - -[General] -Name = Robossembler_ABS-Grey-Rough -Description = Generic ABS material for Robossembler project's pipeline. -Father = Thermoplast - -[Mechanical] -Density = 1060 kg/m^3 -PoissonRatio = 0.37 -UltimateTensileStrength = 38.8 MPa -YieldStrength = 44.1 MPa -YoungsModulus = 2300 MPa - -[Thermal] -SpecificHeat = 2050 J/kg/K -ThermalConductivity = 0.158 W/m/K -ThermalExpansionCoefficient = 0.000093 m/m/K - -[Rendering] -DiffuseColor = (0.5, 0.5, 0.5, 1.0) -EmissiveColor = (0.0, 0.0, 0.0, 1.0) -Shininess = 35 -TexturePath = ~/texture.jpg -Transparency = 0.0 - -[VectorRendering] -ViewColor = (0.0, 0.0, 1.0, 1.0) - -[UserDefined] -usernum = 0.0 -userstr = String diff --git a/freecad_workbench/freecad/robossembler/robossembler_FEM_materials/Robossembler_ABS-White-Rough.FCMat b/freecad_workbench/freecad/robossembler/robossembler_FEM_materials/Robossembler_ABS-White-Rough.FCMat deleted file mode 100644 index e84e279..0000000 --- a/freecad_workbench/freecad/robossembler/robossembler_FEM_materials/Robossembler_ABS-White-Rough.FCMat +++ /dev/null @@ -1,33 +0,0 @@ -; Robossembler_ABS-White-Rough -; (c) 2023 brothermechanic (CC-BY 3.0) - -[General] -Name = Robossembler_ABS-White-Rough -Description = Generic ABS material for Robossembler project's pipeline. -Father = Thermoplast - -[Mechanical] -Density = 1060 kg/m^3 -PoissonRatio = 0.37 -UltimateTensileStrength = 38.8 MPa -YieldStrength = 44.1 MPa -YoungsModulus = 2300 MPa - -[Thermal] -SpecificHeat = 2050 J/kg/K -ThermalConductivity = 0.158 W/m/K -ThermalExpansionCoefficient = 0.000093 m/m/K - -[Rendering] -DiffuseColor = (0.95, 0.95, 0.95, 1.0) -EmissiveColor = (0.0, 0.0, 0.0, 1.0) -Shininess = 35 -TexturePath = ~/texture.jpg -Transparency = 0.0 - -[VectorRendering] -ViewColor = (0.0, 0.0, 1.0, 1.0) - -[UserDefined] -usernum = 0.0 -userstr = String diff --git a/freecad_workbench/freecad/robossembler/robossembler_FEM_materials/Robossembler_Al.FCMat b/freecad_workbench/freecad/robossembler/robossembler_FEM_materials/Robossembler_Al.FCMat deleted file mode 100644 index abb7e30..0000000 --- a/freecad_workbench/freecad/robossembler/robossembler_FEM_materials/Robossembler_Al.FCMat +++ /dev/null @@ -1,36 +0,0 @@ -; Robossembler_Aluminum -; (c) 2023 brothermechanic (CC-BY 3.0) - -[General] -Name = Robossembler_Al -Description = Generic Aluminum material for Robossembler project's pipeline. -Father = Metal -KindOfMaterial = Aluminium -ColorReferenceURL = https://docs.unrealengine.com/4.27/en-US/RenderingAndGraphics/Materials/PhysicallyBased/ - -[Mechanical] -Density = 2700 kg/m^3 -PoissonRatio = 0.35 -ShearModulus = 25.0 GPa -UltimateTensileStrength = 310 MPa -YoungsModulus = 70000 MPa - -[Thermal] -SpecificHeat = 897.0 J/kg/K -ThermalConductivity = 237.0 W/m/K -ThermalExpansionCoefficient = 23.1 µm/m/K - -[Electromagnetic] -ElectricalConductivity = 370370.4 S/m -RelativePermeability = 1.0 - -[Rendering] -DiffuseColor = (0.913, 0.921, 0.925, 1.0) -EmissiveColor = (0.0, 0.0, 0.0, 1.0) -Shininess = 25 -TexturePath = ~/texture.jpg -Transparency = 0.0 - -[UserDefined] -usernum = 0.0 -userstr = String diff --git a/freecad_workbench/freecad/robossembler/robossembler_FEM_materials/Robossembler_Cu.FCMat b/freecad_workbench/freecad/robossembler/robossembler_FEM_materials/Robossembler_Cu.FCMat deleted file mode 100644 index 977e9ab..0000000 --- a/freecad_workbench/freecad/robossembler/robossembler_FEM_materials/Robossembler_Cu.FCMat +++ /dev/null @@ -1,37 +0,0 @@ -; Robossembler_Copper -; (c) 2023 brothermechanic (CC-BY 3.0) - -[General] -Name = Robossembler_Cu -Description = Generic Copper material for Robossembler project's pipeline. -Father = Metal -KindOfMaterial = Copper -ColorReferenceURL = https://docs.unrealengine.com/4.27/en-US/RenderingAndGraphics/Materials/PhysicallyBased/ - -[Mechanical] -Density = 8960 kg/m^3 -PoissonRatio = 0.343 -ShearModulus = 46.0 GPa -UltimateTensileStrength = 210 MPa -YieldStrength = 33.3 MPa -YoungsModulus = 119 GPa - -[Thermal] -SpecificHeat = 385.0 J/kg/K -ThermalConductivity = 398.0 W/m/K -ThermalExpansionCoefficient = 16.5 µm/m/K - -[Electromagnetic] -ElectricalConductivity = 59.59 MS/m -RelativePermeability = 0.999994 - -[Rendering] -DiffuseColor = (0.955, 0.637, 0.538, 1.0) -EmissiveColor = (0.0, 0.0, 0.0, 1.0) -Shininess = 25 -TexturePath = ~/texture.jpg -Transparency = 0.0 - -[UserDefined] -usernum = 0.0 -userstr = String diff --git a/freecad_workbench/freecad/robossembler/robossembler_FEM_materials/Robossembler_Fe.FCMat b/freecad_workbench/freecad/robossembler/robossembler_FEM_materials/Robossembler_Fe.FCMat deleted file mode 100644 index 9038547..0000000 --- a/freecad_workbench/freecad/robossembler/robossembler_FEM_materials/Robossembler_Fe.FCMat +++ /dev/null @@ -1,37 +0,0 @@ -; Robossembler_Iron -; (c) 2023 brothermechanic (CC-BY 3.0) - -[General] -Name = Robossembler_Fe -Description = Generic Iron material for Robossembler project's pipeline. -Father = Metal -KindOfMaterial = Iron -ColorReferenceURL = https://docs.unrealengine.com/4.27/en-US/RenderingAndGraphics/Materials/PhysicallyBased/ - -[Mechanical] -Density = 7874 kg/m^3 -PoissonRatio = 0.29 -ShearModulus = 82.0 GPa -UltimateTensileStrength = 497 MPa -YieldStrength = 428 MPa -YoungsModulus = 211 GPa - -[Thermal] -SpecificHeat = 460.5 J/kg/K -ThermalConductivity = 80.4 W/m/K -ThermalExpansionCoefficient = 11.8 µm/m/K - -[Electromagnetic] -ElectricalConductivity = 10.3 MS/m -RelativePermeability = 5000.0 - -[Rendering] -DiffuseColor = (0.560, 0.570, 0.580, 1.0) -EmissiveColor = (0.0, 0.0, 0.0, 1.0) -Shininess = 25 -TexturePath = ~/texture.jpg -Transparency = 0.0 - -[UserDefined] -usernum = 0.0 -userstr = String diff --git a/freecad_workbench/freecad/robossembler/robossembler_FEM_materials/Robossembler_Steel.FCMat b/freecad_workbench/freecad/robossembler/robossembler_FEM_materials/Robossembler_Steel.FCMat deleted file mode 100644 index 036b02d..0000000 --- a/freecad_workbench/freecad/robossembler/robossembler_FEM_materials/Robossembler_Steel.FCMat +++ /dev/null @@ -1,33 +0,0 @@ -; Robossembler_Steel -; (c) 2023 brothermechanic (CC-BY 3.0) - -[General] -Name = Robossembler_Steel -Description = Generic Steel material for Robossembler project's pipeline. -Father = Metal -ColorReferenceURL = https://docs.unrealengine.com/4.27/en-US/RenderingAndGraphics/Materials/PhysicallyBased/ - -[Mechanical] -Density = 7900 kg/m^3 -PoissonRatio = 0.3 -YoungsModulus = 200000 MPa - -[Thermal] -SpecificHeat = 500 J/kg/K -ThermalConductivity = 50 W/m/K -ThermalExpansionCoefficient = 0.000012 m/m/K - -[Electromagnetic] -ElectricalConductivity = 370370.4 S/m -RelativePermeability = 1.0 - -[Rendering] -DiffuseColor = (0.550, 0.556, 0.554, 1.0) -EmissiveColor = (0.0, 0.0, 0.0, 1.0) -Shininess = 50 -TexturePath = ~/texture.jpg -Transparency = 0.0 - -[UserDefined] -usernum = 0.0 -userstr = String diff --git a/freecad_workbench/freecad/robossembler/scenarios/robossembler_freecad_export_scenario.py b/freecad_workbench/freecad/robossembler/scenarios/robossembler_freecad_export_scenario.py deleted file mode 100644 index c487650..0000000 --- a/freecad_workbench/freecad/robossembler/scenarios/robossembler_freecad_export_scenario.py +++ /dev/null @@ -1,75 +0,0 @@ -import FreeCAD -import os -import ImportGui -import shutil - -from freecad.robossembler.usecases.export_assembly_them_all_usecase import ExportAssemblyThemAllUseCase -from freecad.robossembler.usecases.export_usecase import EXPORT_TYPES -from freecad.robossembler.usecases.export_usecase import ExportUseCase -from freecad.robossembler.usecases.get_sdf_geometry_usecase import SdfGeometryUseCase -from freecad.robossembler.usecases.assembly_parse_usecase import AssemblyParseUseCase -from freecad.robossembler.usecases.geometry_usecase import GeometryUseCase -from model.geometry_part import GeometryPart -from model.files_generator import FolderGenerator -from freecad.robossembler.helper.fs import FS -from PySide import QtGui - - - -class RobossemblerFreeCadExportScenario: - - def call(self): - print(2012) - path = self.qtGuiFeature() - if path == None: - return - self.systemHelper(path) - - def qtGuiFeature(self): - if FreeCAD.ActiveDocument == None: - FreeCAD.Console.PrintError("No active document") - - p = QtGui.QFileDialog.getExistingDirectoryUrl() - path = p.path() - - if path == '': - return None - return path - - def systemHelper(self, path: str): - - root_label = FreeCAD.ActiveDocument.RootObjects[0].Label - directory = path + '/' + root_label - - if not os.path.exists(directory): - os.makedirs(directory) - - __objs__ = FreeCAD.ActiveDocument.RootObjects - directoryExport = directory + '/' - os.makedirs(directoryExport + FolderGenerator.ASSETS.value) - os.makedirs(directoryExport + FolderGenerator.SDF.value) - os.makedirs(directoryExport + FolderGenerator.SDF.value + '/' + FolderGenerator.MESHES.value) - os.makedirs(directoryExport + FolderGenerator.ASSEMBlY.value) - f = open(directory + "/step-structure.json", "w") - f.write(AssemblyParseUseCase().toJson()) - f.close() - self.geometry(directory) - ExportAssemblyThemAllUseCase().call(directoryExport) - ImportGui.export(__objs__, directoryExport + 'assembly.step') - - shutil.make_archive(directory, 'zip', directory) - - shutil.rmtree(directory) - return True - - def geometry(self, outPutsPath: str): - exportUseCase = ExportUseCase.call(outPutsPath,EXPORT_TYPES.OBJ) - for el in SdfGeometryUseCase().call(exportUseCase): - FS.writeFile(el.toJSON(), outPutsPath + - '/' + FolderGenerator.ASSETS.value + '/', el.name + '.json',) - - - - - - \ No newline at end of file diff --git a/freecad_workbench/freecad/robossembler/usecases/asm4parser_usecase.py b/freecad_workbench/freecad/robossembler/usecases/asm4parser_usecase.py deleted file mode 100644 index f732d1b..0000000 --- a/freecad_workbench/freecad/robossembler/usecases/asm4parser_usecase.py +++ /dev/null @@ -1,53 +0,0 @@ -import FreeCAD as App - -class Asm4StructureParseUseCase: - _parts = [] - _label = [] - - def getSubPartsLabel(self, group): - groupLabel = [] - for el in group: - if str(el) == '': - groupLabel.append(el.Label) - return groupLabel - - def parseLabel(self, nextGroup, label, level=2, nextGroupParse=0): - if nextGroup.__len__() == nextGroupParse: - return - else: - groupParts = [] - - for el in nextGroup: - if str(el) == '': - groupParts.append(el) - - for el in groupParts: - if str(el) == '': - label.append({ - "level": level, - "attachedTo": el.AttachedTo.split('#'), - "label": el.Label, - "axis": self.getSubPartsLabel(el.Group) - }) - - def initParse(self): - - model = App.ActiveDocument.RootObjects[1] - self._label.append({ - "level": 1, - "attachedTo": "Parent Assembly", - "label": model.Label, - "axis": self.getSubPartsLabel(model.Group) - }) - for parent in model.Group: - if str(parent) == '': - self._label.append({ - "level": 1, - "attachedTo": parent.AttachedTo.split('#'), - "label": parent.Label, - "axis": self.getSubPartsLabel(parent.Group) - }) - print(self._label) - - - \ No newline at end of file diff --git a/freecad_workbench/freecad/robossembler/usecases/assembly_parse_usecase.py b/freecad_workbench/freecad/robossembler/usecases/assembly_parse_usecase.py deleted file mode 100644 index e3b4e0d..0000000 --- a/freecad_workbench/freecad/robossembler/usecases/assembly_parse_usecase.py +++ /dev/null @@ -1,58 +0,0 @@ -import FreeCAD as App -def is_object_solid(obj): - """If obj is solid return True""" - if not isinstance(obj, App.DocumentObject): - return False - if hasattr(obj, 'Group'): - return False - - if not hasattr(obj, 'Shape'): - return False - # if not hasattr(obj.Shape, 'Mass'): - # return False - if not hasattr(obj.Shape, 'Solids'): - return False - - if len(obj.Shape.Solids) == 0: - return False - - return True - - -class AssemblyParseUseCase: - _parts = [] - - _asm = [] - - def getAsm(self): - return self._asm - - def __init__(self) -> None: - if (self._asm.__len__() == 0): - self.initParse() - pass - - def initParse(self): - for el in App.ActiveDocument.Objects: - if (is_object_solid(el)): - self._asm.append(el.Label) - - def toJson(self): - return str(self._asm).replace('\'', "\"") - - def getSubPartsLink(self, group): - groupLink = {} - for el in group: - if (is_object_solid(el)): - if str(el.Shape).find('Solid') != -1: - if groupLink.get(el.Label) == None: - groupLink[el.Label] = [] - for i in el.Group: - if str(i).find('Pad') != -1: - groupLink[el.Label].append(i) - if groupLink.__len__() == 0: - return None - return groupLink - - def getLinkedProperty(self): - return self._asm diff --git a/freecad_workbench/freecad/robossembler/usecases/export_assembly_them_all_usecase.py b/freecad_workbench/freecad/robossembler/usecases/export_assembly_them_all_usecase.py deleted file mode 100644 index f74c56f..0000000 --- a/freecad_workbench/freecad/robossembler/usecases/export_assembly_them_all_usecase.py +++ /dev/null @@ -1,92 +0,0 @@ - - -from typing import List -import FreeCAD as App -import Part -from model.join_mesh_model import JoinMeshModel -from model.mesh_part_model import MeshPartModel -from helper.fs import FS -from helper.is_solid import is_object_solid -from model.simple_copy_part_model import SimpleCopyPartModel -from model.files_generator import FolderGenerator -from usecases.assembly_parse_usecase import AssemblyParseUseCase -import importOBJ -import os -import json - - -class ExportAssemblyThemAllUseCase: - - def call(self, path): - assembly = AssemblyParseUseCase().getAsm() - asmStructure = {} - inc = 0 - for el in assembly: - if (inc != 0): - asmStructure[inc] = { - "child": el, - "parents": assembly[0:inc] - } - inc += 1 - objectsFreeCad = App.ActiveDocument.Objects - asmSolids = {} - for k, v in asmStructure.items(): - assemblyParentList = v['parents'] - assemblyChild = v['child'] - for el in assemblyParentList: - for solid in objectsFreeCad: - if (el == solid.Label): - if (asmSolids.get(k) is None): - - asmSolids[k] = {'parents': [], 'child': list( - filter(lambda x: x.Label == assemblyChild, objectsFreeCad))[0]} - - asmSolids[k]['parents'].append(solid) - - inc = 0 - for k, v in asmSolids.items(): - geometry = {"0": [], "1": []} - if (k != 0): - App.activeDocument().addObject("Part::Compound", "Compound") - - copyLinks = list( - map(lambda el: SimpleCopyPartModel(el), v['parents'])) - - if copyLinks != None: - App.activeDocument().Compound.Links = list( - map(lambda el: el.getPart(), copyLinks)) - - object = App.activeDocument().getObject('Compound') - boundBox = object.Shape.BoundBox - geometry['0'].append(boundBox.XMax) - geometry['0'].append(boundBox.YMax) - geometry['0'].append(boundBox.ZMax) - - os.makedirs( - path + FolderGenerator.ASSEMBlY.value + '/' + '0000' + str(k)) - boundBoxChild = v['child'].Shape.BoundBox - geometry['1'].append(boundBoxChild.XMax) - geometry['1'].append(boundBoxChild.YMax) - geometry['1'].append(boundBoxChild.ZMax) - meshParents = [] - - for el in v['parents']: - meshParents.append(MeshPartModel(el)) - joinMesh = JoinMeshModel(meshParents) - for el in meshParents: - el.remove() - importOBJ.export(joinMesh.mesh, path + FolderGenerator.ASSEMBlY.value + - '/' + '0000' + str(k) + '/' + str(1) + '.obj') - joinMesh.remove() - importOBJ.export(v['child'], path + FolderGenerator.ASSEMBlY.value + - '/' + '0000' + str(k) + '/' + str(0) + '.obj') - FS.writeFile(json.dumps(geometry), path + FolderGenerator.ASSEMBlY.value + - '/' + '0000' + str(k) + '/', 'translation.json') - - App.ActiveDocument.removeObject("Compound") - for el in copyLinks: - el.remove() - App.activeDocument().recompute() - inc += 1 - - diff --git a/freecad_workbench/freecad/robossembler/usecases/export_usecase.py b/freecad_workbench/freecad/robossembler/usecases/export_usecase.py deleted file mode 100644 index c4e59d8..0000000 --- a/freecad_workbench/freecad/robossembler/usecases/export_usecase.py +++ /dev/null @@ -1,36 +0,0 @@ -import importDAE -import importOBJ -import Mesh -import FreeCAD as App -from model.files_generator import FolderGenerator -from helper.is_solid import is_object_solid -from enum import Enum - -class EXPORT_TYPES(Enum): - STL = 'STL' - DAO = 'DAO' - OBJ = 'OBJ' - -#экспорт stl и urdf из freecad -class ExportUseCase: - def call(path: str, type: EXPORT_TYPES): - meshes = {} - for el in App.ActiveDocument.Objects: - if (is_object_solid(el)): - match type.value: - case EXPORT_TYPES.STL.value: - Mesh.export([el], path + '/' + FolderGenerator.SDF.value + - '/' + FolderGenerator.MESHES.value + '/' + el.Label + '.stl') - meshes[el.Label] = '/' + FolderGenerator.MESHES.value + \ - '/' + el.Label + '.stl' - - case EXPORT_TYPES.DAO.value: - importDAE.export([el], path + '/' + FolderGenerator.SDF.value + - '/' + FolderGenerator.MESHES.value + '/' + el.Label + '.dae') - case EXPORT_TYPES.OBJ.value: - importOBJ.export([el], path + '/' + FolderGenerator.SDF.value + - '/' + FolderGenerator.MESHES.value + '/' + el.Label + '.obj') - meshes[el.Label] = '/' + FolderGenerator.MESHES.value + \ - '/' + el.Label + '.obj' - - return meshes diff --git a/freecad_workbench/freecad/robossembler/usecases/geometry_usecase.py b/freecad_workbench/freecad/robossembler/usecases/geometry_usecase.py deleted file mode 100644 index 13ebfd2..0000000 --- a/freecad_workbench/freecad/robossembler/usecases/geometry_usecase.py +++ /dev/null @@ -1,58 +0,0 @@ - -import FreeCAD as App -from helper.is_solid import is_object_solid - - -class GeometryUseCase: - def call() -> dict: - labels = [] - Error = False - for el in App.ActiveDocument.Objects: - try: - - if is_object_solid(el): - labels.append(el.Label) - - geometry = { - "euler": { - "x": None, - "y": None, - "z": None - }, - "position": { - "x": None, - "y": None, - "z": None - }, - "rotation": { - "x": None, - "y": None, - "z": None - }, - "center": { - "x": None, - "y": None, - "z": None - }, - - } - - boundBox = el.Shape.BoundBox - geometry["center"]["x"] = boundBox.Center.x - geometry["center"]["y"] = boundBox.Center.y - geometry["center"]["z"] = boundBox.Center.z - geometry["position"]['x'] = boundBox.XMax - geometry["position"]['y'] = boundBox.YMax - geometry["position"]['z'] = boundBox.ZMax - rotation = el.Placement.Rotation - geometry["rotation"]['x'] = rotation.Axis.z - geometry["rotation"]['y'] = rotation.Axis.y - geometry["rotation"]['z'] = rotation.Axis.z - euler = el.Placement.Rotation.toEuler() - geometry["euler"]['x'] = euler[0] - geometry["euler"]['y'] = euler[1] - geometry["euler"]['z'] = euler[2] - except Exception as e: - print(e) - # App.Console.PrintMessage("Clicked on position: ("+str(pos[0])+", "+str(pos[1])+")\n") - return {"geometry": geometry, "labels": labels, "label": el.Label} diff --git a/freecad_workbench/freecad/robossembler/usecases/get_sdf_geometry_usecase.py b/freecad_workbench/freecad/robossembler/usecases/get_sdf_geometry_usecase.py deleted file mode 100644 index 2516164..0000000 --- a/freecad_workbench/freecad/robossembler/usecases/get_sdf_geometry_usecase.py +++ /dev/null @@ -1,81 +0,0 @@ -import FreeCAD as App -from model.sdf_geometry_model import SdfGeometryModel - -from helper.is_solid import is_object_solid - - -class SdfGeometryUseCase: - ShapePropertyCheck = ['Mass','MatrixOfInertia','Placement', ] - PartPropertyCheck = ['Shape'] - def call(self, stlPaths:dict) -> list[SdfGeometryModel]: - materialSolid = {} - for el in App.ActiveDocument.Objects: - if str(el) == '': - friction = el.Material.get('SlidingFriction') - for i in el.References: - materialSolid[i[0].Label] = friction - geometry = [] - try: - for el in App.ActiveDocument.Objects: - if is_object_solid(el): - for prop in self.PartPropertyCheck: - if prop in el: - App.Console.PrintMessage(el.Label + ' ' + 'Dont exists property: ' + prop) - return - for prop in self.ShapePropertyCheck: - if prop in el.Shape: - App.Console.PrintMessage(el.Label + ' ' + 'Dont exists property: ' + prop) - return - # com = el.Shape.CenterOfMass or el.Shape.CenterOfGravity - # if "Shape" in el: - # App.Console.PrintMessage(el.Label + ' ' + 'Dont exists Shape') - # return - # if "Mass" in el.Shape: - - mass = el.Shape.Mass - inertia = el.Shape.MatrixOfInertia - pos = el.Shape.Placement - inertia = el.Shape.MatrixOfInertia - name = el.Label - ixx = str(inertia.A11 / 1000000) - ixy = str(inertia.A12 / 1000000) - ixz = str(inertia.A13 / 1000000) - iyy = str(inertia.A22 / 1000000) - iyz = str(inertia.A23 / 1000000) - izz = str(inertia.A33 / 1000000) - massSDF = str(mass / 1000000) - posX = str(pos.Base[0] / 1000000) - posY = str(pos.Base[1] / 1000000) - posZ = str(pos.Base[2] / 1000000) - eulerX = str(pos.Rotation.toEuler()[0]) - eulerY = str(pos.Rotation.toEuler()[1]) - eulerZ = str(pos.Rotation.toEuler()[2]) - - geometry.append( - SdfGeometryModel( - stl=stlPaths.get(el.Label), - name=name, - ixx=ixx, - ixz=ixz, - ixy=ixy, - iyy=iyy, - iyz=iyz, - izz=izz, - massSDF=massSDF, - posX=posX, - posY=posY, - posZ=posZ, - eulerX=eulerX, - eulerY=eulerY, - eulerZ=eulerZ, - friction=materialSolid.get(el.Label) or '', - ) - ) - except Exception as e: - print(200) - return geometry - - - - - diff --git a/freecad_workbench/freecad/robossembler/utils/README.md b/freecad_workbench/freecad/robossembler/utils/README.md deleted file mode 100644 index fa505b2..0000000 --- a/freecad_workbench/freecad/robossembler/utils/README.md +++ /dev/null @@ -1,9 +0,0 @@ -## FreeCAD's tools for publishing .FCStd scene. - - -```python -import sys -sys.path.append('/path/to/freecad_exporters') -import freecad_exporters -freecad_exporters.publish_project_database() -``` diff --git a/freecad_workbench/freecad/robossembler/utils/__init__.py b/freecad_workbench/freecad/robossembler/utils/__init__.py deleted file mode 100644 index 88d3fa9..0000000 --- a/freecad_workbench/freecad/robossembler/utils/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# ***** BEGIN GPL LICENSE BLOCK ***** -# -# Copyright (C) 2021-2024 Robossembler LLC -# -# Created by Ilia Kurochkin (brothermechanic) -# contact: brothermechanic@yandex.com -# -# This file is part of Robossembler Framework -# project repo: https://gitlab.com/robossembler/framework -# -# Robossembler Framework 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 . -# -# ***** END GPL LICENSE BLOCK ***** -# -# coding: utf-8 -''' -DESCRIPTION. -FreeCAD modules for Robosembler project pipeline. -''' -from .freecad_exporters import publish_project_database -from .freecad_tools import get_material_paths diff --git a/freecad_workbench/freecad/robossembler/utils/freecad_exporters.py b/freecad_workbench/freecad/robossembler/utils/freecad_exporters.py deleted file mode 100644 index 0b6e917..0000000 --- a/freecad_workbench/freecad/robossembler/utils/freecad_exporters.py +++ /dev/null @@ -1,235 +0,0 @@ -''' -DESCRIPTION. -FreeCAD's tools for publishing .FCStd scene. -''' -import logging -import json -import os -import shutil -import FreeCAD -import freecad.robossembler.utils.freecad_tools as freecad_tools - -logger = logging.getLogger(__name__) -logging.basicConfig(level=logging.INFO) - - -def export_assembly_trees(doc, clones_dic=None) -> list: - ''' Read FreeCAD .FCStd hierarchy and store it to assembly JSON config files. ''' - # determine root locators - default_origins = [] - for obj in doc.Objects: - if obj.isDerivedFrom('PartDesign::CoordinateSystem'): - if (hasattr(obj, 'Robossembler_DefaultOrigin') - and getattr(obj, 'Robossembler_DefaultOrigin')): - default_origins.append(obj) - if len(default_origins) > 1: - root_locators = [] - for lcs in default_origins: - if hasattr(lcs, 'Robossembler_RootLocator'): - root_locators.append(getattr(lcs, 'Robossembler_DefaultOrigin')) - else: - logger.warning('RootLocator attribute not found for %s LCS! ' - 'So %s used as Root Locator!', - lcs.Label, lcs.InList[0].Label) - root_locators.append(lcs.InList[0]) - else: - root_locators = [ - root for root in doc.Objects - if not root.InList - if root.isDerivedFrom('App::Part')] - - trees = [] - for root_locator in root_locators: - dict_tree = {} - freecad_tools.hierarchy_tree(root_locator, dict_tree, clones_dic) - trees.append(dict_tree) - # write file - project_dir = os.path.dirname(doc.FileName) - trees_path = os.path.join(project_dir, 'trees.json') - with open(trees_path, 'w', encoding='utf-8') as json_file: - json.dump(trees, json_file, ensure_ascii=False, indent=4) - logger.info('Assembly tree saved successfully to %s!', trees_path) - - logger.info('Saved %s assembly trees!', len(trees)) - - return trees_path - - -def export_parts_database( - doc, - clones_dic=None, **tesselation_params): - ''' - Collect parts database and export as JSON config file - [ - { - 'name': '', - 'part_path': '', - 'material_path': '' - }, - {...}, - ] - ''' - # path directory - project_dir = os.path.dirname(doc.FileName) - materials_dir = os.path.join(project_dir, 'parts', 'materials') - if os.path.exists(materials_dir): - shutil.rmtree(materials_dir) - os.makedirs(materials_dir) - else: - os.makedirs(materials_dir) - objects_dir = os.path.join(project_dir, 'parts', 'objects') - if os.path.exists(objects_dir): - shutil.rmtree(objects_dir) - os.makedirs(objects_dir) - else: - os.makedirs(objects_dir) - - # collect all materials - fem_mats = [fem_mat for fem_mat in doc.Objects - if fem_mat.isDerivedFrom('App::MaterialObjectPython')] - material_paths = freecad_tools.get_material_paths() - - parts_db = [] - for obj in doc.Objects: - - # skip hidden objects - if not obj.Visibility: - continue - - # skip non part objects - if not obj.isDerivedFrom('Part::Feature'): - continue - - # skip lcs objects - if obj.isDerivedFrom('PartDesign::CoordinateSystem'): - continue - - # skip non solid part objects - forsed_nonsolid = ( - hasattr(obj, 'Robossembler_NonSolid') - and getattr(obj, 'Robossembler_NonSolid')) - if not freecad_tools.is_object_solid(obj) or forsed_nonsolid: - logger.warning('Part has non solid shape! Please check %s', obj.Label) - continue - - db_obj = { - 'name': '', - 'part_path': '', - 'material_path': '' - } - - db_obj['name'] = obj.Label - if clones_dic: - for k, v in clones_dic.items(): - if obj.Label in v: - db_obj['name'] = k - - robossembler_attrs = [attr for attr in dir(obj) if 'Robossembler' in attr] - if robossembler_attrs: - db_obj['attributes'] = [] - for attr in robossembler_attrs: - db_obj['attributes'].append({attr: getattr(obj, attr)}) - - part_path = os.path.join(objects_dir, db_obj['name'] + '.stl') - if os.path.exists(part_path): - # this is clone - continue - mesh_from_shape = freecad_tools.tesselation( - obj, doc, - # TODO adaptive=(not forsed_nonsolid), - adaptive=False, - **tesselation_params - ) - # export to stl files - #Mesh.export([mesh_from_shape], part_path, tolerance=linear_deflection) - mesh_from_shape.Mesh.write(part_path) - db_obj['part_path'] = os.path.relpath(part_path, project_dir) - logger.info('Part %s exported to stl file %s.', obj.Label, part_path) - - # find linked material path - fem_mat_name = [fem_mat.Material['CardName'] - for fem_mat in fem_mats - for ref in fem_mat.References - if ref[0].Label == obj.Label] - if fem_mat_name: - for source_path in material_paths: - if fem_mat_name[0] not in source_path: - continue - material_path = os.path.join( - materials_dir, os.path.basename(source_path)) - if not os.path.exists(material_path): - shutil.copy2(source_path, material_path) - db_obj['material_path'] = os.path.relpath(material_path, project_dir) - - # append to database - parts_db.append(db_obj) - - logger.info('Passed %s parts without errors', len(parts_db)) - parts_db_path = os.path.join(project_dir, 'parts.json') - with open(parts_db_path, 'w', encoding='utf-8') as json_file: - json.dump(parts_db, json_file, ensure_ascii=False, indent=4) - logger.info('Parts Database exported successfully to %s!', parts_db_path) - - return parts_db_path - -def save_FCStd_project(doc): - if doc is not None: - # path directory - project_path = doc.FileName - project_dir = os.path.dirname(project_path) - if project_dir: - project_dir, project_filename = os.path.split(project_path) - new_path = os.path.join(project_dir, project_filename) - FreeCAD.save(doc, new_path) - FreeCAD.Console.PrintMessage("Проект сохранен в {path}\n".format(path=str(new_path))) - else: - FreeCAD.Console.PrintError("Проект не был сохранен, поэтому невозможно сохранить с тем же именем.\n") - else: - FreeCAD.Console.PrintError("Документ не найден.\n") - - - -def publish_project_database(doc): - ''' - Publish FCStd document to CG pipeline: - - Exetute openned FreeCAD document. - - Save FCStd document to database root path. - - Export all assembly trees with LCS DefaultOrigin, - or single one as JSON hierarchy tree. - - Set tesselate solid parts to mesh. - - Export all tesselated parts to STL files. - - Return document as JSON dictionary. - ''' - tesselation_params = { - # Select tesselation method: Standard or FEM. - 'tesselation_method': 'Standard', - # Max linear distance error - 'linear_deflection': 0.1, - # Max angular distance error - 'angular_deflection': 20.0, - # For FEM method only! Finite element size in mm - 'fem_size': 10.0 - } - - # TODO Save FCStd project file - #doc.saveAs(u"//") - - clones_dic = freecad_tools.collect_clones(doc) - tree_files = export_assembly_trees(doc, clones_dic) - parts_data = export_parts_database(doc, clones_dic, **tesselation_params) - - try: - doc.save() - except OSError as e: - FreeCAD.Console.PrintError("Document Not Saved!") - else: - FreeCAD.Console.PrintMessage('FreeCAD document {s} saved!\n'.format(s=doc.Label)) - - # save_FCStd_project(doc) - - # logger.info('FreeCAD document %s published!', doc.Label) - return doc.Label - -def cmd_publish_project_database(): - doc = FreeCAD.getDocument(FreeCAD.ActiveDocument.Label) - publish_project_database(doc) \ No newline at end of file diff --git a/freecad_workbench/freecad/robossembler/utils/freecad_processor.py b/freecad_workbench/freecad/robossembler/utils/freecad_processor.py deleted file mode 100644 index 35617f5..0000000 --- a/freecad_workbench/freecad/robossembler/utils/freecad_processor.py +++ /dev/null @@ -1,17 +0,0 @@ - -import sys -import FreeCAD as App -from .freecad_exporters import publish_project_database - -def process_file(): - - filename = App.getDocument(App.ActiveDocument.Label) - publish_project_database(filename) - - -if __name__ == "__main__": - if len(sys.argv) != 2: - print("Использование: python main.py ") - else: - filename = sys.argv[1] - process_file(filename) \ No newline at end of file diff --git a/freecad_workbench/freecad/robossembler/utils/freecad_tools.py b/freecad_workbench/freecad/robossembler/utils/freecad_tools.py deleted file mode 100644 index d156024..0000000 --- a/freecad_workbench/freecad/robossembler/utils/freecad_tools.py +++ /dev/null @@ -1,306 +0,0 @@ -# ***** BEGIN GPL LICENSE BLOCK ***** -# -# Copyright (C) 2021-2024 Robossembler LLC -# -# Created by Ilia Kurochkin (brothermechanic) -# contact: brothermechanic@yandex.com -# -# This file is part of Robossembler Framework -# project repo: https://gitlab.com/robossembler/framework -# -# Robossembler Framework 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 . -# -# ***** END GPL LICENSE BLOCK ***** -# -# coding: utf-8 -''' -DESCRIPTION. -Various FreeCAD's analise, tesselation and parsing tools. -''' -__version__ = '0.5' - -import difflib -import glob -import logging -import math -import os -import xml.dom.minidom - -import FreeCAD -import Part -import MeshPart - -logger = logging.getLogger(__name__) -logging.basicConfig(level=logging.INFO) - - -def is_object_solid(obj) -> bool: - ''' - Simple FreeCAD's object test for manifold mawater-tight surface. - - :param obj: part, FreeCAD Part::Feature object - :returns: boolean of obj solid state - ''' - if not isinstance(obj, FreeCAD.DocumentObject): - return False - - if not obj.isDerivedFrom('Part::Feature'): - return False - - if obj.isDerivedFrom('PartDesign::CoordinateSystem'): - return False - - if not hasattr(obj, 'Shape'): - return False - - return obj.Shape.isClosed() - - -def collect_clones(doc) -> list: - ''' - This script find equal cad parts in a FreeCAD .FCStd scene. - - :param doc: freecad document by name or current document - :returns: {'basename': ['c1', 'c2', 'c4']} - ''' - doc_clones = {} - parts = [item for item in doc.Objects if is_object_solid(item) if item.Visibility] - for part in parts: - # collect clones lists - item_clones = [] - for other in parts: - if other == part: - continue - if (len(other.Shape.Vertexes) == len(part.Shape.Vertexes) - and len(other.Shape.Edges) == len(part.Shape.Edges) - and len(other.Shape.Faces) == len(part.Shape.Faces)): - if round(other.Shape.Volume, 7) == round(part.Shape.Volume, 7): - logger.info('Objects has equal Shapes: %s and %s ', - part.Label, other.Label) - item_clones.append(other.Label) - # if part has clones - if item_clones: - item_clones.append(part.Label) - # find common basename for all clones - idx = 0 - common_name = item_clones[0].lower() - while idx < len(item_clones): - match_data = difflib.SequenceMatcher( - None, common_name, item_clones[idx].lower() - ).find_longest_match() - common_name = common_name[match_data.a:match_data.a + match_data.size] - idx += 1 - # if names has or hasn't common patterns - item_base_name = common_name.strip(' .,_-') or item_clones[0] - # sort list names - item_clones.sort() - # add only unical list of clones - if item_clones not in doc_clones.values(): - doc_clones[item_base_name] = item_clones - return doc_clones - - -def tesselation(obj, - doc, - adaptive=False, - linear_deflection=0.1, - angular_deflection=20, - tesselation_method='Standard', - fem_size=50.0) -> list: - ''' - Perform part's shape tesselation. - ''' - shape = obj.Shape.copy() - shape.Placement = obj.Placement.inverse().multiply(shape.Placement) - mesh_from_shape = doc.addObject('Mesh::Feature', 'mesh_from_shape') - if tesselation_method == 'Standard': - mesh_from_shape.Mesh = MeshPart.meshFromShape( - Shape=shape, - LinearDeflection=linear_deflection, - AngularDeflection=math.radians(angular_deflection), - Relative=False) - elif tesselation_method == 'FEM': - mesh_from_shape.Mesh = MeshPart.meshFromShape( - Shape=shape, - MaxLength=fem_size) - else: - raise TypeError('Wrong tesselation method! ' - 'Standard and FEM methods are supported only!') - - # for solids only - volume = shape.Volume - mesh_shape = Part.Shape() - mesh_shape.makeShapeFromMesh(mesh_from_shape.Mesh.Topology, 0.100000, False) - mesh_volume = mesh_shape.Volume - - if adaptive: - deviation = 100 * (volume - mesh_volume) / volume - if deviation > 0.05: - logger.info( - 'Percentage tesselation deviation for %s object is %s! ' - 'Double increasing mesh detalisation!', - obj.Label, deviation) - linear_deflection = linear_deflection / 2 - angular_deflection = angular_deflection / 2 - doc.removeObject('mesh_from_shape') - doc.recompute() - tesselation( - obj, doc, adaptive, linear_deflection, angular_deflection, - tesselation_method, fem_size) - - return mesh_from_shape - - -def config_parser(comfig_path, param_path, param_name, param_type=None) -> str: - ''' - Parse FreeCAD XML confings - ''' - root_node = xml.dom.minidom.parse(comfig_path).childNodes[0] - node_names = ['Root'] + param_path.split('/') + [param_name] - - for node_name in node_names: - for child in root_node.childNodes: - if hasattr(child, 'getAttribute') and child.getAttribute('Name') == node_name: - root_node = child - break - else: - return None - - tagname = root_node.tagName - - if param_type is not None and tagname != param_type: - return None - - if tagname == 'FCText': - if root_node.firstChild: - return root_node.firstChild._get_data() - return '' - - if tagname == 'FCBool': - return bool(root_node.getAttribute('Value')) - - if tagname in ('FCInt', 'FCUInt'): - return int(root_node.getAttribute('Value')) - - if tagname == 'FCFloat': - return float(root_node.getAttribute('Value')) - - return root_node.getAttribute('Value') - - -def get_material_paths() -> list: - ''' - Collect all available material paths - ''' - material_paths = [] - system_dir = os.path.join( - FreeCAD.getResourceDir(), - 'Mod/Material') - material_paths.extend( - [item for item in glob.glob(f'{system_dir}/**', recursive=True) - if item.endswith('.FCMat')] - ) - user_dir = os.path.join( - FreeCAD.getUserAppDataDir(), - 'Mod/Material') - material_paths.extend( - [item for item in glob.glob(f'{user_dir}/**', recursive=True) - if item.endswith('.FCMat')] - ) - custom_dir = [] - if config_parser( - FreeCAD.ConfigGet("UserParameter"), - 'BaseApp/Preferences/Mod/Material/Resources', - 'UseMaterialsFromCustomDir', 'FCBool' - ): - custom_dir = config_parser( - FreeCAD.ConfigGet("UserParameter"), - 'BaseApp/Preferences/Mod/Material/Resources', - 'CustomMaterialsDir', 'FCText' - ) - material_paths.extend( - [item for item in glob.glob(f'{custom_dir}/**', recursive=True) - if item.endswith('.FCMat')] - ) - return material_paths - - -def hierarchy_tree(obj, dict_tree, clones_dic=None) -> dict: - ''' - Collect hierarchy tree as dict dict_tree - { - 'type': '', - 'name': '', - 'base_name': '', - 'pose': [{'loc_xyz': []}, {'rot_xyzw': []}], - 'attributes': [], - 'children': [ - { - 'type': '', - 'name': '', - 'base_name': '', - 'loc_xyz': [], - 'rot_xyzw': [], - 'attributes': [], - 'children': [...] - }, - {...}, - ] - } - ''' - # collect type - if obj.isDerivedFrom('Part::Feature'): - if obj.isDerivedFrom('PartDesign::CoordinateSystem'): - dict_tree['type'] = 'LCS' - else: - dict_tree['type'] = 'PART' - elif obj.isDerivedFrom('App::Part'): - dict_tree['type'] = 'LOCATOR' - else: - return False - # collect name - dict_tree['name'] = obj.Label - # collect base_name - if clones_dic: - if obj.isDerivedFrom('Part::Feature') and ( - not obj.isDerivedFrom('PartDesign::CoordinateSystem')): - dict_tree['base_name'] = obj.Label - for k, v in clones_dic.items(): - if obj.Label in v: - dict_tree['base_name'] = k - # collect transforms - dict_tree['pose'] = [ - {'loc_xyz': list(obj.Placement.Base)}, - {'rot_xyzw': list(obj.Placement.Rotation.Q)} - ] - # collect attributes - dict_tree['attributes'] = [] - robossembler_attrs = [attr for attr in dir(obj) if 'Robossembler' in attr] - if robossembler_attrs: - for attr in robossembler_attrs: - dict_tree['attributes'].append({attr: getattr(obj, attr)}) - # collect children for LOCATOR only - if obj.OutList and obj.isDerivedFrom('App::Part'): - dict_tree['children'] = [] - for child in obj.OutList: - # skip hidden objects - if not child.Visibility: - continue - # skip helper objects - if (child.isDerivedFrom('Part::Feature') - or child.isDerivedFrom('App::Part')): - dict_tree['children'].append({}) - hierarchy_tree(child, dict_tree['children'][-1], clones_dic) - return True diff --git a/freecad_workbench/freecad/robossembler/valid_sequences.py b/freecad_workbench/freecad/robossembler/valid_sequences.py deleted file mode 100644 index 7bf1387..0000000 --- a/freecad_workbench/freecad/robossembler/valid_sequences.py +++ /dev/null @@ -1,36 +0,0 @@ -import json - -def load_data(file_path): - with open(file_path, 'r') as file: - return json.load(file) - -def is_valid_sequence(sequence, constraints): - for constraint in constraints: - if constraint[0] in sequence and constraint[1] in sequence: - if sequence.index(constraint[0]) > sequence.index(constraint[1]): - return False - return True - -def save_sequences(sequences, file_path): - with open(file_path, 'w') as file: - json.dump(sequences, file, indent=4) - -# Load data from files -adjacency_matrix = load_data('adjacency_matrix.json') -constraints = load_data('constraints.json') -sequences = load_data('sequences.json') - -# Get all parts and first detail -all_parts = adjacency_matrix['allParts'] -first_detail = adjacency_matrix['firstDetail'] - -# Filter valid sequences -valid_sequences = [] -for sequence in sequences: - if len(set(sequence)) == len(set(all_parts)): #and is_valid_sequence(sequence, constraints): - valid_sequences.append(sequence) - -# Save valid sequences to file -save_sequences(valid_sequences, 'valid_sequences.json') - -print(f"Найдено {len(valid_sequences)} допустимых последовательностей сборки.") diff --git a/freecad_workbench/freecad/robossembler/version.py b/freecad_workbench/freecad/robossembler/version.py deleted file mode 100644 index 49f34f4..0000000 --- a/freecad_workbench/freecad/robossembler/version.py +++ /dev/null @@ -1 +0,0 @@ -__version__ = "0.2.0" \ No newline at end of file diff --git a/freecad_workbench/freecad/update_workbench.sh b/freecad_workbench/freecad/update_workbench.sh deleted file mode 100755 index 3ac11df..0000000 --- a/freecad_workbench/freecad/update_workbench.sh +++ /dev/null @@ -1,29 +0,0 @@ -#!/bin/bash - -# Укажите путь к папке, которую нужно скопировать -SOURCE_DIR="/home/markvoltov/GitProjects/framework/freecad_workbench/freecad/robossembler" - -# Укажите путь к папке, которую нужно заменить -DEST_DIR="/home/markvoltov/.local/share/FreeCAD/Mod/freecad_workbench" - -# Проверка, что исходная папка существует -if [ ! -d "$SOURCE_DIR" ]; then - echo "Исходная папка не существует: $SOURCE_DIR" - exit 1 -fi - -# Удаление содержимого папки назначения -if [ -d "$DEST_DIR" ]; then - echo "Удаление содержимого папки назначения: $DEST_DIR" - rm -rf "$DEST_DIR/*" -else - # Создание папки назначения, если её нет - echo "Создание папки назначения: $DEST_DIR" - mkdir -p "$DEST_DIR" -fi - -# Копирование содержимого исходной папки в папку назначения -echo "Копирование содержимого из $SOURCE_DIR в $DEST_DIR" -cp -r "$SOURCE_DIR/." "$DEST_DIR/" - -echo "Копирование завершено" diff --git a/freecad_workbench/setup.py b/freecad_workbench/setup.py deleted file mode 100644 index b0bd9d3..0000000 --- a/freecad_workbench/setup.py +++ /dev/null @@ -1,22 +0,0 @@ -from setuptools import setup -import os -# from freecad.robossembler.version import __version__ -# name: this is the name of the distribution. -# Packages using the same name here cannot be installed together - -version_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), - "freecad", "robossembler", "version.py") -with open(version_path) as fp: - exec(fp.read()) - -setup(name='freecad.robossembler', - version=str(__version__), - packages=['freecad', - 'freecad.robossembler', - 'freecad.robossembler.utils'], - maintainer="Mark Voltov", - maintainer_email="ius.mark.alex@gmail.com", - url="https://gitlab.com/robossembler/framework", - description="FreeCAD Robossembler Workbench - Assembly Sequence Planning, Analysis", - install_requires=[], # should be satisfied by FreeCAD's system dependencies already - include_package_data=True) diff --git a/rcg_pipeline b/rcg_pipeline new file mode 160000 index 0000000..768f372 --- /dev/null +++ b/rcg_pipeline @@ -0,0 +1 @@ +Subproject commit 768f372edc214ca16e6d54660ca0cca2932b9a99 diff --git a/rcg_pipeline/LICENSE b/rcg_pipeline/LICENSE deleted file mode 100644 index 6fb6a01..0000000 --- a/rcg_pipeline/LICENSE +++ /dev/null @@ -1,157 +0,0 @@ -# GNU LESSER GENERAL PUBLIC LICENSE - -Version 3, 29 June 2007 - -Copyright (C) 2007 Free Software Foundation, Inc. - - -Everyone is permitted to copy and distribute verbatim copies of this -license document, but changing it is not allowed. - -This version of the GNU Lesser General Public License incorporates the -terms and conditions of version 3 of the GNU General Public License, -supplemented by the additional permissions listed below. - -## 0. Additional Definitions. - -As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the -GNU General Public License. - -"The Library" refers to a covered work governed by this License, other -than an Application or a Combined Work as defined below. - -An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - -A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - -The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - -The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - -## 1. Exception to Section 3 of the GNU GPL. - -You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - -## 2. Conveying Modified Versions. - -If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - -- a) under this License, provided that you make a good faith effort - to ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or -- b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - -## 3. Object Code Incorporating Material from Library Header Files. - -The object code form of an Application may incorporate material from a -header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - -- a) Give prominent notice with each copy of the object code that - the Library is used in it and that the Library and its use are - covered by this License. -- b) Accompany the object code with a copy of the GNU GPL and this - license document. - -## 4. Combined Works. - -You may convey a Combined Work under terms of your choice that, taken -together, effectively do not restrict modification of the portions of -the Library contained in the Combined Work and reverse engineering for -debugging such modifications, if you also do each of the following: - -- a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. -- b) Accompany the Combined Work with a copy of the GNU GPL and this - license document. -- c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. -- d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of - this License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with - the Library. A suitable mechanism is one that (a) uses at run - time a copy of the Library already present on the user's - computer system, and (b) will operate properly with a modified - version of the Library that is interface-compatible with the - Linked Version. -- e) Provide Installation Information, but only if you would - otherwise be required to provide such information under section 6 - of the GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the Application - with a modified version of the Linked Version. (If you use option - 4d0, the Installation Information must accompany the Minimal - Corresponding Source and Corresponding Application Code. If you - use option 4d1, you must provide the Installation Information in - the manner specified by section 6 of the GNU GPL for conveying - Corresponding Source.) - -## 5. Combined Libraries. - -You may place library facilities that are a work based on the Library -side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - -- a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities, conveyed under the terms of this License. -- b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - -## 6. Revised Versions of the GNU Lesser General Public License. - -The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser 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 Library -as you received it specifies that a certain numbered version of the -GNU Lesser General Public License "or any later version" applies to -it, you have the option of following the terms and conditions either -of that published version or of any later version published by the -Free Software Foundation. If the Library as you received it does not -specify a version number of the GNU Lesser General Public License, you -may choose any version of the GNU Lesser General Public License ever -published by the Free Software Foundation. - -If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. diff --git a/rcg_pipeline/Makefile b/rcg_pipeline/Makefile deleted file mode 100644 index 0e844dc..0000000 --- a/rcg_pipeline/Makefile +++ /dev/null @@ -1,31 +0,0 @@ -.FORCE: - -BLUE=\033[0;34m -BLACK=\033[0;30m - -help: - @echo "$(BLUE) make test - run all unit tests" - @echo " make coverage - run unit tests and coverage report" - @echo " make dist - build dist files" - @echo " make upload - upload to PyPI" - @echo " make clean - remove dist and docs build files" - @echo " make help - this message$(BLACK)" - -test: - pytest - -coverage: - coverage run --omit=\*/test_\* -m unittest - coverage report - -dist: .FORCE - #$(MAKE) test - python -m build - ls -lh dist - -upload: .FORCE - twine upload dist/* - -clean: .FORCE - -rm -r *.egg-info - -rm -r dist build diff --git a/rcg_pipeline/README.md b/rcg_pipeline/README.md deleted file mode 100644 index e4791f5..0000000 --- a/rcg_pipeline/README.md +++ /dev/null @@ -1,35 +0,0 @@ -## Robossembler CG Pipeline - -Алгоритмы запуска технологии компьютерной графики. - -Пакетное производство 3д ассетов из базы данных тесселированных объектов САПР (parts) их сборочной иерархии. - -Поддерживается работа поверх Blender в качестве модуля! - -Этапы алгоритма: - -* генерация Blender сцены, -* исправоение parts объектов, -* генерация и назначение CG материала parts объектам, -* перестроение иерархии сборок на основе данных LCS объектов, -* группировка parts объектов объектов в составные RENDER ассеты, -* генерация, и развертка монолитных VISUAL ассетов из RENDER ассетов, -* запекание поверхности и материала RENDER ассетоа в текстуры VISUAL ассетов, -* назначение материалов и тестур VISUAL ассетам, -* генерация COLLISION ассетов из VISUAL ассетов, -- экспорт всех типов ассетов в требуемые форматы базы данных. - -Пример запуска:: -```python -# nixGL /nix/store/gd3shnza1i50zn8zs04fa729ribr88m9-python3-3.11.8/bin/python3 - -import sys -sys.path.append('/nix/store/-bpy-4.1.0/lib/python3.11/site-packages') -sys.path.append('/path/to/rcg_pipeline') -sys.path.append('/nix/store/-python3.11-numpy-1.26.4/lib/python3.11/site-packages') -import rcg_pipeline -project_dir = '/path/to/' - -rcg_pipeline.libs.generate_libs_database(project_dir) -rcg_pipeline.render_asset.build_render_assets(project_dir) -``` diff --git a/rcg_pipeline/pyproject.toml b/rcg_pipeline/pyproject.toml deleted file mode 100644 index f17dea1..0000000 --- a/rcg_pipeline/pyproject.toml +++ /dev/null @@ -1,29 +0,0 @@ -[build-system] -requires = ["setuptools >= 69.0"] -build-backend = "setuptools.build_meta" - -[tool.setuptools] -packages = ["rcg_pipeline", "rcg_pipeline.export", "rcg_pipeline.utils"] - -[project] -name = "rcg_pipeline" -version = "1.0.0" -description = "Robossembler CG Pipeline" -readme = "README.md" -license = {file = "LICENSE"} -authors = [{name = "Ilia Kurochkin", email = "brothermechanic@yandex.com"}] -maintainers = [{name = "Igor Brylyov", email = "movefasta@dezcom.org"}] -requires-python = ">= 3.10" -dependencies = ["numpy >= 1.26.4", "bpy >= 4.1.0"] -classifiers = [ - "Development Status :: 3 - Alpha", - "Programming Language :: Python :: 3", - "Operating System :: Linux", -] -keywords = ["cg", "robossembler", "blender", "engineering", "robotics", "gamedev"] - -[project.urls] -Homepage = "https://robossembler.org/" -Documentation = "https://robossembler.org/docs/technologies/cad-cg-pipeline" -Repository = "https://gitlab.com/robossembler/framework.git" -Issues = "https://gitlab.com/robossembler/framework/-/issues" diff --git a/rcg_pipeline/rcg_pipeline/__init__.py b/rcg_pipeline/rcg_pipeline/__init__.py deleted file mode 100644 index 14bd09b..0000000 --- a/rcg_pipeline/rcg_pipeline/__init__.py +++ /dev/null @@ -1,62 +0,0 @@ -# ***** BEGIN GPL LICENSE BLOCK ***** -# -# Copyright (C) 2021-2024 Robossembler LLC -# -# Created by Ilia Kurochkin (brothermechanic) -# contact: brothermechanic@yandex.com -# -# This file is part of Robossembler Framework -# project repo: https://gitlab.com/robossembler/framework -# -# Robossembler Framework 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 . -# -# ***** END GPL LICENSE BLOCK ***** -# -# coding: utf-8 -''' -DESCRIPTION. -Computer Graphics Pipeline for Robossembler Framework. -Batch production of 3d assets from the database -of tessellated CAD objects (parts) and their assembling hierarchy. -''' - -__title__ = 'Robossembler CG Pipeline' -__version__ = '1.0.0' -__author__ = 'Ilia Kurochkin' -__email__ = 'brothermechanic@yandex.com' -__copyright__ = 'Copyright (C) 2021-2024 Robossembler LLC' -__url__ = ['https://robossembler.org'] -__license__ = 'GPL-3' -#__all__ = ['libs', 'render_asset', 'rcg_full_pipeline'] - -import logging - -from . import libs -from . import render_asset - -logger = logging.getLogger(__name__) -logging.basicConfig(level=logging.INFO) - - -def rcg_full_pipeline(project_dir): - ''' - ''' - # 1 generate libs - libs.generate_libs_database(project_dir) - - # 2 build render assets - render_asset.build_render_assets(project_dir) - - return True diff --git a/rcg_pipeline/rcg_pipeline/export/__init__.py b/rcg_pipeline/rcg_pipeline/export/__init__.py deleted file mode 100644 index 8f79be7..0000000 --- a/rcg_pipeline/rcg_pipeline/export/__init__.py +++ /dev/null @@ -1,77 +0,0 @@ -# ***** BEGIN GPL LICENSE BLOCK ***** -# -# Copyright (C) 2024 Ilia Kurochkin -# -# Created by Ilia Kurochkin (brothermechanic) -# contact: brothermechanic@yandex.com -# -# This 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 . -# -# ***** END GPL LICENSE BLOCK ***** -# -# coding: utf-8 -''' -DESCRIPTION. -Decorator for export functions. -''' - -import os -import bpy -import mathutils - - -def export_decorator(func): - - def wrapper(**kwargs): - bpy.ops.object.select_all(action='DESELECT') - # add defaults - kwargs.setdefault('global_scale', 1000) - kwargs.setdefault('axis_forward', 'Y') - kwargs.setdefault('axis_up', 'Z') - kwargs.setdefault('file_dir', '//') - kwargs.setdefault('sub_dir', '') - kwargs.setdefault('reset_transforms', False) - - if kwargs['reset_transforms']: - obj = bpy.data.objects.get(kwargs['obj_name']) - obj.name = kwargs['obj_name'] + '_orig' - obj_data = obj.data.copy() - obj_tmp = obj.copy() - obj_tmp.data = obj_data - obj_tmp.name = kwargs['obj_name'] - bpy.context.collection.objects.link(obj_tmp) - obj_tmp.parent = None - obj_tmp.matrix_world = mathutils.Matrix() - - obj = bpy.data.objects.get(kwargs['obj_name']) - # deselect all but just one object and make it active - bpy.ops.object.select_all(action='DESELECT') - obj.select_set(state=True) - bpy.context.view_layer.objects.active = obj - file_dir = os.path.join(kwargs['file_dir'], kwargs['sub_dir']) - os.makedirs(file_dir, exist_ok=True) - kwargs['outpath'] = os.path.join(file_dir, kwargs['obj_name']) - # return export function - file_path = func(**kwargs) - - #cleanup temporary object - if kwargs['reset_transforms']: - bpy.data.objects.remove(obj, do_unlink=True) - obj = bpy.data.objects.get(kwargs['obj_name'] + '_orig') - obj.name = kwargs['obj_name'] - - return file_path - - return wrapper diff --git a/rcg_pipeline/rcg_pipeline/export/dae.py b/rcg_pipeline/rcg_pipeline/export/dae.py deleted file mode 100644 index 18ac50e..0000000 --- a/rcg_pipeline/rcg_pipeline/export/dae.py +++ /dev/null @@ -1,75 +0,0 @@ -# ***** BEGIN GPL LICENSE BLOCK ***** -# -# Copyright (C) 2024 Ilia Kurochkin -# -# Created by Ilia Kurochkin (brothermechanic) -# contact: brothermechanic@yandex.com -# -# This 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 . -# -# ***** END GPL LICENSE BLOCK ***** -# -# coding: utf-8 -''' -DESCRIPTION. -Collada object exporter. -''' - -__version__ = '0.3' - -import bpy -from . import export_decorator - - -@export_decorator -def export(**kwargs): - file_path = ('{}.dae'.format(kwargs['outpath'])) - - bpy.ops.wm.collada_export( - filepath=file_path, - check_existing=False, - apply_modifiers=True, - export_mesh_type=0, - export_mesh_type_selection='view', - export_global_forward_selection=kwargs['axis_forward'], - export_global_up_selection=kwargs['axis_up'], - apply_global_orientation=False, - selected=True, - include_children=False, - include_armatures=False, - include_shapekeys=False, - deform_bones_only=False, - include_animations=False, - include_all_actions=True, - export_animation_type_selection='sample', - sampling_rate=1, - keep_smooth_curves=False, - keep_keyframes=False, - keep_flat_curves=False, - active_uv_only=False, - use_texture_copies=True, - triangulate=True, - use_object_instantiation=True, - use_blender_profile=True, - sort_by_name=False, - export_object_transformation_type=0, - export_object_transformation_type_selection='matrix', - export_animation_transformation_type=0, - export_animation_transformation_type_selection='matrix', - open_sim=False, - limit_precision=False, - keep_bind_info=False) - - return file_path diff --git a/rcg_pipeline/rcg_pipeline/export/fbx.py b/rcg_pipeline/rcg_pipeline/export/fbx.py deleted file mode 100644 index 41848f6..0000000 --- a/rcg_pipeline/rcg_pipeline/export/fbx.py +++ /dev/null @@ -1,84 +0,0 @@ -# ***** BEGIN GPL LICENSE BLOCK ***** -# -# Copyright (C) 2024 Ilia Kurochkin -# -# Created by Ilia Kurochkin (brothermechanic) -# contact: brothermechanic@yandex.com -# -# This 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 . -# -# ***** END GPL LICENSE BLOCK ***** -# -# coding: utf-8 -''' -DESCRIPTION. -FBX object exporter. -''' - -__version__ = "0.3" - -import bpy -from . import export_decorator - - -@export_decorator -def export(**kwargs): - file_path = ('{}.fbx'.format(kwargs['outpath'])) - - bpy.ops.export_scene.fbx( - filepath=file_path, - check_existing=False, - filter_glob="*.fbx", - use_selection=True, - use_visible=False, - use_active_collection=False, - global_scale=1, - apply_unit_scale=True, - apply_scale_options='FBX_SCALE_NONE', - use_space_transform=True, - bake_space_transform=False, - object_types={'MESH'}, - use_mesh_modifiers=True, - use_mesh_modifiers_render=True, - mesh_smooth_type='FACE', - colors_type='SRGB', - use_subsurf=False, - use_mesh_edges=False, - use_tspace=False, - use_triangles=True, - use_custom_props=False, - add_leaf_bones=True, - primary_bone_axis='Y', - secondary_bone_axis='X', - use_armature_deform_only=False, - armature_nodetype='NULL', - bake_anim=False, - bake_anim_use_all_bones=True, - bake_anim_use_nla_strips=True, - bake_anim_use_all_actions=True, - bake_anim_force_startend_keying=True, - bake_anim_step=1, - bake_anim_simplify_factor=1, - path_mode='AUTO', - embed_textures=False, - batch_mode='OFF', - use_batch_own_dir=True, - use_metadata=True, - # '-Z' - axis_forward=kwargs['axis_forward'], - # 'Y' - axis_up=kwargs['axis_up']) - - return file_path diff --git a/rcg_pipeline/rcg_pipeline/export/glb.py b/rcg_pipeline/rcg_pipeline/export/glb.py deleted file mode 100644 index 9195d4c..0000000 --- a/rcg_pipeline/rcg_pipeline/export/glb.py +++ /dev/null @@ -1,84 +0,0 @@ -# ***** BEGIN GPL LICENSE BLOCK ***** -# -# Copyright (C) 2024 Ilia Kurochkin -# -# Created by Ilia Kurochkin (brothermechanic) -# contact: brothermechanic@yandex.com -# -# This 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 . -# -# ***** END GPL LICENSE BLOCK ***** -# -# coding: utf-8 -''' -DESCRIPTION. -glTF object exporter. -''' - -__version__ = "0.3" - -import bpy -from . import export_decorator - - -@export_decorator -def export(**kwargs): - file_path = ('{}.glb'.format(kwargs['outpath'])) - - bpy.ops.export_scene.gltf( - filepath=file_path, - check_existing=False, - gltf_export_id="", - export_use_gltfpack=False, - export_format='GLB', - export_copyright="glTF object exporter", - export_image_format='AUTO', - export_image_add_webp=False, - export_image_webp_fallback=False, - export_texture_dir="", - export_jpeg_quality=75, - export_image_quality=75, - export_keep_originals=False, - export_texcoords=True, - export_normals=True, - # no custom - export_draco_mesh_compression_enable=False, - export_tangents=False, - export_materials='EXPORT', - export_unused_images=False, - export_unused_textures=False, - export_attributes=False, - # custom - use_selection=True, - use_visible=False, - use_renderable=False, - use_active_collection_with_nested=True, - use_active_collection=False, - use_active_scene=False, - export_extras=False, - # no custom - export_yup=True, - export_apply=False, - # custom - export_animations=False, - # custom - export_morph=False, - export_skins=False, - export_hierarchy_flatten_bones=False, - export_original_specular=False, - will_save_settings=False, - export_hierarchy_full_collections=False) - - return file_path diff --git a/rcg_pipeline/rcg_pipeline/export/obj.py b/rcg_pipeline/rcg_pipeline/export/obj.py deleted file mode 100644 index 476d73a..0000000 --- a/rcg_pipeline/rcg_pipeline/export/obj.py +++ /dev/null @@ -1,58 +0,0 @@ -# ***** BEGIN GPL LICENSE BLOCK ***** -# -# Copyright (C) 2024 Ilia Kurochkin -# -# Created by Ilia Kurochkin (brothermechanic) -# contact: brothermechanic@yandex.com -# -# This 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 . -# -# ***** END GPL LICENSE BLOCK ***** -# -# coding: utf-8 -''' -DESCRIPTION. -obj object exporter. -''' - -__version__ = "0.1" - -import bpy -from . import export_decorator - - -@export_decorator -def export(**kwargs): - file_path = ('{}.obj'.format(kwargs['outpath'])) - - bpy.ops.wm.obj_export( - filepath=file_path, - check_existing=False, - export_animation=False, - forward_axis='NEGATIVE_Z', - up_axis='Y', - global_scale=1, - apply_modifiers=True, - export_selected_objects=True, - export_uv=True, - export_normals=True, - export_colors=True, - export_materials=True, - export_pbr_extensions=False, - path_mode='AUTO', - export_triangulated_mesh=True, - export_smooth_groups=True) - - return file_path diff --git a/rcg_pipeline/rcg_pipeline/export/ply.py b/rcg_pipeline/rcg_pipeline/export/ply.py deleted file mode 100644 index aeca279..0000000 --- a/rcg_pipeline/rcg_pipeline/export/ply.py +++ /dev/null @@ -1,55 +0,0 @@ -# ***** BEGIN GPL LICENSE BLOCK ***** -# -# Copyright (C) 2024 Ilia Kurochkin -# -# Created by Ilia Kurochkin (brothermechanic) -# contact: brothermechanic@yandex.com -# -# This 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 . -# -# ***** END GPL LICENSE BLOCK ***** -# -# coding: utf-8 -''' -DESCRIPTION. -PLY object exporter. -''' - -__version__ = "0.3" - -import bpy -from . import export_decorator - - -@export_decorator -def export(**kwargs): - file_path = ('{}.ply'.format(kwargs['outpath'])) - - bpy.ops.wm.ply_export( - filepath=file_path, - check_existing=False, - forward_axis=kwargs['axis_forward'], - up_axis=kwargs['axis_up'], - global_scale=kwargs['global_scale'], - apply_modifiers=True, - export_selected_objects=True, - export_uv=True, - export_normals=True, - export_colors='SRGB', - export_attributes=True, - export_triangulated_mesh=True, - ascii_format=True) - - return file_path diff --git a/rcg_pipeline/rcg_pipeline/export/stl.py b/rcg_pipeline/rcg_pipeline/export/stl.py deleted file mode 100644 index 93b549c..0000000 --- a/rcg_pipeline/rcg_pipeline/export/stl.py +++ /dev/null @@ -1,52 +0,0 @@ -# ***** BEGIN GPL LICENSE BLOCK ***** -# -# Copyright (C) 2024 Ilia Kurochkin -# -# Created by Ilia Kurochkin (brothermechanic) -# contact: brothermechanic@yandex.com -# -# This 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 . -# -# ***** END GPL LICENSE BLOCK ***** -# -# coding: utf-8 -''' -DESCRIPTION. -STL object exporter. -''' - -__version__ = '0.3' - -import bpy -from . import export_decorator - - -@export_decorator -def export(**kwargs): - file_path = ('{}.stl'.format(kwargs['outpath'])) - - bpy.ops.wm.stl_export( - filepath=file_path, - check_existing=False, - ascii_format=False, - use_batch=False, - export_selected_objects=True, - global_scale=kwargs['global_scale'], - use_scene_unit=False, - forward_axis=kwargs['axis_forward'], - up_axis=kwargs['axis_up'], - apply_modifiers=True) - - return file_path diff --git a/rcg_pipeline/rcg_pipeline/libs.py b/rcg_pipeline/rcg_pipeline/libs.py deleted file mode 100644 index 710b285..0000000 --- a/rcg_pipeline/rcg_pipeline/libs.py +++ /dev/null @@ -1,204 +0,0 @@ -# ***** BEGIN GPL LICENSE BLOCK ***** -# -# Copyright (C) 2021-2024 Robossembler LLC -# -# Created by Ilia Kurochkin (brothermechanic) -# contact: brothermechanic@yandex.com -# -# This file is part of Robossembler Framework -# project repo: https://gitlab.com/robossembler/framework -# -# Robossembler Framework 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 . -# -# ***** END GPL LICENSE BLOCK ***** -# -# coding: utf-8 -''' -DESCRIPTION. -Generate CG libs database for Robossembler Framework. -''' - -__version__ = '1.0' - -import logging -import json -import math -import os -import shutil - -import bpy - -from .utils.collection_tools import remove_collections_with_objects -from .utils.cleanup_orphan_data import cleanup_orphan_data -from .utils.object_transforms import apply_transforms -from .material_generators import material_generator, black_material -from .utils.object_converter import mesh_to_mesh -from .export import dae, fbx, glb, ply -import .export.obj as obj_export -logger = logging.getLogger(__name__) - - -def generate_libs_database(project_dir): - ''' Generate Blender LIBS database from PARTs database. ''' - parts_data_path = os.path.join(project_dir, 'parts.json') - if not os.path.exists(parts_data_path): - raise Exception('No parts database found! Check %s directory' % project_dir) - with open(parts_data_path, encoding='utf-8') as data: - parts_data = json.load(data) - - libs_data = [] - - # material libs - materials_dir = os.path.join(project_dir, 'libs', 'materials') - if os.path.exists(materials_dir): - shutil.rmtree(materials_dir) - os.makedirs(materials_dir) - else: - os.makedirs(materials_dir) - - for part in parts_data: - bpy.ops.wm.read_homefile() - obj = bpy.data.objects['Cube'] - if not part.get('material_path'): - continue - material_name = os.path.splitext(os.path.basename(part['material_path']))[0] - # do not regenerate exists material - material_in_libs = False - for lib in libs_data: - if lib['type'] == 'MATERIAL' and lib['name'] == material_name: - material_in_libs = True - break - if material_in_libs: - continue - # generate material - mat = material_generator(obj, os.path.join(project_dir, part['material_path'])) - bpy.data.materials[mat.name].use_fake_user = True - remove_collections_with_objects() - cleanup_orphan_data() - bpy.data.materials.remove(bpy.data.materials['Dots Stroke']) - bpy.ops.wm.previews_ensure() - - img = bpy.data.images.new(mat.name, *mat.preview.image_size, alpha=True) - img.pixels.foreach_set(mat.preview.image_pixels_float) - img_path = os.path.join(materials_dir, mat.name + '.png') - img.save(filepath=img_path) - - blend_path = os.path.join(materials_dir, mat.name + '.blend') - logger.info('Material stored as libs %s to %s.', mat.name, materials_dir) - bpy.ops.wm.save_as_mainfile(filepath=blend_path, compress=True) - - libs_data.append( - { - 'type': mat.rna_type.name.upper(), - 'name': mat.name, - 'path': os.path.relpath(blend_path, project_dir), - 'thumbnail': os.path.relpath(img_path, project_dir), - } - ) - - # object libs - objects_dir = os.path.join(project_dir, 'libs', 'objects') - if os.path.exists(objects_dir): - shutil.rmtree(objects_dir) - os.makedirs(objects_dir) - else: - os.makedirs(objects_dir) - - for part in parts_data: - bpy.ops.wm.read_homefile() - remove_collections_with_objects() - cleanup_orphan_data() - obj_collection = bpy.data.collections.new(part['name']) - bpy.context.scene.collection.children.link(obj_collection) - # set active to collection - active_collection = bpy.context.view_layer.layer_collection.children[part['name']] - bpy.context.view_layer.active_layer_collection = active_collection - # import stl file - bpy.ops.wm.stl_import( - filepath=os.path.join(project_dir, part['part_path']), - global_scale=0.001, - use_facet_normal=False, - forward_axis='Y', - up_axis='Z') - obj = bpy.data.objects.get(part['name']) - if not obj: - raise Exception('STL Import Fail for %s' % part['name']) - apply_transforms(obj, scale=True) - # setup material - if part.get('material_path'): - material_name = os.path.splitext(os.path.basename(part['material_path']))[0] - for lib in libs_data: - if lib['type'] == 'MATERIAL' and lib['name'] == material_name: - lib_path = os.path.join(project_dir, lib['path']) - bpy.ops.wm.link( - filepath=lib_path, - directory=os.path.join(lib_path, 'Material'), - filename=lib['name'], - relative_path=True, - do_reuse_local_id=True) - obj.data.materials.append(bpy.data.materials[lib['name']]) - else: - black_material(obj) - - with bpy.context.temp_override(selected_editable_objects=[obj]): - bpy.ops.object.shade_smooth_by_angle(angle=math.radians(12)) - obj.modifiers.new( - type='WEIGHTED_NORMAL', name='weighted_normal').keep_sharp = True - obj = mesh_to_mesh(obj) - - obj.asset_mark() - obj.asset_generate_preview() - img = bpy.data.images.new(part['name'], *obj.preview.image_size, alpha=True) - img.pixels.foreach_set(obj.preview.image_pixels_float) - img_path = os.path.join(objects_dir, part['name'] + '.png') - img.save(filepath=img_path) - obj.asset_clear() - - blend_path = os.path.join(objects_dir, part['name'] + '.blend') - logger.info('Object stored as libs %s to %s.', part['name'], objects_dir) - bpy.ops.wm.save_as_mainfile(filepath=blend_path, compress=True) - - libs_data.append( - { - 'type': obj.rna_type.name.upper(), - 'name': part['name'], - 'path': os.path.relpath(blend_path, project_dir), - 'dae': os.path.relpath( - dae.export(obj_name=part['name'], file_dir=objects_dir), - project_dir), - 'fbx': os.path.relpath( - fbx.export(obj_name=part['name'], file_dir=objects_dir, - axis_forward='-Z', axis_up='Y'), - project_dir), - 'glb': os.path.relpath( - glb.export(obj_name=part['name'], file_dir=objects_dir), - project_dir), - 'ply': os.path.relpath( - ply.export(obj_name=part['name'], file_dir=objects_dir), - project_dir), - 'obj': os.path.relpath( - obj_export.export(obj_name=part['name'], file_dir=objects_dir), - project_dir), - 'thumbnail': os.path.relpath(img_path, project_dir), - } - ) - - # write db file - libs_data_path = os.path.join(project_dir, 'libs.json') - with open(libs_data_path, 'w', encoding='utf-8') as libs_data_file: - json.dump(libs_data, libs_data_file, ensure_ascii=False, indent=4) - logger.info('Database saved successfully to %s!', libs_data_path) - - return libs_data_path diff --git a/rcg_pipeline/rcg_pipeline/material_generators.py b/rcg_pipeline/rcg_pipeline/material_generators.py deleted file mode 100644 index 9f05cd2..0000000 --- a/rcg_pipeline/rcg_pipeline/material_generators.py +++ /dev/null @@ -1,165 +0,0 @@ -# ***** BEGIN GPL LICENSE BLOCK ***** -# -# Copyright (C) 2021-2024 Robossembler LLC -# -# Created by Ilia Kurochkin (brothermechanic) -# contact: brothermechanic@yandex.com -# -# This file is part of Robossembler Framework -# project repo: https://gitlab.com/robossembler/framework -# -# Robossembler Framework 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 . -# -# ***** END GPL LICENSE BLOCK ***** -# -# coding: utf-8 -''' -DESCRIPTION. -Blender material generation functions. -''' - -__version__ = '1.0' - -import configparser -import logging -import os - -import bpy -from bpy_extras.node_shader_utils import PrincipledBSDFWrapper - -from .utils.shininess_to_roughness import shiny_to_rough - -logger = logging.getLogger(__name__) - - -def black_material(obj): - ''' Generate absolute black body shader ''' - mat_name = 'Robossembler_Black_Body' - - if mat_name in bpy.data.materials: - # assign material to object - if len(obj.material_slots) < 1: - obj.data.materials.append(bpy.data.materials[mat_name]) - else: - obj.material_slots[0].material = bpy.data.materials[mat_name] - else: - bmat = bpy.data.materials.new(name=mat_name) - bmat.use_nodes = True - bmat.diffuse_color = (0, 0, 0, 1) - principled = bmat.node_tree.nodes['Principled BSDF'] - principled.inputs['Base Color'].default_value = (0, 0, 0, 1) - principled.inputs['Specular IOR Level'].default_value = 0.0 - principled.inputs['Roughness'].default_value = 1.0 - # assign material to object - if len(obj.material_slots) < 1: - obj.data.materials.append(bmat) - else: - obj.material_slots[0].material = bmat - - logger.debug('Material was assigned to object: %s -> %s', bmat.name, obj.name) - return bmat - - -def material_generator(obj, material_path): - ''' Generate shader from FreeCAD's FEM material ''' - material = configparser.ConfigParser() - with open(material_path, encoding='utf-8') as data: - material.read_file(data) - mat_name = os.path.splitext(os.path.basename(material_path))[0] - if mat_name != material['General']['Name']: - logger.warning( - 'Material %s is not supported! ' - 'For Robossembler CG Pipeline material should have ' - 'a same Name and FCMat filename!', - mat_name) - return black_material(obj) - - if mat_name in bpy.data.materials: - # assign material to object - if len(obj.material_slots) < 1: - obj.data.materials.append(bpy.data.materials[mat_name]) - else: - obj.material_slots[0].material = bpy.data.materials[mat_name] - - logger.debug('Material was assigned to object: %s -> %s', mat_name, obj.name) - return obj - - if 'Rendering' not in material: - logger.warning( - 'Material %s is not supported! ' - 'For Robossembler CG Pipeline material should have ' - 'Rendering category with shading parameters!', - mat_name) - return black_material(obj) - - rendering = material['Rendering'] - - if rendering.get('DiffuseColor'): - d_col_str = rendering['DiffuseColor'] - d_col4 = tuple(map(float, d_col_str[1:-1].split(', '))) - d_col = d_col4[:-1] - else: - logger.warning( - 'DiffuseColor not found for %s %s.', mat_name, obj.name) - d_col = (1.0, 0.0, 0.0) - if rendering.get('Father'): - if rendering['Father'] == 'Metal': - me = 1 - else: - me = 0 - else: - me = 0 - if rendering.get('Shininess'): - shiny = float(rendering['Shininess']) - if shiny == 0: - rg = 0.5 - else: - rg = shiny_to_rough(shiny) - else: - rg = 0.5 - if rendering.get('EmissiveColor'): - e_col_str = rendering['EmissiveColor'] - e_col4 = tuple(map(float, e_col_str[1:-1].split(', '))) - e_col = e_col4[:-1] - else: - e_col = (0.0, 0.0, 0.0) - if rendering.get('Transparency'): - tr_str = rendering['Transparency'] - alpha = 1.0 - float(tr_str) - else: - alpha = 1.0 - - bmat = bpy.data.materials.new(name=mat_name) - bmat.use_nodes = True - principled = PrincipledBSDFWrapper(bmat, is_readonly=False) - principled.base_color = d_col - principled.metallic = me - principled.roughness = rg - principled.emission_color = e_col - principled.alpha = alpha - bevel = bmat.node_tree.nodes.new(type="ShaderNodeBevel") - bevel.location = -300, -300 - bevel.samples = 32 - bevel.inputs[0].default_value = 0.001 - principled_node = bmat.node_tree.nodes["Principled BSDF"] - bmat.node_tree.links.new(bevel.outputs['Normal'], principled_node.inputs['Normal']) - # assign material to object - if len(obj.material_slots) < 1: - obj.data.materials.append(bmat) - else: - obj.material_slots[0].material = bmat - - logger.debug('Material was assigned to object: %s -> %s', bmat.name, obj.name) - return bmat diff --git a/rcg_pipeline/rcg_pipeline/render_asset.py b/rcg_pipeline/rcg_pipeline/render_asset.py deleted file mode 100644 index d6954dc..0000000 --- a/rcg_pipeline/rcg_pipeline/render_asset.py +++ /dev/null @@ -1,256 +0,0 @@ -# ***** BEGIN GPL LICENSE BLOCK ***** -# -# Copyright (C) 2021-2024 Robossembler LLC -# -# Created by Ilia Kurochkin (brothermechanic) -# contact: brothermechanic@yandex.com -# -# This file is part of Robossembler Framework -# project repo: https://gitlab.com/robossembler/framework -# -# Robossembler Framework 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 . -# -# ***** END GPL LICENSE BLOCK ***** -# -# coding: utf-8 -''' -DESCRIPTION. -Generate render asset from assembly tree and CG libs database. -''' - -__version__ = '1.0' - -import logging -import json -import os -import random -import shutil - -import bpy -from mathutils import Vector, Matrix - -from .utils.collection_tools import remove_collections_with_objects -from .utils.cleanup_orphan_data import cleanup_orphan_data -from .utils.object_relations import unparenting, parenting -from .utils.object_transforms import round_transforms - -logger = logging.getLogger(__name__) - - -def recursive_layer_collection(layer_coll, coll_name): - found = None - if layer_coll.name == coll_name: - return layer_coll - for layer in layer_coll.children: - found = recursive_layer_collection(layer, coll_name) - if found: - return found - return False - - -def assembly_builder(item, libs_data, libs_data_dir, collection=None, parent=None): - ''' - ''' - if not collection: - collection = bpy.context.scene.collection - - item_obj = None - - if item['type'] == 'LOCATOR': - item_obj = bpy.data.objects.new(item['name'], None) - item_obj.empty_display_type = 'CUBE' - item_obj.empty_display_size = 0.0005 - collection.objects.link(item_obj) - - elif item['type'] == 'LCS': - item_obj = bpy.data.objects.new(item['name'], None) - item_obj.empty_display_type = 'ARROWS' - item_obj.empty_display_size = round(random.uniform(0.05, 0.15), 3) - item_obj.show_in_front = True - collection.objects.link(item_obj) - - elif item['type'] == 'PART': - item_data = [ - data for data in libs_data - if data['type'] == 'OBJECT' - if data['name'] == item['base_name']] - if not item_data: - logger.error('No %s in database!', item['base_name']) - return False - # if there is local base_named object in scene -> rename it - local_obj = None - # for clones - if item['base_name'] != item['name']: - local_obj = [ - loc for loc in bpy.data.objects - if loc.name == item['base_name'] - if not loc.library] - if local_obj: - local_obj[0].name += '_loc' - item_file_path = os.path.join(libs_data_dir, item_data[0]['path']) - # TODO already linked - bpy.ops.wm.link( - filepath=item_file_path, - directory=os.path.join(item_file_path, 'Collection'), - filename=item['base_name'], - relative_path=True, - do_reuse_local_id=True, - active_collection=True, - ) - item_obj = bpy.data.objects[item['base_name']] - # for clones - if item['base_name'] != item['name']: - item_obj.name = item['name'] - # rename local back - if local_obj: - local_obj[0].name = item['base_name'] - item_obj.empty_display_type = 'PLAIN_AXES' - item_obj.empty_display_size = 0.0005 - - else: - logger.error('Unknown object type %s of %s', item['type'], item['name']) - return False - - item_obj.location = Vector(item['pose'][0]['loc_xyz']) * 0.001 - item_obj.rotation_mode = 'QUATERNION' - item_obj.rotation_quaternion = [ - item['pose'][1]['rot_xyzw'][3]] + item['pose'][1]['rot_xyzw'][:3] - - if item.get('attributes'): - for attr in item['attributes']: - item_obj[list(attr)[0]] = attr[list(attr)[0]] - - item_obj.parent = parent - - if item.get('children'): - for child_item in item.get('children'): - assembly_builder( - child_item, libs_data, libs_data_dir, collection, parent=item_obj) - - return True - - -def assembly_rebuilder(): - ''' Restructure assembling hierarchy. ''' - default_origin = [ - lcs for lcs in bpy.data.objects - if lcs.type == 'EMPTY' - if lcs.get('Robossembler_SocketFlow') == 'inlet' - if lcs.get('Robossembler_DefaultOrigin')] - if not default_origin: - raise Exception('Default Origin not found!') - if len(default_origin) > 1: - raise Exception('Several Default Origins do not supported!') - default_origin = default_origin[0] - - root_locator = [ - obj for obj in bpy.data.objects - if not obj.parent - if not obj.library] - for i in root_locator: - print(i.name) - if len(root_locator) > 1: - raise Exception('Render asset should consist of only one hierarchy!') - root_locator = root_locator[0] - - # retree_by lcs - for lcs in bpy.data.objects: - if lcs.type == 'EMPTY': - if lcs.get('Robossembler_SocketFlow'): - unparenting(lcs) - round_transforms(lcs) - - parenting(default_origin, root_locator) - - for lcs in bpy.data.objects: - if lcs.type == 'EMPTY': - if lcs.get('Robossembler_SocketFlow'): - if lcs != default_origin: - parenting(default_origin, lcs) - - default_origin.matrix_world = Matrix() - - logger.info('Restructuring assembling hierarchy finished!') - - return default_origin - - -def build_render_assets(project_dir): - ''' - ''' - assets_data = [] - - libs_data_path = os.path.join(project_dir, 'libs.json') - if not os.path.exists(libs_data_path): - raise Exception('No libs database found! Check %s directory' % project_dir) - with open(libs_data_path, encoding='utf-8') as data: - libs_data = json.load(data) - trees_path = os.path.join(project_dir, 'trees.json') - if not os.path.exists(trees_path): - raise Exception('No trees database found! Check %s directory' % project_dir) - with open(trees_path, encoding='utf-8') as data: - tree_item_list = json.load(data) - - # render assets dir - render_assets_dir = os.path.join(project_dir, 'assets', 'render') - if os.path.exists(render_assets_dir): - shutil.rmtree(render_assets_dir) - os.makedirs(render_assets_dir) - else: - os.makedirs(render_assets_dir) - - for tree_item in tree_item_list: - # start from stratch - bpy.ops.wm.read_homefile() - remove_collections_with_objects() - cleanup_orphan_data() - - # create redner collection - render_collection = bpy.data.collections.new(tree_item['name']) - bpy.context.scene.collection.children.link(render_collection) - active_collection = recursive_layer_collection( - bpy.context.view_layer.layer_collection, - render_collection.name) - bpy.context.view_layer.active_layer_collection = active_collection - - # build original hierarchy - assembly_builder(tree_item, libs_data, project_dir, render_collection) - # rebuild to LCS hierarchy - assembly_rebuilder() - - # mark as asset - render_collection.asset_mark() - # TODO collection thumbnail - - blend_path = os.path.join(render_assets_dir, tree_item['name'] + '.blend') - bpy.ops.wm.save_as_mainfile(filepath=blend_path) - logger.info('Render asset %s generated!', tree_item['name']) - - assets_data.append( - { - 'type': 'RENDER', - 'name': tree_item['name'], - 'path': os.path.relpath(blend_path, project_dir), - 'thumbnail': '' - } - ) - logger.info('%s Render Assets was generated!', len(tree_item_list)) - # write db file - assets_data_path = os.path.join(project_dir, 'assets.json') - with open(assets_data_path, 'w', encoding='utf-8') as assets_data_file: - json.dump(assets_data, assets_data_file, ensure_ascii=False, indent=4) - logger.info('Database saved successfully to %s!', assets_data_path) - - return render_assets_dir diff --git a/rcg_pipeline/rcg_pipeline/utils/__init__.py b/rcg_pipeline/rcg_pipeline/utils/__init__.py deleted file mode 100644 index 062386f..0000000 --- a/rcg_pipeline/rcg_pipeline/utils/__init__.py +++ /dev/null @@ -1,28 +0,0 @@ -# ***** BEGIN GPL LICENSE BLOCK ***** -# -# Copyright (C) 2024 Ilia Kurochkin -# -# Created by Ilia Kurochkin (brothermechanic) -# contact: brothermechanic@yandex.com -# -# This 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 . -# -# ***** END GPL LICENSE BLOCK ***** -# -# coding: utf-8 -''' -DESCRIPTION. -Blender utils. -''' diff --git a/rcg_pipeline/rcg_pipeline/utils/cleanup_orphan_data.py b/rcg_pipeline/rcg_pipeline/utils/cleanup_orphan_data.py deleted file mode 100644 index c9555c9..0000000 --- a/rcg_pipeline/rcg_pipeline/utils/cleanup_orphan_data.py +++ /dev/null @@ -1,67 +0,0 @@ -# ***** BEGIN GPL LICENSE BLOCK ***** -# -# Copyright (C) 2024 Ilia Kurochkin -# -# Created by Ilia Kurochkin (brothermechanic) -# contact: brothermechanic@yandex.com -# -# This 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 . -# -# ***** END GPL LICENSE BLOCK ***** -# -# coding: utf-8 -''' -DESCRIPTION. -Blender scene from stratch. -''' - -__version__ = '0.1' - -import bpy - - -def cleanup_orphan_data(): - '''Removes all data without users''' - for block in bpy.data.meshes: - if block.users == 0: - bpy.data.meshes.remove(block) - - for block in bpy.data.materials: - if block.users == 0: - bpy.data.materials.remove(block) - - for block in bpy.data.textures: - if block.users == 0: - bpy.data.textures.remove(block) - - for block in bpy.data.images: - if block.users == 0: - bpy.data.images.remove(block) - - for block in bpy.data.collections: - if block.users == 0: - bpy.data.collections.remove(block) - - for block in bpy.data.cameras: - if block.users == 0: - bpy.data.cameras.remove(block) - - for block in bpy.data.lights: - if block.users == 0: - bpy.data.lights.remove(block) - - for block in bpy.data.scenes: - if block.users == 0: - bpy.data.scenes.remove(block) diff --git a/rcg_pipeline/rcg_pipeline/utils/collection_tools.py b/rcg_pipeline/rcg_pipeline/utils/collection_tools.py deleted file mode 100644 index 702579e..0000000 --- a/rcg_pipeline/rcg_pipeline/utils/collection_tools.py +++ /dev/null @@ -1,92 +0,0 @@ -# ***** BEGIN GPL LICENSE BLOCK ***** -# -# Copyright (C) 2024 Ilia Kurochkin -# -# Created by Ilia Kurochkin (brothermechanic) -# contact: brothermechanic@yandex.com -# -# This 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 . -# -# ***** END GPL LICENSE BLOCK ***** -# -# coding: utf-8 -''' -DESCRIPTION. -Various collection tools. -''' - -__version__ = '0.1' - -import bpy -from collections import defaultdict - - -def copy_objects(from_col, to_col, linked, double_lut): - '''Function copying objects from collection to collection.''' - for obj in from_col.objects: - double = obj.copy() - if not linked and obj.data: - double.data = double.data.copy() - to_col.objects.link(double) - double_lut[obj] = double - return True - - -def copy_collections_recursive(collection, suffix='copy', linked=False): - '''Function recursive copying collection.''' - double_lut = defaultdict(lambda: None) - parent = [p for p in (bpy.data.collections[:] + [bpy.context.scene.collection]) - if collection.name in p.children.keys()][0] - - def _copy(parent, collection, suffix, linked=False): - '''Function copying collection.''' - clone_collection = bpy.data.collections.new( - '_'.join((collection.name, suffix)) - ) - copy_objects(collection, clone_collection, linked, double_lut) - - for _collection in collection.children: - _copy(clone_collection, _collection, suffix, linked) - - parent.children.link(clone_collection) - - _copy(parent, collection, suffix, linked) - for obj, double in tuple(double_lut.items()): - parent = double_lut[obj.parent] - if parent: - double.parent = parent - return '_'.join((collection.name, suffix)) - - -def unlink_from_collections(obj): - ''' Unlinking object from all collections. ''' - for col in bpy.data.collections: - if obj.name in col.objects: - col.objects.unlink(obj) - return obj - - -def remove_collections_with_objects(collection=None): - '''Removes all collection (or given) with objects from scene ''' - if collection: - for obj in collection.objects: - bpy.data.objects.remove(obj, do_unlink=True) - bpy.data.collections.remove(collection) - else: - for col in bpy.data.collections: - for obj in col.objects: - bpy.data.objects.remove(obj, do_unlink=True) - bpy.data.collections.remove(col) - return True diff --git a/rcg_pipeline/rcg_pipeline/utils/generative_modifiers.py b/rcg_pipeline/rcg_pipeline/utils/generative_modifiers.py deleted file mode 100644 index df9073d..0000000 --- a/rcg_pipeline/rcg_pipeline/utils/generative_modifiers.py +++ /dev/null @@ -1,173 +0,0 @@ -# ***** BEGIN GPL LICENSE BLOCK ***** -# -# Copyright (C) 2024 Ilia Kurochkin -# -# Created by Ilia Kurochkin (brothermechanic) -# contact: brothermechanic@yandex.com -# -# This 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 . -# -# ***** END GPL LICENSE BLOCK ***** -# -# coding: utf-8 -''' -DESCRIPTION. -Basic mesh processing for asset pipeline. -DEPRECATED -''' - -__version__ = '0.1' - -import bpy - - -def shell_remesher(lowpoly_obj, mod_name='shell_mod', tree_name='shell_tree'): - ''' Conctruct geometry nodes modifier. ''' - - modifier = lowpoly_obj.modifiers.new(mod_name, type='NODES') - tree = bpy.data.node_groups.new(name=tree_name, type='GeometryNodeTree') - modifier.node_group = tree - - group_input = tree.nodes.new(type='NodeGroupInput') - - collection_info = tree.nodes.new(type='GeometryNodeCollectionInfo') - collection_info.location = (300, 0) - collection_info.transform_space = 'RELATIVE' - - tree.interface.new_socket(name='Collection', in_out='INPUT', - socket_type='NodeSocketCollection') - tree.links.new(group_input.outputs['Collection'], - collection_info.inputs['Collection']) - - realize_instances = tree.nodes.new(type='GeometryNodeRealizeInstances') - realize_instances.location = (600, 0) - - tree.links.new(collection_info.outputs[0], - realize_instances.inputs['Geometry']) - - mesh_to_volume = tree.nodes.new(type='GeometryNodeMeshToVolume') - mesh_to_volume.location = (900, 0) - mesh_to_volume.resolution_mode = 'VOXEL_SIZE' - mesh_to_volume.inputs['Density'].default_value = 10.0 - mesh_to_volume.inputs['Voxel Size'].default_value = 0.005 - #mesh_to_volume.inputs['Exterior Band Width'].default_value = 0.005 - - tree.links.new(realize_instances.outputs['Geometry'], - mesh_to_volume.inputs['Mesh']) - - volume_to_mesh = tree.nodes.new(type='GeometryNodeVolumeToMesh') - volume_to_mesh.location = (1200, 0) - - tree.links.new(mesh_to_volume.outputs['Volume'], - volume_to_mesh.inputs['Volume']) - - extrude_mesh = tree.nodes.new(type='GeometryNodeExtrudeMesh') - extrude_mesh.location = (1500, 0) - extrude_mesh.inputs['Offset Scale'].default_value = 0.001 - extrude_mesh.inputs['Individual'].default_value = False - - tree.links.new(volume_to_mesh.outputs['Mesh'], - extrude_mesh.inputs['Mesh']) - - # 1 pass - mesh_to_volume = tree.nodes.new(type='GeometryNodeMeshToVolume') - mesh_to_volume.location = (1800, 0) - mesh_to_volume.resolution_mode = 'VOXEL_SIZE' - mesh_to_volume.inputs['Density'].default_value = 1.0 - mesh_to_volume.inputs['Voxel Size'].default_value = 0.003 - #mesh_to_volume.inputs['Exterior Band Width'].default_value = 0.003 - - tree.links.new(extrude_mesh.outputs['Mesh'], - mesh_to_volume.inputs['Mesh']) - - volume_to_mesh = tree.nodes.new(type='GeometryNodeVolumeToMesh') - volume_to_mesh.location = (2100, 0) - - tree.links.new(mesh_to_volume.outputs['Volume'], - volume_to_mesh.inputs['Volume']) - - set_position_01 = tree.nodes.new(type='GeometryNodeSetPosition') - set_position_01.location = (2400, -300) - - tree.links.new(volume_to_mesh.outputs['Mesh'], - set_position_01.inputs['Geometry']) - - # 2 pass - mesh_to_volume = tree.nodes.new(type='GeometryNodeMeshToVolume') - mesh_to_volume.location = (2700, 0) - mesh_to_volume.resolution_mode = 'VOXEL_SIZE' - mesh_to_volume.inputs['Density'].default_value = 1.0 - mesh_to_volume.inputs['Voxel Size'].default_value = 0.001 - #mesh_to_volume.inputs['Exterior Band Width'].default_value = 0.001 - - tree.links.new(set_position_01.outputs['Geometry'], - mesh_to_volume.inputs['Mesh']) - - volume_to_mesh = tree.nodes.new(type='GeometryNodeVolumeToMesh') - volume_to_mesh.location = (3000, 0) - - tree.links.new(mesh_to_volume.outputs['Volume'], - volume_to_mesh.inputs['Volume']) - - set_position_02 = tree.nodes.new(type='GeometryNodeSetPosition') - set_position_02.location = (3300, -300) - - tree.links.new(volume_to_mesh.outputs['Mesh'], - set_position_02.inputs['Geometry']) - - # 3 pass - mesh_to_volume = tree.nodes.new(type='GeometryNodeMeshToVolume') - mesh_to_volume.location = (3600, 0) - mesh_to_volume.resolution_mode = 'VOXEL_SIZE' - mesh_to_volume.inputs['Density'].default_value = 1.0 - mesh_to_volume.inputs['Voxel Size'].default_value = 0.0005 - #mesh_to_volume.inputs['Exterior Band Width'].default_value = 0.0001 - - tree.links.new(set_position_02.outputs['Geometry'], - mesh_to_volume.inputs['Mesh']) - - volume_to_mesh = tree.nodes.new(type='GeometryNodeVolumeToMesh') - volume_to_mesh.location = (3900, 0) - - tree.links.new(mesh_to_volume.outputs['Volume'], - volume_to_mesh.inputs['Volume']) - - set_position_03 = tree.nodes.new(type='GeometryNodeSetPosition') - set_position_03.location = (4200, -300) - - tree.links.new(volume_to_mesh.outputs['Mesh'], - set_position_03.inputs['Geometry']) - - group_output = tree.nodes.new(type='NodeGroupOutput') - group_output.location = (4500, 0) - - tree.interface.new_socket(name='Geometry', in_out='OUTPUT', - socket_type='NodeSocketGeometry') - tree.links.new(set_position_03.outputs['Geometry'], - group_output.inputs['Geometry']) - - geometry_proximity = tree.nodes.new(type='GeometryNodeProximity') - geometry_proximity.location = (1200, -1000) - - tree.links.new(realize_instances.outputs['Geometry'], - geometry_proximity.inputs['Target']) - tree.links.new(geometry_proximity.outputs['Position'], - set_position_01.inputs['Position']) - tree.links.new(geometry_proximity.outputs['Position'], - set_position_02.inputs['Position']) - tree.links.new(geometry_proximity.outputs['Position'], - set_position_03.inputs['Position']) - - return modifier diff --git a/rcg_pipeline/rcg_pipeline/utils/mesh_tools.py b/rcg_pipeline/rcg_pipeline/utils/mesh_tools.py deleted file mode 100644 index 6d8e075..0000000 --- a/rcg_pipeline/rcg_pipeline/utils/mesh_tools.py +++ /dev/null @@ -1,118 +0,0 @@ -# ***** BEGIN GPL LICENSE BLOCK ***** -# -# Copyright (C) 2024 Ilia Kurochkin -# -# Created by Ilia Kurochkin (brothermechanic) -# contact: brothermechanic@yandex.com -# -# This 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 . -# -# ***** END GPL LICENSE BLOCK ***** -# -# coding: utf-8 -''' -DESCRIPTION. -Various mesh tools for Edit Mode. -''' - -__version__ = '0.1' - -import math -import bpy -import bmesh - - -def select_peaks(me, peak_limit_angle=60, peak_accuracy_angle=10): - ''' Select sharp vertices that stand alone. ''' - bm = bmesh.from_edit_mesh(me) - - def is_sharp(vert, eps=math.radians(peak_limit_angle)): - sharps = [] - face_before = None - for face in vert.link_faces: - if face_before: - face_angle = face.normal.angle(face_before.normal) - if face_angle > math.radians(peak_accuracy_angle): - angle = vert.normal.angle(face.normal) - if angle > eps: - sharps.append(angle) - face_before = face - return ( - (len(sharps) + 1) == len(vert.link_faces) - or (len(sharps) + 2) == len(vert.link_faces) - ) - - def non_single(vert): - for edge in vert.link_edges: - if edge.other_vert(vert).select: - return False - return True - - for v in bm.verts: - v.select_set( - is_sharp(v) - ) - - for v in bm.verts: - if v.select: - v.select_set( - non_single(v) - ) - - bmesh.update_edit_mesh(me) - return me - - -def select_zero_faces(me): - ''' Select very small faces. ''' - bm = bmesh.from_edit_mesh(me) - for myface in bm.faces: - if myface.calc_area() < 1e-7: - myface.select_set(True) - bmesh.update_edit_mesh(me) - return me - - -def select_stratched_edges(me, edge_length_limit=0.002): - ''' Select very stratched edges of small faces. ''' - bm = bmesh.from_edit_mesh(me) - faces_stratched = [f for f in bm.faces if f.calc_area() < 1e-6] - for face in faces_stratched: - edges_lengths = {e: e.calc_length() for e in face.edges} - edge_max_length = max(edges_lengths.values()) - if edge_max_length > edge_length_limit: - edge_max = [k for k, v in edges_lengths.items() if v == edge_max_length][0] - edge_max.select_set(True) - bmesh.update_edit_mesh(me) - return me - - -def collect_less_volume_objs(objs: list, min_volume): - ''' Separate selection for less volume objects. ''' - less_volume_objs = [] - for obj in objs: - bpy.ops.object.select_all(action='DESELECT') - if obj.type != 'MESH': - continue - # requed for bmesh - obj.hide_set(False) - obj.select_set(state=True) - if obj.type == 'MESH': - bpy.ops.object.mode_set(mode='EDIT') - bm = bmesh.from_edit_mesh(obj.data) - if bm.calc_volume() < min_volume: - less_volume_objs.append(obj) - bpy.ops.object.mode_set(mode='OBJECT') - return less_volume_objs diff --git a/rcg_pipeline/rcg_pipeline/utils/object_converter.py b/rcg_pipeline/rcg_pipeline/utils/object_converter.py deleted file mode 100644 index 61a30d1..0000000 --- a/rcg_pipeline/rcg_pipeline/utils/object_converter.py +++ /dev/null @@ -1,53 +0,0 @@ -# ***** BEGIN GPL LICENSE BLOCK ***** -# -# Copyright (C) 2024 Ilia Kurochkin -# -# Created by Ilia Kurochkin (brothermechanic) -# contact: brothermechanic@yandex.com -# -# This 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 . -# -# ***** END GPL LICENSE BLOCK ***** -# -# coding: utf-8 -''' -DESCRIPTION. -Convert all deformers and modifiers of object to it's mesh. -''' - -__version__ = '0.1' - -import bpy - - -def mesh_to_mesh(obj): - ''' Convert all deformers and modifiers of object to it's mesh. ''' - if obj and obj.type == 'MESH': - deg = bpy.context.evaluated_depsgraph_get() - eval_mesh = obj.evaluated_get(deg).data.copy() - - orig_name = obj.name - obj.name = '{}_temp'.format(orig_name) - converted_obj = bpy.data.objects.new(orig_name, eval_mesh) - converted_obj.matrix_world = obj.matrix_world - - bpy.context.view_layer.update() - converted_obj.matrix_world = obj.matrix_world.copy() - - obj.users_collection[0].objects.link(converted_obj) - - bpy.data.objects.remove(obj, do_unlink=True) - - return converted_obj diff --git a/rcg_pipeline/rcg_pipeline/utils/object_relations.py b/rcg_pipeline/rcg_pipeline/utils/object_relations.py deleted file mode 100644 index 06b45e8..0000000 --- a/rcg_pipeline/rcg_pipeline/utils/object_relations.py +++ /dev/null @@ -1,50 +0,0 @@ -# ***** BEGIN GPL LICENSE BLOCK ***** -# -# Copyright (C) 2024 Ilia Kurochkin -# -# Created by Ilia Kurochkin (brothermechanic) -# contact: brothermechanic@yandex.com -# -# This 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 . -# -# ***** END GPL LICENSE BLOCK ***** -# -# coding: utf-8 -''' -DESCRIPTION. -Blender object relations functions. -''' - -__version__ = '0.1' - -import bpy - - -def parenting(parent, child): - ''' Parenting child object to parent object. ''' - child.parent = parent - child.matrix_parent_inverse = parent.matrix_world.inverted() - return child - - -def unparenting(child): - ''' Unarenting child object from parent object. ''' - # update database - bpy.context.view_layer.update() - - world_matrix = child.matrix_world.copy() - child.parent = None - child.matrix_world = world_matrix - return child diff --git a/rcg_pipeline/rcg_pipeline/utils/object_transforms.py b/rcg_pipeline/rcg_pipeline/utils/object_transforms.py deleted file mode 100644 index f2119dc..0000000 --- a/rcg_pipeline/rcg_pipeline/utils/object_transforms.py +++ /dev/null @@ -1,88 +0,0 @@ -# ***** BEGIN GPL LICENSE BLOCK ***** -# -# Copyright (C) 2024 Ilia Kurochkin -# -# Created by Ilia Kurochkin (brothermechanic) -# contact: brothermechanic@yandex.com -# -# This 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 . -# -# ***** END GPL LICENSE BLOCK ***** -# -# coding: utf-8 -''' -DESCRIPTION. -Blender object transforms functions. -''' - -__version__ = '0.3' - -from mathutils import Matrix, Vector, Quaternion -import bpy - - -def apply_transforms(obj, location=False, rotation=False, scale=False): - ''' bake local object transforms ''' - # original idea from https://github.com/machin3io/MACHIN3tools - # update database - bpy.context.view_layer.update() - - def get_loc_matrix(location): - return Matrix.Translation(location) - - def get_rot_matrix(rotation): - return rotation.to_matrix().to_4x4() - - def get_sca_matrix(scale): - scene_scale_martix = Matrix() - for i in range(3): - scene_scale_martix[i][i] = scale[i] - return scene_scale_martix - - if location and rotation and scale: - loc, rot, sca = obj.matrix_world.decompose() - mesh_martix = get_loc_matrix(loc) @ get_rot_matrix( - rot) @ get_sca_matrix(sca) - obj.data.transform(mesh_martix) - apply_matrix = get_loc_matrix(Vector.Fill(3, 0)) @ get_rot_matrix(Quaternion()) @ get_sca_matrix(Vector.Fill(3, 1)) - obj.matrix_world = apply_matrix - else: - if location: - raise Exception( - 'Location only applies with all transformations (rotate and scale) together!' - ) - if rotation: - loc, rot, sca = obj.matrix_world.decompose() - mesh_martix = get_rot_matrix(rot) - obj.data.transform(mesh_martix) - apply_matrix = get_loc_matrix(loc) @ get_rot_matrix(Quaternion()) @ get_sca_matrix(sca) - obj.matrix_world = apply_matrix - - if scale: - loc, rot, sca = obj.matrix_world.decompose() - mesh_martix = get_sca_matrix(sca) - obj.data.transform(mesh_martix) - apply_matrix = get_loc_matrix(loc) @ get_rot_matrix(rot) @ get_sca_matrix(Vector.Fill(3, 1)) - obj.matrix_world = apply_matrix - - obj.rotation_mode = 'XYZ' - return obj - - -def round_transforms(obj): - ''' Geting location of object and round it. ''' - for idx, axis in enumerate(obj.location[:]): - obj.location[idx] = round(axis, 5) - return obj.location diff --git a/rcg_pipeline/rcg_pipeline/utils/shininess_to_roughness.py b/rcg_pipeline/rcg_pipeline/utils/shininess_to_roughness.py deleted file mode 100644 index 2bfa837..0000000 --- a/rcg_pipeline/rcg_pipeline/utils/shininess_to_roughness.py +++ /dev/null @@ -1,42 +0,0 @@ -# ***** BEGIN GPL LICENSE BLOCK ***** -# -# original alg from https://github.com/assimp/assimp/issues/4573 -# Copyright (C) 2024 Ilia Kurochkin -# -# Created by Ilia Kurochkin (brothermechanic) -# contact: brothermechanic@yandex.com -# -# This 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 . -# -# ***** END GPL LICENSE BLOCK ***** -# -# coding: utf-8 -''' -DESCRIPTION. -Math function. -''' - -__version__ = '0.1' - -import math - - -def shiny_to_rough(shininess): - ''' convert shiny to roughness ''' - a, b = -1.0, 2.0 - c = (shininess / 100.0) - 1.0 - D = math.pow(b, 2) - (4 * a * c) - roughness = (-b + math.sqrt(D)) / (2 * a) - return max(roughness, 0) diff --git a/simulation/insertion_vector_predicate/assembly b/simulation/insertion_vector_predicate/assembly new file mode 160000 index 0000000..29db7df --- /dev/null +++ b/simulation/insertion_vector_predicate/assembly @@ -0,0 +1 @@ +Subproject commit 29db7df4d7f2e6055f3f26fc5c11a424954f7308