Compare commits
21 commits
master
...
solve_opti
Author | SHA1 | Date | |
---|---|---|---|
![]() |
862a61b1e7 | ||
![]() |
deee7b4329 | ||
![]() |
ca0df838a2 | ||
![]() |
a59b3a4775 | ||
ee1afe7869 | |||
0ec56f1eb8 | |||
ff087ffbf8 | |||
![]() |
70004486c7 | ||
![]() |
c2e375f854 | ||
28a8648651 | |||
4477a15909 | |||
2b845403cd | |||
![]() |
0de605f314 | ||
![]() |
7ffa0acee9 | ||
![]() |
ecb43845a6 | ||
![]() |
052dd86d94 | ||
![]() |
8fba62e8a3 | ||
![]() |
a4da4aee68 | ||
![]() |
db4e0d7ac9 | ||
![]() |
b766e36c31 | ||
![]() |
3e7bfba178 |
8
.gitmodules
vendored
|
@ -1,9 +1,3 @@
|
|||
[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 = simulation/insertion_vector_predicate/assembly
|
||||
path = insertion_vector_predicate/assembly
|
||||
url = https://github.com/yunshengtian/Assemble-Them-All
|
||||
|
|
674
LICENSE
|
@ -1,674 +0,0 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) 2024 Igor Brylev
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) 2024 Igor Brylev
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
|
@ -1,412 +0,0 @@
|
|||
import blenderproc as bproc
|
||||
"""
|
||||
renderBOPdataset2
|
||||
Общая задача: common pipeline
|
||||
Реализуемая функция: создание датасета в формате BOP с заданными параметрами рандомизации
|
||||
Используется модуль blenderproc
|
||||
|
||||
02.05.2024 @shalenikol release 0.1
|
||||
02.07.2024 @shalenikol release 0.2
|
||||
28.10.2024 @shalenikol release 0.3
|
||||
"""
|
||||
import numpy as np
|
||||
import argparse
|
||||
import random
|
||||
import os
|
||||
import shutil
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import bpy
|
||||
|
||||
VHACD_PATH = "blenderproc_resources/vhacd"
|
||||
DIR_MODELS = "models"
|
||||
DIR_MESH = "assets/libs/objects/"
|
||||
FILE_LOG_SCENE = "res.txt"
|
||||
FILE_RBS_INFO = "rbs_info.json"
|
||||
FILE_GT_COCO = "scene_gt_coco.json"
|
||||
EXT_MODELS = ".fbx"
|
||||
TEXTURE_TMPL = "*.jpg"
|
||||
|
||||
Not_Categories_Name = True # наименование категории в COCO-аннотации отсутствует
|
||||
|
||||
def _get_list_texture(rel_path: str) -> list:
|
||||
# local_path/texture/
|
||||
loc = os.path.dirname(os.path.dirname(rnd_par.output_dir))
|
||||
path = os.path.join(loc, rel_path)
|
||||
return list(Path(path).absolute().rglob(TEXTURE_TMPL))
|
||||
|
||||
# def _get_path_model(name_model: str) -> str:
|
||||
# # TODO on name_model find path for mesh (model.fbx)
|
||||
# # local_path/assets/libs/objects # assets/mesh/
|
||||
# loc = os.path.dirname(os.path.dirname(rnd_par.output_dir))
|
||||
# return os.path.join(loc, DIR_MESH + name_model + EXT_MODELS)
|
||||
|
||||
def _get_path_object(name_obj: str) -> str:
|
||||
# TODO on name_obj find path for scene object (object.fbx)
|
||||
# loc = os.path.dirname(os.path.dirname(rnd_par.output_dir))
|
||||
# return os.path.join(loc, DIR_MESH + name_obj + EXT_MODELS)
|
||||
return os.path.join(rnd_par.details_dir, name_obj + EXT_MODELS)
|
||||
|
||||
def convert2relative(height, width, bbox):
|
||||
"""
|
||||
YOLO format use relative coordinates for annotation
|
||||
"""
|
||||
x, y, w, h = bbox
|
||||
x += w/2
|
||||
y += h/2
|
||||
return x/width, y/height, w/width, h/height
|
||||
|
||||
def render() -> int:
|
||||
i = 0
|
||||
for obj in all_meshs:
|
||||
# Make the object actively participate in the physics simulation
|
||||
obj.enable_rigidbody(active=True, collision_shape="COMPOUND")
|
||||
# Also use convex decomposition as collision shapes
|
||||
obj.build_convex_decomposition_collision_shape(VHACD_PATH)
|
||||
i += 1
|
||||
# print(f"{i} : {obj.get_name()}")
|
||||
|
||||
objs = all_meshs + rnd_par.scene.objs
|
||||
|
||||
log_txt = os.path.join(os.path.dirname(rnd_par.output_dir), FILE_LOG_SCENE)
|
||||
with open(log_txt, "w") as fh:
|
||||
for i,o in enumerate(objs):
|
||||
loc = o.get_location()
|
||||
euler = o.get_rotation_euler()
|
||||
fh.write(f"{i} : {o.get_name()} {loc} {euler} category_id = {o.get_cp('category_id')}\n")
|
||||
|
||||
# define a light and set its location and energy level
|
||||
ls = []
|
||||
for l in rnd_par.scene.light_data:
|
||||
light = bproc.types.Light(name=f"l{l['id']}")
|
||||
light.set_type(l["type"])
|
||||
light.set_location(l["loc_xyz"]) #[5, -5, 5])
|
||||
light.set_rotation_euler(l["rot_euler"]) #[-0.063, 0.6177, -0.1985])
|
||||
ls += [light]
|
||||
|
||||
# define the camera intrinsics
|
||||
bproc.camera.set_intrinsics_from_blender_params(1,
|
||||
rnd_par.image_size_wh[0],
|
||||
rnd_par.image_size_wh[1],
|
||||
lens_unit="FOV")
|
||||
|
||||
# add segmentation masks (per class and per instance)
|
||||
bproc.renderer.enable_segmentation_output(map_by=["category_id", "instance", "name"])
|
||||
|
||||
# activate depth rendering
|
||||
bproc.renderer.enable_depth_output(activate_antialiasing=False)
|
||||
|
||||
# res_dir = os.path.join(rnd_par.output_dir, rnd_par.ds_name)
|
||||
res_dir = rnd_par.output_dir
|
||||
if os.path.isdir(res_dir):
|
||||
shutil.rmtree(res_dir)
|
||||
# Цикл рендеринга
|
||||
# Do multiple times: Position the shapenet objects using the physics simulator and render X images with random camera poses
|
||||
for r in range(rnd_par.n_series):
|
||||
print(f"********** Series : {r+1}")
|
||||
is_texture = True if "texture_path" in rnd_par.models_randomization else False
|
||||
if is_texture:
|
||||
val = rnd_par.models_randomization["texture_path"]
|
||||
l_texture = _get_list_texture(val)
|
||||
image = bpy.data.images.load(filepath=str(l_texture[r % len(l_texture)]))
|
||||
# один случайный объект в кадре / все заданные объекты
|
||||
random_obj = random.choice(range(rnd_par.models.n_item))
|
||||
meshs = []
|
||||
for i,o in enumerate(all_meshs): # активные модели
|
||||
if rnd_par.single_object and i != random_obj:
|
||||
continue
|
||||
meshs += [o]
|
||||
if is_texture:
|
||||
mats = o.get_materials()
|
||||
for mat in mats:
|
||||
# image = bpy.data.images.load(filepath=str(random.choice(l_texture)))
|
||||
mat.set_principled_shader_value("Base Color", image)
|
||||
|
||||
for i,o in enumerate(rnd_par.scene.objs): # объекты сцены
|
||||
rnd_mat = rnd_par.scene.obj_data[i]["material_randomization"]
|
||||
mats = o.get_materials() #[0]
|
||||
for mat in mats:
|
||||
val = rnd_mat["specular"]
|
||||
mat.set_principled_shader_value("Specular", random.uniform(val[0], val[1]))
|
||||
val = rnd_mat["roughness"]
|
||||
mat.set_principled_shader_value("Roughness", random.uniform(val[0], val[1]))
|
||||
val = rnd_mat["metallic"]
|
||||
mat.set_principled_shader_value("Metallic", random.uniform(val[0], val[1]))
|
||||
if "texture_path" in rnd_mat: # путь к текстурам (*.jpg)
|
||||
val = rnd_mat["texture_path"]
|
||||
val = _get_list_texture(val)
|
||||
image = bpy.data.images.load(filepath=str(random.choice(val)))
|
||||
mat.set_principled_shader_value("Base Color", image)
|
||||
else:
|
||||
val = rnd_mat["base_color"]
|
||||
mat.set_principled_shader_value("Base Color", np.random.uniform(val[0], val[1]))
|
||||
# mat.set_principled_shader_value("Base Color", image)
|
||||
|
||||
# Randomly set the color and energy
|
||||
for i,l in enumerate(ls):
|
||||
current = rnd_par.scene.light_data[i]
|
||||
l.set_color(np.random.uniform(current["color_range_low"], current["color_range_high"]))
|
||||
energy = current["energy_range"]
|
||||
l.set_energy(random.uniform(energy[0], energy[1]))
|
||||
|
||||
# Clear all key frames from the previous run
|
||||
bproc.utility.reset_keyframes()
|
||||
|
||||
# Define a function that samples 6-DoF poses
|
||||
def sample_pose(obj: bproc.types.MeshObject):
|
||||
obj.set_location(np.random.uniform(rnd_par.loc_range_low, rnd_par.loc_range_high)) #[-1, -1, 0], [1, 1, 2]))
|
||||
obj.set_rotation_euler(bproc.sampler.uniformSO3())
|
||||
|
||||
# Sample the poses of all shapenet objects above the ground without any collisions in-between
|
||||
bproc.object.sample_poses(meshs,
|
||||
objects_to_check_collisions = meshs + rnd_par.scene.collision_objects,
|
||||
sample_pose_func = sample_pose)
|
||||
|
||||
# Run the simulation and fix the poses of the shapenet objects at the end
|
||||
bproc.object.simulate_physics_and_fix_final_poses(min_simulation_time=4, max_simulation_time=20, check_object_interval=1)
|
||||
|
||||
# Find point of interest, all cam poses should look towards it
|
||||
poi = bproc.object.compute_poi(meshs)
|
||||
|
||||
coord_max = [0.1, 0.1, 0.1]
|
||||
coord_min = [0., 0., 0.]
|
||||
|
||||
with open(log_txt, "a") as fh:
|
||||
fh.write("*****************\n")
|
||||
fh.write(f"{r}) poi = {poi}\n")
|
||||
i = 0
|
||||
for o in meshs:
|
||||
i += 1
|
||||
loc = o.get_location()
|
||||
euler = o.get_rotation_euler()
|
||||
fh.write(f" {i} : {o.get_name()} {loc} {euler}\n")
|
||||
for j in range(3):
|
||||
if loc[j] < coord_min[j]:
|
||||
coord_min[j] = loc[j]
|
||||
if loc[j] > coord_max[j]:
|
||||
coord_max[j] = loc[j]
|
||||
|
||||
# Sample up to X camera poses
|
||||
#an = np.random.uniform(0.78, 1.2) #1. #0.35
|
||||
for i in range(rnd_par.n_cam_pose):
|
||||
# Sample location
|
||||
location = bproc.sampler.shell(center=rnd_par.center_shell,
|
||||
radius_min=rnd_par.radius_range[0],
|
||||
radius_max=rnd_par.radius_range[1],
|
||||
elevation_min=rnd_par.elevation_range[0],
|
||||
elevation_max=rnd_par.elevation_range[1])
|
||||
# координата, по которой будем сэмплировать положение камеры
|
||||
j = random.randint(0, 2)
|
||||
# разовый сдвиг по случайной координате
|
||||
d = (coord_max[j] - coord_min[j]) / rnd_par.n_sample_on_pose
|
||||
if location[j] < 0:
|
||||
d = -d
|
||||
for _ in range(rnd_par.n_sample_on_pose):
|
||||
# Compute rotation based on vector going from location towards poi
|
||||
rotation_matrix = bproc.camera.rotation_from_forward_vec(poi - location, inplane_rot=np.random.uniform(-0.7854, 0.7854))
|
||||
# Add homog cam pose based on location an rotation
|
||||
cam2world_matrix = bproc.math.build_transformation_mat(location, rotation_matrix)
|
||||
bproc.camera.add_camera_pose(cam2world_matrix)
|
||||
location[j] -= d
|
||||
# render the whole pipeline
|
||||
data = bproc.renderer.render()
|
||||
# Write data to bop format
|
||||
bproc.writer.write_bop(res_dir,
|
||||
target_objects = all_meshs, # Optional[List[MeshObject]] = None
|
||||
depths = data["depth"],
|
||||
depth_scale = 1.0,
|
||||
colors = data["colors"],
|
||||
color_file_format=rnd_par.image_format,
|
||||
append_to_existing_output = (r>0),
|
||||
save_world2cam = False) # world coords are arbitrary in most real BOP datasets
|
||||
# dataset="robo_ds",
|
||||
|
||||
models_dir = os.path.join(res_dir, DIR_MODELS)
|
||||
os.mkdir(models_dir)
|
||||
|
||||
data = []
|
||||
for i,objn in enumerate(rnd_par.models.names):
|
||||
rec = {}
|
||||
rec["id"] = i+1
|
||||
rec["name"] = objn
|
||||
rec["model"] = os.path.join(DIR_MODELS, os.path.split(rnd_par.models.filenames[i])[1]) # путь относительный
|
||||
t = [obj.get_bound_box(local_coords=True).tolist() for obj in all_meshs if obj.get_name() == objn]
|
||||
rec["cuboid"] = t[0]
|
||||
data.append(rec)
|
||||
shutil.copy2(rnd_par.models.filenames[i], models_dir)
|
||||
f = (os.path.splitext(rnd_par.models.filenames[i]))[0] + ".mtl" # файл материала
|
||||
if os.path.isfile(f):
|
||||
shutil.copy2(f, models_dir)
|
||||
|
||||
with open(os.path.join(res_dir, FILE_RBS_INFO), "w") as fh:
|
||||
json.dump(data, fh, indent=2)
|
||||
|
||||
"""
|
||||
!!! categories -> name берётся из category_id !!!
|
||||
см.ниже
|
||||
blenderproc.python.writer : BopWriterUtility.py
|
||||
class _BopWriterUtility
|
||||
def calc_gt_coco
|
||||
...
|
||||
CATEGORIES = [{'id': obj.get_cp('category_id'), 'name': str(obj.get_cp('category_id')), 'supercategory':
|
||||
dataset_name} for obj in dataset_objects]
|
||||
|
||||
поэтому заменим наименование категории в аннотации
|
||||
"""
|
||||
def change_categories_name(dir: str):
|
||||
coco_file = os.path.join(dir,FILE_GT_COCO)
|
||||
with open(coco_file, "r") as fh:
|
||||
data = json.load(fh)
|
||||
cats = data["categories"]
|
||||
|
||||
for i,cat in enumerate(cats):
|
||||
cat["name"] = rnd_par.models.names[i] #obj_names[i]
|
||||
|
||||
with open(coco_file, "w") as fh:
|
||||
json.dump(data, fh, indent=1)
|
||||
|
||||
def explore(path: str):
|
||||
if not os.path.isdir(path):
|
||||
return
|
||||
folders = [
|
||||
os.path.join(path, o)
|
||||
for o in os.listdir(path)
|
||||
if os.path.isdir(os.path.join(path, o))
|
||||
]
|
||||
for path_entry in folders:
|
||||
print(path_entry)
|
||||
if os.path.isfile(os.path.join(path_entry,FILE_GT_COCO)):
|
||||
change_categories_name(path_entry)
|
||||
else:
|
||||
explore(path_entry)
|
||||
|
||||
if Not_Categories_Name:
|
||||
explore(res_dir)
|
||||
return 0 # success
|
||||
|
||||
def _get_models(par, data) -> int:
|
||||
global all_meshs
|
||||
|
||||
par.models = lambda: None
|
||||
par.models.n_item = len(data)
|
||||
if par.models.n_item == 0:
|
||||
return 0 # no models
|
||||
|
||||
# загрузим объекты
|
||||
par.models.names = [] # obj_names
|
||||
par.models.filenames = [] # obj_filenames
|
||||
i = 1
|
||||
for f in data:
|
||||
nam = f["name"]
|
||||
par.models.names.append(nam)
|
||||
ff = f["fbx"] # _get_path_model(nam)
|
||||
par.models.filenames.append(ff)
|
||||
if not os.path.isfile(ff):
|
||||
print(f"Error: no such file '{ff}'")
|
||||
return -1
|
||||
# !!! dir with meshs
|
||||
par.details_dir = os.path.split(ff)[0]
|
||||
|
||||
obj = bproc.loader.load_obj(ff)
|
||||
all_meshs += obj
|
||||
obj[0].set_cp("category_id", i) # начиная с 1
|
||||
i += 1
|
||||
return par.models.n_item
|
||||
|
||||
def _get_scene(par, data) -> int:
|
||||
# load scene
|
||||
par.scene = lambda: None
|
||||
objs = data["objects"]
|
||||
par.scene.n_obj = len(objs)
|
||||
if par.scene.n_obj == 0:
|
||||
return 0 # empty scene
|
||||
lights = data["lights"]
|
||||
par.scene.n_light = len(lights)
|
||||
if par.scene.n_light == 0:
|
||||
return 0 # no lighting
|
||||
if len(rnd_par.details_dir) == 0:
|
||||
return 0 # no path to details
|
||||
|
||||
par.scene.objs = []
|
||||
par.scene.collision_objects = []
|
||||
for f in objs:
|
||||
ff = _get_path_object(f["name"])
|
||||
if not os.path.isfile(ff):
|
||||
print(f"Error: no such file '{ff}'")
|
||||
return -1
|
||||
obj = bproc.loader.load_obj(ff)
|
||||
obj[0].set_cp("category_id", 999)
|
||||
coll = f["collision_shape"]
|
||||
if len(coll) > 0:
|
||||
obj[0].enable_rigidbody(False, collision_shape=coll)
|
||||
par.scene.collision_objects += obj
|
||||
par.scene.objs += obj
|
||||
|
||||
if not par.scene.collision_objects:
|
||||
print("Collision objects not found in the scene")
|
||||
return 0
|
||||
par.scene.obj_data = objs
|
||||
par.scene.light_data = lights
|
||||
return par.scene.n_obj
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--form", required=True, help="Json-string with dataset parameters")
|
||||
parser.add_argument("--path", required=True, help="Output path")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.form[-5:] == ".json":
|
||||
if not os.path.isfile(args.form):
|
||||
print(f"Error: no such file '{args.form}'")
|
||||
exit(-1)
|
||||
with open(args.form, "r") as f:
|
||||
j_data = f.read()
|
||||
else:
|
||||
j_data = args.form
|
||||
try:
|
||||
cfg = json.loads(j_data)
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"JSon error: {e}")
|
||||
exit(-2)
|
||||
|
||||
# output_dir = args.path
|
||||
|
||||
ds_cfg = cfg["output"] # dataset config
|
||||
generation = ds_cfg["generation"]
|
||||
cam_pos = ds_cfg["camera_position"]
|
||||
models_randomization = ds_cfg["models_randomization"]
|
||||
|
||||
rnd_par = lambda: None
|
||||
rnd_par.output_dir = args.path # cfg["local_path"]
|
||||
|
||||
if not os.path.isdir(rnd_par.output_dir):
|
||||
print(f"Error: invalid path '{rnd_par.output_dir}'")
|
||||
exit(-3)
|
||||
|
||||
rnd_par.single_object = False # True
|
||||
rnd_par.details_dir = ""
|
||||
# rnd_par.ds_name = os.path.split(rnd_par.output_dir)[1] # cfg["name"]
|
||||
rnd_par.dataset_objs = ds_cfg["datasetObjects"]["details"] # ["knight"]
|
||||
rnd_par.n_cam_pose = generation["n_cam_pose"]
|
||||
rnd_par.n_sample_on_pose = generation["n_sample_on_pose"]
|
||||
rnd_par.n_series = generation["n_series"]
|
||||
rnd_par.image_format = generation["image_format"]
|
||||
rnd_par.image_size_wh = generation["image_size_wh"]
|
||||
rnd_par.center_shell = cam_pos["center_shell"]
|
||||
rnd_par.radius_range = cam_pos["radius_range"]
|
||||
rnd_par.elevation_range = cam_pos["elevation_range"]
|
||||
rnd_par.models_randomization = models_randomization
|
||||
rnd_par.loc_range_low = models_randomization["loc_range_low"]
|
||||
rnd_par.loc_range_high = models_randomization["loc_range_high"]
|
||||
|
||||
bproc.init()
|
||||
|
||||
all_meshs = []
|
||||
if _get_models(rnd_par, rnd_par.dataset_objs) <= 0:
|
||||
print("Error: no models in config")
|
||||
exit(-4)
|
||||
if _get_scene(rnd_par, ds_cfg["scene"]) <= 0:
|
||||
print("Error: empty scene in config")
|
||||
exit(-5)
|
||||
exit(render())
|
|
@ -1,17 +0,0 @@
|
|||
# Фреймворк: отладка.
|
||||
|
||||
После того как был отлажен механизм обнаружения объектов на основе метода YoloV4 и в результате его испытаний, нами было принято решение имплементировать более совершенный и современный метод Yolo 8-ой версии ([YoloV8](https://github.com/ultralytics/ultralytics)).
|
||||
На основе предыдущего опыта был взят за основу lifecycle-узел ROS2, который управлялся бы исполнением действий деревьев поведения (Behavior Tree). В ходе работы над этим модулем и дальнейшей отладки выявились преимущества метода YoloV8 в сравнении с YoloV4: файл весов модели 8-й версии по размеру составил около 6 МБ, в 4-й - около 244 МБ. Также на реальных изображениях распечатанных нами моделей улучшилась их точность распознавания (рис.1). В качестве моделей мы использовали набор шахматных фигур, распечатанных на 3D-принтере.
|
||||
|
||||

|
||||
Рис.1
|
||||
|
||||
Когда отлаживался модуль распознавания объектов (Object Detection), выявилась сложность проектирования и отладки этого навыка. Необходимо было кроме основной логики ROS-узла создавать и отлаживать передачу параметров в дереве поведения. И была предложена схема обобщения интерфейса для любых навыков.
|
||||
|
||||

|
||||
|
||||
В ней предположено использовать отдельный интерфейсный узел (Interface Node), который будет реализовывать взаимодействие системы исполнения дерева поведения (BT Engine Node) c библиотекой навыков. А сами навыки предложено упаковывать в отдельные ROS-пакеты с json-файлом описания, который позволит декларативно описывать элементы интерфейса, а также схему запуска навыков.
|
||||
|
||||
Такой интерфейсный узел был реализован и позволил упростить как составление и выполнение дерева поведения, так и облегчить создание самой библиотеки навыков.
|
||||
|
||||
Первым навыком, который использовал интерфейсный узел, стала имплементация метода оценки 6D-позы объекта [DOPE](https://github.com/NVlabs/Deep_Object_Pose).
|
Before Width: | Height: | Size: 166 KiB |
Before Width: | Height: | Size: 46 KiB |
|
@ -1,123 +0,0 @@
|
|||
# Рандомизация
|
||||
|
||||
### При обучении робота (Илья Ураев)
|
||||
|
||||
- Гравитация
|
||||
- Положение камеры
|
||||
- Конфигурацию робота (положение джоинтов так называется)
|
||||
- Положение объекта или точки куда надо дотянутся
|
||||
- Текстуру поверхности размещения
|
||||
- Ну и я думаю чтобы с robot_builder смотрелось, то можно рандомизировать число степеней свободы робота.
|
||||
- Можно рандомизировать позиции спавна робота
|
||||
|
||||
### При создании датасета (Александр Шушпанов)
|
||||
|
||||
- Зона локации (спавна) активных объектов
|
||||
- Позиция камеры: радиус сферы размещения и наклон, центр этой сферы
|
||||
- Источники света: количество, тип, локализация в пространстве, цветность, сила света
|
||||
- Свойства материала по отражению света: зеркальность, шероховатость, металлизация, цвет
|
||||
|
||||
Гиперпараметры.
|
||||
- количество серий (спавна активных объектов)
|
||||
- количество позиций камеры на одну серию
|
||||
- количество сдвигов камеры на 1 позу
|
||||
|
||||
### Общий список параметров рандомизации
|
||||
|
||||
- Положение искомого(активного) объекта(-ов) в рабочей зоне
|
||||
- Позиция камеры: радиус сферы размещения и наклон, центр этой сферы
|
||||
- Текстуры повехностей объектов и/или свойства материала по отражению света: зеркальность, шероховатость, металлизация, цвет
|
||||
- Источники света: количество, тип, локализация в пространстве, цветность, сила света
|
||||
- Конфигурация робота (положение джоинтов), число степеней свободы и его начальное расположение
|
||||
- Гравитация
|
||||
|
||||
## Web-сервис для генерации датасетов
|
||||
|
||||
Для реализации пользовательского интерфейса web-сервиса нами была разработана схема описания параметров рандомизации. Её использование позволяет изменять конфигурацию параметров в зависимости от задачи. Предполагается в дальнейшем использовать модуль ввода параметров в том числе и в задачах обучения с подкреплением.
|
||||
|
||||
Пример такой схемы:
|
||||
```
|
||||
ENUM T = "ObjectDetection","PoseEstimation"
|
||||
ENUM C = "","BOX","SPHERE","CAPSULE","CYLINDER","CONE","CONVEX_HULL","MESH","COMPOUND"
|
||||
ENUM L = "POINT","SUN"
|
||||
ENUM F = "JPEG","PNG"
|
||||
|
||||
MODELS = {
|
||||
"id": ${ID:number:1},
|
||||
"name": ${NAME:string:""},
|
||||
"model": ${MODEL:string:"models/1.fbx"}
|
||||
}
|
||||
OBJECTS_SCENE = {
|
||||
"name": ${NAME:string:""},
|
||||
"collision_shape": ${enum:C:"BOX"},
|
||||
"loc_xyz": [${LOC_XYZ_1:number:0}, ${LOC_XYZ_2:number:0}, ${LOC_XYZ_3:number:0}],
|
||||
"rot_euler": [${ROT_EULER_1:number:0}, ${ROT_EULER_2:number:0}, ${ROT_EULER_3:number:0}],
|
||||
"material_randomization": {
|
||||
"specular": [${SPECULAR_1:number:0}, ${SPECULAR_2:number:1}],
|
||||
"roughness": [${ROUGHNESS_1:number:0}, ${ROUGHNESS_2:number:1}],
|
||||
"metallic": [${METALLIC_1:number:0}, ${METALLIC_2:number:1}],
|
||||
"base_color": [
|
||||
[
|
||||
${BASE_COLOR_1:number:0},
|
||||
${BASE_COLOR_2:number:0},
|
||||
${BASE_COLOR_3:number:0},
|
||||
${BASE_COLOR_4:number:1}
|
||||
],
|
||||
[
|
||||
${BASE_COLOR_5:number:1},
|
||||
${BASE_COLOR_6:number:1},
|
||||
${BASE_COLOR_7:number:1},
|
||||
${BASE_COLOR_8:number:1}
|
||||
]
|
||||
]
|
||||
}
|
||||
}
|
||||
LIGHTS = {
|
||||
"id": ${ID:number:1},
|
||||
"type": ${enum:L:"POINT"},
|
||||
"loc_xyz": [${LOC_XYZ_1:number:5}, ${LOC_XYZ_2:number:5}, ${LOC_XYZ_3:number:5}],
|
||||
"rot_euler": [${ROT_EULER_1:number:-0.06}, ${ROT_EULER_2:number:0.61}, ${ROT_EULER_3:number:-0.19}],
|
||||
"color_range_low": [${COLOR_RANGE_LOW_1:number:0.5}, ${COLOR_RANGE_LOW_2:number:0.5}, ${COLOR_RANGE_LOW_3:number:0.5}],
|
||||
"color_range_high":[${COLOR_RANGE_HIGH_1:number:1}, ${COLOR_RANGE_HIGH_2:number:1}, ${COLOR_RANGE_HIGH_3:number:1}],
|
||||
"energy_range":[${ENERGY_RANGE_1:number:400},${ENERGY_RANGE_2:number:900}]
|
||||
}
|
||||
|
||||
{
|
||||
"typedataset": ${enum:T:"ObjectDetection"},
|
||||
"dataset_path": ${DATASET_PATH:string},
|
||||
"models":${ARRAY:MODELS:[]},
|
||||
"models_randomization":{
|
||||
"loc_range_low": [${LOC_RANGE_LOW_1:number:-1}, ${LOC_RANGE_LOW_2:number:-1}, ${LOC_RANGE_LOW_3:number:0}],
|
||||
"loc_range_high": [${LOC_RANGE_HIGH_1:number:1}, ${LOC_RANGE_HIGH_2:number:1}, ${LOC_RANGE_HIGH_3:number:2}]
|
||||
},
|
||||
"scene":{
|
||||
"objects": ${ARRAY:OBJECTS_SCENE:[]},
|
||||
"lights": ${ARRAY:LIGHTS:[]},
|
||||
},
|
||||
"camera_position":{
|
||||
"center_shell": [${CENTER_SHELL_1:number:0}, ${CENTER_SHELL_2:number:0}, ${CENTER_SHELL_3:number:0}],
|
||||
"radius_range": [${RADIUS_RANGE_1:number:0.4}, ${RADIUS_RANGE_2:number:1.4}],
|
||||
"elevation_range": [${ELEVATION_RANGE_1:number:10}, ${ELEVATION_RANGE_2:number:90}]
|
||||
},
|
||||
"generation":{
|
||||
"n_cam_pose": ${N_CAM_POSE:number:5},
|
||||
"n_sample_on_pose": ${N_SAMPLE_ON_POSE:number:3},
|
||||
"n_series": ${N_SERIES:number:100},
|
||||
"image_format": ${enum:F:"jpg"},
|
||||
"image_size_wh": [${IMAGE_SIZE_WH_1:number:640}, ${IMAGE_SIZE_WH_2:number:480}]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Вначале описываются перечисления - ENUM, которым присваиваются имена и список возможных значений. Затем описываются составные именованные объекты, а затем основной блок описания параметров. Этот блок представляет из себя JSON-словарь параметров, который будет подготовлен на выходе модуля ввода параметров. Каждый ключ этого словаря дополняется мини-схемой описания вводимого значения.
|
||||
Формат:
|
||||
```
|
||||
${<имя_переменной>:<тип>:<значение_по_умолчанию>}
|
||||
```
|
||||
либо массив объектов
|
||||
```
|
||||
${ARRAY:<имя_объекта>:[]}
|
||||
```
|
||||
|
||||
В нашем алгоритме формирования датасета для задач компьютерного зрения (ObjectDetection, PoseEstimation) выбран формат [BOP: Benchmark for 6D Object Pose Estimation](https://bop.felk.cvut.cz/home/), в его [BOP-Classic](https://bop.felk.cvut.cz/datasets/) версии.
|
||||
Он содержит в своей аннотации все необходимые данные (ground truth) для обучения нейросетевых моделей поиску объектов на изображении, а также распознавания поз искомых объектов.
|
|
@ -1,377 +1,3 @@
|
|||
## Мета-модель фреймворка
|
||||
|
||||
## Соответствие Digital Twin Definition Language и мета-модели Robossembler
|
||||
|
||||
Слои абстракции
|
||||
1. DTDL - BASETYPES, COMPLEXTYPES (Array, Map, ...), DT_TYPES
|
||||
2. ROBOSSEMBLER_CONTEXT (Represents)
|
||||
3. USE_CASE_CONTEXT (Entities)
|
||||
4. USE_CASE_INSTANCE (Product)
|
||||
|
||||
## Сравнение мета-моделей Digital Twin Definition Language и ROS 2
|
||||
|
||||
| Сущность | DTDL | ROS | Robonomics |
|
||||
| - | - | - | - |
|
||||
| Описывает всё содержимое двойника, включая ниже приведённые сущности | **Interface** | **Interface Spec** | - |
|
||||
| Передаваемые данные и их тип | **Telemetry** | **Topic** | **Datalog Hash** |
|
||||
| Свойство, описывающее какое-то состояние двойника, может быть read-only или read/write; также описывает синхронизацию состояния между компонентами (например, показание датчика записано в облако) | **Property** | **Parameters** | **Launch Param** |
|
||||
| Функция или операция, которая может быть осуществлена над двойником (например, `reboot`) | **Command** | **Service** / **Action** | **Launch** |
|
||||
| Структура из примитивных типов (Array, Enum, Map, Object) данных для сериализации (в JSON, Avro, Protobuf) | **Schema** | **IDL** | - |
|
||||
| Часть интерфейса (отношение part-of с каким-то другим двойником) | **Component** | - | - |
|
||||
| Связь с другим цифровым двойником. Связи могут представлять различные семантические значения. Например, `contains` ("этаж содержит комнату"), `cools` ("hvac cools room"), `isBilledTo` ("счёт выставляется пользователю") | **Relationship** | - | - |
|
||||
|
||||
|
||||
```json
|
||||
# базовые типы значений (из JSON Schema)
|
||||
"string","number", "boolean", "array", "object";
|
||||
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"REPRESENT": {
|
||||
"type": {
|
||||
"enum": [ "OBJECT_LINK", "KEY", "FILEPATH", "VALUE", "TREE", "ARRAY", "SEQUENCE" ]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# представления
|
||||
ENUM REPRESENT = "OBJECT_LINK", # строка-ссылка на объект (ENTITY)
|
||||
"KEY", # уникальный ключ в виде строки (используется как идентификатор записи)
|
||||
"FILEPATH", # строка - путь к файлу
|
||||
"VALUE", # непосредственное значение
|
||||
"TREE", # представление в виде дерева
|
||||
"ARRAY", # массив значений
|
||||
"SEQUENCE"; # массив ссылок на объект определённого типа
|
||||
|
||||
# сущности
|
||||
|
||||
ENUM ENTITY = "MESH", "PART", "ASSET", "BTREE", "BTACTION", "SKILL", "DATASET", "INTERFACE", "WEIGHTS", "DEVICE";
|
||||
|
||||
ENUM DEVICE = "ROBOT", "SENSOR";
|
||||
|
||||
type SCENE = {
|
||||
"objects": [ { ref: "1", type: "PART" }; { ref: "2", type: "PART" }; ]
|
||||
};
|
||||
|
||||
type PARAM = {
|
||||
"sid": \${KEY:string:""},
|
||||
"name": \${NAME:string:""},
|
||||
"represent": \${REPRESENT:Enum<REPRESENT>:"VALUE"},
|
||||
"link": \${LINK:Enum<LINK>:"topic"}
|
||||
};
|
||||
|
||||
### тип поверхность детали
|
||||
|
||||
type MESH/SURFACE = {
|
||||
"sid": \${KEY:string:""};
|
||||
"path": { "stl": "PATH/*.stl", "brep": "PATH/*.brep", "fbx": "PATH/*.fbx", }
|
||||
};
|
||||
|
||||
type PART = {
|
||||
"sid": \${NAME:string:""},
|
||||
"name": \${NAME:string:""},
|
||||
"pose6d": { "loc_xyz": \${XYZ:Array<number>3:[0.0,0.0,0.0] }, "rot_xyzw": \${XYZW:Array<number>4:[0.0,0.0,0.0,1.0]} },
|
||||
"attributes": [
|
||||
"Robossembler_NonSolid": True
|
||||
],
|
||||
"surface": { "stl": "PATH/*.stl", "brep": "PATH/*.brep", },
|
||||
"material": "/path/to/robossembler/materials/mmm.FCMat",
|
||||
"unit_scale": \${UNIT_SCALE:number:1.0},
|
||||
"dimensions": \${Array<number>3:[0.0,0.0,0.0]},
|
||||
"assets": { "fbx": "PATH/*.fbx", "blend": "PATH/*.blend", }
|
||||
};
|
||||
|
||||
type DATASET = {
|
||||
"sid": \${NAME:string:""},
|
||||
"name": \${NAME:string:""},
|
||||
"objects": \${SEQUENCE:PART},
|
||||
"environment": \${SEQUENCE:PART},
|
||||
"randomisation": \${FILE}
|
||||
};
|
||||
|
||||
type WEIGHTS = {
|
||||
"sid": \${NAME:string:""},
|
||||
"name": \${NAME:string:""},
|
||||
"file": \${FILE:string:"*.pth"},
|
||||
"epoch": \${EPOCH:number:""},
|
||||
"dataset": \${OBJECT_LINK:DATASET}
|
||||
};
|
||||
|
||||
type TOPIC = {
|
||||
"sid": ...,
|
||||
"name": "topic_name",
|
||||
"msg": "sensor_msgs/Image",
|
||||
};
|
||||
|
||||
DEVICE = {
|
||||
"sid": 1235,
|
||||
"name": "dev",
|
||||
"topics": \${SEQUENCE:TOPIC},
|
||||
}
|
||||
|
||||
// DEVICE -> TOPIC LIST -> {DEVICE: {TOPIC LIST}}
|
||||
|
||||
type POSE_ESTIMATION = {
|
||||
"object_name": \${OBJECT_LINK:PART},
|
||||
"weights": \${OBJECT_LINK:WEIGHTS},
|
||||
"topic_name": \${OBJECT_LINK:TOPIC}
|
||||
};
|
||||
|
||||
type SKILL = {
|
||||
"sid": \${NAME:string:""},
|
||||
"name": \${NAME:string:""},
|
||||
"interface": \${INTERFACE}
|
||||
};
|
||||
|
||||
command_LifeCycle = "run", "stop"
|
||||
|
||||
type ASSEMBLY_SEQUENCE = \{SEQUENCE:TASK};
|
||||
|
||||
# task1 = { source_state = []; target_state = [ p1 ] }
|
||||
# task2 = { source_state = [ p1 ]; target_state = [ p1 p2 ] }
|
||||
# task3 = { source_state = [ p1 p2 ]; target_state = [ p1 p2 p3 ] }
|
||||
|
||||
task = { source_state = \${TREE:PART}; target_state = \${TREE:PART} }
|
||||
|
||||
type TASK = {
|
||||
"sid": ...
|
||||
"action": \${BT_TREE}
|
||||
"source_state": \${TREE:PART} // PART
|
||||
"target_state": \${TREE:PART} // PRODUCT
|
||||
};
|
||||
|
||||
type DOMAIN = {
|
||||
"objects": \{SEQUENCE:PART}
|
||||
"predicates": \{OBJECT_LINK:CONDITION}
|
||||
"actions": \${OBJECT_LINK:BT_ACTION}
|
||||
};
|
||||
|
||||
type BTREE = {
|
||||
"sid": \${NAME:string:""},
|
||||
"name": \${NAME:string:""},
|
||||
};
|
||||
|
||||
```
|
||||
|
||||
## Device Package
|
||||
|
||||
### Camera
|
||||
|
||||
```json
|
||||
{
|
||||
"DevicePackage": { "name": "Robossembler", "version": "1.0", "format": "1" },
|
||||
"Module": { "name": "RealSense Dxx", "description": "ROS Wrapper for Intel(R) RealSense(TM) Cameras" },
|
||||
"Launch": { "package": "realsense2_camera", "executable": "rs_launch.py" },
|
||||
"DTwin": [
|
||||
{ "interface": {
|
||||
"input": [
|
||||
{ "name": "camera_namespace", "type": "STRING" }, // -- /robot_drawer/455_1/camera_info
|
||||
{ "name": "camera_name", "type": "STRING" },
|
||||
{ "name": "serial_port", "type": "STRING" },
|
||||
],
|
||||
"output": [
|
||||
{ "name": "camera_info", "type": "TOPIC", "topic_name": "/${camera_namespace}/${camera_name}/camera_info" },
|
||||
{ "name": "pose", "type": "TOPIC", "msg": "Pose" }
|
||||
]
|
||||
},
|
||||
}
|
||||
],
|
||||
"Settings": [
|
||||
{ "name": "camera_config", "description": "Camera Config", "type":"file", "defaultValue": "{ rgb_camera.profile: 1280x720x15 }" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Robot RBS
|
||||
|
||||
|
||||
```json
|
||||
{
|
||||
"DevicePackage": { "name": "Robossembler", "version": "1.0", "format": "1" },
|
||||
"Module": { "name": "RBS", "description": "Main Robot" },
|
||||
"Launch": { "package": "rbs_bringup", "executable": "single_robot.launch.py" },
|
||||
"DTwin": [
|
||||
{ "interface": {
|
||||
"input": [
|
||||
{ "name": "robot_namespace", "type": "STRING", "defaultValue": "rbs_arm" },
|
||||
{ "name": "dof", "type": "INT", "defaultValue": 6 }
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"Settings": [
|
||||
{ "name": "robot_type", "description": "Type of robot by name", "defaultValue": "rbs_arm" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Robot UR5
|
||||
|
||||
|
||||
```json
|
||||
{
|
||||
"DevicePackage": { "name": "Robossembler", "version": "1.0", "format": "1" },
|
||||
"Module": { "name": "UR", "description": "..." },
|
||||
"Launch": { "package": "ur_package", "executable": "ur5_single_arm.py" },
|
||||
"DTwin": [
|
||||
{ "interface": {
|
||||
"input": [
|
||||
{ "robot_namespace": "robot1" },
|
||||
],
|
||||
},
|
||||
}
|
||||
],
|
||||
"Settings": [
|
||||
{ "name": "", "description": "Config", "type":"file", "defaultValue": "{}" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"SkillPackage": { "name": "Robossembler", "version": "1.0", "format": "1" },
|
||||
"Module": { "name": "PoseEstimation", "description": "Pose Estimation skill with DOPE" },
|
||||
"Launch": { "package": "rbs_perception", "executable": "pe_dope_lc.py", "name": "lc_dope" },
|
||||
"BTAction": [
|
||||
{ "name": "peConfigure",
|
||||
"type": "run",
|
||||
"interface": {
|
||||
"input": [
|
||||
{ "name": "image_raw", "type": "TOPIC", "msg": "Image" },
|
||||
{ "name": "camera_info", "type": "TOPIC", "msg": "CameraInfo" },
|
||||
{ "name": "object_name", "type": "PART", "msgs": "Part" }, // string
|
||||
{ "name": "weights", "type": "WEIGHTS", "msgs": "" },
|
||||
],
|
||||
"output": [
|
||||
{ "name": "pose_estimation", "type": "TOPIC" },
|
||||
]
|
||||
},
|
||||
},
|
||||
{ "name": "peStop", "type": "stop", "interface": { "input": [], "output": [] } }
|
||||
],
|
||||
"Settings": [
|
||||
{ "name": "publishDelay", "description": "Publish Delay", "type":"float", "defaultValue": 0.5 },
|
||||
{ "name": "tf2_send_pose", "description": "Transform Pose", "type":"int", "defaultValue": 1 },
|
||||
{ "name": "mesh_scale", "description": "Part Mesh Scale", "type":"float", "defaultValue": 0.001 }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Атомарные навыки
|
||||
|
||||
```xml
|
||||
<TreeNodesModel>
|
||||
<SubTree ID="GraspObject">
|
||||
<input_port default="false" name="__shared_blackboard"></input_port>
|
||||
<input_port name="pose_vec"/>
|
||||
<input_port name="robot_name"/>
|
||||
</SubTree>
|
||||
<Action ID="GripperAction">
|
||||
<input_port name="action">Open or close</input_port>
|
||||
<input_port name="gripper_name"/>
|
||||
</Action>
|
||||
<SubTree ID="InspectWorkspace">
|
||||
<input_port default="true" name="__shared_blackboard">
|
||||
<input_port name="pose_vec"/>
|
||||
<input_port name="robot_name"/>
|
||||
</SubTree>
|
||||
<Condition ID="IsObjectInWorkspace">
|
||||
<input_port name="topic_name"/>
|
||||
</Condition>
|
||||
<Condition ID="IsObjectVisible"/>
|
||||
<Action ID="MoveToPose">
|
||||
<input_port name="cancel_timeout"/>
|
||||
<input_port name="pose"/>
|
||||
<input_port name="robot_name"/>
|
||||
<input_port name="server_name"/>
|
||||
<input_port name="server_timeout"/>
|
||||
</Action>
|
||||
<Action ID="MoveToPoseArray">
|
||||
<input_port name="cancel_timeout"/>
|
||||
<input_port name="pose_vec_in"/>
|
||||
<output_port name="pose_vec_out"/>
|
||||
<input_port name="robot_name"/>
|
||||
<input_port name="server_name"/>
|
||||
<input_port name="server_timeout"/>
|
||||
</Action>
|
||||
<SubTree ID="PlaceObject">
|
||||
<input_port default="true" name="__shared_blackboard"></input_port>
|
||||
<input_port name="pose_vec"/>
|
||||
<input_port name="robot_name"/>
|
||||
</SubTree>
|
||||
<Action ID="PoseEstimationCleanup"/>
|
||||
<Action ID="PoseEstimationConfigure">
|
||||
<input_port name="object_name"/>
|
||||
<output_port name="topic_name"/>
|
||||
<input_port name="weight_file"/>
|
||||
</Action>
|
||||
<Action ID="RbsBtAction">
|
||||
<input_port name="command"/>
|
||||
<input_port name="do"/>
|
||||
<input_port name="server_name"/>
|
||||
<input_port name="server_timeout"/>
|
||||
</Action>
|
||||
</TreeNodesModel>
|
||||
```
|
||||
|
||||
## Пример интерфейса в DTDL
|
||||
|
||||
```json
|
||||
{
|
||||
"@context": "...;3",
|
||||
"@id": "robossember_assembly;1",
|
||||
"@type": "Interface",
|
||||
"displayName": "Bolt",
|
||||
"contents": [
|
||||
{
|
||||
"@type": "Property",
|
||||
"name": "Label",
|
||||
"schema": "string"
|
||||
},
|
||||
{
|
||||
"@type": "Property",
|
||||
"name": "mesh",
|
||||
"writable": true,
|
||||
"schema": "string"
|
||||
},
|
||||
{
|
||||
"@type": "Telemetry",
|
||||
"name": "Pose6D",
|
||||
"writable": true,
|
||||
"schema": {
|
||||
"@type": "Object",
|
||||
"fields": [
|
||||
{
|
||||
"name": "x",
|
||||
"schema": "double"
|
||||
},
|
||||
{
|
||||
"name": "y",
|
||||
"schema": "double"
|
||||
},
|
||||
{
|
||||
"name": "z",
|
||||
"schema": "double"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"@type": "Relationship",
|
||||
"name": "contains",
|
||||
"target": "dtmi:com:robossember_assembly:Bolt;1"
|
||||
},
|
||||
{
|
||||
"@type": "Component",
|
||||
"name": "frontCamera",
|
||||
"schema": "dtmi:com:example:Camera;3"
|
||||
},
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Пример файла описания сцены из Blender
|
||||
|
||||
TODO: рассписать потребность в основных элементах, что и для чего
|
||||
|
|
|
@ -1 +0,0 @@
|
|||
Subproject commit 08db6583ce94895103c94b1b70b4846ef581e624
|
505
freecad_workbench/LICENSE
Normal file
|
@ -0,0 +1,505 @@
|
|||
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!
|
||||
|
1
freecad_workbench/MANIFEST.in
Normal file
|
@ -0,0 +1 @@
|
|||
recursive-include freecad/robossembler/resources *
|
51
freecad_workbench/Makefile
Normal file
|
@ -0,0 +1,51 @@
|
|||
# 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
|
9
freecad_workbench/README.md
Normal file
|
@ -0,0 +1,9 @@
|
|||
## Модули проекта 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```
|
||||
|
127
freecad_workbench/docs/commands.md
Normal file
|
@ -0,0 +1,127 @@
|
|||
# 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 <App/Document.h>
|
||||
#include <Gui/Command.h>
|
||||
#include <Gui/Control.h>
|
||||
#include <Gui/Document.h>
|
||||
|
||||
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/Command.h>
|
||||
|
||||
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;
|
||||
}
|
||||
```
|
110
freecad_workbench/freecad/robossembler/BoMList.py
Normal file
|
@ -0,0 +1,110 @@
|
|||
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)
|
19
freecad_workbench/freecad/robossembler/CHANGELOG.md
Normal file
|
@ -0,0 +1,19 @@
|
|||
# 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
|
||||
-
|
826
freecad_workbench/freecad/robossembler/Frames.py
Normal file
|
@ -0,0 +1,826 @@
|
|||
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
|
566
freecad_workbench/freecad/robossembler/GazeboExport.py
Normal file
|
@ -0,0 +1,566 @@
|
|||
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": <obj>, "mesh": <meshuri> } }
|
||||
# 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
|
||||
|
168
freecad_workbench/freecad/robossembler/GraspPose.py
Normal file
|
@ -0,0 +1,168 @@
|
|||
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
|
||||
|
287
freecad_workbench/freecad/robossembler/GripPoseGenerator.py
Normal file
|
@ -0,0 +1,287 @@
|
|||
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("Тело не найдено в активном документе.")
|
||||
|
||||
|
504
freecad_workbench/freecad/robossembler/LICENSE
Normal file
|
@ -0,0 +1,504 @@
|
|||
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.
|
||||
|
||||
<one line to give the library's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
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!
|
11
freecad_workbench/freecad/robossembler/README.md
Normal file
|
@ -0,0 +1,11 @@
|
|||
Общее руководство работы с планировщиком сборки.
|
||||
|
||||
1. Открыть сборку. С помощью команд верстака Robossembler, используя команды "Create Assembly Parameters", "Create fastener set", "Create assembly sequence", произвести разметку элементов сборки. Произвести экспорт настроек с помощью функции
|
||||
export assembly settings. На выходе получим файл assembly_settings.json
|
||||
2. Запустить geometric_feasibility_predicate/main.py, указав в env.json значения cadFilePath (путь к сборке) и outPath (путь вывода). Рекомендуется хранить все файлы в одном месте с проектом На выходе получается файл adjacency_matrix.json
|
||||
|
||||
3. ( опционально) Запустить файл solve_optimizer , получить упрощенную матрицу смежности в виде reduced_adjacency_matrix.json
|
||||
|
||||
4. Произвести расчет последовательности доступным способом, напр. через get_sequences.json или с помощью asp.
|
||||
|
||||
5. (Если применено упрощение) Добавить исключенные компоненты с помощью соотв. функции.
|
665
freecad_workbench/freecad/robossembler/Tools.py
Normal file
|
@ -0,0 +1,665 @@
|
|||
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: <obj>, graspposes: {}, placements : {}, mesh: <mesh_uri> } }
|
||||
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
|
|
@ -0,0 +1,73 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<ui version="4.0">
|
||||
<class>FeatureFrameCreator</class>
|
||||
<widget class="QDialog" name="FeatureFrameCreator">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>235</width>
|
||||
<height>238</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="sizePolicy">
|
||||
<sizepolicy hsizetype="Minimum" vsizetype="Minimum">
|
||||
<horstretch>0</horstretch>
|
||||
<verstretch>0</verstretch>
|
||||
</sizepolicy>
|
||||
</property>
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>235</width>
|
||||
<height>238</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="baseSize">
|
||||
<size>
|
||||
<width>235</width>
|
||||
<height>238</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="windowTitle">
|
||||
<string>Feature Frame</string>
|
||||
</property>
|
||||
<widget class="QGraphicsView" name="Preview">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>30</x>
|
||||
<y>29</y>
|
||||
<width>170</width>
|
||||
<height>151</height>
|
||||
</rect>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QComboBox" name="ChoicesBox">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>30</x>
|
||||
<y>190</y>
|
||||
<width>171</width>
|
||||
<height>27</height>
|
||||
</rect>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="PickedTypeLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>35</x>
|
||||
<y>10</y>
|
||||
<width>161</width>
|
||||
<height>20</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>TextLabel</string>
|
||||
</property>
|
||||
<property name="alignment">
|
||||
<set>Qt::AlignCenter</set>
|
||||
</property>
|
||||
</widget>
|
||||
</widget>
|
||||
<resources/>
|
||||
<connections/>
|
||||
</ui>
|
520
freecad_workbench/freecad/robossembler/UI/FramePlacer.ui
Normal file
|
@ -0,0 +1,520 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<ui version="4.0">
|
||||
<class>dialog</class>
|
||||
<widget class="QDialog" name="dialog">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>299</width>
|
||||
<height>292</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="sizePolicy">
|
||||
<sizepolicy hsizetype="Minimum" vsizetype="Minimum">
|
||||
<horstretch>0</horstretch>
|
||||
<verstretch>0</verstretch>
|
||||
</sizepolicy>
|
||||
</property>
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>299</width>
|
||||
<height>292</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="windowTitle">
|
||||
<string>Part Frame Creator</string>
|
||||
</property>
|
||||
<widget class="QDoubleSpinBox" name="XBox">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>52</x>
|
||||
<y>85</y>
|
||||
<width>103</width>
|
||||
<height>27</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="toolTip">
|
||||
<string>Offset in part frame x direction</string>
|
||||
</property>
|
||||
<property name="suffix">
|
||||
<string> mm</string>
|
||||
</property>
|
||||
<property name="minimum">
|
||||
<double>-1000.000000000000000</double>
|
||||
</property>
|
||||
<property name="maximum">
|
||||
<double>1000.000000000000000</double>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QDoubleSpinBox" name="YBox">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>52</x>
|
||||
<y>118</y>
|
||||
<width>103</width>
|
||||
<height>27</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="toolTip">
|
||||
<string>offset in part frame z direction</string>
|
||||
</property>
|
||||
<property name="suffix">
|
||||
<string> mm</string>
|
||||
</property>
|
||||
<property name="minimum">
|
||||
<double>-1000.000000000000000</double>
|
||||
</property>
|
||||
<property name="maximum">
|
||||
<double>1000.000000000000000</double>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QDoubleSpinBox" name="ZBox">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>52</x>
|
||||
<y>151</y>
|
||||
<width>103</width>
|
||||
<height>27</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="toolTip">
|
||||
<string>offset in part frame z direction</string>
|
||||
</property>
|
||||
<property name="suffix">
|
||||
<string> mm</string>
|
||||
</property>
|
||||
<property name="decimals">
|
||||
<number>2</number>
|
||||
</property>
|
||||
<property name="minimum">
|
||||
<double>-1000.000000000000000</double>
|
||||
</property>
|
||||
<property name="maximum">
|
||||
<double>1000.000000000000000</double>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="XLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>9</x>
|
||||
<y>85</y>
|
||||
<width>16</width>
|
||||
<height>17</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>x</string>
|
||||
</property>
|
||||
<property name="buddy">
|
||||
<cstring>XBox</cstring>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="YLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>9</x>
|
||||
<y>118</y>
|
||||
<width>16</width>
|
||||
<height>17</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>y</string>
|
||||
</property>
|
||||
<property name="buddy">
|
||||
<cstring>YBox</cstring>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="ZLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>9</x>
|
||||
<y>151</y>
|
||||
<width>16</width>
|
||||
<height>17</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>z</string>
|
||||
</property>
|
||||
<property name="buddy">
|
||||
<cstring>ZBox</cstring>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="RollLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>161</x>
|
||||
<y>85</y>
|
||||
<width>24</width>
|
||||
<height>17</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="toolTip">
|
||||
<string>roll offset from part frame</string>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>roll</string>
|
||||
</property>
|
||||
<property name="buddy">
|
||||
<cstring>RollBox</cstring>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="PitchLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>161</x>
|
||||
<y>118</y>
|
||||
<width>35</width>
|
||||
<height>17</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="toolTip">
|
||||
<string>pitch offset from part frame</string>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>pitch</string>
|
||||
</property>
|
||||
<property name="buddy">
|
||||
<cstring>PitchBox</cstring>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="YawLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>161</x>
|
||||
<y>151</y>
|
||||
<width>29</width>
|
||||
<height>17</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="toolTip">
|
||||
<string>yaw offset from part frame</string>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>yaw</string>
|
||||
</property>
|
||||
<property name="buddy">
|
||||
<cstring>YawBox</cstring>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QDoubleSpinBox" name="RollBox">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>228</x>
|
||||
<y>85</y>
|
||||
<width>61</width>
|
||||
<height>27</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="toolTip">
|
||||
<string>roll offset from part frame</string>
|
||||
</property>
|
||||
<property name="suffix">
|
||||
<string>°</string>
|
||||
</property>
|
||||
<property name="decimals">
|
||||
<number>1</number>
|
||||
</property>
|
||||
<property name="maximum">
|
||||
<double>360.000000000000000</double>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QDoubleSpinBox" name="PitchBox">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>228</x>
|
||||
<y>118</y>
|
||||
<width>61</width>
|
||||
<height>27</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="toolTip">
|
||||
<string>pitch offset from part frame</string>
|
||||
</property>
|
||||
<property name="suffix">
|
||||
<string>°</string>
|
||||
</property>
|
||||
<property name="decimals">
|
||||
<number>1</number>
|
||||
</property>
|
||||
<property name="maximum">
|
||||
<double>360.000000000000000</double>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QDoubleSpinBox" name="YawBox">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>228</x>
|
||||
<y>151</y>
|
||||
<width>61</width>
|
||||
<height>27</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="toolTip">
|
||||
<string>yaw offset from part frame</string>
|
||||
</property>
|
||||
<property name="suffix">
|
||||
<string>°</string>
|
||||
</property>
|
||||
<property name="decimals">
|
||||
<number>1</number>
|
||||
</property>
|
||||
<property name="maximum">
|
||||
<double>360.000000000000000</double>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QPlainTextEdit" name="FrameLabelField">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>94</x>
|
||||
<y>9</y>
|
||||
<width>195</width>
|
||||
<height>31</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="sizePolicy">
|
||||
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
|
||||
<horstretch>0</horstretch>
|
||||
<verstretch>0</verstretch>
|
||||
</sizepolicy>
|
||||
</property>
|
||||
<property name="toolTip">
|
||||
<string>Label of the frame</string>
|
||||
</property>
|
||||
<property name="statusTip">
|
||||
<string>Label of the new frame</string>
|
||||
</property>
|
||||
<property name="whatsThis">
|
||||
<string>Label of the new frame, must be unique</string>
|
||||
</property>
|
||||
<property name="verticalScrollBarPolicy">
|
||||
<enum>Qt::ScrollBarAlwaysOff</enum>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="FrameLabelLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>9</x>
|
||||
<y>9</y>
|
||||
<width>79</width>
|
||||
<height>31</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Frame label</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="OffsetLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>9</x>
|
||||
<y>48</y>
|
||||
<width>281</width>
|
||||
<height>31</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="toolTip">
|
||||
<string>Define an offset from the part frame if needed</string>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Offset from part frame</string>
|
||||
</property>
|
||||
<property name="alignment">
|
||||
<set>Qt::AlignCenter</set>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="ScaleLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>160</x>
|
||||
<y>180</y>
|
||||
<width>71</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="toolTip">
|
||||
<string>Scale of the axis arrows</string>
|
||||
</property>
|
||||
<property name="statusTip">
|
||||
<string>Scale of the axis arrows</string>
|
||||
</property>
|
||||
<property name="whatsThis">
|
||||
<string>Scale of the axis arrows</string>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Axis scale</string>
|
||||
</property>
|
||||
<property name="alignment">
|
||||
<set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QDoubleSpinBox" name="ScaleBox">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>230</x>
|
||||
<y>180</y>
|
||||
<width>60</width>
|
||||
<height>27</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="toolTip">
|
||||
<string>Scale of the axis arrows</string>
|
||||
</property>
|
||||
<property name="statusTip">
|
||||
<string>Scale of the axis arrows</string>
|
||||
</property>
|
||||
<property name="whatsThis">
|
||||
<string>Scale of the axis arrows</string>
|
||||
</property>
|
||||
<property name="minimum">
|
||||
<double>0.100000000000000</double>
|
||||
</property>
|
||||
<property name="maximum">
|
||||
<double>2.000000000000000</double>
|
||||
</property>
|
||||
<property name="singleStep">
|
||||
<double>0.010000000000000</double>
|
||||
</property>
|
||||
<property name="value">
|
||||
<double>0.110000000000000</double>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="OptionsLabel">
|
||||
<property name="enabled">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>20</x>
|
||||
<y>220</y>
|
||||
<width>66</width>
|
||||
<height>31</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="visible">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Options</string>
|
||||
</property>
|
||||
<property name="buddy">
|
||||
<cstring>OptionsBox</cstring>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QComboBox" name="OptionsBox">
|
||||
<property name="enabled">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>210</x>
|
||||
<y>220</y>
|
||||
<width>78</width>
|
||||
<height>27</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="visible">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QDoubleSpinBox" name="UBox">
|
||||
<property name="enabled">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>100</x>
|
||||
<y>250</y>
|
||||
<width>62</width>
|
||||
<height>27</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="visible">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QDoubleSpinBox" name="VBox">
|
||||
<property name="enabled">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>220</x>
|
||||
<y>250</y>
|
||||
<width>62</width>
|
||||
<height>27</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="visible">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="ULabel">
|
||||
<property name="enabled">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>80</x>
|
||||
<y>250</y>
|
||||
<width>16</width>
|
||||
<height>31</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="visible">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>u</string>
|
||||
</property>
|
||||
<property name="buddy">
|
||||
<cstring>UBox</cstring>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="VLabel">
|
||||
<property name="enabled">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>200</x>
|
||||
<y>250</y>
|
||||
<width>16</width>
|
||||
<height>31</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="visible">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>v</string>
|
||||
</property>
|
||||
<property name="buddy">
|
||||
<cstring>VBox</cstring>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="CoordsLabel">
|
||||
<property name="enabled">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>20</x>
|
||||
<y>256</y>
|
||||
<width>51</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="visible">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Coords:</string>
|
||||
</property>
|
||||
</widget>
|
||||
</widget>
|
||||
<resources/>
|
||||
<connections/>
|
||||
</ui>
|
262
freecad_workbench/freecad/robossembler/UI/InsertTaskCreator.ui
Normal file
|
@ -0,0 +1,262 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<ui version="4.0">
|
||||
<class>Dialog</class>
|
||||
<widget class="QDialog" name="Dialog">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>323</width>
|
||||
<height>325</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>316</width>
|
||||
<height>325</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="windowTitle">
|
||||
<string>Dialog</string>
|
||||
</property>
|
||||
<widget class="QLabel" name="TaskLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>10</x>
|
||||
<y>20</y>
|
||||
<width>71</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Task Label</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QPushButton" name="SelectButton">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>150</x>
|
||||
<y>290</y>
|
||||
<width>161</width>
|
||||
<height>27</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Get from selection</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLineEdit" name="TaskLabelField">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>100</x>
|
||||
<y>20</y>
|
||||
<width>211</width>
|
||||
<height>27</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>0</width>
|
||||
<height>0</height>
|
||||
</size>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="HoleLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>10</x>
|
||||
<y>50</y>
|
||||
<width>31</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Hole</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="PegLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>10</x>
|
||||
<y>130</y>
|
||||
<width>31</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Peg</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="HolePartLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>50</x>
|
||||
<y>70</y>
|
||||
<width>41</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Part:</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="HoleFaceLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>50</x>
|
||||
<y>90</y>
|
||||
<width>41</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Face:</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="PegPartLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>50</x>
|
||||
<y>150</y>
|
||||
<width>41</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Part:</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="PegFaceLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>50</x>
|
||||
<y>170</y>
|
||||
<width>41</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Face:</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="HolePartField">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>100</x>
|
||||
<y>70</y>
|
||||
<width>231</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>PartLabel</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="HoleFaceIDField">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>100</x>
|
||||
<y>90</y>
|
||||
<width>231</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>FaceID</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="PegFaceIDField">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>100</x>
|
||||
<y>170</y>
|
||||
<width>231</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>FaceID</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="PegPartField">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>100</x>
|
||||
<y>150</y>
|
||||
<width>231</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>PartLabel</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="HoleFeatureSummary">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>100</x>
|
||||
<y>110</y>
|
||||
<width>231</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Feature Description</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="HoleFeatureLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>30</x>
|
||||
<y>110</y>
|
||||
<width>61</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Feature:</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="PegFeatureSummary">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>100</x>
|
||||
<y>190</y>
|
||||
<width>231</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Feature Description</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="PegFeatureLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>30</x>
|
||||
<y>190</y>
|
||||
<width>61</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Feature:</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QPushButton" name="AnimateButton">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>10</x>
|
||||
<y>290</y>
|
||||
<width>131</width>
|
||||
<height>27</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Animate</string>
|
||||
</property>
|
||||
</widget>
|
||||
</widget>
|
||||
<resources/>
|
||||
<connections/>
|
||||
</ui>
|
520
freecad_workbench/freecad/robossembler/UI/PartFrameCreator.ui
Normal file
|
@ -0,0 +1,520 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<ui version="4.0">
|
||||
<class>dialog</class>
|
||||
<widget class="QDialog" name="dialog">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>299</width>
|
||||
<height>292</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="sizePolicy">
|
||||
<sizepolicy hsizetype="Minimum" vsizetype="Minimum">
|
||||
<horstretch>0</horstretch>
|
||||
<verstretch>0</verstretch>
|
||||
</sizepolicy>
|
||||
</property>
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>299</width>
|
||||
<height>292</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="windowTitle">
|
||||
<string>Part Frame Creator</string>
|
||||
</property>
|
||||
<widget class="QDoubleSpinBox" name="XBox">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>52</x>
|
||||
<y>85</y>
|
||||
<width>103</width>
|
||||
<height>27</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="toolTip">
|
||||
<string>Offset in part frame x direction</string>
|
||||
</property>
|
||||
<property name="suffix">
|
||||
<string> mm</string>
|
||||
</property>
|
||||
<property name="minimum">
|
||||
<double>-1000.000000000000000</double>
|
||||
</property>
|
||||
<property name="maximum">
|
||||
<double>1000.000000000000000</double>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QDoubleSpinBox" name="YBox">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>52</x>
|
||||
<y>118</y>
|
||||
<width>103</width>
|
||||
<height>27</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="toolTip">
|
||||
<string>offset in part frame z direction</string>
|
||||
</property>
|
||||
<property name="suffix">
|
||||
<string> mm</string>
|
||||
</property>
|
||||
<property name="minimum">
|
||||
<double>-1000.000000000000000</double>
|
||||
</property>
|
||||
<property name="maximum">
|
||||
<double>1000.000000000000000</double>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QDoubleSpinBox" name="ZBox">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>52</x>
|
||||
<y>151</y>
|
||||
<width>103</width>
|
||||
<height>27</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="toolTip">
|
||||
<string>offset in part frame z direction</string>
|
||||
</property>
|
||||
<property name="suffix">
|
||||
<string> mm</string>
|
||||
</property>
|
||||
<property name="decimals">
|
||||
<number>2</number>
|
||||
</property>
|
||||
<property name="minimum">
|
||||
<double>-1000.000000000000000</double>
|
||||
</property>
|
||||
<property name="maximum">
|
||||
<double>1000.000000000000000</double>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="XLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>9</x>
|
||||
<y>85</y>
|
||||
<width>16</width>
|
||||
<height>17</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>x</string>
|
||||
</property>
|
||||
<property name="buddy">
|
||||
<cstring>XBox</cstring>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="YLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>9</x>
|
||||
<y>118</y>
|
||||
<width>16</width>
|
||||
<height>17</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>y</string>
|
||||
</property>
|
||||
<property name="buddy">
|
||||
<cstring>YBox</cstring>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="ZLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>9</x>
|
||||
<y>151</y>
|
||||
<width>16</width>
|
||||
<height>17</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>z</string>
|
||||
</property>
|
||||
<property name="buddy">
|
||||
<cstring>ZBox</cstring>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="RollLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>161</x>
|
||||
<y>85</y>
|
||||
<width>24</width>
|
||||
<height>17</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="toolTip">
|
||||
<string>roll offset from part frame</string>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>roll</string>
|
||||
</property>
|
||||
<property name="buddy">
|
||||
<cstring>RollBox</cstring>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="PitchLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>161</x>
|
||||
<y>118</y>
|
||||
<width>35</width>
|
||||
<height>17</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="toolTip">
|
||||
<string>pitch offset from part frame</string>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>pitch</string>
|
||||
</property>
|
||||
<property name="buddy">
|
||||
<cstring>PitchBox</cstring>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="YawLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>161</x>
|
||||
<y>151</y>
|
||||
<width>29</width>
|
||||
<height>17</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="toolTip">
|
||||
<string>yaw offset from part frame</string>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>yaw</string>
|
||||
</property>
|
||||
<property name="buddy">
|
||||
<cstring>YawBox</cstring>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QDoubleSpinBox" name="RollBox">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>228</x>
|
||||
<y>85</y>
|
||||
<width>61</width>
|
||||
<height>27</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="toolTip">
|
||||
<string>roll offset from part frame</string>
|
||||
</property>
|
||||
<property name="suffix">
|
||||
<string>°</string>
|
||||
</property>
|
||||
<property name="decimals">
|
||||
<number>1</number>
|
||||
</property>
|
||||
<property name="maximum">
|
||||
<double>360.000000000000000</double>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QDoubleSpinBox" name="PitchBox">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>228</x>
|
||||
<y>118</y>
|
||||
<width>61</width>
|
||||
<height>27</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="toolTip">
|
||||
<string>pitch offset from part frame</string>
|
||||
</property>
|
||||
<property name="suffix">
|
||||
<string>°</string>
|
||||
</property>
|
||||
<property name="decimals">
|
||||
<number>1</number>
|
||||
</property>
|
||||
<property name="maximum">
|
||||
<double>360.000000000000000</double>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QDoubleSpinBox" name="YawBox">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>228</x>
|
||||
<y>151</y>
|
||||
<width>61</width>
|
||||
<height>27</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="toolTip">
|
||||
<string>yaw offset from part frame</string>
|
||||
</property>
|
||||
<property name="suffix">
|
||||
<string>°</string>
|
||||
</property>
|
||||
<property name="decimals">
|
||||
<number>1</number>
|
||||
</property>
|
||||
<property name="maximum">
|
||||
<double>360.000000000000000</double>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QPlainTextEdit" name="FrameLabelField">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>94</x>
|
||||
<y>9</y>
|
||||
<width>195</width>
|
||||
<height>31</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="sizePolicy">
|
||||
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
|
||||
<horstretch>0</horstretch>
|
||||
<verstretch>0</verstretch>
|
||||
</sizepolicy>
|
||||
</property>
|
||||
<property name="toolTip">
|
||||
<string>Label of the frame</string>
|
||||
</property>
|
||||
<property name="statusTip">
|
||||
<string>Label of the new frame</string>
|
||||
</property>
|
||||
<property name="whatsThis">
|
||||
<string>Label of the new frame, must be unique</string>
|
||||
</property>
|
||||
<property name="verticalScrollBarPolicy">
|
||||
<enum>Qt::ScrollBarAlwaysOff</enum>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="FrameLabelLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>9</x>
|
||||
<y>9</y>
|
||||
<width>79</width>
|
||||
<height>31</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Frame label</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="OffsetLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>9</x>
|
||||
<y>48</y>
|
||||
<width>281</width>
|
||||
<height>31</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="toolTip">
|
||||
<string>Define an offset from the part frame if needed</string>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Offset from part frame</string>
|
||||
</property>
|
||||
<property name="alignment">
|
||||
<set>Qt::AlignCenter</set>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="ScaleLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>160</x>
|
||||
<y>180</y>
|
||||
<width>71</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="toolTip">
|
||||
<string>Scale of the axis arrows</string>
|
||||
</property>
|
||||
<property name="statusTip">
|
||||
<string>Scale of the axis arrows</string>
|
||||
</property>
|
||||
<property name="whatsThis">
|
||||
<string>Scale of the axis arrows</string>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Axis scale</string>
|
||||
</property>
|
||||
<property name="alignment">
|
||||
<set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QDoubleSpinBox" name="ScaleBox">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>230</x>
|
||||
<y>180</y>
|
||||
<width>60</width>
|
||||
<height>27</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="toolTip">
|
||||
<string>Scale of the axis arrows</string>
|
||||
</property>
|
||||
<property name="statusTip">
|
||||
<string>Scale of the axis arrows</string>
|
||||
</property>
|
||||
<property name="whatsThis">
|
||||
<string>Scale of the axis arrows</string>
|
||||
</property>
|
||||
<property name="minimum">
|
||||
<double>0.100000000000000</double>
|
||||
</property>
|
||||
<property name="maximum">
|
||||
<double>2.000000000000000</double>
|
||||
</property>
|
||||
<property name="singleStep">
|
||||
<double>0.010000000000000</double>
|
||||
</property>
|
||||
<property name="value">
|
||||
<double>0.110000000000000</double>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="OptionsLabel">
|
||||
<property name="enabled">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>20</x>
|
||||
<y>220</y>
|
||||
<width>66</width>
|
||||
<height>31</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="visible">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Options</string>
|
||||
</property>
|
||||
<property name="buddy">
|
||||
<cstring>OptionsBox</cstring>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QComboBox" name="OptionsBox">
|
||||
<property name="enabled">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>210</x>
|
||||
<y>220</y>
|
||||
<width>78</width>
|
||||
<height>27</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="visible">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QDoubleSpinBox" name="UBox">
|
||||
<property name="enabled">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>100</x>
|
||||
<y>250</y>
|
||||
<width>62</width>
|
||||
<height>27</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="visible">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QDoubleSpinBox" name="VBox">
|
||||
<property name="enabled">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>220</x>
|
||||
<y>250</y>
|
||||
<width>62</width>
|
||||
<height>27</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="visible">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="ULabel">
|
||||
<property name="enabled">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>80</x>
|
||||
<y>250</y>
|
||||
<width>16</width>
|
||||
<height>31</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="visible">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>u</string>
|
||||
</property>
|
||||
<property name="buddy">
|
||||
<cstring>UBox</cstring>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="VLabel">
|
||||
<property name="enabled">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>200</x>
|
||||
<y>250</y>
|
||||
<width>16</width>
|
||||
<height>31</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="visible">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>v</string>
|
||||
</property>
|
||||
<property name="buddy">
|
||||
<cstring>VBox</cstring>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="CoordsLabel">
|
||||
<property name="enabled">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>20</x>
|
||||
<y>256</y>
|
||||
<width>51</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="visible">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Coords:</string>
|
||||
</property>
|
||||
</widget>
|
||||
</widget>
|
||||
<resources/>
|
||||
<connections/>
|
||||
</ui>
|
239
freecad_workbench/freecad/robossembler/UI/ScrewTaskCreator.ui
Normal file
|
@ -0,0 +1,239 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<ui version="4.0">
|
||||
<class>Dialog</class>
|
||||
<widget class="QDialog" name="Dialog">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>337</width>
|
||||
<height>322</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>337</width>
|
||||
<height>322</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="windowTitle">
|
||||
<string>Dialog</string>
|
||||
</property>
|
||||
<widget class="QLabel" name="HoleLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>20</x>
|
||||
<y>50</y>
|
||||
<width>31</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Hole</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="PegPartLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>60</x>
|
||||
<y>150</y>
|
||||
<width>41</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Part:</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="PegFaceLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>60</x>
|
||||
<y>170</y>
|
||||
<width>41</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Face:</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="PegFaceIDField">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>110</x>
|
||||
<y>170</y>
|
||||
<width>231</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>FaceID</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="TaskLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>20</x>
|
||||
<y>20</y>
|
||||
<width>71</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Task Label</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLineEdit" name="TaskLabelField">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>110</x>
|
||||
<y>20</y>
|
||||
<width>211</width>
|
||||
<height>27</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>0</width>
|
||||
<height>0</height>
|
||||
</size>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QPushButton" name="AnimateButton">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>20</x>
|
||||
<y>290</y>
|
||||
<width>131</width>
|
||||
<height>27</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Animate</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QPushButton" name="SelectButton">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>160</x>
|
||||
<y>290</y>
|
||||
<width>161</width>
|
||||
<height>27</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Get from selection</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="HoleFaceIDField">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>110</x>
|
||||
<y>90</y>
|
||||
<width>231</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>FaceID</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="HolePartLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>60</x>
|
||||
<y>70</y>
|
||||
<width>41</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Part:</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="HoleFaceLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>60</x>
|
||||
<y>90</y>
|
||||
<width>41</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Face:</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="PegLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>20</x>
|
||||
<y>130</y>
|
||||
<width>41</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Screw</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="HolePartField">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>110</x>
|
||||
<y>70</y>
|
||||
<width>231</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>PartLabel</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="PegPartField">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>110</x>
|
||||
<y>150</y>
|
||||
<width>231</width>
|
||||
<height>21</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>PartLabel</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="ScrewTypeLabel">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>30</x>
|
||||
<y>190</y>
|
||||
<width>66</width>
|
||||
<height>17</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Type:</string>
|
||||
</property>
|
||||
<property name="alignment">
|
||||
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QLabel" name="ScrewTypeField">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>110</x>
|
||||
<y>190</y>
|
||||
<width>161</width>
|
||||
<height>17</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>ThreadType</string>
|
||||
</property>
|
||||
</widget>
|
||||
</widget>
|
||||
<resources/>
|
||||
<connections/>
|
||||
</ui>
|
7
freecad_workbench/freecad/robossembler/__init__.py
Normal file
|
@ -0,0 +1,7 @@
|
|||
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")
|
40
freecad_workbench/freecad/robossembler/asm_graph.py
Normal file
|
@ -0,0 +1,40 @@
|
|||
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, 'path_to_img')
|
28
freecad_workbench/freecad/robossembler/asm_main.py
Normal file
|
@ -0,0 +1,28 @@
|
|||
import FreeCAD as App
|
||||
from .geometric_feasibility_predicate.main import main as asm_analysis
|
||||
from get_sequences import process_adjacency_data
|
||||
from valid_sequences import filter_valid_sequences
|
||||
from solve_optimizer import restore_full_sequence # Убедитесь, что эта функция импортирована
|
||||
from constraints_operator import collect_assembly_settings
|
||||
|
||||
def main(flag):
|
||||
# Выполняем анализ сборки и получаем необходимые данные
|
||||
#flag используется для того, чтобы выбирать между обычным и оптимизированным вариантом работы
|
||||
intersection_geometry, sequences, topologyMatrix = asm_analysis()
|
||||
adjacency_matrix = topologyMatrix.matrix
|
||||
assembly_settings = collect_assembly_settings()
|
||||
|
||||
# Упрощаем матрицу смежности
|
||||
if flag:
|
||||
simplified_matrix = simplify_adjacency_matrix(assembly_settings, adjacency_matrix)
|
||||
all_parts, graph, first_detail, leaf_nodes, all_sequences = process_adjacency_data(simplified_matrix)
|
||||
else:
|
||||
all_parts, graph, first_detail, leaf_nodes, all_sequences = process_adjacency_data(adjacency_matrix)
|
||||
|
||||
# Фильтруем допустимые последовательности
|
||||
valid_sequences = filter_valid_sequences(adjacency_matrix, sequences, assembly_settings)
|
||||
full_sequence = restore_full_sequence(assembly_settings, all_sequences)
|
||||
|
||||
return full_sequence
|
||||
|
||||
main()
|
|
@ -0,0 +1,43 @@
|
|||
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('path_to_adjacency_matrix.json')
|
||||
assembly_graph = create_assembly_graph(sequence)
|
||||
|
||||
draw_graph(assembly_graph)
|
||||
|
||||
# main()
|
23
freecad_workbench/freecad/robossembler/autodock_generator.py
Normal file
|
@ -0,0 +1,23 @@
|
|||
import FreeCAD as App
|
||||
import FreeCADGui as Gui
|
||||
import Draft
|
||||
import json
|
||||
|
||||
sequence_file = 'path_to_sequencesjson'
|
||||
|
||||
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')
|
||||
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"cadFilePath": "path/to/file",
|
||||
"outPath": "out/path"
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
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()
|
|
@ -0,0 +1,18 @@
|
|||
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
|
|
@ -0,0 +1,32 @@
|
|||
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()
|
|
@ -0,0 +1,13 @@
|
|||
from enum import Enum
|
||||
|
||||
|
||||
class FilesGenerator(Enum):
|
||||
DETAIL = 'detail.json'
|
||||
ASSEMBLY = 'assembly.json'
|
||||
|
||||
|
||||
class FolderGenerator(Enum):
|
||||
MESHES = 'meshes'
|
||||
ASSETS = 'assets'
|
||||
SDF = 'sdf'
|
||||
ASSEMBlY = 'assembly'
|
|
@ -0,0 +1,86 @@
|
|||
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)
|
|
@ -0,0 +1,33 @@
|
|||
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)
|
|
@ -0,0 +1,32 @@
|
|||
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)
|
|
@ -0,0 +1,141 @@
|
|||
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)
|
|
@ -0,0 +1,158 @@
|
|||
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("'", '"')
|
|
@ -0,0 +1,30 @@
|
|||
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)
|
|
@ -0,0 +1,40 @@
|
|||
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",
|
||||
)
|
|
@ -0,0 +1,53 @@
|
|||
import FreeCAD as App
|
||||
|
||||
class Asm4StructureParseUseCase:
|
||||
_parts = []
|
||||
_label = []
|
||||
|
||||
def getSubPartsLabel(self, group):
|
||||
groupLabel = []
|
||||
for el in group:
|
||||
if str(el) == '<Part::PartFeature>':
|
||||
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) == '<App::Link object>':
|
||||
groupParts.append(el)
|
||||
|
||||
for el in groupParts:
|
||||
if str(el) == '<App::Link object>':
|
||||
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) == '<App::Link object>':
|
||||
self._label.append({
|
||||
"level": 1,
|
||||
"attachedTo": parent.AttachedTo.split('#'),
|
||||
"label": parent.Label,
|
||||
"axis": self.getSubPartsLabel(parent.Group)
|
||||
})
|
||||
print(self._label)
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
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
|
|
@ -0,0 +1,118 @@
|
|||
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
|
|
@ -0,0 +1,35 @@
|
|||
# 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
|
|
@ -0,0 +1,58 @@
|
|||
|
||||
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}
|
|
@ -0,0 +1,74 @@
|
|||
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) == "<App::MaterialObjectPython object>":
|
||||
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
|
96
freecad_workbench/freecad/robossembler/cad_stability_check/.gitignore
vendored
Normal file
|
@ -0,0 +1,96 @@
|
|||
# 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/
|
|
@ -0,0 +1,461 @@
|
|||
# Алгоритм генерации графа с помощью оценки стабильности подсборок в физическом движке 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()
|
95
freecad_workbench/freecad/robossembler/cad_stability_input/.gitignore
vendored
Normal file
|
@ -0,0 +1,95 @@
|
|||
# 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
|
|
@ -0,0 +1,505 @@
|
|||
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!
|
||||
|
95
freecad_workbench/freecad/robossembler/cad_stability_input/cad_stability_input/.gitignore
vendored
Normal file
|
@ -0,0 +1,95 @@
|
|||
# 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
|
|
@ -0,0 +1,505 @@
|
|||
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!
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
import os
|
||||
from .version import __version__
|
||||
|
||||
ICONPATH = os.path.join(os.path.dirname(__file__), "resources")
|
|
@ -0,0 +1,89 @@
|
|||
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
|
|
@ -0,0 +1,134 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!-- Created with Inkscape (http://www.inkscape.org/) -->
|
||||
|
||||
<svg
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
width="64"
|
||||
height="64"
|
||||
id="svg2985"
|
||||
version="1.1"
|
||||
inkscape:version="0.48.5 r10040"
|
||||
sodipodi:docname="button_valid.svg">
|
||||
<defs
|
||||
id="defs2987">
|
||||
<linearGradient
|
||||
inkscape:collect="always"
|
||||
id="linearGradient3774">
|
||||
<stop
|
||||
style="stop-color:#4e9a06;stop-opacity:1"
|
||||
offset="0"
|
||||
id="stop3776" />
|
||||
<stop
|
||||
style="stop-color:#8ae234;stop-opacity:1"
|
||||
offset="1"
|
||||
id="stop3778" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
inkscape:collect="always"
|
||||
xlink:href="#linearGradient4082"
|
||||
id="linearGradient3922-0"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
gradientTransform="matrix(-0.56091264,-0.498646,0.48035179,-0.58227539,-177.89813,269.15635)"
|
||||
x1="10.387"
|
||||
y1="453.77875"
|
||||
x2="56.319412"
|
||||
y2="483.99524" />
|
||||
<linearGradient
|
||||
id="linearGradient4082">
|
||||
<stop
|
||||
id="stop4084"
|
||||
offset="0"
|
||||
style="stop-color:#4e9a06;stop-opacity:1" />
|
||||
<stop
|
||||
id="stop4086"
|
||||
offset="1"
|
||||
style="stop-color:#8ae234;stop-opacity:1" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
inkscape:collect="always"
|
||||
xlink:href="#linearGradient3774"
|
||||
id="linearGradient3780"
|
||||
x1="30"
|
||||
y1="-2"
|
||||
x2="26"
|
||||
y2="-26"
|
||||
gradientUnits="userSpaceOnUse" />
|
||||
<linearGradient
|
||||
inkscape:collect="always"
|
||||
xlink:href="#linearGradient3774"
|
||||
id="linearGradient2999"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
x1="30"
|
||||
y1="-2"
|
||||
x2="26"
|
||||
y2="-26" />
|
||||
</defs>
|
||||
<sodipodi:namedview
|
||||
id="base"
|
||||
pagecolor="#ffffff"
|
||||
bordercolor="#666666"
|
||||
borderopacity="1.0"
|
||||
inkscape:pageopacity="0.0"
|
||||
inkscape:pageshadow="2"
|
||||
inkscape:zoom="15.696216"
|
||||
inkscape:cx="42.681569"
|
||||
inkscape:cy="45.101596"
|
||||
inkscape:current-layer="g2995"
|
||||
showgrid="true"
|
||||
inkscape:grid-bbox="true"
|
||||
inkscape:document-units="px"
|
||||
inkscape:window-width="1600"
|
||||
inkscape:window-height="837"
|
||||
inkscape:window-x="0"
|
||||
inkscape:window-y="27"
|
||||
inkscape:window-maximized="1">
|
||||
<inkscape:grid
|
||||
type="xygrid"
|
||||
id="grid2983"
|
||||
empspacing="2"
|
||||
visible="true"
|
||||
enabled="true"
|
||||
snapvisiblegridlinesonly="true" />
|
||||
</sodipodi:namedview>
|
||||
<metadata
|
||||
id="metadata2990">
|
||||
<rdf:RDF>
|
||||
<cc:Work
|
||||
rdf:about="">
|
||||
<dc:format>image/svg+xml</dc:format>
|
||||
<dc:type
|
||||
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
|
||||
<dc:title></dc:title>
|
||||
</cc:Work>
|
||||
</rdf:RDF>
|
||||
</metadata>
|
||||
<g
|
||||
id="layer1"
|
||||
inkscape:label="Layer 1"
|
||||
inkscape:groupmode="layer"
|
||||
transform="translate(0,48)">
|
||||
<g
|
||||
id="g2995"
|
||||
transform="matrix(1.2252683,0,0,1.2252683,-6.3014179,2.4330891)">
|
||||
<path
|
||||
sodipodi:nodetypes="ccccccc"
|
||||
inkscape:connector-curvature="0"
|
||||
id="path4088"
|
||||
d="m 15.48076,-21.246576 10.519239,10.519232 21.038474,-21.038464 7.889428,7.889424 L 25.999999,5.0515065 7.5913312,-13.357152 z"
|
||||
style="fill:url(#linearGradient2999);fill-opacity:1;stroke:#172a04;stroke-width:1.63229537;stroke-linecap:butt;stroke-linejoin:round;stroke-opacity:1" />
|
||||
<path
|
||||
sodipodi:nodetypes="ccccccc"
|
||||
inkscape:connector-curvature="0"
|
||||
id="path3004"
|
||||
d="M 9.9510978,-13.350403 15.477822,-18.889628 26,-8.4375583 47.031855,-29.448573 52.57108,-23.872581 26,2.7352662 z"
|
||||
style="fill:none;stroke:#8ae234;stroke-width:1.63229549;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" />
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
After Width: | Height: | Size: 4.1 KiB |
|
@ -0,0 +1,142 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink"
|
||||
version="1.1"
|
||||
id="svg6248"
|
||||
height="64px"
|
||||
width="64px">
|
||||
<defs
|
||||
id="defs6250">
|
||||
<linearGradient
|
||||
id="linearGradient3253">
|
||||
<stop
|
||||
id="stop3255"
|
||||
offset="0"
|
||||
style="stop-color:#89d5f8;stop-opacity:1;" />
|
||||
<stop
|
||||
id="stop3257"
|
||||
offset="1"
|
||||
style="stop-color:#00899e;stop-opacity:1;" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id="linearGradient6816">
|
||||
<stop
|
||||
id="stop6818"
|
||||
offset="0"
|
||||
style="stop-color:#000000;stop-opacity:1;" />
|
||||
<stop
|
||||
id="stop6820"
|
||||
offset="1"
|
||||
style="stop-color:#000000;stop-opacity:0;" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id="linearGradient6781">
|
||||
<stop
|
||||
id="stop6783"
|
||||
offset="0"
|
||||
style="stop-color:#ffffff;stop-opacity:1;" />
|
||||
<stop
|
||||
id="stop6785"
|
||||
offset="1"
|
||||
style="stop-color:#3465a4;stop-opacity:0;" />
|
||||
</linearGradient>
|
||||
<radialGradient
|
||||
gradientUnits="userSpaceOnUse"
|
||||
gradientTransform="matrix(1.1581633,0,0,0.6558985,-7.29237,16.126077)"
|
||||
r="25.198714"
|
||||
fy="51.929391"
|
||||
fx="33.369828"
|
||||
cy="51.929391"
|
||||
cx="33.369828"
|
||||
id="radialGradient6822"
|
||||
xlink:href="#linearGradient6816" />
|
||||
<radialGradient
|
||||
gradientUnits="userSpaceOnUse"
|
||||
gradientTransform="matrix(0.9724373,-0.105657,5.0523169e-2,0.4650009,-0.3519546,9.5854384)"
|
||||
r="27.986705"
|
||||
fy="17.013988"
|
||||
fx="18.417862"
|
||||
cy="17.013988"
|
||||
cx="18.417862"
|
||||
id="radialGradient3259"
|
||||
xlink:href="#linearGradient3253" />
|
||||
<radialGradient
|
||||
r="27.986705"
|
||||
fy="17.013988"
|
||||
fx="18.417862"
|
||||
cy="17.013988"
|
||||
cx="18.417862"
|
||||
gradientTransform="matrix(0.9724373,-0.105657,0.05052317,0.4650009,-0.3519546,9.5854384)"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
id="radialGradient3270"
|
||||
xlink:href="#linearGradient3253" />
|
||||
</defs>
|
||||
<metadata
|
||||
id="metadata6253">
|
||||
<rdf:RDF>
|
||||
<cc:Work
|
||||
rdf:about="">
|
||||
<dc:format>image/svg+xml</dc:format>
|
||||
<dc:type
|
||||
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
|
||||
<dc:title></dc:title>
|
||||
</cc:Work>
|
||||
</rdf:RDF>
|
||||
</metadata>
|
||||
<g
|
||||
id="layer1">
|
||||
<g
|
||||
transform="matrix(-1,0,0,0.99363058,4,0.0382165)"
|
||||
id="g3913-7">
|
||||
<path
|
||||
style="fill:none;stroke:#042a2a;stroke-width:6.01919985;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:6.01920039"
|
||||
d="M -55,47.282051 -28,35.564103 -28,4.974359 -55,16.692308 z"
|
||||
id="path3003-5-3-0" />
|
||||
<path
|
||||
style="fill:none;stroke:#16d0d2;stroke-width:2.00640011;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:6.01920003"
|
||||
d="M -55,47.282051 -28,35.564103 -28,4.974359 -55,16.692308 z"
|
||||
id="path3003-5-3-1-9" />
|
||||
</g>
|
||||
<g
|
||||
transform="translate(60,0)"
|
||||
id="g3913">
|
||||
<path
|
||||
style="fill:none;stroke:#042a2a;stroke-width:6;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:6"
|
||||
d="M -55,47.307692 -28,35.615385 -28,5 -55,16.692308 z"
|
||||
id="path3003-5-3" />
|
||||
<path
|
||||
style="fill:none;stroke:#16d0d2;stroke-width:2;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:6"
|
||||
d="M -55,47.307692 -28,35.615385 -28,5 -55,16.692308 z"
|
||||
id="path3003-5-3-1" />
|
||||
</g>
|
||||
<path
|
||||
id="path3003"
|
||||
d="M 32,59 5,47.307692 5,16.692308 32,28.384615 z"
|
||||
style="fill:none;stroke:#042a2a;stroke-width:6;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" />
|
||||
<path
|
||||
id="path3003-5"
|
||||
d="M 32,59 59,47.307692 59,16.692308 32,28.384615 z"
|
||||
style="fill:none;stroke:#042a2a;stroke-width:6;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" />
|
||||
<path
|
||||
id="path3003-2-2"
|
||||
d="M 59,16.692308 32,28.384615 5,16.692308 32,5 z"
|
||||
style="fill:none;stroke:#042a2a;stroke-width:6;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" />
|
||||
<path
|
||||
id="path3003-3"
|
||||
d="M 32,59 5,47.307692 5,16.692308 32,28.384615 z"
|
||||
style="fill:none;stroke:#16d0d2;stroke-width:2;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" />
|
||||
<path
|
||||
id="path3003-5-6"
|
||||
d="M 32,59 59,47.307692 59,16.692308 32,28.384615 z"
|
||||
style="fill:none;stroke:#16d0d2;stroke-width:2;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" />
|
||||
<path
|
||||
id="path3003-2"
|
||||
d="M 59,16.692308 32,28.384615 5,16.692308 32,5 z"
|
||||
style="fill:none;stroke:#34e0e2;stroke-width:2;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" />
|
||||
</g>
|
||||
</svg>
|
After Width: | Height: | Size: 5.4 KiB |
|
@ -0,0 +1,166 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!-- Created with Inkscape (http://www.inkscape.org/) -->
|
||||
|
||||
<svg
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
version="1.1"
|
||||
width="64.1875"
|
||||
height="64.1875"
|
||||
id="svg3799"
|
||||
inkscape:version="0.91 r13725"
|
||||
sodipodi:docname="my_resources.svg">
|
||||
<sodipodi:namedview
|
||||
pagecolor="#ffffff"
|
||||
bordercolor="#666666"
|
||||
borderopacity="1"
|
||||
objecttolerance="10"
|
||||
gridtolerance="10"
|
||||
guidetolerance="10"
|
||||
inkscape:pageopacity="0"
|
||||
inkscape:pageshadow="2"
|
||||
inkscape:window-width="1855"
|
||||
inkscape:window-height="1056"
|
||||
id="namedview3241"
|
||||
showgrid="false"
|
||||
inkscape:zoom="3.2883564"
|
||||
inkscape:cx="103.51645"
|
||||
inkscape:cy="-10.131949"
|
||||
inkscape:window-x="65"
|
||||
inkscape:window-y="24"
|
||||
inkscape:window-maximized="1"
|
||||
inkscape:current-layer="svg3799" />
|
||||
<defs
|
||||
id="defs3801">
|
||||
<marker
|
||||
refX="0"
|
||||
refY="0"
|
||||
orient="auto"
|
||||
id="EmptyTriangleOutL"
|
||||
style="overflow:visible">
|
||||
<path
|
||||
d="m 5.77,0 -8.65,5 0,-10 8.65,5 z"
|
||||
transform="matrix(0.8,0,0,0.8,-4.8,0)"
|
||||
id="path4487"
|
||||
style="fill:#ffffff;fill-rule:evenodd;stroke:#000000;stroke-width:1pt" />
|
||||
</marker>
|
||||
<marker
|
||||
refX="0"
|
||||
refY="0"
|
||||
orient="auto"
|
||||
id="DotS"
|
||||
style="overflow:visible">
|
||||
<path
|
||||
d="m -2.5,-1 c 0,2.76 -2.24,5 -5,5 -2.76,0 -5,-2.24 -5,-5 0,-2.76 2.24,-5 5,-5 2.76,0 5,2.24 5,5 z"
|
||||
transform="matrix(0.2,0,0,0.2,1.48,0.2)"
|
||||
id="path4394"
|
||||
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt" />
|
||||
</marker>
|
||||
<marker
|
||||
refX="0"
|
||||
refY="0"
|
||||
orient="auto"
|
||||
id="DotL"
|
||||
style="overflow:visible">
|
||||
<path
|
||||
d="m -2.5,-1 c 0,2.76 -2.24,5 -5,5 -2.76,0 -5,-2.24 -5,-5 0,-2.76 2.24,-5 5,-5 2.76,0 5,2.24 5,5 z"
|
||||
transform="matrix(0.8,0,0,0.8,5.92,0.8)"
|
||||
id="path4388"
|
||||
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt" />
|
||||
</marker>
|
||||
<marker
|
||||
refX="0"
|
||||
refY="0"
|
||||
orient="auto"
|
||||
id="Tail"
|
||||
style="overflow:visible">
|
||||
<g
|
||||
transform="scale(-1.2,-1.2)"
|
||||
id="g4363">
|
||||
<path
|
||||
d="M -3.8048674,-3.9585227 0.54352094,0"
|
||||
id="path4365"
|
||||
style="fill:none;stroke:#000000;stroke-width:0.80000001;stroke-linecap:round" />
|
||||
<path
|
||||
d="M -1.2866832,-3.9585227 3.0617053,0"
|
||||
id="path4367"
|
||||
style="fill:none;stroke:#000000;stroke-width:0.80000001;stroke-linecap:round" />
|
||||
<path
|
||||
d="M 1.3053582,-3.9585227 5.6537466,0"
|
||||
id="path4369"
|
||||
style="fill:none;stroke:#000000;stroke-width:0.80000001;stroke-linecap:round" />
|
||||
<path
|
||||
d="M -3.8048674,4.1775838 0.54352094,0.21974226"
|
||||
id="path4371"
|
||||
style="fill:none;stroke:#000000;stroke-width:0.80000001;stroke-linecap:round" />
|
||||
<path
|
||||
d="M -1.2866832,4.1775838 3.0617053,0.21974226"
|
||||
id="path4373"
|
||||
style="fill:none;stroke:#000000;stroke-width:0.80000001;stroke-linecap:round" />
|
||||
<path
|
||||
d="M 1.3053582,4.1775838 5.6537466,0.21974226"
|
||||
id="path4375"
|
||||
style="fill:none;stroke:#000000;stroke-width:0.80000001;stroke-linecap:round" />
|
||||
</g>
|
||||
</marker>
|
||||
<marker
|
||||
refX="0"
|
||||
refY="0"
|
||||
orient="auto"
|
||||
id="Arrow1Sstart"
|
||||
style="overflow:visible">
|
||||
<path
|
||||
d="M 0,0 5,-5 -12.5,0 5,5 0,0 z"
|
||||
transform="matrix(0.2,0,0,0.2,1.2,0)"
|
||||
id="path4339"
|
||||
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt" />
|
||||
</marker>
|
||||
<marker
|
||||
refX="0"
|
||||
refY="0"
|
||||
orient="auto"
|
||||
id="Arrow1Lstart"
|
||||
style="overflow:visible">
|
||||
<path
|
||||
d="M 0,0 5,-5 -12.5,0 5,5 0,0 z"
|
||||
transform="matrix(0.8,0,0,0.8,10,0)"
|
||||
id="path4327"
|
||||
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt" />
|
||||
</marker>
|
||||
</defs>
|
||||
<metadata
|
||||
id="metadata3804">
|
||||
<rdf:RDF>
|
||||
<cc:Work
|
||||
rdf:about="">
|
||||
<dc:format>image/svg+xml</dc:format>
|
||||
<dc:type
|
||||
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
|
||||
<dc:title></dc:title>
|
||||
</cc:Work>
|
||||
</rdf:RDF>
|
||||
</metadata>
|
||||
<rect
|
||||
style="fill:none;stroke:#ff0000;stroke-width:10"
|
||||
id="rect4592"
|
||||
width="43.182667"
|
||||
height="47.440113"
|
||||
x="10.643615"
|
||||
y="8.2324944" />
|
||||
<text
|
||||
xml:space="preserve"
|
||||
style="font-style:normal;font-weight:normal;font-size:40px;line-height:125%;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
|
||||
x="19.766714"
|
||||
y="45.637199"
|
||||
id="text4594"
|
||||
sodipodi:linespacing="125%"><tspan
|
||||
sodipodi:role="line"
|
||||
id="tspan4596"
|
||||
x="19.766714"
|
||||
y="45.637199">T</tspan></text>
|
||||
</svg>
|
After Width: | Height: | Size: 5.2 KiB |
|
@ -0,0 +1 @@
|
|||
__version__ = "0.8.1"
|
|
@ -0,0 +1,47 @@
|
|||
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()
|
|
@ -0,0 +1,4 @@
|
|||
import os
|
||||
from .version import __version__
|
||||
|
||||
ICONPATH = os.path.join(os.path.dirname(__file__), "resources")
|
|
@ -0,0 +1,89 @@
|
|||
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
|
|
@ -0,0 +1,134 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!-- Created with Inkscape (http://www.inkscape.org/) -->
|
||||
|
||||
<svg
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
width="64"
|
||||
height="64"
|
||||
id="svg2985"
|
||||
version="1.1"
|
||||
inkscape:version="0.48.5 r10040"
|
||||
sodipodi:docname="button_valid.svg">
|
||||
<defs
|
||||
id="defs2987">
|
||||
<linearGradient
|
||||
inkscape:collect="always"
|
||||
id="linearGradient3774">
|
||||
<stop
|
||||
style="stop-color:#4e9a06;stop-opacity:1"
|
||||
offset="0"
|
||||
id="stop3776" />
|
||||
<stop
|
||||
style="stop-color:#8ae234;stop-opacity:1"
|
||||
offset="1"
|
||||
id="stop3778" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
inkscape:collect="always"
|
||||
xlink:href="#linearGradient4082"
|
||||
id="linearGradient3922-0"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
gradientTransform="matrix(-0.56091264,-0.498646,0.48035179,-0.58227539,-177.89813,269.15635)"
|
||||
x1="10.387"
|
||||
y1="453.77875"
|
||||
x2="56.319412"
|
||||
y2="483.99524" />
|
||||
<linearGradient
|
||||
id="linearGradient4082">
|
||||
<stop
|
||||
id="stop4084"
|
||||
offset="0"
|
||||
style="stop-color:#4e9a06;stop-opacity:1" />
|
||||
<stop
|
||||
id="stop4086"
|
||||
offset="1"
|
||||
style="stop-color:#8ae234;stop-opacity:1" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
inkscape:collect="always"
|
||||
xlink:href="#linearGradient3774"
|
||||
id="linearGradient3780"
|
||||
x1="30"
|
||||
y1="-2"
|
||||
x2="26"
|
||||
y2="-26"
|
||||
gradientUnits="userSpaceOnUse" />
|
||||
<linearGradient
|
||||
inkscape:collect="always"
|
||||
xlink:href="#linearGradient3774"
|
||||
id="linearGradient2999"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
x1="30"
|
||||
y1="-2"
|
||||
x2="26"
|
||||
y2="-26" />
|
||||
</defs>
|
||||
<sodipodi:namedview
|
||||
id="base"
|
||||
pagecolor="#ffffff"
|
||||
bordercolor="#666666"
|
||||
borderopacity="1.0"
|
||||
inkscape:pageopacity="0.0"
|
||||
inkscape:pageshadow="2"
|
||||
inkscape:zoom="15.696216"
|
||||
inkscape:cx="42.681569"
|
||||
inkscape:cy="45.101596"
|
||||
inkscape:current-layer="g2995"
|
||||
showgrid="true"
|
||||
inkscape:grid-bbox="true"
|
||||
inkscape:document-units="px"
|
||||
inkscape:window-width="1600"
|
||||
inkscape:window-height="837"
|
||||
inkscape:window-x="0"
|
||||
inkscape:window-y="27"
|
||||
inkscape:window-maximized="1">
|
||||
<inkscape:grid
|
||||
type="xygrid"
|
||||
id="grid2983"
|
||||
empspacing="2"
|
||||
visible="true"
|
||||
enabled="true"
|
||||
snapvisiblegridlinesonly="true" />
|
||||
</sodipodi:namedview>
|
||||
<metadata
|
||||
id="metadata2990">
|
||||
<rdf:RDF>
|
||||
<cc:Work
|
||||
rdf:about="">
|
||||
<dc:format>image/svg+xml</dc:format>
|
||||
<dc:type
|
||||
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
|
||||
<dc:title></dc:title>
|
||||
</cc:Work>
|
||||
</rdf:RDF>
|
||||
</metadata>
|
||||
<g
|
||||
id="layer1"
|
||||
inkscape:label="Layer 1"
|
||||
inkscape:groupmode="layer"
|
||||
transform="translate(0,48)">
|
||||
<g
|
||||
id="g2995"
|
||||
transform="matrix(1.2252683,0,0,1.2252683,-6.3014179,2.4330891)">
|
||||
<path
|
||||
sodipodi:nodetypes="ccccccc"
|
||||
inkscape:connector-curvature="0"
|
||||
id="path4088"
|
||||
d="m 15.48076,-21.246576 10.519239,10.519232 21.038474,-21.038464 7.889428,7.889424 L 25.999999,5.0515065 7.5913312,-13.357152 z"
|
||||
style="fill:url(#linearGradient2999);fill-opacity:1;stroke:#172a04;stroke-width:1.63229537;stroke-linecap:butt;stroke-linejoin:round;stroke-opacity:1" />
|
||||
<path
|
||||
sodipodi:nodetypes="ccccccc"
|
||||
inkscape:connector-curvature="0"
|
||||
id="path3004"
|
||||
d="M 9.9510978,-13.350403 15.477822,-18.889628 26,-8.4375583 47.031855,-29.448573 52.57108,-23.872581 26,2.7352662 z"
|
||||
style="fill:none;stroke:#8ae234;stroke-width:1.63229549;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" />
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
After Width: | Height: | Size: 4.1 KiB |
|
@ -0,0 +1,142 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink"
|
||||
version="1.1"
|
||||
id="svg6248"
|
||||
height="64px"
|
||||
width="64px">
|
||||
<defs
|
||||
id="defs6250">
|
||||
<linearGradient
|
||||
id="linearGradient3253">
|
||||
<stop
|
||||
id="stop3255"
|
||||
offset="0"
|
||||
style="stop-color:#89d5f8;stop-opacity:1;" />
|
||||
<stop
|
||||
id="stop3257"
|
||||
offset="1"
|
||||
style="stop-color:#00899e;stop-opacity:1;" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id="linearGradient6816">
|
||||
<stop
|
||||
id="stop6818"
|
||||
offset="0"
|
||||
style="stop-color:#000000;stop-opacity:1;" />
|
||||
<stop
|
||||
id="stop6820"
|
||||
offset="1"
|
||||
style="stop-color:#000000;stop-opacity:0;" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id="linearGradient6781">
|
||||
<stop
|
||||
id="stop6783"
|
||||
offset="0"
|
||||
style="stop-color:#ffffff;stop-opacity:1;" />
|
||||
<stop
|
||||
id="stop6785"
|
||||
offset="1"
|
||||
style="stop-color:#3465a4;stop-opacity:0;" />
|
||||
</linearGradient>
|
||||
<radialGradient
|
||||
gradientUnits="userSpaceOnUse"
|
||||
gradientTransform="matrix(1.1581633,0,0,0.6558985,-7.29237,16.126077)"
|
||||
r="25.198714"
|
||||
fy="51.929391"
|
||||
fx="33.369828"
|
||||
cy="51.929391"
|
||||
cx="33.369828"
|
||||
id="radialGradient6822"
|
||||
xlink:href="#linearGradient6816" />
|
||||
<radialGradient
|
||||
gradientUnits="userSpaceOnUse"
|
||||
gradientTransform="matrix(0.9724373,-0.105657,5.0523169e-2,0.4650009,-0.3519546,9.5854384)"
|
||||
r="27.986705"
|
||||
fy="17.013988"
|
||||
fx="18.417862"
|
||||
cy="17.013988"
|
||||
cx="18.417862"
|
||||
id="radialGradient3259"
|
||||
xlink:href="#linearGradient3253" />
|
||||
<radialGradient
|
||||
r="27.986705"
|
||||
fy="17.013988"
|
||||
fx="18.417862"
|
||||
cy="17.013988"
|
||||
cx="18.417862"
|
||||
gradientTransform="matrix(0.9724373,-0.105657,0.05052317,0.4650009,-0.3519546,9.5854384)"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
id="radialGradient3270"
|
||||
xlink:href="#linearGradient3253" />
|
||||
</defs>
|
||||
<metadata
|
||||
id="metadata6253">
|
||||
<rdf:RDF>
|
||||
<cc:Work
|
||||
rdf:about="">
|
||||
<dc:format>image/svg+xml</dc:format>
|
||||
<dc:type
|
||||
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
|
||||
<dc:title></dc:title>
|
||||
</cc:Work>
|
||||
</rdf:RDF>
|
||||
</metadata>
|
||||
<g
|
||||
id="layer1">
|
||||
<g
|
||||
transform="matrix(-1,0,0,0.99363058,4,0.0382165)"
|
||||
id="g3913-7">
|
||||
<path
|
||||
style="fill:none;stroke:#042a2a;stroke-width:6.01919985;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:6.01920039"
|
||||
d="M -55,47.282051 -28,35.564103 -28,4.974359 -55,16.692308 z"
|
||||
id="path3003-5-3-0" />
|
||||
<path
|
||||
style="fill:none;stroke:#16d0d2;stroke-width:2.00640011;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:6.01920003"
|
||||
d="M -55,47.282051 -28,35.564103 -28,4.974359 -55,16.692308 z"
|
||||
id="path3003-5-3-1-9" />
|
||||
</g>
|
||||
<g
|
||||
transform="translate(60,0)"
|
||||
id="g3913">
|
||||
<path
|
||||
style="fill:none;stroke:#042a2a;stroke-width:6;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:6"
|
||||
d="M -55,47.307692 -28,35.615385 -28,5 -55,16.692308 z"
|
||||
id="path3003-5-3" />
|
||||
<path
|
||||
style="fill:none;stroke:#16d0d2;stroke-width:2;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:6"
|
||||
d="M -55,47.307692 -28,35.615385 -28,5 -55,16.692308 z"
|
||||
id="path3003-5-3-1" />
|
||||
</g>
|
||||
<path
|
||||
id="path3003"
|
||||
d="M 32,59 5,47.307692 5,16.692308 32,28.384615 z"
|
||||
style="fill:none;stroke:#042a2a;stroke-width:6;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" />
|
||||
<path
|
||||
id="path3003-5"
|
||||
d="M 32,59 59,47.307692 59,16.692308 32,28.384615 z"
|
||||
style="fill:none;stroke:#042a2a;stroke-width:6;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" />
|
||||
<path
|
||||
id="path3003-2-2"
|
||||
d="M 59,16.692308 32,28.384615 5,16.692308 32,5 z"
|
||||
style="fill:none;stroke:#042a2a;stroke-width:6;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" />
|
||||
<path
|
||||
id="path3003-3"
|
||||
d="M 32,59 5,47.307692 5,16.692308 32,28.384615 z"
|
||||
style="fill:none;stroke:#16d0d2;stroke-width:2;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" />
|
||||
<path
|
||||
id="path3003-5-6"
|
||||
d="M 32,59 59,47.307692 59,16.692308 32,28.384615 z"
|
||||
style="fill:none;stroke:#16d0d2;stroke-width:2;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" />
|
||||
<path
|
||||
id="path3003-2"
|
||||
d="M 59,16.692308 32,28.384615 5,16.692308 32,5 z"
|
||||
style="fill:none;stroke:#34e0e2;stroke-width:2;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" />
|
||||
</g>
|
||||
</svg>
|
After Width: | Height: | Size: 5.4 KiB |
|
@ -0,0 +1,166 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!-- Created with Inkscape (http://www.inkscape.org/) -->
|
||||
|
||||
<svg
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
version="1.1"
|
||||
width="64.1875"
|
||||
height="64.1875"
|
||||
id="svg3799"
|
||||
inkscape:version="0.91 r13725"
|
||||
sodipodi:docname="my_resources.svg">
|
||||
<sodipodi:namedview
|
||||
pagecolor="#ffffff"
|
||||
bordercolor="#666666"
|
||||
borderopacity="1"
|
||||
objecttolerance="10"
|
||||
gridtolerance="10"
|
||||
guidetolerance="10"
|
||||
inkscape:pageopacity="0"
|
||||
inkscape:pageshadow="2"
|
||||
inkscape:window-width="1855"
|
||||
inkscape:window-height="1056"
|
||||
id="namedview3241"
|
||||
showgrid="false"
|
||||
inkscape:zoom="3.2883564"
|
||||
inkscape:cx="103.51645"
|
||||
inkscape:cy="-10.131949"
|
||||
inkscape:window-x="65"
|
||||
inkscape:window-y="24"
|
||||
inkscape:window-maximized="1"
|
||||
inkscape:current-layer="svg3799" />
|
||||
<defs
|
||||
id="defs3801">
|
||||
<marker
|
||||
refX="0"
|
||||
refY="0"
|
||||
orient="auto"
|
||||
id="EmptyTriangleOutL"
|
||||
style="overflow:visible">
|
||||
<path
|
||||
d="m 5.77,0 -8.65,5 0,-10 8.65,5 z"
|
||||
transform="matrix(0.8,0,0,0.8,-4.8,0)"
|
||||
id="path4487"
|
||||
style="fill:#ffffff;fill-rule:evenodd;stroke:#000000;stroke-width:1pt" />
|
||||
</marker>
|
||||
<marker
|
||||
refX="0"
|
||||
refY="0"
|
||||
orient="auto"
|
||||
id="DotS"
|
||||
style="overflow:visible">
|
||||
<path
|
||||
d="m -2.5,-1 c 0,2.76 -2.24,5 -5,5 -2.76,0 -5,-2.24 -5,-5 0,-2.76 2.24,-5 5,-5 2.76,0 5,2.24 5,5 z"
|
||||
transform="matrix(0.2,0,0,0.2,1.48,0.2)"
|
||||
id="path4394"
|
||||
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt" />
|
||||
</marker>
|
||||
<marker
|
||||
refX="0"
|
||||
refY="0"
|
||||
orient="auto"
|
||||
id="DotL"
|
||||
style="overflow:visible">
|
||||
<path
|
||||
d="m -2.5,-1 c 0,2.76 -2.24,5 -5,5 -2.76,0 -5,-2.24 -5,-5 0,-2.76 2.24,-5 5,-5 2.76,0 5,2.24 5,5 z"
|
||||
transform="matrix(0.8,0,0,0.8,5.92,0.8)"
|
||||
id="path4388"
|
||||
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt" />
|
||||
</marker>
|
||||
<marker
|
||||
refX="0"
|
||||
refY="0"
|
||||
orient="auto"
|
||||
id="Tail"
|
||||
style="overflow:visible">
|
||||
<g
|
||||
transform="scale(-1.2,-1.2)"
|
||||
id="g4363">
|
||||
<path
|
||||
d="M -3.8048674,-3.9585227 0.54352094,0"
|
||||
id="path4365"
|
||||
style="fill:none;stroke:#000000;stroke-width:0.80000001;stroke-linecap:round" />
|
||||
<path
|
||||
d="M -1.2866832,-3.9585227 3.0617053,0"
|
||||
id="path4367"
|
||||
style="fill:none;stroke:#000000;stroke-width:0.80000001;stroke-linecap:round" />
|
||||
<path
|
||||
d="M 1.3053582,-3.9585227 5.6537466,0"
|
||||
id="path4369"
|
||||
style="fill:none;stroke:#000000;stroke-width:0.80000001;stroke-linecap:round" />
|
||||
<path
|
||||
d="M -3.8048674,4.1775838 0.54352094,0.21974226"
|
||||
id="path4371"
|
||||
style="fill:none;stroke:#000000;stroke-width:0.80000001;stroke-linecap:round" />
|
||||
<path
|
||||
d="M -1.2866832,4.1775838 3.0617053,0.21974226"
|
||||
id="path4373"
|
||||
style="fill:none;stroke:#000000;stroke-width:0.80000001;stroke-linecap:round" />
|
||||
<path
|
||||
d="M 1.3053582,4.1775838 5.6537466,0.21974226"
|
||||
id="path4375"
|
||||
style="fill:none;stroke:#000000;stroke-width:0.80000001;stroke-linecap:round" />
|
||||
</g>
|
||||
</marker>
|
||||
<marker
|
||||
refX="0"
|
||||
refY="0"
|
||||
orient="auto"
|
||||
id="Arrow1Sstart"
|
||||
style="overflow:visible">
|
||||
<path
|
||||
d="M 0,0 5,-5 -12.5,0 5,5 0,0 z"
|
||||
transform="matrix(0.2,0,0,0.2,1.2,0)"
|
||||
id="path4339"
|
||||
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt" />
|
||||
</marker>
|
||||
<marker
|
||||
refX="0"
|
||||
refY="0"
|
||||
orient="auto"
|
||||
id="Arrow1Lstart"
|
||||
style="overflow:visible">
|
||||
<path
|
||||
d="M 0,0 5,-5 -12.5,0 5,5 0,0 z"
|
||||
transform="matrix(0.8,0,0,0.8,10,0)"
|
||||
id="path4327"
|
||||
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt" />
|
||||
</marker>
|
||||
</defs>
|
||||
<metadata
|
||||
id="metadata3804">
|
||||
<rdf:RDF>
|
||||
<cc:Work
|
||||
rdf:about="">
|
||||
<dc:format>image/svg+xml</dc:format>
|
||||
<dc:type
|
||||
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
|
||||
<dc:title></dc:title>
|
||||
</cc:Work>
|
||||
</rdf:RDF>
|
||||
</metadata>
|
||||
<rect
|
||||
style="fill:none;stroke:#ff0000;stroke-width:10"
|
||||
id="rect4592"
|
||||
width="43.182667"
|
||||
height="47.440113"
|
||||
x="10.643615"
|
||||
y="8.2324944" />
|
||||
<text
|
||||
xml:space="preserve"
|
||||
style="font-style:normal;font-weight:normal;font-size:40px;line-height:125%;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
|
||||
x="19.766714"
|
||||
y="45.637199"
|
||||
id="text4594"
|
||||
sodipodi:linespacing="125%"><tspan
|
||||
sodipodi:role="line"
|
||||
id="tspan4596"
|
||||
x="19.766714"
|
||||
y="45.637199">T</tspan></text>
|
||||
</svg>
|
After Width: | Height: | Size: 5.2 KiB |
|
@ -0,0 +1 @@
|
|||
__version__ = "0.8.1"
|
|
@ -0,0 +1,47 @@
|
|||
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()
|
27
freecad_workbench/freecad/robossembler/chekingEntities.py
Normal file
|
@ -0,0 +1,27 @@
|
|||
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}")
|
||||
|
||||
|
|
@ -0,0 +1,82 @@
|
|||
import networkx as nx
|
||||
|
||||
|
||||
class GraphProcessor:
|
||||
graph = None
|
||||
|
||||
def __init__(self, adjacency_matrix):
|
||||
self.adjacency_matrix = adjacency_matrix
|
||||
self.graph = self.load_graph_from_data()
|
||||
|
||||
def load_graph_from_data(self):
|
||||
G = nx.Graph()
|
||||
|
||||
for part1, neighbors in self.adjacency_matrix.items():
|
||||
for neighbor in neighbors:
|
||||
G.add_edge(part1, neighbor)
|
||||
|
||||
return G
|
||||
|
||||
|
||||
class EdgeBetweensClustering:
|
||||
def __init__(self, graph):
|
||||
self.graph = graph.copy()
|
||||
self.clusters = []
|
||||
|
||||
def cluster(self):
|
||||
while self.graph.number_of_edges() > 0:
|
||||
edge_betweens = nx.edge_betweenness_centrality(self.graph)
|
||||
max_betweens_edge = max(edge_betweens, key=edge_betweens.get)
|
||||
self.graph.remove_edge(*max_betweens_edge)
|
||||
components = list(nx.connected_components(self.graph))
|
||||
if components not in self.clusters:
|
||||
self.clusters.append(components)
|
||||
return []
|
||||
|
||||
def get_clusters(self):
|
||||
return self.clusters
|
||||
|
||||
|
||||
class ClusterisationSequenceUseCase:
|
||||
def call(self, adjacency_matrix):
|
||||
graph_processor = GraphProcessor(adjacency_matrix)
|
||||
G = graph_processor.load_graph_from_data()
|
||||
ebc = EdgeBetweensClustering(G)
|
||||
ebc.cluster()
|
||||
clusters = ebc.get_clusters()
|
||||
|
||||
for i in range(len(clusters)):
|
||||
for j in range(len(clusters[i])):
|
||||
clusters[i][j] = list(clusters[i][j])
|
||||
|
||||
# Создание списка последовательностей сборки
|
||||
assembly_sequences = []
|
||||
for cluster in clusters:
|
||||
sequence = []
|
||||
for component in cluster:
|
||||
sequence.extend(component)
|
||||
assembly_sequences.append(sequence)
|
||||
|
||||
return assembly_sequences
|
||||
|
||||
|
||||
# # Вызов функции
|
||||
# adjacency_matrix = {
|
||||
# 'body_down': ['sol_gear', 'planet_gear', 'planet_gear003', 'planet_gear004', 'planet_gear005', 'planet_gear002', 'body_up', 'bolt', 'bolt2', 'bolt3', 'bolt4'],
|
||||
# 'sol_gear': ['body_down', 'output_shaft', 'planet_gear', 'planet_gear003', 'planet_gear004', 'planet_gear005', 'planet_gear002'],
|
||||
# 'output_shaft': ['sol_gear', 'planet_gear', 'planet_gear003', 'planet_gear004', 'planet_gear005', 'planet_gear002', 'body_up'],
|
||||
# 'planet_gear': ['body_down', 'sol_gear', 'output_shaft'],
|
||||
# 'planet_gear003': ['body_down', 'sol_gear', 'output_shaft'],
|
||||
# 'planet_gear004': ['body_down', 'sol_gear', 'output_shaft'],
|
||||
# 'planet_gear005': ['body_down', 'sol_gear', 'output_shaft'],
|
||||
# 'planet_gear002': ['body_down', 'sol_gear', 'output_shaft'],
|
||||
# 'body_up': ['body_down', 'output_shaft', 'bolt', 'bolt2', 'bolt3', 'bolt4'],
|
||||
# 'bolt': ['body_down', 'body_up'],
|
||||
# 'bolt2': ['body_down', 'body_up'],
|
||||
# 'bolt3': ['body_down', 'body_up'],
|
||||
# 'bolt4': ['body_down', 'body_up']
|
||||
# }
|
||||
# print(adjacency_matrix)
|
||||
# use_case = ClusterisationSequenceUseCase()
|
||||
# assembly_sequences = use_case.call(adjacency_matrix)
|
||||
# print(assembly_sequences)
|
185
freecad_workbench/freecad/robossembler/constraints_operator.py
Normal file
|
@ -0,0 +1,185 @@
|
|||
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)
|
||||
|
||||
#для работы с данными как с переменной
|
||||
def collect_assembly_settings():
|
||||
doc = App.activeDocument()
|
||||
if not doc:
|
||||
return None
|
||||
|
||||
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 None
|
||||
|
||||
assembly_settings = []
|
||||
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
|
||||
})
|
||||
assembly_settings.append(obj_dict)
|
||||
|
||||
return assembly_settings
|
||||
|
||||
# create_fastener_set()
|
||||
# create_assembly_sequence()
|
||||
# create_clearance_constraint()
|
||||
# export_assembly_settings()
|
51
freecad_workbench/freecad/robossembler/export_entities.py
Normal file
|
@ -0,0 +1,51 @@
|
|||
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()
|
||||
|
175
freecad_workbench/freecad/robossembler/freecad_to_json.py
Normal file
|
@ -0,0 +1,175 @@
|
|||
'''
|
||||
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!')
|
|
@ -0,0 +1,2 @@
|
|||
/Users/idontsudo/Desktop/FreeCAD.app/Contents/MacOS/FreeCAD
|
||||
freecadcmd main.py
|
|
@ -0,0 +1,5 @@
|
|||
{
|
||||
"cadFilePath": "path_to_cad_file",
|
||||
"outPath": "out_path",
|
||||
"objectIndentation": 0
|
||||
}
|
|
@ -0,0 +1,63 @@
|
|||
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")
|
|
@ -0,0 +1,789 @@
|
|||
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
|
||||
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
|
||||
|
||||
#функция, проверяющая, открывается ли программа через консоль или через верстак freecad.
|
||||
def get_paths():
|
||||
if 'FreeCAD' in globals():
|
||||
active_doc = FreeCAD.activeDocument()
|
||||
if active_doc:
|
||||
cadFilePath = active_doc.FileName
|
||||
outPath = os.path.dirname(cadFilePath)
|
||||
else:
|
||||
raise Exception("Нет активного документа в FreeCAD.")
|
||||
else:
|
||||
with open('env.json', 'r', encoding='utf-8') as file:
|
||||
env_data = json.load(file)
|
||||
cadFilePath = env_data.get('cadFilePath')
|
||||
outPath = env_data.get('outPath')
|
||||
if not cadFilePath or not outPath:
|
||||
raise Exception("Не найдены cadFilePath или outPath в env.json.")
|
||||
|
||||
return cadFilePath, outPath
|
||||
|
||||
|
||||
|
||||
def main():
|
||||
if 'FreeCAD' in globals():
|
||||
active_doc = FreeCAD.activeDocument()
|
||||
if active_doc:
|
||||
cadFilePath = active_doc.FileName
|
||||
outPath = os.path.dirname(cadFilePath)
|
||||
else:
|
||||
# raise Exception("Нет активного документа в FreeCAD.")
|
||||
# else:
|
||||
env = FS.readJSON("env.json")
|
||||
print(env)
|
||||
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
|
||||
|
||||
FreeCAD.open(cadFilePath)
|
||||
|
||||
|
||||
|
||||
topologyMatrix = CadAdjacencyMatrix().matrixBySurfaces()
|
||||
|
||||
sequences = {
|
||||
"sequences": AllSequences(topologyMatrix.matrix).adj_matrix_names
|
||||
}
|
||||
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") is None:
|
||||
intersection_geometry["status"] = False
|
||||
intersection_geometry["recalculations"] = []
|
||||
intersection_geometry["recalculations"].append(
|
||||
{"area": area, "connect": el.get("child") + " " + el.get("parent")}
|
||||
)
|
||||
# print(intersection_geometry, sequences, topologyMatrix.to_dict())
|
||||
return intersection_geometry, sequences, topologyMatrix.to_dict()
|
||||
|
||||
# ExitFreeCadUseCase.call() Сейчас пока не нужна
|
||||
# return intersection_geometry, sequences, topologyMatrix.to_dict()
|
||||
|
||||
|
||||
# main()
|
77
freecad_workbench/freecad/robossembler/get_sequences.py
Normal file
|
@ -0,0 +1,77 @@
|
|||
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('path_to_adjacency_matrix.json')
|
||||
# # constraints = load_constraints('constraints.json')
|
||||
# all_parts = data['allParts']
|
||||
# print(all_parts)
|
||||
# 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)} допустимых последовательностей сборки.")
|
||||
|
||||
def process_adjacency_data(topology_matrix):
|
||||
all_parts = topology_matrix['allParts']
|
||||
graph = create_graph(topology_matrix)
|
||||
first_detail = topology_matrix['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)
|
||||
|
||||
return all_parts, graph, first_detail, leaf_nodes, all_sequences
|
|
@ -0,0 +1,26 @@
|
|||
import json
|
||||
import networkx as nx
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
# Загружаем данные из файла
|
||||
with open('path_tp_simplified_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()
|
14
freecad_workbench/freecad/robossembler/helper/fs.py
Normal file
|
@ -0,0 +1,14 @@
|
|||
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)
|
18
freecad_workbench/freecad/robossembler/helper/is_solid.py
Normal file
|
@ -0,0 +1,18 @@
|
|||
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
|
102
freecad_workbench/freecad/robossembler/init_gui.py
Normal file
|
@ -0,0 +1,102 @@
|
|||
import os
|
||||
import FreeCADGui as Gui
|
||||
import FreeCAD as App
|
||||
|
||||
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'
|
||||
|
||||
|
||||
def QT_TRANSLATE_NOOP(ctx, txt):
|
||||
return txt
|
||||
|
||||
|
||||
def translate(ctx, txt):
|
||||
return txt
|
||||
|
||||
|
||||
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())
|
162
freecad_workbench/freecad/robossembler/markup_entities.py
Normal file
|
@ -0,0 +1,162 @@
|
|||
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()
|
BIN
freecad_workbench/freecad/robossembler/pddl/Printer.FCStd
Normal file
97
freecad_workbench/freecad/robossembler/pddl/domain.pddl
Normal file
|
@ -0,0 +1,97 @@
|
|||
(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)))
|
||||
)
|
||||
)
|
||||
)
|
181
freecad_workbench/freecad/robossembler/pddl/freecad2pddl.py
Normal file
|
@ -0,0 +1,181 @@
|
|||
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()
|
||||
|
||||
|
||||
|
116
freecad_workbench/freecad/robossembler/pddl/insertion_vector_predicate/.gitignore
vendored
Normal file
|
@ -0,0 +1,116 @@
|
|||
# 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
|
|
@ -0,0 +1,33 @@
|
|||
# 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. результат : траектории вставки
|
|
@ -0,0 +1 @@
|
|||
Subproject commit 395ee5b638ccaa0cbe5b48101655560e49365195
|
|
@ -0,0 +1,205 @@
|
|||
|
||||
|
||||
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()
|
|
@ -0,0 +1,174 @@
|
|||
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 = "path_to_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()
|
|
@ -0,0 +1,3 @@
|
|||
spatialmath-python
|
||||
scipy
|
||||
uuid
|
69
freecad_workbench/freecad/robossembler/pddl/my_problem.pddl
Normal file
|
@ -0,0 +1,69 @@
|
|||
(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
|
||||
; но пока что это можно прописать текстом
|
||||
|
||||
|
||||
; предикаты -
|
||||
; рука доступна - рука
|
||||
; сборка в зоне - сборка зона
|
||||
; деталь часть сборки - деталь сборка
|
||||
; собрана - сборка
|
||||
; сборочный порядок - предсборка следсборка
|
||||
|
||||
; +
|
||||
; деталь в зоне - деталь зона
|
||||
; принтер доступен - принтер
|
||||
|
98
freecad_workbench/freecad/robossembler/pddl/printETA.py
Normal file
|
@ -0,0 +1,98 @@
|
|||
|
||||
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)
|
||||
|