2025-07-01

This commit is contained in:
2026-03-17 14:30:01 -06:00
parent f9a22056dd
commit 62b5978595
4579 changed files with 1257472 additions and 0 deletions
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://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
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+125
View File
@@ -0,0 +1,125 @@
# EdgeFlow
This addon adds operators to blender which help when dealing with curved shaped meshes.
Feel free to create issues, file requests etc. but be aware of that I might not find time to work on this as much as I'd probably need to.
## Installation
Master is stable - adventures are in the Dev branch.
The addon should work from blender 3.5+ and also work in the current blender release.
* Get the latest EdgeFlow.zip release in: https://github.com/BenjaminSauder/EdgeFlow/releases
* start Blender and open the user preferences
* switch to the Add-ons tab and click the 'Install...' button
* locate the downloaded EdgeFlow.zip file and double-click it to install
* search for the addon "EdgeFlow"
* activate the addon by ticking the checkbox (hit the Save User Settings button at the bottom if your blender is setup that way)
#### Where are these located in blender?
The operators can be accessed via the 3D View in the Mesh>Edge and Mesh>Vertex menu, the corresponding
rightclick viewport context menus or the default shortcut Ctrl-E / Ctrl-V.
![grafik](https://github.com/BenjaminSauder/EdgeFlow/assets/13512160/e29dcb97-e9fa-47b2-a789-3a800a33b35a)
## Tools
### Set Flow:
![grafik](https://github.com/BenjaminSauder/EdgeFlow/assets/13512160/5397adac-54c4-48c8-9999-e121c85db7d6)
My stab at implementing a set flow operator for blender, which is a popular tool in many 3d applications. This adjusts the edgeloop via a spline interpolation such that it respects the flow of the surrounding geometry.
The tool operates orthogonal to the direction of the flow of the edgeloop, indicated by the orange in the image.
**Mix:** Blend between intial vertex positions and the interpolated result.
**Tension:** Controls the strengh of offset.
**Iterations:** How often the operation will be repeated.
**Min Angle:** Cut off angle of the smoothing. Falls back to a linearely extrapolated position if the angle is beyond threshold.
In this example the control points for the spline smoothing are around the corner - which creates a nasty bulge. With the min angle one can force the alghorithm to find a better solution.
![grafik](https://github.com/BenjaminSauder/EdgeFlow/assets/13512160/778a2e59-435d-4338-b2ff-40fc2c444d82)
**Blend Mode:**
- Absolute: Use a number of vertices along the edgeloop to control the blend length.
- Factor: Blend length defined by a factor of the length from the edgeloop.
**Blend Start:** Number of vertices from the start of the edgeloop | The partial length from the start of the edgeloop.
**Blend End:** Number of vertices from the end of the edgeloop | The partial length from the end of the edgeloop.
**Blend Curve:** Linear or Smoothstep blend of the values along the edgeloop.
Notice how the shape changes from straight to curved at the right image. This obviously only works for edgeloops which are not cyclic.
![grafik](https://github.com/BenjaminSauder/EdgeFlow/assets/13512160/fd584d3f-f232-4351-a251-1863c0d5a4e3)
### Set Linear:
This makes each selected edge loop a straight line between start and end point. The spacing of all the other points can either be spaced evenly, or projected from the original distances.
The tool operates in the direction of the flow of the edgeloop, indicated by the green in the image.
![grafik](https://github.com/BenjaminSauder/EdgeFlow/assets/13512160/f53f5544-a3ea-4afe-aea8-ddb5e792bfbc)
**Space evenly:** Place the vertices on the loop in regular distances.
### Set Curve:
This tool curves each selected edge loop onto a spline which is controled by the first and the last edge of the edgeloop.
The tool operates in the direction of the flow of the edgeloop, indicated by the green in the image.
![grafik](https://github.com/BenjaminSauder/EdgeFlow/assets/13512160/f7e1690d-e852-4dec-bd40-956b470f94bf)
**Mix:** Blend between intial vertex positions and the interpolated result.
**Tension:** Controls the strengh of offset.
**Use Rail:** Customize the interpolation by using the first and last edge of the edgeloop to control the curvature.
**Rail Mode:** Switch rail mode between using absolute units or a factor of the length of the edge.
**Rail Start:** Choose how long the rail is at the start.
**Rail End:** Choose how long the rail is at the end.
### Set Vertex Curve:
This tool moves vertices to a curve based on vertex selections. The picking order of the selected vertices defines the outcome of the tool.
So it's very important to select in the correct order.
- **2 vertices are selected:** a half circle is constructed between the points.
- **3 vertices are selected:** all inbetween points are placed onto a circle which goes through the selected points. You can think of it as start - middle - end points in the selection.
- **4 or more vertices are selected:** the tool constructs a spline and projects all points onto it.
![grafik](https://github.com/BenjaminSauder/EdgeFlow/assets/13512160/26a48c27-a5da-4a8a-b42f-55e700d03b1a)
**Tension:** Controls the strengh of offset
**Use Topology Distance:** Force the path search to ignore edge lenghts, so only topological distance is used to find the inbetween vertices.
**Flip Half Circle:** (only for 2 vertices) Flip the direction of the half circle.
**Rotate Half Circle:** (only for 2 vertices) Rotate the half circle orthogonal to the intial orientation.
**Space evenly:** (only for 3 or more vertices) Place the vertices in even distances.
## How Set Flow works
Back when I first got to see this in action I did quite not understand how it all worked - so I thought it might be well worth adding a quick description to better understand how the underlaying mechanics work.
![grafik](https://github.com/BenjaminSauder/EdgeFlow/assets/13512160/c7875b5a-1f8f-407a-a05f-2f0705ac4cf3)
The tool goes over each edge from an edgeloop, and then goes over each vert for this edge. For every vert it searches the points C1-C4 which are used as 'control points' for the spline interpolation - quite similar to how every vector drawing programm works.
So its all depending on the surrounding geometry - which also means if we have multiple neighbouring edgeloops they all influence each other once we start applying this smoothing. Doing the same operation a few times helps to balance it all out and converges quickly into something stable after a few iterations - so hence the need for such an option.
# Credits
Maintainer:
Benjamin Sauder
Additional contributions:
- IngoClemens
- ora-0
## Developer Notes
I had to reimplement the edge loop selection from blender because I needed to go from a spaghetti edge selection to sorted edgeloops. While I like that I was able to reproduce blenders selection behaviour I still think I might have overlooked something on how to do it with the regular api - any hints?
I tried different spline interpolation implementations but settled with a hermite interpolation from http://paulbourke.net/miscellaneous/interpolation/ as it has this nice tension variable.
+164
View File
@@ -0,0 +1,164 @@
bl_info = {
"name": "EdgeFlow",
"category": "Mesh",
"author": "Benjamin Sauder",
"description": "Helps adjusting geometry to curved surfaces",
"version": (1, 1, 2),
"location": "Mesh > Edge > Set Edge Flow",
"blender": (3, 5, 1),
"tracker_url": "https://github.com/BenjaminSauder/EdgeFlow/issues",
"wiki_url": "https://github.com/BenjaminSauder/EdgeFlow" ,
}
if "bpy" in locals():
import importlib
importlib.reload(util)
importlib.reload(edgeloop)
importlib.reload(interpolate)
importlib.reload(op_set_edge_flow)
importlib.reload(op_set_edge_linear)
importlib.reload(op_set_edge_curve)
importlib.reload(op_set_vertex_curve)
else:
from . import (
util,
interpolate,
edgeloop,
op_set_edge_flow,
op_set_edge_linear,
op_set_edge_curve,
op_set_vertex_curve,
)
import bpy
from bpy.types import Menu
from bpy.props import BoolProperty, EnumProperty
def menu_func_edges(self, context):
layout = self.layout
layout.separator()
layout.operator_context = "INVOKE_DEFAULT"
layout.operator(op_set_edge_flow.SetEdgeFlowOP.bl_idname, text='Set Flow')
layout.operator(op_set_edge_curve.SetEdgeCurveOP.bl_idname, text='Set Curve')
layout.operator(op_set_edge_linear.SetEdgeLinearOP.bl_idname, text='Set Linear')
def menu_func_vertices(self, context):
layout = self.layout
layout.separator()
layout.operator_context = "INVOKE_DEFAULT"
layout.operator(op_set_vertex_curve.SetVertexCurveOp.bl_idname, text='Set Vertex Curve')
list_insertion_options = [
("BOTTOM", "Bottom of Menu", "", 1),
("TOP", "Top of menu", "", 2),
]
def on_preferences_update(self, context):
preferences = bpy.context.preferences.addons[__package__].preferences
bpy.types.VIEW3D_MT_edit_mesh_context_menu.remove(menu_func_context_menu)
if preferences.add_to_rightclick_menu:
if preferences.list_insertion_choice == 'BOTTOM':
bpy.types.VIEW3D_MT_edit_mesh_context_menu.append(menu_func_context_menu)
else:
bpy.types.VIEW3D_MT_edit_mesh_context_menu.prepend(menu_func_context_menu)
class Preferences(bpy.types.AddonPreferences):
bl_idname = __package__
add_to_rightclick_menu: BoolProperty(name="Extend rightlick menu", default=True, update=on_preferences_update)
list_insertion_choice: EnumProperty(name="Add at", items=list_insertion_options, default=2, update=on_preferences_update)
def draw(self, context):
layout = self.layout
layout.use_property_split = True
layout.use_property_decorate = False # No animation.
layout.label(text="UI Options")
col = layout.column(heading="Add commands to rightlick menu")
col.prop(self, "add_to_rightclick_menu", text="")
row = col.row()
row.prop(self, "list_insertion_choice")
row.enabled = self.add_to_rightclick_menu
class VIEW3D_MT_edit_mesh_set_flow(Menu):
bl_label = "Set Flow"
def draw(self, context):
layout = self.layout
mesh_select_mode = context.scene.tool_settings.mesh_select_mode[:3]
if mesh_select_mode == (True, False, False):
layout.operator(op_set_vertex_curve.SetVertexCurveOp.bl_idname, text='Set Vertex Curve')
elif mesh_select_mode == (False, True, False):
layout.operator(op_set_edge_flow.SetEdgeFlowOP.bl_idname, text='Set Flow')
layout.operator(op_set_edge_curve.SetEdgeCurveOP.bl_idname, text='Set Curve')
layout.operator(op_set_edge_linear.SetEdgeLinearOP.bl_idname, text='Set Linear')
def menu_func_context_menu(self, context):
preferences = bpy.context.preferences.addons[__package__].preferences
mesh_select_mode = context.scene.tool_settings.mesh_select_mode[:3]
if mesh_select_mode == (True, False, False) or mesh_select_mode == (False, True, False):
if preferences.list_insertion_choice == 'BOTTOM':
self.layout.separator()
self.layout.menu("VIEW3D_MT_edit_mesh_set_flow")
if preferences.list_insertion_choice == 'TOP':
self.layout.separator()
# stuff which needs to be registered in blender
classes = [
Preferences,
op_set_edge_flow.SetEdgeFlowOP,
op_set_edge_linear.SetEdgeLinearOP,
op_set_edge_curve.SetEdgeCurveOP,
op_set_vertex_curve.SetVertexCurveOp,
VIEW3D_MT_edit_mesh_set_flow,
]
def register():
for c in classes:
bpy.utils.register_class(c)
preferences = bpy.context.preferences.addons[__package__].preferences
bpy.types.VIEW3D_MT_edit_mesh_edges.append(menu_func_edges)
bpy.types.VIEW3D_MT_edit_mesh_vertices.append(menu_func_vertices)
if preferences.add_to_rightclick_menu:
if preferences.list_insertion_choice == 'BOTTOM':
bpy.types.VIEW3D_MT_edit_mesh_context_menu.append(menu_func_context_menu)
else:
bpy.types.VIEW3D_MT_edit_mesh_context_menu.prepend(menu_func_context_menu)
def unregister():
preferences = bpy.context.preferences.addons[__package__].preferences
if preferences.add_to_rightclick_menu:
bpy.types.VIEW3D_MT_edit_mesh_context_menu.remove(menu_func_context_menu)
bpy.types.VIEW3D_MT_edit_mesh_edges.remove(menu_func_edges)
bpy.types.VIEW3D_MT_edit_mesh_vertices.remove(menu_func_vertices)
for c in classes:
bpy.utils.unregister_class(c)
@@ -0,0 +1,36 @@
schema_version = "1.0.0"
# Example of manifest file for a Blender extension
# Change the values according to your extension
id = "EdgeFlow"
version = "1.1.2"
name = "EdgeFlow"
tagline = "Helps adjusting mesh geometry to curved surfaces"
maintainer = "Benjamin Sauder"
type = "add-on"
# Optional link to documentation, support, source files, etc
website = "https://github.com/BenjaminSauder/EdgeFlow/"
# Optional list defined by Blender and server, see:
# https://docs.blender.org/manual/en/dev/advanced/extensions/tags.html
tags = ["Mesh", "Modeling"]
blender_version_min = "4.2.0"
# License conforming to https://spdx.org/licenses/ (use "SPDX: prefix)
# https://docs.blender.org/manual/en/dev/advanced/extensions/licenses.html
license = [
"SPDX:GPL-3.0-or-later",
]
# [permissions]
# None
paths_exclude_pattern = [
"__pycache__/",
"/.resource/",
"/.git/",
"/.vscode/",
"/*.zip",
]
@@ -0,0 +1,49 @@
import math
# https://blender.stackexchange.com/questions/186067/what-is-the-bmesh-equivalent-to-bpy-ops-mesh-shortest-path-select
class _Node:
@property
def edges(self):
return (e for e in self.vert.link_edges if not e.tag)
def __init__(self, v):
self.vert = v
self.length = math.inf
self.shortest_path = []
def find_path(bm, v_start, v_target=None, use_topology_distance=False):
for e in bm.edges:
e.tag = False
d = {v: _Node(v) for v in bm.verts}
node = d[v_start]
node.length = 0
visiting = [node]
while visiting:
node = visiting.pop(0)
if node.vert is v_target:
return d
for e in node.edges:
e.tag = True
if use_topology_distance:
length = node.length + 1
else:
length = node.length + e.calc_length()
v = e.other_vert(node.vert)
visit = d[v]
visiting.append(visit)
if visit.length > length:
visit.length = length
visit.shortest_path = node.shortest_path + [e]
visiting.sort(key=lambda n: n.length)
return d
+524
View File
@@ -0,0 +1,524 @@
import bpy
import bmesh
import math
import mathutils
from . import interpolate
from .op_set_vertex_curve import map_segment_onto_spline
class Loop():
def __init__(self, bm, edges):
self.bm = bm
self.edges = edges
#ordered verts of this loop
self.verts = []
if len(self.edges) > 1:
last_vert = None
for p in self.edges[0].verts:
if p not in self.edges[1].verts:
last_vert = p
self.verts.append(last_vert)
for i in range(len(self.edges)):
vert = self.edges[i].other_vert(last_vert)
self.verts.append(vert)
last_vert = vert
else:
self.verts = [self.edges[0].verts[0], self.edges[0].verts[1]]
# make sure start vert stays 'stable'
if self.verts[0].co.x + self.verts[0].co.y + self.verts[0].co.z < self.verts[-1].co.x + self.verts[-1].co.y + self.verts[-1].co.z:
self.verts.reverse()
self.edges.reverse()
#store intial vertex coordinates
self.initial_vert_positions = []
for i, v in enumerate(self.verts):
self.initial_vert_positions.append(v.co.copy())
self.is_cyclic = self.verts[0] == self.verts[-1]
# print("edgeloop length: %s" % len(self.edges))
self.valences = []
self.ring = {}
for e in self.edges:
self.ring[e] = []
self.edge_rings = {}
self.ends = {}
def __str__(self):
str = "\n"
for index, edge in enumerate(self.edges):
str += "edge: %s -" % (edge.index)
str += " valence: %s" % self.valences[index]
for r in self.get_ring(edge):
str += " | %s " % r.index
# print(self.edge_ring.values())
# for k,v in self.edge_ring.items():
# print("key: ", k.index)
# print("value: ", v)
# for loop in self.edge_ring[edge]:
# str += " = %s " % loop.edge.index
str += "\n"
ends = self.get_ring_ends(edge)
for e in ends:
str += " end: %s" % e.index
str += "\n"
return str
def __repr__(self):
return self.__str__()
def set_ring(self, edge, ring_edge):
if edge in self.ring and len(self.ring[edge]) <= 2:
self.ring[edge].append(ring_edge)
def get_ring(self, edge):
if edge in self.ring:
return self.ring[edge]
raise Exception("edge not in Edgeloop!")
def select(self):
for edge in self.edges:
edge.select = True
def get_ring_ends(self, edge):
ring = self.edge_rings[edge]
return (ring[0], ring[len(ring) - 1])
def set_curve_flow(self, tension, use_rail, rail_type, rail_start, rail_end):
count = len(self.edges)
if count < 2 or self.is_cyclic:
return
self.bm.verts.ensure_lookup_table()
self.bm.edges.ensure_lookup_table()
start_vert, end_vert = None, None
#get starting points
for p in self.edges[0].verts:
if p not in self.edges[1].verts:
start_vert = p
for p in self.edges[-1].verts:
if p not in self.edges[-2].verts:
end_vert = p
def print_bm_loop(corner):
'''
Vert -> head -- Edge -> Tail
link_loop_prev => where head points to
'''
def get_string(corner):
return f"{corner.index} | vert: {corner.vert.index} edge: {corner.edge.index}"
print("----------------------------")
l = corner
print("corner: ", get_string(l))
l = corner.link_loop_next
print("link_loop_next ", get_string(l))
l = corner.link_loop_prev
print("link_loop_prev ", get_string(l))
l = corner.link_loop_radial_next
print("link_loop_radial_next", get_string(l))
l = corner.link_loop_radial_prev
print("link_loop_radial_prev", get_string(l))
print("----------------------------")
def find_direction(point, edge):
if len(point.link_edges) == 2:
# |_ corner case with mesh borders
a = point.link_edges[0].other_vert(point).co - point.co
b = point.link_edges[1].other_vert(point).co - point.co
# if a is edge
if point.link_edges[0] == edge:
c = a.cross(b)
d = c.cross(b)
# if b is edge
else:
c = b.cross(a)
d = c.cross(a)
return -d.normalized()
elif len(point.link_edges) == 3:
# original_corner = point.link_loops[0]
# for corner in point.link_loops:
# if corner.vert == point and corner.edge == edge:
# original_corner = corner
# edge is at an 'end'
# _|_
if len(edge.link_faces) == 2:
a = edge.other_vert(point).co - point.co
n = edge.link_loops[0].face.normal + edge.link_loops[1].face.normal
n = n.normalized()
c = a.cross(n)
c = c.cross(-n)
return c.normalized()
else:
# |_
# |
# search for the edge which is not neighbouring
# to the face connected to the input edge
for e in point.link_edges:
is_connected_to_end_edge = False
for f in e.link_faces:
if f in edge.link_faces:
is_connected_to_end_edge = True
break
if not is_connected_to_end_edge:
b = e.other_vert(point)
break
a = point
c = a.co - b.co
return c.normalized()
elif len(point.link_edges) == 4:
# regular quad case
# _|_
# |
for corner in edge.link_loops:
if corner.vert == point:
a = point
b = corner.link_loop_prev.link_loop_radial_prev.link_loop_prev.vert
c = a.co - b.co
return c.normalized()
else:
a = edge.other_vert(point).co - point.co
n = edge.link_loops[0].face.normal + edge.link_loops[1].face.normal
n = n.normalized()
c = a.cross(n)
c = c.cross(n)
return -c.normalized()
# if use_rail:
# dir1 = self.edges[0].other_vert(start_vert).co - start_vert.co
# dir1 = dir1.normalized()
# dir2 = self.edges[-1].other_vert(end_vert).co - end_vert.co
# dir2 = dir2.normalized()
# else:
# dir1 = find_direction(start_vert, self.edges[0])
# dir2 = find_direction(end_vert, self.edges[-1])
dir1_unnormalized = self.edges[0].other_vert(start_vert).co - start_vert.co
dir1 = dir1_unnormalized.normalized()
dir2_unnormalized = self.edges[-1].other_vert(end_vert).co - end_vert.co
dir2 = dir2_unnormalized.normalized()
if use_rail:
if rail_type == 'ABSOLUTE':
p1 = start_vert.co + (dir1_unnormalized - dir1 * rail_start)
p4 = end_vert.co + (dir2_unnormalized - dir2 * rail_end)
else: # == 'FACTOR'
p1 = start_vert.co + dir1_unnormalized * rail_start
p4 = end_vert.co + dir2_unnormalized * rail_end
else:
p1 = start_vert.co
p4 = end_vert.co
scale = (p1 - p4).length * 0.5
scale *= tension
p2 = p1 + (dir1 * scale)
p3 = p4 + (dir2 * scale)
# add_debug_verts = False
# if add_debug_verts:
# bmesh.ops.create_vert(self.bm, co=p1)
# bmesh.ops.create_vert(self.bm, co=p4)
# bmesh.ops.create_vert(self.bm, co=p2)
# bmesh.ops.create_vert(self.bm, co=p3)
spline_points = []
precision = 1000
spline_points = mathutils.geometry.interpolate_bezier(p1, p2, p3, p4, precision)
map_segment_onto_spline(self.verts, spline_points)
def straighten(self, distance):
'''
this makes takes the end points of an edge and places them even distanced to the 'next' vert in the extension of the edge loop
Moves A and B:
A' ------ A - B -- B'
to:
A' --- A --- B --- B'
'''
edge = self.edges[0]
def find_neighbour(p):
link_edges = set(p.link_edges)
link_edges.remove(edge)
#print("face a:", edge.link_faces[0].index, "face b:", edge.link_faces[1].index)
faceA_is_quad = len(edge.link_faces[0].verts) == 4
edges = link_edges
if faceA_is_quad:
edges -= set(edge.link_faces[0].edges)
if not edge.is_boundary:
faceB_is_quad = len(edge.link_faces[1].verts) == 4
if faceB_is_quad:
edges -= set(edge.link_faces[1].edges)
v = mathutils.Vector((0, 0, 0))
count = 0
for e in edges:
for vert in e.verts:
if vert == p:
continue
v += vert.co
count += 1
if count > 0:
v /= count
return v
a1 = edge.verts[0]
a2 = edge.verts[1]
a1_len = len(a1.link_edges)
a2_len = len(a2.link_edges)
if a1_len <= 3 or a2_len <= 3:
return
b1 = find_neighbour(a1)
b2 = find_neighbour(a2)
direction = (b2 - b1).normalized()
max_distance = (b2 - b1).length
if distance * 2.0 > max_distance:
distance = max_distance * 0.5
a1.co = b1 + distance * direction
a2.co = b2 - distance * direction
def set_linear(self, even_spacing):
count = len(self.edges)
if count < 2 or self.is_cyclic:
return
for p in self.edges[0].verts:
if p not in self.edges[1].verts:
p1 = p
for p in self.edges[-1].verts:
if p not in self.edges[-2].verts:
p2 = p
direction = (p2.co - p1.co)
direction = direction / (count)
direction_normalized = direction.normalized()
last_vert = p1
for i in range(count - 1):
vert = self.edges[i].other_vert(last_vert)
if even_spacing:
vert.co = p1.co + direction * (i + 1)
else:
proj = vert.co - p1.co
scalar = proj.dot(direction_normalized)
vert.co = p1.co + (direction_normalized * scalar)
last_vert = vert
def blend_start_end(self, blend_start, blend_end, blend_type):
if self.is_cyclic:
# print("skip cyclic loop")
return
count = len(self.verts)
start_count = blend_start
end_count = blend_end
if start_count + end_count >= count:
if start_count < end_count:
end_count = max(count - start_count - 1, 0)
elif end_count < start_count:
start_count = max(count - end_count - 1, 0)
else:
midCount = math.floor(count / 2)
start_count = count - midCount
end_count = count - start_count
#print(f"start:{blend_start} - end:{blend_end} - vertcount: {count}")
#print(f"start_count:{start_count} - end_count:{end_count} - count: {count}")
def apply_blend(blend_range, reverse):
indices = list(range(count))
if reverse:
indices.reverse()
distances = [0]
total_length = 0
for i in range(1, blend_range+1):
a = self.verts[indices[i]]
b = self.verts[indices[i-1]]
length = (a.co - b.co).length
total_length += length
distances.append(total_length)
# print(f"total length: {total_length} - number of distances: {len(distances)}")
if total_length == 0:
return
for i in range(blend_range+1):
blend_value = distances[i] / total_length
if blend_type == 'SMOOTH':
blend_value = interpolate.smooth_step(0.0, 1.0, blend_value)
vert = self.verts[indices[i]]
intital_position = self.initial_vert_positions[indices[i]]
vert.co = intital_position.lerp(vert.co, blend_value)
if blend_start > 0:
apply_blend(min(count-1, start_count), reverse=False)
if blend_end > 0:
apply_blend(min(count-1, end_count), reverse=True)
def set_flow(self, tension, min_angle):
for edge in self.edges:
target = {}
if edge.is_boundary:
continue
for loop in edge.link_loops:
# todo check triangles/ngons?
ring1 = loop.link_loop_next.link_loop_next
ring2 = loop.link_loop_radial_prev.link_loop_prev.link_loop_prev
center = edge.other_vert(loop.vert)
p1 = None
p2 = ring1.vert
p3 = ring2.link_loop_radial_next.vert
p4 = None
#print("ring1 %s - %s" % (ring1.vert.index, ring1.edge.index))
#print("ring2 %s - %s" % (ring2.vert.index, ring2.edge.index))
# print("p2: %s - p3: %s " % (p2.index, p3.index))
result = []
if not ring1.edge.is_boundary:
final = ring1.link_loop_radial_next.link_loop_next
a, b = final.edge.verts
if p2 == a:
p1 = b.co
else:
p1 = a.co
a = (p1 - p2.co).normalized()
b = (center.co - p2.co).normalized()
dot = min(1.0, max(-1.0, a.dot(b)))
angle = math.acos(dot)
if angle < min_angle:
# print("r1: %s" % (math.degrees(angle)))
p1 = p2.co - (p3.co - p2.co) * 0.5
# bmesh.ops.create_vert(self.bm, co=p1)
else:
p1 = p2.co - (p3.co - p2.co)
# bmesh.ops.create_vert(self.bm, co=p1)
result.append(p1)
result.append(p2.co)
if not ring2.edge.is_boundary:
is_quad = len(ring2.face.verts) == 4
# if is_quad:
final = ring2.link_loop_radial_prev.link_loop_prev
# else:
# final = ring2
#print("is_quad:", is_quad, " - ", final.edge.index)
a, b = final.edge.verts
if p3 == a:
p4 = b.co
else:
p4 = a.co
a = (p4 - p3.co).normalized()
b = (center.co - p3.co).normalized()
dot = min(1.0, max(-1.0, a.dot(b)))
angle = math.acos(dot)
if angle < min_angle:
# print("r2: %s" % (math.degrees(angle)))
p4 = p3.co - (p2.co - p3.co) * 0.5
# bmesh.ops.create_vert(self.bm, co=p4)
else:
# radial_next doenst work at boundary
p3 = ring2.edge.other_vert(p3)
p4 = p3.co - (p2.co - p3.co)
# bmesh.ops.create_vert(self.bm, co=p4)
result.append(p3.co)
result.append(p4)
target[center] = result
for vert, points in target.items():
p1, p2, p3, p4 = points
if p1 == p2 or p3 == p4:
print("invalid input - two control points are identical!")
continue
# normalize point distances so that long edges dont skew the curve
d = (p2 - p3).length * 0.5
p1 = p2 + (d * (p1 - p2).normalized())
p4 = p3 + (d * (p4 - p3).normalized())
# result = interpolate.catmullrom(p1, p2, p3, p4, 1, 3)[1]
result = interpolate.hermite_3d(p1, p2, p3, p4, 0.5, -tension, 0)
result = mathutils.Vector(result)
vert.co = result
@@ -0,0 +1,99 @@
import numpy as np
import math
import mathutils
def catmullrom(P0, P1, P2, P3, a, nPoints=100):
"""
P0, P1, P2, and P3 should be (x,y,z) point pairs that define the Catmull-Rom spline.
nPoints is the number of points to include in this curve segment.
"""
# Convert the points to numpy so that we can do array multiplication
P0, P1, P2, P3 = map(np.array, [P0, P1, P2, P3])
# Calculate t0 to t4
alpha = a
def tj(ti, Pi, Pj):
xi, yi, zi = Pi
xj, yj, zj = Pj
# ( ( (xj-xi)**2 + (yj-yi)**2 )**0.5 )**alpha + ti
a = (xj - xi) ** 2 + (yj - yi) ** 2 + (zj - zi) ** 2
b = a ** 0.5
c = b ** alpha
return c + ti
t0 = 0
t1 = tj(t0, P0, P1)
t2 = tj(t1, P1, P2)
t3 = tj(t2, P2, P3)
# Only calculate points between P1 and P2
t = np.linspace(t1, t2, nPoints)
# Reshape so that we can multiply by the points P0 to P3
# and get a point for each value of t.
t = t.reshape(len(t), 1)
A1 = (t1 - t) / (t1 - t0) * P0 + (t - t0) / (t1 - t0) * P1
A2 = (t2 - t) / (t2 - t1) * P1 + (t - t1) / (t2 - t1) * P2
A3 = (t3 - t) / (t3 - t2) * P2 + (t - t2) / (t3 - t2) * P3
B1 = (t2 - t) / (t2 - t0) * A1 + (t - t0) / (t2 - t0) * A2
B2 = (t3 - t) / (t3 - t1) * A2 + (t - t1) / (t3 - t1) * A3
C = (t2 - t) / (t2 - t1) * B1 + (t - t1) / (t2 - t1) * B2
return C
def hermite_1d(y0, y1, y2, y3, mu, tension, bias):
mu2 = mu * mu
mu3 = mu2 * mu
m0 = (y1 - y0) * (1 + bias) * (1 - tension) / 2
m0 += (y2 - y1) * (1 - bias) * (1 - tension) / 2
m1 = (y2 - y1) * (1 + bias) * (1 - tension) / 2
m1 += (y3 - y2) * (1 - bias) * (1 - tension) / 2
a0 = 2 * mu3 - 3 * mu2 + 1
a1 = mu3 - 2 * mu2 + mu
a2 = mu3 - mu2
a3 = -2 * mu3 + 3 * mu2
return a0 * y1 + a1 * m0 + a2 * m1 + a3 * y2
def hermite_3d(p1, p2, p3, p4, mu, tension, bias):
'''
Mu: For interpolated values between p2 and p3 mu ranges between 0 and 1
Tension: 1 is high, 0 normal, -1 is low
Bias: 0 is even,
positive is towards first segment,
negative towards the other
:return: List
'''
x = hermite_1d(p1[0], p2[0], p3[0], p4[0], mu, tension, bias)
y = hermite_1d(p1[1], p2[1], p3[1], p4[1], mu, tension, bias)
z = hermite_1d(p1[2], p2[2], p3[2], p4[2], mu, tension, bias)
return [x, y, z]
def smooth_step(a, b, x):
'''
Perform Hermite interpolation between two values
'''
value = clamp((x - a) / (b - a))
return value * value * (3 - 2 * value)
def clamp(x, lowerlimit = 0.0, upperlimit = 1.0):
'''
Constrain a value to lie between two further values
'''
if (x < lowerlimit): return lowerlimit
if (x > upperlimit): return upperlimit
return x
@@ -0,0 +1,95 @@
import math
import time
import bpy
from bpy.props import BoolProperty, IntProperty, FloatProperty, EnumProperty
import bmesh
from . import op_set_edge_flow
class SetEdgeCurveOP(bpy.types.Operator, op_set_edge_flow.SetEdgeLoopBase):
bl_idname = "mesh.set_edge_curve"
bl_label = "Set Edge Curve"
bl_options = {'REGISTER', 'UNDO'}
bl_description = "Adjust curvature along the direction the edgeloop\nALT: reuse last settings"
rail_mode = (
("ABSOLUTE", "Absolute", "", 1),
("FACTOR", "Factor", "", 2),
)
mix: FloatProperty(name="Mix", default=1.0, min=0.0, max=1.0, subtype='FACTOR', description="Interpolate between inital position and the calculated end position")
tension : IntProperty(name="Tension", default=100, soft_min=-500, soft_max=500, description="Tension can be used to tighten up the curvature")
use_rail : BoolProperty(name="Use Rail", default=False, description="Customize the interpolation by using the first and last edge of the edgeloop to control the curvature")
rail_mode: bpy.props.EnumProperty(name="Rail Mode", items=rail_mode, default=2, description="Switch rail mode between using absolute units or a factor of the length of the edge")
rail_start_width : FloatProperty(name="Rail Start", default=1.0, subtype='DISTANCE', description="Choose how long the rail is at the start")
rail_end_width : FloatProperty(name="Rail End", default=1.0, subtype='DISTANCE', description="Choose how long the rail is at the end")
rail_start_factor : FloatProperty(name="Rail Start", default=1.0, soft_min=0.0, soft_max=1.5, subtype='FACTOR', description="Choose how long the rail is at the start")
rail_end_factor : FloatProperty(name="Rail End", default=1.0, soft_min=0.0, soft_max=1.5, subtype='FACTOR', description="Choose how long the rail is at the end")
def execute(self, context):
if not self.is_invoked:
return self.invoke(context, None)
else:
self.revert_to_intial_positions()
refresh_positions = self.mix == self.last_mix
if refresh_positions:
for obj in self.objects:
for edgeloop in self.edgeloops[obj]:
if self.rail_mode == 'ABSOLUTE':
rail_start = self.rail_start_width
rail_end = self.rail_end_width
else:
rail_start = self.rail_start_factor
rail_end = self.rail_end_factor
edgeloop.set_curve_flow(self.tension / 100.0, self.use_rail, self.rail_mode, rail_start, rail_end)
self.store_final_positions()
self.apply_mix()
for obj in self.objects:
self.bm[obj].normal_update()
bmesh.update_edit_mesh(obj.data)
self.last_mix = self.mix
self.is_invoked = False
return {'FINISHED'}
def draw(self, context):
layout = self.layout
layout.use_property_split = True
column = layout.column(align=True)
column.prop(self, "mix")
column.prop(self, "tension")
column.separator()
column.prop(self, "use_rail")
# Create a sub layout so that we can grey-out this if use_rail is unchecked
sub_column = column.column(align=True)
row = sub_column.row()
row.prop(self, "rail_mode", expand=True)
if self.rail_mode == 'ABSOLUTE':
sub_column.prop(self, "rail_start_width", slider=False)
sub_column.prop(self, "rail_end_width", slider=False)
else:
sub_column.prop(self, "rail_start_factor")
sub_column.prop(self, "rail_end_factor")
sub_column.enabled = self.use_rail
def invoke(self, context, event):
super(SetEdgeCurveOP, self).invoke(context)
if event and not event.alt:
self.tension = 100
self.mix = 1.0
return self.execute(context)
@@ -0,0 +1,207 @@
import math
import time
import bpy
from bpy.props import IntProperty, FloatProperty, EnumProperty
import bmesh
from . import util
class SetEdgeLoopBase():
mix: FloatProperty(name="Mix", default=1.0, min=0.0, max=1.0, subtype='FACTOR', description="Interpolate between inital position and the calculated end position")
def get_bm(self, obj):
bm = bmesh.from_edit_mesh(obj.data)
bm.verts.ensure_lookup_table()
return bm
def revert_to_intial_positions(self):
for obj in self.objects:
for index, pos in self.intial_vert_positions[obj].items():
vert = self.bm[obj].verts[index]
vert.co = pos
def store_final_positions(self):
self.final_vert_positions = {}
for obj in self.objects:
self.final_vert_positions[obj] = {}
for index in self.intial_vert_positions[obj].keys():
v = self.bm[obj].verts[index]
p = v.co.copy()
self.final_vert_positions[obj][v.index] = p
def apply_mix(self):
if self.mix < 1.0 or (self.mix == 1.0 and self.last_mix < 1.0):
for obj in self.objects:
for edgeloop in self.edgeloops[obj]:
for vert in edgeloop.verts:
a = self.intial_vert_positions[obj][vert.index]
b = self.final_vert_positions[obj][vert.index]
vert.co = a.lerp(b, self.mix)
@classmethod
def poll(cls, context):
return (
context.space_data.type == 'VIEW_3D'
and context.active_object is not None
and context.active_object.type == "MESH"
and context.active_object.mode == 'EDIT')
'''
The base invoke stores affected objects, bmesh and intial vertex positions.
The 'redo' calls by the undo system makes the bm invalid - so i have to look it up again...
The storing of the intial vertex positions should only happen on the intial code path.
'''
def invoke(self, context):
self.is_invoked = True
self.last_mix = self.mix
self.intial_vert_positions = {}
self.final_vert_positions = {}
self.objects = set(context.selected_editable_objects) if context.selected_editable_objects else set([context.object])
self.bm = {}
self.edgeloops = {}
store_intial_positions = not self.intial_vert_positions
ignore = set()
for obj in self.objects:
if obj.mode != 'EDIT':
ignore.add(obj)
continue
bm = self.get_bm(obj)
edges = [e for e in bm.edges if e.select]
if len(edges) == 0:
ignore.add(obj)
continue
self.bm[obj] = bm
edge_loops = util.get_edgeloops(bm, edges)
self.edgeloops[obj] = edge_loops
if store_intial_positions:
self.intial_vert_positions[obj] = {}
for e in edges:
for v in e.verts:
if v.index not in self.intial_vert_positions[obj]:
p = v.co.copy()
p = p.freeze()
self.intial_vert_positions[obj][v.index] = p
self.objects = self.objects - ignore
class SetEdgeFlowOP(bpy.types.Operator, SetEdgeLoopBase):
bl_idname = "mesh.set_edge_flow"
bl_label = "Set Edge Flow"
bl_options = {'REGISTER', 'UNDO'}
bl_description = "Adjust curvature to match surface defined by edges crossing the edgeloop\nALT: reuse last settings"
blend_mode = (
("ABSOLUTE", "Absolute", "", 1),
("FACTOR", "Factor", "", 2),
)
blend_type = (
("LINEAR", "Linear", ""),
("SMOOTH", "Smooth", ""),
)
tension: IntProperty(name="Tension", default=180, min=-500, max=500, description="Tension can be used to tighten up the curvature")
iterations: IntProperty(name="Iterations", default=8, min=1, soft_max=32, description="How often the curveature operation is repeated")
blend_mode: bpy.props.EnumProperty(name="Blend Mode", items=blend_mode, description="Switch blend mode between absolute vertex counts and a factor of the whole edgeloop")
blend_start_int: bpy.props.IntProperty(name="Blend Start", default=0, min=0, description="The number of vertices from the start of the loop used to blend to the adjusted loop position")
blend_end_int: bpy.props.IntProperty(name="Blend End", default=0, min=0, description="The number of vertices from the end of the loop used to blend to the adjusted loop position")
blend_start_float: bpy.props.FloatProperty(name="Blend Start", default=0.0, min=0.0, max=1.0, subtype='FACTOR', description="Loop fraction from the start of the loop used to blend to the adjusted loop position")
blend_end_float: bpy.props.FloatProperty(name="Blend End", default=0.0, min=0.0, max=1.0, subtype='FACTOR', description="Loop fraction from the end of the loop used to blend to the adjusted loop position")
blend_type: bpy.props.EnumProperty(name="Blend Curve", items=blend_type, description="The interpolation used to blend between the adjusted loop position and the unaffected start and/or end points")
min_angle : IntProperty(name="Min Angle", default=0, min=0, max=180, subtype='FACTOR', description="After which angle the edgeloop curvature is ignored")
def draw(self, context):
layout = self.layout
layout.use_property_split = True
column = layout.column(align=True)
column.prop(self, "mix")
column.prop(self, "tension")
column.prop(self, "iterations")
column.prop(self, "min_angle")
column.separator()
row = column.row()
row.prop(self, "blend_mode", expand=True)
if self.blend_mode == 'ABSOLUTE':
column.prop(self, "blend_start_int")
column.prop(self, "blend_end_int")
else:
column.prop(self, "blend_start_float")
column.prop(self, "blend_end_float")
row = column.row()
row.prop(self, "blend_type", expand=True)
def execute(self, context):
if not self.is_invoked:
return self.invoke(context, None)
refresh_positions = self.mix == self.last_mix
if refresh_positions:
for obj in self.objects:
for i in range(self.iterations):
for edgeloop in self.edgeloops[obj]:
edgeloop.set_flow(tension=self.tension / 100.0,
min_angle=math.radians(self.min_angle))
for edgeloop in self.edgeloops[obj]:
if self.blend_mode == 'ABSOLUTE':
start = self.blend_start_int
end = self.blend_end_int
else:
count = len(edgeloop.verts)
start = round(count * self.blend_start_float)
end = round(count * self.blend_end_float)
edgeloop.blend_start_end(blend_start=start, blend_end=end, blend_type=self.blend_type)
self.store_final_positions()
self.apply_mix()
for obj in self.objects:
self.bm[obj].normal_update()
bmesh.update_edit_mesh(obj.data)
self.last_mix = self.mix
self.is_invoked = False
return {'FINISHED'}
def invoke(self, context, event):
super(SetEdgeFlowOP, self).invoke(context)
if event and not event.alt:
self.mix = 1.0
self.tension = 180
self.iterations = 16
self.min_angle = 0
self.blend_start_int = 0
self.blend_end_int = 0
self.blend_start_float = 0
self.blend_end_float = 0
return self.execute(context)
@@ -0,0 +1,56 @@
import bpy
from bpy.props import BoolProperty, FloatProperty, EnumProperty
import bmesh
from . import util
from . import op_set_edge_flow
class SetEdgeLinearOP(bpy.types.Operator, op_set_edge_flow.SetEdgeLoopBase):
bl_idname = "mesh.set_edge_linear"
bl_label = "Set Edge Linear"
bl_options = {'REGISTER', 'UNDO'}
bl_description = "Makes edge loops linear between start and end vertices"
space_evenly: BoolProperty(name="Space evenly", default=False,
description="Spread the vertices in even distances")
def invoke(self, context, event):
super(SetEdgeLinearOP, self).invoke(context)
if event and not event.alt:
self.mix = 1.0
return self.execute(context)
def can_straighten(self):
for obj in self.objects:
for edgeloop in self.edgeloops[obj]:
if len(edgeloop.edges) != 1:
return False
return True
def execute(self, context):
if not self.is_invoked:
return self.invoke(context, None)
else:
self.revert_to_intial_positions()
refresh_positions = self.mix == self.last_mix
if refresh_positions:
for obj in self.objects:
for edgeloop in self.edgeloops[obj]:
edgeloop.set_linear(self.space_evenly)
self.store_final_positions()
self.apply_mix()
for obj in self.objects:
self.bm[obj].normal_update()
bmesh.update_edit_mesh(obj.data)
self.last_mix = self.mix
self.is_invoked = False
return {'FINISHED'}
@@ -0,0 +1,584 @@
import math
import bpy
from bpy.props import IntProperty, FloatProperty, BoolProperty
import bmesh
import mathutils
from . import interpolate
from . import dijkstra
def collect_vert_path(bm, selected, use_topology_distance):
'''
Find the shortest paths from the selected verts this is based on input order.
[a,b,c] -> ([a,b],[b,c])
'''
current = len(selected) - 1
path = []
while current > 0:
start = bm.verts[selected[current]]
end = bm.verts[selected[current-1]]
current -= 1
nodes = dijkstra.find_path(
bm, start, end, use_topology_distance=use_topology_distance)
path.append((start, end, nodes))
vert_path = []
for p in path:
start, end, nodes = p
node = nodes[end]
start_end_path = node.shortest_path
if start not in vert_path:
vert_path.append(start)
for e in start_end_path:
if e.verts[0] not in vert_path:
vert_path.append(e.verts[0])
elif e.verts[1] not in vert_path:
vert_path.append(e.verts[1])
vert_path = list(reversed(vert_path))
return vert_path
def split_vert_path_into_segments(bm, selected, vert_path):
'''
Splits the vert path into segments based on selected vertices
selected [a1,b1,c1,d1] vert_path[a1, a2, a3, b, b2, c1, c2, c3, d1] -> [a1,b1,c1,d1], ([a1,a2,a3,b], [b1,b2,c], [c1,c2,3,d])
'''
knots = []
segments = [[]]
for v in vert_path:
current_knot_index = len(knots)
current_knot = bm.verts[selected[current_knot_index]]
if v == current_knot:
knots.append(current_knot)
segments[-1].append(v)
if current_knot_index != 0 and current_knot_index != len(selected)-1:
segments.append([v])
else:
segments[-1].append(v)
return knots, segments
def map_segment_onto_spline(segment, positions):
'''
Calculates the total arc length, and evenly distributes the points based on this.
'''
if len(segment) == 1:
return
total_lenght = 0
for index in range(1, len(positions)):
total_lenght += (positions[index] - positions[index-1]).magnitude
segment_part_length = total_lenght / float(len(segment)-1)
current_segment_index = 1
current_length = 0
for index in range(1, len(positions)):
current_length += (positions[index] - positions[index-1]).magnitude
if current_length >= segment_part_length:
remainder = current_length - segment_part_length
current_length = current_length % segment_part_length
p1 = positions[index-1]
p2 = positions[index]
p = p1 + (p1-p2).normalized() * remainder
if current_segment_index != 0 and current_segment_index != len(segment)-1:
v = segment[current_segment_index]
v.co = p
current_segment_index += 1
def curve_hermite(bm, selected, vert_path, tension, space_evenly):
knots, segments = split_vert_path_into_segments(bm, selected, vert_path)
if len(knots) == 1:
return 1, 'Path found is too short - try toggling "Edge Distance"'
total_spline = []
for index, segment in enumerate(segments):
is_start = index == 0
is_end = index == len(segments)-1
# print("--")
if not is_start and not is_end:
# print("middle segment:")
p0 = knots[index-1].co
p1 = knots[index].co
p2 = knots[index+1].co
p3 = knots[index+2].co
elif is_start:
# print("start segment:")
p1 = knots[index].co
p2 = knots[index+1].co
delta = (p1-p2)
p3 = knots[index+2].co
p3 = p2 - ((p2-p3).normalized() * delta.magnitude)
# do a topology search to find the 'previous' edge
for corner in knots[index].link_loops:
if corner.link_loop_next.vert == segment[index+1]:
p0 = corner.link_loop_prev.link_loop_radial_prev.link_loop_prev
break
elif corner.link_loop_prev.vert == segment[index+1]:
p0 = corner.link_loop_radial_prev.link_loop_next.link_loop_next
break
p0 = p0.vert.co
elif is_end:
# print("end segment:")
p1 = knots[-2].co
p2 = knots[-1].co
delta = (p0-p1)
p0 = knots[-3].co
p0 = p1 - ((p1-p0).normalized() * delta.magnitude)
# do a topology search to find the 'previous' edge
for corner in knots[-1].link_loops:
if corner.link_loop_next.vert == segment[-2]:
p3 = corner.link_loop_prev.link_loop_radial_prev.link_loop_prev
break
elif corner.link_loop_prev.vert == segment[-2]:
p3 = corner.link_loop_radial_prev.link_loop_next.link_loop_next
break
p3 = p3.vert.co
bias = 0
spline_points = []
precision = 1000
for i in range(precision):
mu = i / float(precision)
spline_pos = interpolate.hermite_3d(
p0, p1, p2, p3, mu, -tension, bias)
v = mathutils.Vector(spline_pos)
spline_points.append(v)
if not space_evenly:
map_segment_onto_spline(segment, spline_points)
else:
total_spline.extend(spline_points)
if space_evenly:
map_segment_onto_spline(vert_path, total_spline)
return 0, ""
def curve_bezier(bm, selected, vert_path):
knots, segments = split_vert_path_into_segments(bm, selected, vert_path)
for index, segment in enumerate(segments):
is_start = index == 0
is_end = index == len(segments)-1
if not is_start and not is_end:
p0 = knots[index-1]
p1 = knots[index]
p2 = knots[index+1]
p3 = knots[index+2]
center_dir_left = (p1.co-p0.co + p1.co-p2.co).normalized()
up_dir_left = center_dir_left.cross(p2.co - p1.co).normalized()
tangent_left = up_dir_left.cross(center_dir_left).normalized()
dot_left = center_dir_left.dot((p1.co-p2.co).normalized())
center_dir_right = (p1.co-p2.co + p3.co-p2.co).normalized()
up_dir_right = center_dir_right.cross(p2.co - p3.co).normalized()
tangent_right = up_dir_right.cross(center_dir_right).normalized()
dot_right = center_dir_right.dot((p1.co-p2.co).normalized())
length_left = (p2.co - p1.co).magnitude * dot_left * 0.5
length_right = (p3.co - p2.co).magnitude * dot_right * 0.5
elif is_start:
p1 = knots[index]
p2 = knots[index+1]
p3 = knots[index+2]
center_dir_right = (p2.co-p1.co + p2.co-p3.co).normalized()
up_dir_right = center_dir_right.cross(p2.co - p3.co).normalized()
tangent_right = up_dir_right.cross(center_dir_right).normalized()
dot_right = center_dir_right.dot((p2.co-p1.co).normalized())
tangent_left = center_dir_right
length_right = (p3.co - p2.co).magnitude * dot_right * 0.5
length_left = length_right
elif is_end:
p0 = knots[-3]
p1 = knots[-2]
p2 = knots[-1]
center_dir_left = (p1.co-p0.co + p1.co-p2.co).normalized()
up_dir_left = center_dir_left.cross(p2.co - p1.co).normalized()
tangent_left = up_dir_left.cross(center_dir_left).normalized()
dot_left = center_dir_left.dot((p1.co-p2.co).normalized())
print(dot_left, dot_right)
tangent_right = center_dir_left
length_left = (p1.co - p2.co).magnitude * dot_left * 0.5
length_right = length_left
p1_knot = p1.co + tangent_left * length_left
p2_knot = p2.co + tangent_right * length_right
print(f"(p1: {p1.co}, p1_knot: {p1_knot}")
print(f"(p2: {p2.co}, p2_knot: {p2_knot}")
precision = 100
positions = mathutils.geometry.interpolate_bezier(
p1.co, p1_knot, p2_knot, p2.co, len(segment) * precision)
total_lenght = 0
for index in range(len(positions)):
if index == 0:
continue
total_lenght += (positions[index] - positions[index-1]).magnitude
segment_part_length = total_lenght / float(len(segment)-1)
print("total_lenght:", total_lenght)
print("segment_part_length:", segment_part_length)
current_segment_index = 1
current_length = 0
for index in range(len(positions)):
if index == 0:
continue
current_length += (positions[index] - positions[index-1]).magnitude
if current_length > segment_part_length:
current_length = 0 # segment_part_length
# todo maybe interpolate between these two points?
print(current_segment_index, "/", len(segment))
p = positions[index]
if current_segment_index != 0 and current_segment_index != len(segment)-1:
v = segment[current_segment_index]
v.co = p
current_segment_index += 1
# positions = mathutils.geometry.interpolate_bezier(p1.co, p1_knot, p2_knot, p2.co, len(segment))
# for index, v in enumerate(segment):
# if index != 0 and index != len(segment)-1:
# v.co = positions[index]
# print("." * 66)
return 0
def circle_3_points(bm, selected, vert_path, tension, space_evenly):
knots, segments = split_vert_path_into_segments(bm, selected, vert_path)
vert_a = knots[0]
vert_b = knots[1]
vert_c = knots[2]
a = vert_a.co
b = vert_b.co
c = vert_c.co
# If tension is zero, use linear interpolation
if tension == -1.0:
positions = []
samples = len(vert_path)*100
for sample in range(samples):
mu = sample / samples
positions.append(a.lerp(c, mu))
map_segment_onto_spline(vert_path, positions)
return 0, ""
ac_center = (a+c) * 0.5
b = b + (b-ac_center).normalized() * tension
ab = b-a
bc = c-b
up = ab.cross(bc).normalized()
p1 = a + ab * 0.5
p3 = b + bc * 0.5
p2 = ab.cross(up).normalized()
p4 = bc.cross(up).normalized()
intersection = mathutils.geometry.intersect_line_line(
p1, p1 + p2, p3, p3 + p4)
if not intersection:
return 1, "found no intersection"
center = intersection[0]
start = a - center
middle = b - center
end = c - center
radius = (a - center).magnitude
if space_evenly:
positions = []
samples = len(vert_path)*100
for sample in range(samples):
mu = sample / samples
if mu <= 0.5:
interpolated = start.slerp(middle, mu * 2.0)
interpolated = interpolated.normalized() * radius
else:
interpolated = middle.slerp(end, (mu-0.5) * 2.0)
interpolated = interpolated.normalized() * radius
positions.append(interpolated + center)
map_segment_onto_spline(vert_path, positions)
else:
for index, vert in enumerate(segments[0]):
mu = index / (len(segments[0])-1)
interpolated = start.slerp(middle, mu)
interpolated = interpolated.normalized() * radius
vert.co = interpolated + center
for index, vert in enumerate(segments[1]):
mu = index / (len(segments[1])-1)
interpolated = middle.slerp(end, mu)
interpolated = interpolated.normalized() * radius
vert.co = interpolated + center
return 0, ""
def circle_2_points(bm, selected, vert_path, tension, flip, rotate):
'''
Spaces the vertices into a half circle between two points, orientation is based on the topology of the first vert
'''
tension += 1.0
vert_a = bm.verts[selected[0]]
vert_c = bm.verts[selected[1]]
a = vert_a.co
c = vert_c.co
# If tension is zero, use linear interpolation
if tension == 0.0:
positions = []
samples = len(vert_path)*100
for sample in range(samples):
mu = sample / samples
positions.append(a.lerp(c, mu))
map_segment_onto_spline(vert_path, positions)
return 0, ""
radius = (a - c).magnitude * 0.5
n = vert_a.normal.cross(c-a).normalized()
if rotate:
n = n.cross(a-c).normalized()
if flip:
n = -n
ac_center = (a+c) * 0.5
b = ac_center + n * radius * tension
ab = b-a
bc = c-b
up = ab.cross(bc).normalized()
p1 = a + ab * 0.5
p3 = b + bc * 0.5
p2 = ab.cross(up).normalized()
p4 = bc.cross(up).normalized()
intersection = mathutils.geometry.intersect_line_line(
p1, p1 + p2, p3, p3 + p4)
if not intersection:
return 1, "found no intersection"
center = intersection[0]
start = a - center
middle = b - center
end = c - center
radius = (a - center).magnitude
positions = []
samples = len(vert_path)*100
for sample in range(samples):
mu = sample / samples
if mu <= 0.5:
interpolated = start.slerp(middle, mu * 2.0)
interpolated = interpolated.normalized() * radius
else:
interpolated = middle.slerp(end, (mu-0.5) * 2.0)
interpolated = interpolated.normalized() * radius
positions.append(interpolated + center)
map_segment_onto_spline(vert_path, positions)
return 0, ""
'''
OPERATOR
'''
class SetVertexCurveOp(bpy.types.Operator):
bl_idname = "mesh.align_vertex_curve"
bl_label = "Set Vertex Curve"
bl_options = {'REGISTER', 'UNDO'}
bl_description = '''Curves vertices between the selected vertices in picking order of the selected vertices.
2 vertices selected: placed on a half circle between endpoints.
3 vertices selected: placed onto a circle segment between endpoints.
4+ vertices selected: placed onto a spline going through selected vertices
ALT: reuse last settings
'''
mix: FloatProperty(name="Mix", default=1.0, min=0.0, max=1.0, subtype='FACTOR',
description="Interpolate between inital position and the calculated end position")
tension: IntProperty(name="Tension", default=0, min=-500, max=500,
description="Tension can be used to tighten up the curvature")
use_topology_distance: BoolProperty(name="Use Topology Distance", default=False,
description="Use the edge count instead of edge lengths for distance measure")
flip: BoolProperty(name="Flip Half Circle", default=False,
description="Flip the half circle into other direction")
rotate: BoolProperty(name="Rotate Half Circle", default=False,
description="Rotate the half circle by 90 degrees")
space_evenly: BoolProperty(name="Space evenly", default=False,
description="Spread the vertices in even distances")
def draw(self, context):
layout = self.layout
layout.use_property_split = True
column = layout.column()
column.prop(self, "mix")
column = layout.column(align=True)
column.prop(self, "tension")
column.prop(self, "use_topology_distance")
if self.vert_count == 2:
column.prop(self, "flip")
column.prop(self, "rotate")
if self.vert_count >= 3:
column.prop(self, "space_evenly")
@classmethod
def poll(cls, context):
if (context.space_data.type == 'VIEW_3D'
and context.active_object is not None
and context.active_object.type == "MESH"
and context.active_object.mode == 'EDIT'):
mesh_select_mode = context.scene.tool_settings.mesh_select_mode[:3]
return mesh_select_mode == (True, False, False)
else:
return False
def get_bm(self, me):
bm = bmesh.from_edit_mesh(me)
bm.verts.ensure_lookup_table()
return bm
def get_selected(self, bm):
maybe_selected = [elem.index for elem in bm.select_history if isinstance(
elem, bmesh.types.BMVert)]
selected = list(filter(lambda x: bm.verts[x].select, maybe_selected))
return selected
def invoke(self, context, event):
# print ("-" * 66)
self.intial_vert_positions = []
self.vert_count = 0
if event and not event.alt:
self.mix = 1.0
self.tension = 0
self.use_topology_distance = False
self.space_evenly = False
return self.execute(context)
def execute(self, context):
bm = self.get_bm(context.object.data)
selected = self.get_selected(bm)
self.vert_count = len(selected)
if len(selected) < 2:
self.report(
{'WARNING'}, f"Align vertex curve: Please select 2, 3 or more vertices")
return {'CANCELLED'}
# print ("#" * 66)
vert_path = collect_vert_path(bm, selected, self.use_topology_distance)
if len(self.intial_vert_positions) == 0:
for vert in vert_path:
self.intial_vert_positions.append(vert.co.copy())
tension = self.tension / 100.0
if len(selected) == 2:
result, msg = circle_2_points(
bm, selected, vert_path, tension, self.flip, self.rotate)
elif len(selected) == 3:
result, msg = circle_3_points(
bm, selected, vert_path, tension, self.space_evenly)
else:
result, msg = curve_hermite(
bm, selected, vert_path, tension, self.space_evenly)
if result > 0:
self.report({'INFO'}, msg)
for i, vert in enumerate(vert_path):
vert.co = self.intial_vert_positions[i].lerp(vert.co, self.mix)
bmesh.update_edit_mesh(context.object.data, loop_triangles=True)
return {'FINISHED'}
+318
View File
@@ -0,0 +1,318 @@
from collections import deque
import bpy
import bmesh
from . import edgeloop
def walk_boundary(start_edge, limit_to_edges=None):
edge_loop = set([start_edge])
visited = set()
candidates = [start_edge]
while True:
for candidate in candidates:
for vert in candidate.verts:
if len(vert.link_edges) > 2: # valence of verts as a blocker
for edge in vert.link_edges:
if edge.is_boundary and edge not in edge_loop:
if limit_to_edges != None:
if edge in limit_to_edges:
edge_loop.add(edge)
else:
edge_loop.add(edge)
visited.add(candidate)
candidates = edge_loop - visited
if len(visited) == len(edge_loop):
break
#sorting this mess..
raw_edge_loop = list(edge_loop)
start_edge = raw_edge_loop[0]
raw_edge_loop.remove(start_edge)
sorted_edge_loop = deque()
sorted_edge_loop.append(start_edge)
add = sorted_edge_loop .append
for p in start_edge.verts:
while True:
edge = None
for e in raw_edge_loop:
if p in e.verts:
edge = e
if edge != None:
add(edge)
p = edge.other_vert(p)
raw_edge_loop.remove(edge)
else:
break
add = sorted_edge_loop .appendleft
#for e in list(sorted_edge_loop ):
# print("###", e.index)
if len(sorted_edge_loop ) != len(edge_loop):
raise Exception("WTF")
return list(sorted_edge_loop)
def walk_ngon(start_edge, limit_to_edges=None):
edge_loop = deque()
edge_loop.append(start_edge)
start_loops = []
face_valence = []
for linked_loop in start_edge.link_loops:
vert_count = len(linked_loop.face.verts)
if vert_count > 4:
start_loops.append(linked_loop)
face_valence.append(vert_count)
max_value = max(face_valence)
start_loop = start_loops[face_valence.index(max_value)]
# print(start_loop.vert.index, start_loop.edge.index)
loop = start_loop.link_loop_next
while len(loop.vert.link_edges) < 4 and loop.edge not in edge_loop:
if limit_to_edges != None and loop.edge not in limit_to_edges:
break
edge_loop.append(loop.edge)
# print("next", loop.edge.index)
loop = loop.link_loop_next
# print("switch")
loop = start_loop.link_loop_prev
while len(loop.edge.other_vert(loop.vert).link_edges) < 4 and loop.edge not in edge_loop:
if limit_to_edges != None and loop.edge not in limit_to_edges:
break
edge_loop.appendleft(loop.edge)
loop = loop.link_loop_prev
# print("prev", loop.edge.index)
return list(edge_loop)
def walk_edge_loop(start_edge, limit_to_edges=None):
edge_loop = deque()
edge_loop.append(start_edge)
add = edge_loop.append
for loop in start_edge.link_loops:
start_valence = len(loop.vert.link_edges)
# print("start_valence", start_valence)
if start_valence <= 4:
while True:
valence = len(loop.vert.link_edges)
# print("valence: %s | vert: %s edge: %s" % (valence, loop.vert.index, loop.edge.index))
if valence == 4 and start_valence == valence:
loop = loop.link_loop_prev.link_loop_radial_prev.link_loop_prev
if loop.edge in edge_loop:
break
if limit_to_edges != None:
if loop.edge in limit_to_edges:
add(loop.edge)
else:
break
else:
add(loop.edge)
# print("add edge:", loop.edge.index)
else:
# print("break valence", valence, loop.face != face)
break
else:
pass
# print("ignore this direction")
add = edge_loop.appendleft
return list(edge_loop)
def get_edgeloop(bm, start_edge, limit_to_edges=None):
start_loops = start_edge.link_loops
is_ngon = False
for loop in start_loops:
if len(loop.face.verts) > 4:
is_ngon = True
break
quad_flow = len(start_edge.verts[0].link_edges) == 4 and len(start_edge.verts[1].link_edges) == 4
loop_end = (len(start_edge.verts[0].link_edges) > 4 and len(start_edge.verts[1].link_edges) == 4 or
len(start_edge.verts[0].link_edges) == 4 and len(start_edge.verts[1].link_edges) > 4)
# print( "is quad flow", quad_flow)
# print("is loop end", loop_end)
if is_ngon and not quad_flow and not loop_end:
return edgeloop.Loop(bm, walk_ngon(start_edge, limit_to_edges))
elif start_edge.is_boundary:
return edgeloop.Loop(bm, walk_boundary(start_edge, limit_to_edges))
else:
return edgeloop.Loop(bm, walk_edge_loop(start_edge, limit_to_edges))
def get_edgeloops(bm, edges):
'''
edge_loop = get_edgeloop(edges[0])
for e in edge_loop:
e.select = True
return
'''
not_visited = set(edges)
edge_loops = []
while (len(not_visited) > 0):
next = not_visited.pop()
edge_loop = get_edgeloop(bm, next, not_visited)
edge_loops.append(edge_loop)
for edge in edge_loop.edges:
if edge in not_visited:
not_visited.remove(edge)
# print("edge_loops:", len(edge_loops))
edge_loops = compute_edgeloop_data(edge_loops)
return edge_loops
def find_edge_ring_neighbours(edgeloops, edge_to_Edgeloop):
# find neighbouring edge rings
for edgeloop in edgeloops:
for edge in edgeloop.edges:
if len(edgeloop.get_ring(edge)) == 2:
continue
for link_loop in edge.link_loops:
if len(link_loop.face.verts) != 4:
continue
next = link_loop.link_loop_next.link_loop_next.edge
if next not in edgeloop.get_ring(edge):
if next in edge_to_Edgeloop.keys():
edgeloop.set_ring(edge, next)
edge_to_Edgeloop[next].set_ring(next, edge)
def find_control_edgeloop(edgeloops, edge_to_Edgeloop):
for edgeloop in edgeloops:
for edge in edgeloop.edges:
if edge in edgeloop.edge_rings:
continue
#print("start edge: ", edge.index)
edge_ring = deque()
edge_ring.append(edge.link_loops[0])
ends = []
append_func = edge_ring.append
for index, loop in enumerate(edge.link_loops):
next = loop
prev = None
visited = set()
while True:
ring = next.link_loop_prev.link_loop_prev
#print(ring.edge.index)
if ring in visited:
break
visited.add(ring)
if ring.edge not in edge_to_Edgeloop:
ends.append(ring)
break
# print( ring.edge.index )
append_func(ring)
prev = next
next = ring.link_loop_radial_prev
if ring.edge.is_boundary:
ends.append(ring)
break
#edges have max 2 loops so this I can just switch like this
if index == 0:
append_func = edge_ring.appendleft
#print("edge_ring:")
#for l in edge_ring:
# print(l.edge.index)
for ring in edge_ring:
edge_to_Edgeloop[ring.edge].edge_rings[ring.edge] = edge_ring
edge_to_Edgeloop[ring.edge].ends[ring.edge] = ends
#edgeloop.edge_rings[ring] = edge_ring
def compute_edge_ring_valences(edgeloops, edge_to_Edgeloop):
for edgeloop in edgeloops:
max_valence = -1
for edge in edgeloop.edges:
valence = 0
visited = set()
search = set()
search.add(edge)
while len(search) > 0:
current = search.pop()
visited.add(current)
loop = edge_to_Edgeloop[current]
ring_edges = loop.get_ring(current)
add_to_valence = True
for ring in ring_edges:
if ring not in visited:
search.add(ring)
if add_to_valence:
valence += 1
add_to_valence = False
edgeloop.valences.append(valence)
max_valence = max(max_valence, valence)
edgeloop.max_valence = max_valence
def compute_edgeloop_data(edgeloops):
edge_to_Edgeloop = {}
for edgeloop in edgeloops:
for edge in edgeloop.edges:
edge_to_Edgeloop[edge] = edgeloop
find_edge_ring_neighbours(edgeloops, edge_to_Edgeloop)
compute_edge_ring_valences(edgeloops, edge_to_Edgeloop)
find_control_edgeloop(edgeloops, edge_to_Edgeloop)
result = sorted(edgeloops, key=lambda edgeloop: edgeloop.max_valence)
result = list(reversed(result))
#for el in edgeloops:
# print(el)
return result