EasyWeight: Major update #317
@ -135,7 +135,7 @@ export default defineConfig({
|
||||
],
|
||||
},
|
||||
{ text: 'Contact Sheet', link: '/addons/contactsheet'},
|
||||
{ text: 'Easy Weights', link: '/addons/easy_weights'},
|
||||
{ text: 'Easy Weight', link: '/addons/easy_weight'},
|
||||
{ text: 'Geonode Shapekeys', link: '/addons/geonode_shapekeys'},
|
||||
{ text: 'Grease Converter', link: '/addons/grease_converter'},
|
||||
{ text: 'Lattice Magic', link: '/addons/lattice_magic'},
|
||||
|
74
docs/addons/easy_weight.md
Normal file
74
docs/addons/easy_weight.md
Normal file
@ -0,0 +1,74 @@
|
||||
# Easy Weight
|
||||
|
||||
Easy Weight is an addon focused on quality of life improvements for weight painting in Blender.
|
||||
|
||||
---
|
||||
|
||||
### Installation
|
||||
In Blender 4.2, Easy Weight can be added through the official extensions repository, so you can simply search for it in Blender.
|
||||
|
||||
For older versions, find installation instructions [here](https://studio.blender.org/pipeline/addons/overview).
|
||||
|
||||
## Features
|
||||
|
||||
Easy Weight allows you to control some scene-level tool settings at the user preference level. You can find these in the add-on's preferences.
|
||||
|
||||
![EasyWeight Hotkeys](../media/addons/easy_weight/prefs.png)
|
||||
|
||||
- **Always Auto-Clean**: A new feature in the add-on which cleans zero-weights after each brush stroke.
|
||||
- **Always Show Zero Weights**: Forces [Blender's Show Zero Weights](https://docs.blender.org/manual/en/latest/editors/3dview/display/overlays.html#bpy-types-toolsettings-vertex-group-user) overlay option to "Active".
|
||||
- **Always Auto Normalize**: Forces [Blender's Auto-Normalize](https://docs.blender.org/manual/en/latest/sculpt_paint/weight_paint/tool_settings/options.html#bpy-types-toolsettings-use-auto-normalize) setting to be always on.
|
||||
- **Always Multi-Paint**: Forces [Blender's Multi-Paint](https://docs.blender.org/manual/en/latest/sculpt_paint/weight_paint/tool_settings/options.html#bpy-types-toolsettings-use-multipaint) setting to be always on.
|
||||
|
||||
## Hotkeys
|
||||
You can also find some hotkeys in the preferences. You can customize or disable these as you wish.
|
||||
|
||||
### Weight Paint Pie (W)
|
||||
On the **W** key is this pie menu:
|
||||
![EasyWeight Pie](../media/addons/easy_weight/pie.png)
|
||||
|
||||
- Operators:
|
||||
- **Focus Deforming Bones**: Reveal and isolate all deforming bones contributing to the active mesh.
|
||||
- **Clear Empty Deform Groups**: Remove vertex groups associated with deforming bones, which don't have any weights at all.
|
||||
- **Clear Unused Groups**: Remove vertex groups which are not associated with a deforming bone, and not used by any shape key, modifier, or constraint.
|
||||
- [Assign Automatic From Bones](https://docs.blender.org/manual/en/latest/sculpt_paint/weight_paint/editing.html#bpy-ops-paint-weight-from-bones)
|
||||
- [Normalize Deform Groups](https://docs.blender.org/manual/en/latest/sculpt_paint/weight_paint/editing.html#bpy-ops-object-vertex-group-normalize-all)
|
||||
- Global Brush Settings:
|
||||
- These three options will affect all weight paint brushes in the scene.
|
||||
- [Accumulate](https://docs.blender.org/manual/en/latest/sculpt_paint/brush/brush_settings.html#advanced)
|
||||
- [Falloff Shape](https://docs.blender.org/manual/en/latest/sculpt_paint/brush/falloff.html)
|
||||
- [Paint Through Mesh](https://docs.blender.org/manual/en/latest/sculpt_paint/brush/brush_settings.html#advanced)
|
||||
- Overlay Settings:
|
||||
- [Weight Contours](https://docs.blender.org/manual/en/latest/editors/3dview/display/overlays.html#weight-paint-overlays)
|
||||
- Wireframe
|
||||
- Bones
|
||||
- [Armature Display Type](https://docs.blender.org/manual/en/latest/animation/armatures/properties/display.html#bpy-types-armature-display-type)
|
||||
- In Front (X-Ray)
|
||||
|
||||
## Hunting Rogue Weights
|
||||
|
||||
![Weight Islands](../media/addons/easy_weight/weight_islands.png)
|
||||
|
||||
The Weight Islands panel lets you hunt down unintended rogue weights on a mesh. The workflow goes something like this:
|
||||
- After pressing Calculate Weight Islands and waiting a few seconds, you will see a list of all vertex groups which consist of more than a single island.
|
||||
- Clicking the magnifying glass icon will focus the smallest island in the group, so you can decide what to do with it.
|
||||
- If the island is rogue weights, you can subtract them and go back to the previous step. If not, you can press the checkmark icon next to the magnifying glass, and the vertex group will be hidden from the list.
|
||||
- Continue with this process until all entries are gone from the list.
|
||||
- In the end, you can be 100% sure that you have no rogue weights anywhere on your mesh.
|
||||
|
||||
## Vertex Group Operators
|
||||
|
||||
![Vertex Group Menu](../media/addons/easy_weight/vg_context_menu.png)
|
||||
|
||||
The Vertex Groups context menu is re-organized with more icons and better labels, as well as some additional operators:
|
||||
- **Delete Empty Deform Groups**: Delete deforming groups that don't have any weights.
|
||||
- **Delete Unused Non-Deform Groups**: Delete non-deforming groups that aren't used anywhere, even if they do have weights.
|
||||
- **Delete Unselected Deform Groups**: Delete all deforming groups that don't correspond to a selected pose bone. Only in Weight Paint mode.
|
||||
- **Focus Deforming Bones**: Reveal and select all bones deforming this mesh. Only in Weight Paint mode.
|
||||
- **Symmetrize Vertex Groups**: Symmetrizes vertex groups from left to right side, creating missing groups as needed.
|
||||
|
||||
If you have any more suggestions, feel free to open an Issue with a feature request.
|
||||
|
||||
## Force Apply Mirror Modifier
|
||||
In Blender, you cannot apply a mirror modifier to meshes that have shape keys.
|
||||
This operator tries to anyways, by duplicating your mesh, flipping it on the X axis and merging into the original. It will also flip vertex groups, shape keys, shape key masks, and even (attempt) shape key drivers, assuming everything is named with .L/.R suffixes.
|
@ -1 +0,0 @@
|
||||
<!--@include: ../../scripts-blender/addons/easy_weights/README.md-->
|
BIN
docs/media/addons/easy_weight/pie.png
(Stored with Git LFS)
Normal file
BIN
docs/media/addons/easy_weight/pie.png
(Stored with Git LFS)
Normal file
Binary file not shown.
BIN
docs/media/addons/easy_weight/prefs.png
(Stored with Git LFS)
Normal file
BIN
docs/media/addons/easy_weight/prefs.png
(Stored with Git LFS)
Normal file
Binary file not shown.
BIN
docs/media/addons/easy_weights/custom_wp_context_menu.png
(Stored with Git LFS)
BIN
docs/media/addons/easy_weights/custom_wp_context_menu.png
(Stored with Git LFS)
Binary file not shown.
BIN
docs/media/addons/easy_weights/toggle_wp_shortcut.png
(Stored with Git LFS)
BIN
docs/media/addons/easy_weights/toggle_wp_shortcut.png
(Stored with Git LFS)
Binary file not shown.
BIN
docs/media/addons/easy_weights/wp_context_menu_shortcut.png
(Stored with Git LFS)
BIN
docs/media/addons/easy_weights/wp_context_menu_shortcut.png
(Stored with Git LFS)
Binary file not shown.
@ -22,7 +22,7 @@ The facial rigging is usually done with Rigify's [Action set-up system](https://
|
||||
## Weight Painting
|
||||
Weight painting character meshes to the generated rig has so far happened simply manually, as there hasn't been a need to mass-produce characters with high quality deformation. Still, the **Easy Weight** add-on helps to make this manual weight painting workflow efficient with some custom UI, and less error-prone with a rogue weight checking system. There is also a short tutorial series about my weight painting workflow, which also includes a section about this add-on specifically.
|
||||
|
||||
* [Download Easy Weights](https://studio.blender.org/pipeline/addons/easy_weights)
|
||||
* [Download Easy Weights](https://studio.blender.org/pipeline/addons/easy_weight)
|
||||
* [Weight Painting Course](https://studio.blender.org/training/weight-painting/)
|
||||
|
||||
## Corrective Shape Keys
|
||||
|
674
scripts-blender/addons/easy_weight/LICENSE
Normal file
674
scripts-blender/addons/easy_weight/LICENSE
Normal file
@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
5
scripts-blender/addons/easy_weight/README.md
Normal file
5
scripts-blender/addons/easy_weight/README.md
Normal file
@ -0,0 +1,5 @@
|
||||
# Easy Weight
|
||||
|
||||
Easy Weight is an addon focused on quality of life improvements for weight painting in Blender.
|
||||
|
||||
You can find the documentation [here](https://studio.blender.org/pipeline/addons/easy_weight).
|
@ -1,50 +1,35 @@
|
||||
# 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/>.
|
||||
|
||||
|
||||
from .utils import hotkeys
|
||||
from . import (
|
||||
rogue_weights,
|
||||
vertex_group_menu,
|
||||
vertex_group_operators,
|
||||
weight_paint_context_menu,
|
||||
toggle_weight_paint,
|
||||
force_apply_mirror,
|
||||
smart_weight_transfer,
|
||||
toggle_weight_paint,
|
||||
vertex_group_operators,
|
||||
weight_cleaner,
|
||||
weight_pie,
|
||||
vertex_group_menu,
|
||||
rogue_weights,
|
||||
prefs,
|
||||
)
|
||||
import bpy
|
||||
import importlib
|
||||
|
||||
bl_info = {
|
||||
"name": "Easy Weights",
|
||||
"name": "Easy Weight",
|
||||
"author": "Demeter Dzadik",
|
||||
"version": (0, 1, 3),
|
||||
"blender": (2, 90, 0),
|
||||
"location": "Weight Paint > Weights > Easy Weights",
|
||||
"version": (1, 0, 0),
|
||||
"blender": (4, 2, 0),
|
||||
"location": "3D View -> Sidebar -> Easy Weight",
|
||||
"description": "Operators to make weight painting easier.",
|
||||
"category": "Rigging",
|
||||
"doc_url": "https://studio.blender.org/pipeline/addons/easy_weights",
|
||||
"doc_url": "https://studio.blender.org/pipeline/addons/easy_weight",
|
||||
"tracker_url": "https://projects.blender.org/studio/blender-studio-pipeline",
|
||||
}
|
||||
|
||||
|
||||
modules = [
|
||||
smart_weight_transfer,
|
||||
force_apply_mirror,
|
||||
toggle_weight_paint,
|
||||
weight_paint_context_menu,
|
||||
vertex_group_operators,
|
||||
weight_cleaner,
|
||||
weight_pie,
|
||||
vertex_group_menu,
|
||||
rogue_weights,
|
||||
prefs,
|
||||
@ -82,26 +67,6 @@ def register_unregister_modules(modules, register: bool):
|
||||
def register():
|
||||
register_unregister_modules(modules, True)
|
||||
|
||||
prefs_class = bpy.types.AddonPreferences.bl_rna_get_subclass_py(
|
||||
'EASYWEIGHT_addon_preferences'
|
||||
)
|
||||
prefs_class.hotkeys.append(
|
||||
hotkeys.addon_hotkey_register(
|
||||
op_idname='object.custom_weight_paint_context_menu',
|
||||
keymap_name='Weight Paint',
|
||||
key_id='W',
|
||||
add_on_conflict=False,
|
||||
warn_on_conflict=True,
|
||||
error_on_conflict=False,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def unregister():
|
||||
prefs_class = bpy.types.AddonPreferences.bl_rna_get_subclass_py(
|
||||
'EASYWEIGHT_addon_preferences'
|
||||
)
|
||||
for py_kmi in prefs_class.hotkeys:
|
||||
py_kmi.unregister()
|
||||
|
||||
register_unregister_modules(modules, False)
|
20
scripts-blender/addons/easy_weight/blender_manifest.toml
Normal file
20
scripts-blender/addons/easy_weight/blender_manifest.toml
Normal file
@ -0,0 +1,20 @@
|
||||
schema_version = "1.0.0"
|
||||
|
||||
id = "easyweight"
|
||||
version = "1.0.0"
|
||||
name = "EasyWeight"
|
||||
tagline = "Weight Painting Workflow Boosters"
|
||||
maintainer = "Demeter Dzadik <demeter@blender.org>"
|
||||
type = "add-on"
|
||||
website = "https://studio.blender.org/pipeline/addons/easy_weight"
|
||||
tags = ["Rigging"]
|
||||
|
||||
blender_version_min = "4.2.0"
|
||||
|
||||
license = [
|
||||
"SPDX:GPL-3.0-or-later",
|
||||
]
|
||||
copyright = [
|
||||
"2019-2024 Demeter Dzadik & Blender Studio",
|
||||
]
|
||||
[permissions]
|
306
scripts-blender/addons/easy_weight/prefs.py
Normal file
306
scripts-blender/addons/easy_weight/prefs.py
Normal file
@ -0,0 +1,306 @@
|
||||
import bpy, json
|
||||
from bpy.props import BoolProperty
|
||||
from . import __package__ as base_package
|
||||
|
||||
|
||||
def get_addon_prefs(context=None):
|
||||
if not context:
|
||||
context = bpy.context
|
||||
if base_package.startswith('bl_ext'):
|
||||
# 4.2
|
||||
return context.preferences.addons[base_package].preferences
|
||||
else:
|
||||
return context.preferences.addons[base_package.split(".")[0]].preferences
|
||||
|
||||
|
||||
class EASYWEIGHT_addon_preferences(bpy.types.AddonPreferences):
|
||||
bl_idname = __package__
|
||||
easyweight_keymap_items = {}
|
||||
|
||||
always_show_zero_weights: BoolProperty(
|
||||
name="Always Show Zero Weights",
|
||||
description="A lack of weights will always be indicated with black color to differentiate it from a weight of 0.0 being assigned",
|
||||
default=True,
|
||||
)
|
||||
always_auto_normalize: BoolProperty(
|
||||
name="Always Auto Normalize",
|
||||
description="Weight auto-normalization will always be turned on, so the sum of all deforming weights on a vertex always add up to 1",
|
||||
default=True,
|
||||
)
|
||||
always_multipaint: BoolProperty(
|
||||
name="Always Multi-Paint",
|
||||
description="Multi-paint will always be turned on, allowing you to select more than one deforming bone while weight painting",
|
||||
default=True,
|
||||
)
|
||||
auto_clean_weights: BoolProperty(
|
||||
name="Always Auto Clean",
|
||||
description="While this is enabled, zero-weights will be removed automatically after every brush stroke",
|
||||
default=True,
|
||||
)
|
||||
|
||||
def update_front_faces(self, context):
|
||||
for brush in bpy.data.brushes:
|
||||
if not brush.use_paint_weight:
|
||||
continue
|
||||
brush.use_frontface = self.global_front_faces_only
|
||||
|
||||
def update_accumulate(self, context):
|
||||
for brush in bpy.data.brushes:
|
||||
if not brush.use_paint_weight:
|
||||
continue
|
||||
brush.use_accumulate = self.global_accumulate
|
||||
|
||||
def update_falloff_shape(self, context):
|
||||
for brush in bpy.data.brushes:
|
||||
if not brush.use_paint_weight:
|
||||
continue
|
||||
brush.falloff_shape = 'SPHERE' if self.global_falloff_shape_sphere else 'PROJECTED'
|
||||
for i, val in enumerate(brush.cursor_color_add):
|
||||
if val > 0:
|
||||
brush.cursor_color_add[i] = (
|
||||
0.5 if self.global_falloff_shape_sphere else 2.0)
|
||||
|
||||
global_front_faces_only: BoolProperty(
|
||||
name="Front Faces Only",
|
||||
description="All weight brushes are able to paint on geometry that is facing away from the viewport",
|
||||
update=update_front_faces
|
||||
)
|
||||
global_accumulate: BoolProperty(
|
||||
name="Accumulate",
|
||||
description="All weight paint brushes will accumulate their effect within a single stroke as you move the mouse",
|
||||
update=update_accumulate
|
||||
)
|
||||
global_falloff_shape_sphere: BoolProperty(
|
||||
name="Falloff Shape",
|
||||
description="All weight paint brushes switch between a 3D spherical or a 2D projected circular falloff shape",
|
||||
update=update_falloff_shape,
|
||||
)
|
||||
|
||||
show_hotkeys: BoolProperty(
|
||||
name="Show Hotkeys",
|
||||
description="Reveal the hotkey list. You may customize or disable these hotkeys",
|
||||
default=False,
|
||||
)
|
||||
|
||||
def draw(self, context):
|
||||
layout = self.layout
|
||||
layout.use_property_split = True
|
||||
layout.use_property_decorate = False
|
||||
|
||||
col = layout.column()
|
||||
col.prop(self, 'auto_clean_weights')
|
||||
col.prop(self, 'always_show_zero_weights')
|
||||
col.prop(self, 'always_auto_normalize')
|
||||
col.prop(self, 'always_multipaint')
|
||||
|
||||
main_col = layout.column(align=True)
|
||||
hotkey_col = self.draw_fake_dropdown(main_col, self, 'show_hotkeys', "Hotkeys")
|
||||
if self.show_hotkeys:
|
||||
type(self).draw_hotkey_list(hotkey_col, context)
|
||||
|
||||
# NOTE: This function is copied from CloudRig's prefs.py.
|
||||
def draw_fake_dropdown(self, layout, prop_owner, prop_name, dropdown_text):
|
||||
row = layout.row()
|
||||
split = row.split(factor=0.20)
|
||||
split.use_property_split = False
|
||||
prop_value = prop_owner.path_resolve(prop_name)
|
||||
icon = 'TRIA_DOWN' if prop_value else 'TRIA_RIGHT'
|
||||
split.prop(prop_owner, prop_name, icon=icon, emboss=False, text=dropdown_text)
|
||||
split.prop(prop_owner, prop_name, icon='BLANK1', emboss=False, text="")
|
||||
split = layout.split(factor=0.012)
|
||||
split.row()
|
||||
dropdown_row = split.row()
|
||||
dropdown_col = dropdown_row.column()
|
||||
row = dropdown_col.row()
|
||||
row.use_property_split = False
|
||||
|
||||
return dropdown_col
|
||||
|
||||
# NOTE: This function is copied from CloudRig's prefs.py.
|
||||
@classmethod
|
||||
def draw_hotkey_list(cls, layout, context):
|
||||
hotkey_class = cls
|
||||
user_kc = context.window_manager.keyconfigs.user
|
||||
|
||||
keymap_data = list(hotkey_class.easyweight_keymap_items.items())
|
||||
keymap_data = sorted(keymap_data, key=lambda tup: tup[1][2].name)
|
||||
|
||||
prev_kmi = None
|
||||
for kmi_hash, kmi_tup in keymap_data:
|
||||
addon_kc, addon_km, addon_kmi = kmi_tup
|
||||
|
||||
user_km = user_kc.keymaps.get(addon_km.name)
|
||||
if not user_km:
|
||||
# This really shouldn't happen.
|
||||
continue
|
||||
user_kmi = hotkey_class.find_kmi_in_km_by_hash(user_km, kmi_hash)
|
||||
|
||||
col = layout.column()
|
||||
col.context_pointer_set("keymap", user_km)
|
||||
if user_kmi and prev_kmi and prev_kmi.name != user_kmi.name:
|
||||
col.separator()
|
||||
user_row = col.row()
|
||||
|
||||
if False:
|
||||
# Debug code: Draw add-on and user KeyMapItems side-by-side.
|
||||
split = user_row.split(factor=0.5)
|
||||
addon_row = split.row()
|
||||
user_row = split.row()
|
||||
hotkey_class.draw_kmi(addon_km, addon_kmi, addon_row)
|
||||
if not user_kmi:
|
||||
# This should only happen for one frame during Reload Scripts.
|
||||
print(
|
||||
"EasyWeight: Can't find this hotkey to draw: ",
|
||||
addon_kmi.name,
|
||||
addon_kmi.to_string(),
|
||||
kmi_hash,
|
||||
)
|
||||
continue
|
||||
|
||||
hotkey_class.draw_kmi(user_km, user_kmi, user_row)
|
||||
prev_kmi = user_kmi
|
||||
|
||||
# NOTE: This function is copied from CloudRig's cloudrig.py.
|
||||
@staticmethod
|
||||
def draw_kmi(km, kmi, layout):
|
||||
"""A simplified version of draw_kmi from rna_keymap_ui.py."""
|
||||
|
||||
map_type = kmi.map_type
|
||||
|
||||
col = layout.column()
|
||||
|
||||
split = col.split(factor=0.7)
|
||||
|
||||
# header bar
|
||||
row = split.row(align=True)
|
||||
row.prop(kmi, "active", text="", emboss=False)
|
||||
row.label(text=f'{kmi.name} ({km.name})')
|
||||
|
||||
row = split.row(align=True)
|
||||
sub = row.row(align=True)
|
||||
sub.enabled = kmi.active
|
||||
sub.prop(kmi, "type", text="", full_event=True)
|
||||
|
||||
if kmi.is_user_modified:
|
||||
row.operator("preferences.keyitem_restore", text="", icon='BACK').item_id = kmi.id
|
||||
|
||||
# NOTE: This function is copied from CloudRig's cloudrig.py.
|
||||
@staticmethod
|
||||
def find_kmi_in_km_by_hash(keymap, kmi_hash):
|
||||
"""There's no solid way to match modified user keymap items to their
|
||||
add-on equivalent, which is necessary to draw them in the UI reliably.
|
||||
|
||||
To remedy this, we store a hash in the KeyMapItem's properties.
|
||||
|
||||
This function lets us find a KeyMapItem with a stored hash in a KeyMap.
|
||||
Eg., we can pass a User KeyMap and an Addon KeyMapItem's hash, to find the
|
||||
corresponding user keymap, even if it was modified.
|
||||
|
||||
The hash value is unfortunately exposed to the users, so we just hope they don't touch that.
|
||||
"""
|
||||
|
||||
for kmi in keymap.keymap_items:
|
||||
if not kmi.properties:
|
||||
continue
|
||||
if 'hash' not in kmi.properties:
|
||||
continue
|
||||
|
||||
if kmi.properties['hash'] == kmi_hash:
|
||||
return kmi
|
||||
|
||||
|
||||
def set_brush_prefs_on_file_load(scene):
|
||||
prefs = get_addon_prefs()
|
||||
prefs.global_front_faces_only = prefs.global_front_faces_only
|
||||
prefs.global_accumulate = prefs.global_accumulate
|
||||
prefs.global_falloff_shape_sphere = prefs.global_falloff_shape_sphere
|
||||
|
||||
# NOTE: This function is copied from CloudRig's cloudrig.py.
|
||||
def register_hotkey(
|
||||
bl_idname, hotkey_kwargs, *, key_cat='Window', space_type='EMPTY', op_kwargs={}
|
||||
):
|
||||
"""This function inserts a 'hash' into the created KeyMapItems' properties,
|
||||
so they can be compared to each other, and duplicates can be avoided."""
|
||||
|
||||
wm = bpy.context.window_manager
|
||||
prefs_class = bpy.types.AddonPreferences.bl_rna_get_subclass_py('EASYWEIGHT_addon_preferences')
|
||||
|
||||
addon_keyconfig = wm.keyconfigs.addon
|
||||
if not addon_keyconfig:
|
||||
# This happens when running Blender in background mode.
|
||||
return
|
||||
|
||||
# We limit the hash to a few digits, otherwise it errors when trying to store it.
|
||||
kmi_hash = (
|
||||
hash(json.dumps([bl_idname, hotkey_kwargs, key_cat, space_type, op_kwargs])) % 1000000
|
||||
)
|
||||
|
||||
# If it already exists, don't create it again.
|
||||
for (
|
||||
existing_kmi_hash,
|
||||
existing_kmi_tup,
|
||||
) in prefs_class.easyweight_keymap_items.items():
|
||||
existing_addon_kc, existing_addon_km, existing_kmi = existing_kmi_tup
|
||||
if kmi_hash == existing_kmi_hash:
|
||||
# The hash we just calculated matches one that is in storage.
|
||||
user_kc = wm.keyconfigs.user
|
||||
user_km = user_kc.keymaps.get(existing_addon_km.name)
|
||||
# NOTE: It's possible on Reload Scripts that some KeyMapItems remain in storage,
|
||||
# but are unregistered by Blender for no reason.
|
||||
# I noticed this particularly in the Weight Paint keymap.
|
||||
# So it's not enough to check if a KMI with a hash is in storage, we also need to check if a corresponding user KMI exists.
|
||||
user_kmi = prefs_class.find_kmi_in_km_by_hash(user_km, kmi_hash)
|
||||
if user_kmi:
|
||||
# print("Hotkey already exists, skipping: ", existing_kmi.name, existing_kmi.to_string(), kmi_hash)
|
||||
return
|
||||
|
||||
addon_keymaps = addon_keyconfig.keymaps
|
||||
addon_km = addon_keymaps.get(key_cat)
|
||||
if not addon_km:
|
||||
addon_km = addon_keymaps.new(name=key_cat, space_type=space_type)
|
||||
|
||||
addon_kmi = addon_km.keymap_items.new(bl_idname, **hotkey_kwargs)
|
||||
for key in op_kwargs:
|
||||
value = op_kwargs[key]
|
||||
setattr(addon_kmi.properties, key, value)
|
||||
|
||||
addon_kmi.properties['hash'] = kmi_hash
|
||||
|
||||
prefs_class.easyweight_keymap_items[kmi_hash] = (
|
||||
addon_keyconfig,
|
||||
addon_km,
|
||||
addon_kmi,
|
||||
)
|
||||
|
||||
|
||||
registry = [EASYWEIGHT_addon_preferences]
|
||||
|
||||
|
||||
def register():
|
||||
register_hotkey(
|
||||
'wm.call_menu_pie',
|
||||
hotkey_kwargs={'type': "W", 'value': "PRESS"},
|
||||
key_cat='Weight Paint',
|
||||
op_kwargs={'name': 'EASYWEIGHT_MT_PIE_easy_weight'},
|
||||
)
|
||||
register_hotkey(
|
||||
bl_idname='object.weight_paint_toggle',
|
||||
hotkey_kwargs={'type': 'TAB', 'value': 'PRESS', 'ctrl': True},
|
||||
key_cat='3D View',
|
||||
)
|
||||
|
||||
bpy.app.handlers.load_post.append(set_brush_prefs_on_file_load)
|
||||
|
||||
def unregister_hotkeys():
|
||||
prefs_class = bpy.types.AddonPreferences.bl_rna_get_subclass_py('EASYWEIGHT_addon_preferences')
|
||||
if not prefs_class:
|
||||
return
|
||||
for kmi_hash, kmi_tup in prefs_class.easyweight_keymap_items.items():
|
||||
kc, km, kmi = kmi_tup
|
||||
km.keymap_items.remove(kmi)
|
||||
prefs_class.easyweight_keymap_items = {}
|
||||
|
||||
def unregister():
|
||||
unregister_hotkeys()
|
||||
|
||||
bpy.app.handlers.load_post.remove(set_brush_prefs_on_file_load)
|
@ -1,5 +1,6 @@
|
||||
import bpy
|
||||
from bpy.types import Object, Operator, VIEW3D_MT_paint_weight, VIEW3D_MT_object
|
||||
from .prefs import get_addon_prefs
|
||||
|
||||
# This operator is added to the Object menu.
|
||||
|
||||
@ -27,22 +28,31 @@ def enter_wp(context) -> bool:
|
||||
obj = context.object
|
||||
wm = context.window_manager
|
||||
|
||||
# Store old shading settings in a Custom Property dictionary in the Scene.
|
||||
if 'wpt' not in wm:
|
||||
wm['wpt'] = {}
|
||||
prefs = get_addon_prefs(context)
|
||||
tool_settings = context.scene.tool_settings
|
||||
if prefs.always_show_zero_weights:
|
||||
tool_settings.vertex_group_user = 'ACTIVE'
|
||||
if prefs.always_auto_normalize:
|
||||
tool_settings.use_auto_normalize = True
|
||||
if prefs.always_multipaint:
|
||||
tool_settings.use_multipaint = True
|
||||
|
||||
wpt = wm['wpt']
|
||||
wpt_as_dict = wpt.to_dict()
|
||||
# Store old shading settings in a Custom Property dictionary in the WindowManager.
|
||||
if 'weight_paint_toggle' not in wm:
|
||||
wm['weight_paint_toggle'] = {}
|
||||
|
||||
wp_toggle = wm['weight_paint_toggle']
|
||||
wp_toggle_as_dict = wp_toggle.to_dict()
|
||||
|
||||
# If we are entering WP mode for the first time or if the last time
|
||||
# the operator was exiting WP mode, then save current state.
|
||||
if 'last_switch_in' not in wpt_as_dict or wpt_as_dict['last_switch_in'] == False:
|
||||
wpt['active_object'] = obj
|
||||
if 'last_switch_in' not in wp_toggle_as_dict or wp_toggle_as_dict['last_switch_in'] == False:
|
||||
wp_toggle['active_object'] = obj
|
||||
|
||||
# This flag indicates that the last time this operator ran, we were
|
||||
# switching INTO wp mode.
|
||||
wpt['last_switch_in'] = True
|
||||
wpt['mode'] = obj.mode
|
||||
wp_toggle['last_switch_in'] = True
|
||||
wp_toggle['mode'] = obj.mode
|
||||
|
||||
# Enter WP mode.
|
||||
bpy.ops.object.mode_set(mode='WEIGHT_PAINT')
|
||||
@ -52,21 +62,21 @@ def enter_wp(context) -> bool:
|
||||
if not armature:
|
||||
return
|
||||
# Save all object visibility related info so it can be restored later.
|
||||
wpt['arm_enabled'] = armature.hide_viewport
|
||||
wpt['arm_hide'] = armature.hide_get()
|
||||
wpt['arm_in_front'] = armature.show_in_front
|
||||
wpt['arm_coll_assigned'] = False
|
||||
wp_toggle['arm_enabled'] = armature.hide_viewport
|
||||
wp_toggle['arm_hide'] = armature.hide_get()
|
||||
wp_toggle['arm_in_front'] = armature.show_in_front
|
||||
wp_toggle['arm_coll_assigned'] = False
|
||||
armature.hide_viewport = False
|
||||
armature.hide_set(False)
|
||||
armature.show_in_front = True
|
||||
if context.space_data.local_view:
|
||||
wpt['arm_local_view'] = armature.local_view_get(context.space_data)
|
||||
wp_toggle['arm_local_view'] = armature.local_view_get(context.space_data)
|
||||
armature.local_view_set(context.space_data, True)
|
||||
|
||||
# If the armature is still not visible, add it to the scene root collection.
|
||||
if not armature.visible_get() and not armature.name in context.scene.collection.objects:
|
||||
context.scene.collection.objects.link(armature)
|
||||
wpt['arm_coll_assigned'] = True
|
||||
wp_toggle['arm_coll_assigned'] = True
|
||||
|
||||
if armature.visible_get():
|
||||
context.view_layer.objects.active = armature
|
||||
@ -83,37 +93,37 @@ def leave_wp(context):
|
||||
obj = context.object
|
||||
wm = context.window_manager
|
||||
|
||||
if 'wpt' not in wm or 'mode' not in wm['wpt'].to_dict():
|
||||
if 'weight_paint_toggle' not in wm or 'mode' not in wm['weight_paint_toggle'].to_dict():
|
||||
# There is no saved data to restore from, nothing else to do.
|
||||
bpy.ops.object.mode_set(mode='OBJECT')
|
||||
return {'FINISHED'}
|
||||
|
||||
wpt = wm['wpt']
|
||||
wpt_as_dict = wpt.to_dict()
|
||||
wp_toggle = wm['weight_paint_toggle']
|
||||
wp_toggle_as_dict = wp_toggle.to_dict()
|
||||
|
||||
# Restore mode.
|
||||
bpy.ops.object.mode_set(mode=wpt_as_dict['mode'])
|
||||
bpy.ops.object.mode_set(mode=wp_toggle_as_dict['mode'])
|
||||
|
||||
# Reset the stored data
|
||||
wm['wpt'] = {}
|
||||
wm['weight_paint_toggle'] = {}
|
||||
# Flag to save that the last time the operator ran we were EXITING wp mode.
|
||||
wm['wpt']['last_switch_in'] = False
|
||||
wm['weight_paint_toggle']['last_switch_in'] = False
|
||||
|
||||
armature = get_armature_of_meshob(obj)
|
||||
if not armature:
|
||||
return
|
||||
# If an armature was un-hidden, hide it again.
|
||||
armature.hide_viewport = wpt_as_dict['arm_enabled']
|
||||
armature.hide_set(wpt_as_dict['arm_hide'])
|
||||
armature.show_in_front = wpt_as_dict['arm_in_front']
|
||||
armature.hide_viewport = wp_toggle_as_dict['arm_enabled']
|
||||
armature.hide_set(wp_toggle_as_dict['arm_hide'])
|
||||
armature.show_in_front = wp_toggle_as_dict['arm_in_front']
|
||||
|
||||
# Restore whether the armature is in local view or not.
|
||||
if 'arm_local_view' in wpt_as_dict and context.space_data.local_view:
|
||||
if 'arm_local_view' in wp_toggle_as_dict and context.space_data.local_view:
|
||||
armature.local_view_set(
|
||||
context.space_data, wpt_as_dict['arm_local_view'])
|
||||
context.space_data, wp_toggle_as_dict['arm_local_view'])
|
||||
|
||||
# Remove armature from scene root collection if it was moved there.
|
||||
if wpt_as_dict['arm_coll_assigned']:
|
||||
if wp_toggle_as_dict['arm_coll_assigned']:
|
||||
context.scene.collection.objects.unlink(armature)
|
||||
|
||||
return
|
||||
@ -141,6 +151,9 @@ class EASYWEIGHT_OT_toggle_weight_paint(Operator):
|
||||
return {'FINISHED'}
|
||||
else:
|
||||
leave_wp(context)
|
||||
wm = context.window_manager
|
||||
if 'weight_paint_toggle' in wm:
|
||||
del wm['weight_paint_toggle']
|
||||
return {'FINISHED'}
|
||||
|
||||
|
@ -1,36 +1,28 @@
|
||||
import bpy
|
||||
from bpy.types import Menu
|
||||
|
||||
from .vertex_group_operators import (
|
||||
EASYWEIGHTS_OT_delete_empty_deform_groups,
|
||||
EASYWEIGHTS_OT_focus_deform_bones,
|
||||
EASYWEIGHTS_OT_delete_unselected_deform_groups,
|
||||
EASYWEIGHTS_OT_delete_unused_vertex_groups,
|
||||
)
|
||||
|
||||
|
||||
class MESH_MT_vertex_group_batch_delete(Menu):
|
||||
bl_label = "Batch Delete"
|
||||
|
||||
def draw(self, context):
|
||||
layout = self.layout
|
||||
layout.operator("object.vertex_group_remove", text="All Groups", icon='TRASH').all = True
|
||||
layout.operator(
|
||||
"object.vertex_group_remove",
|
||||
text="All Groups",
|
||||
icon='TRASH'
|
||||
).all = True
|
||||
layout.operator(
|
||||
"object.vertex_group_remove",
|
||||
text="All Unlocked Groups",
|
||||
icon='UNLOCKED'
|
||||
"object.vertex_group_remove", text="All Unlocked Groups", icon='UNLOCKED'
|
||||
).all_unlocked = True
|
||||
layout.separator()
|
||||
layout.operator(EASYWEIGHTS_OT_delete_empty_deform_groups.bl_idname,
|
||||
text="Empty Deform Groups", icon='GROUP_BONE')
|
||||
layout.operator(EASYWEIGHTS_OT_delete_unused_vertex_groups.bl_idname,
|
||||
text="Unused Non-Deform Groups", icon='BRUSH_DATA')
|
||||
layout.operator(EASYWEIGHTS_OT_delete_unselected_deform_groups.bl_idname,
|
||||
text="Unselected Deform Groups", icon='RESTRICT_SELECT_ON')
|
||||
layout.operator(
|
||||
'object.delete_empty_deform_vgroups', text="Empty Deform Groups", icon='GROUP_BONE'
|
||||
)
|
||||
layout.operator(
|
||||
'object.delete_unused_vgroups', text="Unused Non-Deform Groups", icon='BRUSH_DATA'
|
||||
)
|
||||
layout.operator(
|
||||
'object.delete_unselected_deform_vgroups',
|
||||
text="Unselected Deform Groups",
|
||||
icon='RESTRICT_SELECT_ON',
|
||||
)
|
||||
|
||||
|
||||
class MESH_MT_vertex_group_symmetry(Menu):
|
||||
@ -41,37 +33,29 @@ class MESH_MT_vertex_group_symmetry(Menu):
|
||||
layout.operator(
|
||||
"object.vertex_group_mirror",
|
||||
text="Mirror Active Group (Proximity)",
|
||||
icon='AUTOMERGE_OFF'
|
||||
icon='AUTOMERGE_OFF',
|
||||
).use_topology = False
|
||||
layout.operator(
|
||||
"object.vertex_group_mirror",
|
||||
text="Mirror Active Group (Topology)",
|
||||
icon='AUTOMERGE_ON'
|
||||
"object.vertex_group_mirror", text="Mirror Active Group (Topology)", icon='AUTOMERGE_ON'
|
||||
).use_topology = True
|
||||
|
||||
layout.separator()
|
||||
|
||||
layout.operator(
|
||||
"object.symmetrize_vertex_weights",
|
||||
text="Symmetrize Active Group",
|
||||
icon='MOD_MIRROR'
|
||||
"object.symmetrize_vertex_weights", text="Symmetrize Active Group", icon='MOD_MIRROR'
|
||||
).groups = 'ACTIVE'
|
||||
layout.operator(
|
||||
"object.symmetrize_vertex_weights",
|
||||
text="Symmetrize Selected Bones' Groups",
|
||||
icon='MOD_MIRROR'
|
||||
icon='MOD_MIRROR',
|
||||
).groups = 'BONES'
|
||||
op = layout.operator(
|
||||
"object.symmetrize_vertex_weights",
|
||||
text="Symmetrize All Left->Right",
|
||||
icon='MOD_MIRROR'
|
||||
"object.symmetrize_vertex_weights", text="Symmetrize All Left->Right", icon='MOD_MIRROR'
|
||||
)
|
||||
op.groups = 'ALL'
|
||||
op.direction = 'LEFT_TO_RIGHT'
|
||||
op = layout.operator(
|
||||
"object.symmetrize_vertex_weights",
|
||||
text="Symmetrize All Right->Left",
|
||||
icon='MOD_MIRROR'
|
||||
"object.symmetrize_vertex_weights", text="Symmetrize All Right->Left", icon='MOD_MIRROR'
|
||||
)
|
||||
op.groups = 'ALL'
|
||||
op.direction = 'RIGHT_TO_LEFT'
|
||||
@ -100,15 +84,19 @@ class MESH_MT_vertex_group_copy(Menu):
|
||||
def draw(self, context):
|
||||
layout = self.layout
|
||||
|
||||
# TODO: This isn't grayed out when there's no active group.
|
||||
# TODO: Maybe for things that use the active group, we should put the name of the group in the button text? Makes it harder to search tho perhaps. Not even sure if menu search supports dynamic menu text?
|
||||
layout.operator("object.vertex_group_copy",
|
||||
icon='DUPLICATE', text="Duplicate Group")
|
||||
obj = context.object
|
||||
if obj and obj.vertex_groups and obj.vertex_groups.active:
|
||||
layout.operator(
|
||||
"object.vertex_group_copy",
|
||||
icon='DUPLICATE',
|
||||
text=f'Duplicate "{obj.vertex_groups.active.name}"',
|
||||
)
|
||||
layout.separator()
|
||||
layout.operator("object.vertex_group_copy_to_linked",
|
||||
text="Synchronize Groups on All Instances", icon='LINKED')
|
||||
layout.operator("object.vertex_group_copy_to_selected",
|
||||
text="Synchronize Groups on Selected", icon='RESTRICT_SELECT_OFF')
|
||||
layout.operator(
|
||||
"object.vertex_group_copy_to_selected",
|
||||
text="Synchronize Groups on Selected",
|
||||
icon='RESTRICT_SELECT_OFF',
|
||||
)
|
||||
|
||||
|
||||
class MESH_MT_vertex_group_lock(Menu):
|
||||
@ -117,14 +105,13 @@ class MESH_MT_vertex_group_lock(Menu):
|
||||
def draw(self, context):
|
||||
layout = self.layout
|
||||
|
||||
props = layout.operator(
|
||||
"object.vertex_group_lock", icon='LOCKED', text="Lock All")
|
||||
props = layout.operator("object.vertex_group_lock", icon='LOCKED', text="Lock All")
|
||||
props.action, props.mask = 'LOCK', 'ALL'
|
||||
props = layout.operator(
|
||||
"object.vertex_group_lock", icon='UNLOCKED', text="Unlock All")
|
||||
props = layout.operator("object.vertex_group_lock", icon='UNLOCKED', text="Unlock All")
|
||||
props.action, props.mask = 'UNLOCK', 'ALL'
|
||||
props = layout.operator(
|
||||
"object.vertex_group_lock", icon='UV_SYNC_SELECT', text="Invert All Locks")
|
||||
"object.vertex_group_lock", icon='UV_SYNC_SELECT', text="Invert All Locks"
|
||||
)
|
||||
props.action, props.mask = 'INVERT', 'ALL'
|
||||
|
||||
|
||||
@ -140,9 +127,7 @@ class MESH_MT_vertex_group_weight(Menu):
|
||||
text="Remove Selected Verts from All Groups",
|
||||
).use_all_groups = True
|
||||
layout.operator(
|
||||
"object.vertex_group_clean",
|
||||
icon='BRUSH_DATA',
|
||||
text="Clean 0 Weights from All Groups"
|
||||
"object.vertex_group_clean", icon='BRUSH_DATA', text="Clean 0 Weights from All Groups"
|
||||
).group_select_mode = 'ALL'
|
||||
|
||||
layout.separator()
|
||||
@ -150,20 +135,16 @@ class MESH_MT_vertex_group_weight(Menu):
|
||||
layout.operator(
|
||||
"object.vertex_group_remove_from",
|
||||
icon='TRASH',
|
||||
text="Remove All Verts from Selected Group"
|
||||
text="Remove All Verts from Selected Group",
|
||||
).use_all_verts = True
|
||||
|
||||
layout.separator()
|
||||
|
||||
layout.operator(
|
||||
'paint.weight_from_bones',
|
||||
text="Assign Automatic from Bones",
|
||||
icon='BONE_DATA'
|
||||
'paint.weight_from_bones', text="Assign Automatic from Bones", icon='BONE_DATA'
|
||||
).type = 'AUTOMATIC'
|
||||
op = layout.operator(
|
||||
'object.vertex_group_normalize_all',
|
||||
text="Normalize Deform",
|
||||
icon='IPO_SINE'
|
||||
'object.vertex_group_normalize_all', text="Normalize Deform", icon='IPO_SINE'
|
||||
)
|
||||
op.group_select_mode = 'BONE_DEFORM'
|
||||
op.lock_active = False
|
||||
@ -171,12 +152,7 @@ class MESH_MT_vertex_group_weight(Menu):
|
||||
|
||||
def draw_misc(self, context):
|
||||
layout = self.layout
|
||||
layout.operator(EASYWEIGHTS_OT_focus_deform_bones.bl_idname, icon='ZOOM_IN')
|
||||
|
||||
# TODO: Add an operator called "Smart Cleanup" that creates missing mirror groups,
|
||||
# Cleans 0 weights,
|
||||
# Deletes unused deforming groups,
|
||||
# and deletes unused non-deforming groups.
|
||||
layout.operator('object.focus_deform_vgroups', icon='ZOOM_IN')
|
||||
|
||||
|
||||
def draw_vertex_group_menu(self, context):
|
||||
@ -195,23 +171,27 @@ registry = [
|
||||
MESH_MT_vertex_group_sort,
|
||||
MESH_MT_vertex_group_copy,
|
||||
MESH_MT_vertex_group_lock,
|
||||
MESH_MT_vertex_group_weight
|
||||
MESH_MT_vertex_group_weight,
|
||||
]
|
||||
|
||||
|
||||
def register():
|
||||
bpy.types.MESH_MT_vertex_group_context_menu.old_draw = bpy.types.MESH_MT_vertex_group_context_menu.draw
|
||||
bpy.types.MESH_MT_vertex_group_context_menu.old_draw = (
|
||||
bpy.types.MESH_MT_vertex_group_context_menu.draw
|
||||
)
|
||||
bpy.types.MESH_MT_vertex_group_context_menu.remove(
|
||||
bpy.types.MESH_MT_vertex_group_context_menu.draw)
|
||||
bpy.types.MESH_MT_vertex_group_context_menu.draw
|
||||
)
|
||||
|
||||
bpy.types.MESH_MT_vertex_group_context_menu.append(draw_vertex_group_menu)
|
||||
bpy.types.MESH_MT_vertex_group_context_menu.append(draw_misc)
|
||||
|
||||
|
||||
def unregister():
|
||||
bpy.types.MESH_MT_vertex_group_context_menu.draw = bpy.types.MESH_MT_vertex_group_context_menu.old_draw
|
||||
bpy.types.MESH_MT_vertex_group_context_menu.draw = (
|
||||
bpy.types.MESH_MT_vertex_group_context_menu.old_draw
|
||||
)
|
||||
del bpy.types.MESH_MT_vertex_group_context_menu.old_draw
|
||||
|
||||
bpy.types.MESH_MT_vertex_group_context_menu.remove(draw_vertex_group_menu)
|
||||
bpy.types.MESH_MT_vertex_group_context_menu.remove(draw_misc)
|
||||
|
55
scripts-blender/addons/easy_weight/weight_cleaner.py
Normal file
55
scripts-blender/addons/easy_weight/weight_cleaner.py
Normal file
@ -0,0 +1,55 @@
|
||||
import bpy
|
||||
from bpy.app.handlers import persistent
|
||||
from .prefs import get_addon_prefs
|
||||
|
||||
|
||||
@persistent
|
||||
def start_cleaner(scene, depsgraph):
|
||||
bpy.app.handlers.depsgraph_update_pre.append(WeightCleaner.clean_weights)
|
||||
bpy.app.handlers.depsgraph_update_post.append(WeightCleaner.reset_flag)
|
||||
|
||||
|
||||
class WeightCleaner:
|
||||
"""Run bpy.ops.object.vertex_group_clean on every depsgraph update while in weight paint mode (ie. every brush stroke)."""
|
||||
|
||||
# Flag set in post_depsgraph_update, to indicate to pre_depsgraph_update that the depsgraph update has indeed completed.
|
||||
can_clean = True
|
||||
# Flag set by pre_depsgraph_update to indicate to post_depsgraph_update that the cleanup operator is still running (in a different thread).
|
||||
cleaning_in_progress = False
|
||||
|
||||
@classmethod
|
||||
def clean_weights(cls, scene, depsgraph):
|
||||
context = bpy.context
|
||||
prefs = get_addon_prefs(context)
|
||||
if context.mode != 'PAINT_WEIGHT':
|
||||
return
|
||||
if not context or not hasattr(context, 'object') or not context.object:
|
||||
return
|
||||
if not prefs.auto_clean_weights:
|
||||
return
|
||||
if cls.can_clean:
|
||||
cls.can_clean = False
|
||||
cls.cleaning_in_progress = True
|
||||
# This will trigger a depsgraph update, and therefore clean_weights, again.
|
||||
bpy.ops.object.vertex_group_clean(group_select_mode='ALL', limit=0.001)
|
||||
cls.cleaning_in_progress = False
|
||||
|
||||
@classmethod
|
||||
def reset_flag(cls, scene, depsgraph):
|
||||
context = bpy.context
|
||||
if context.mode != 'PAINT_WEIGHT':
|
||||
return
|
||||
if not context or not hasattr(context, 'object') or not context.object:
|
||||
return
|
||||
if cls.cleaning_in_progress:
|
||||
return
|
||||
cls.can_clean = True
|
||||
|
||||
|
||||
def register():
|
||||
start_cleaner(None, None)
|
||||
bpy.app.handlers.load_post.append(start_cleaner)
|
||||
|
||||
|
||||
def unregister():
|
||||
bpy.app.handlers.load_post.remove(start_cleaner)
|
118
scripts-blender/addons/easy_weight/weight_pie.py
Normal file
118
scripts-blender/addons/easy_weight/weight_pie.py
Normal file
@ -0,0 +1,118 @@
|
||||
from bpy.types import Menu
|
||||
from .prefs import get_addon_prefs
|
||||
from .vertex_group_operators import get_deforming_armature
|
||||
|
||||
|
||||
class EASYWEIGHT_MT_PIE_easy_weight(Menu):
|
||||
bl_label = "Easy Weight"
|
||||
|
||||
def draw(self, context):
|
||||
layout = self.layout
|
||||
pie = layout.menu_pie()
|
||||
|
||||
prefs = get_addon_prefs(context)
|
||||
|
||||
# 1) < Operators
|
||||
self.draw_operators(pie.column().box(), context)
|
||||
|
||||
# 2) > Front Faces Only
|
||||
pie.prop(
|
||||
prefs,
|
||||
'global_front_faces_only',
|
||||
icon='OVERLAY',
|
||||
text="Paint Through Mesh",
|
||||
invert_checkbox=True,
|
||||
)
|
||||
|
||||
# 3) V Overlay & Armature Display settings
|
||||
self.draw_overlay_settings(pie.column().box(), context)
|
||||
|
||||
# 4) ^ Accumulate
|
||||
pie.prop(prefs, 'global_accumulate', icon='GP_SELECT_STROKES')
|
||||
|
||||
# 5) <^ Empty
|
||||
pie.separator()
|
||||
|
||||
# 6) ^> Toggle Falloff Shape
|
||||
icon = 'SPHERE' if prefs.global_falloff_shape_sphere else 'MESH_CIRCLE'
|
||||
text = "Spherical" if prefs.global_falloff_shape_sphere else "Projected Circle"
|
||||
pie.prop(
|
||||
prefs,
|
||||
'global_falloff_shape_sphere',
|
||||
text="Falloff Shape: " + text,
|
||||
icon=icon,
|
||||
invert_checkbox=prefs.global_falloff_shape_sphere,
|
||||
)
|
||||
|
||||
# 7) <v Empty
|
||||
pie.separator()
|
||||
|
||||
# 8) v>Empty
|
||||
pie.separator()
|
||||
|
||||
def draw_operators(self, layout, context):
|
||||
layout.label(text="Operators")
|
||||
|
||||
prefs = get_addon_prefs(context)
|
||||
|
||||
deform_rig = get_deforming_armature(context.active_object)
|
||||
if deform_rig:
|
||||
layout.operator('object.focus_deform_vgroups', icon='ZOOM_IN')
|
||||
|
||||
layout.operator(
|
||||
'object.delete_empty_deform_vgroups',
|
||||
text="Clear Empty Deform Groups",
|
||||
icon='GROUP_BONE',
|
||||
)
|
||||
if not prefs.auto_clean_weights:
|
||||
layout.operator(
|
||||
"object.vertex_group_clean", icon='BRUSH_DATA', text="Clean Zero-Weights"
|
||||
).group_select_mode = 'ALL'
|
||||
layout.operator(
|
||||
'object.delete_unused_vgroups', text="Clear Unused Groups", icon='BRUSH_DATA'
|
||||
)
|
||||
|
||||
layout.operator(
|
||||
'paint.weight_from_bones', text="Assign Automatic from Bones", icon='BONE_DATA'
|
||||
).type = 'AUTOMATIC'
|
||||
op = layout.operator(
|
||||
'object.vertex_group_normalize_all', text="Normalize Deform Groups", icon='IPO_SINE'
|
||||
)
|
||||
op.group_select_mode = 'BONE_DEFORM'
|
||||
op.lock_active = False
|
||||
|
||||
def draw_overlay_settings(self, layout, context):
|
||||
overlay = context.space_data.overlay
|
||||
tool_settings = context.tool_settings
|
||||
prefs = get_addon_prefs(context)
|
||||
layout.label(text="Overlay")
|
||||
if not prefs.always_show_zero_weights:
|
||||
row = layout.row()
|
||||
row.prop(tool_settings, "vertex_group_user", text="Zero Weights Display", expand=True)
|
||||
if hasattr(context.space_data, "overlay"):
|
||||
row = layout.row()
|
||||
row.prop(
|
||||
overlay,
|
||||
"show_wpaint_contours",
|
||||
text="Weight Contours",
|
||||
toggle=True,
|
||||
icon='MOD_INSTANCE',
|
||||
)
|
||||
row.prop(overlay, "show_paint_wire", text="Wireframe", toggle=True, icon='SHADING_WIRE')
|
||||
icon = 'HIDE_OFF' if overlay.show_bones else 'HIDE_ON'
|
||||
row.prop(overlay, "show_bones", text="Bones", toggle=True, icon=icon)
|
||||
|
||||
if context.pose_object:
|
||||
col = layout.column()
|
||||
col.label(text="Armature Display")
|
||||
row = col.row(align=True)
|
||||
row.prop(context.pose_object.data, "display_type", expand=True)
|
||||
x_row = col.row()
|
||||
x_row.prop(context.pose_object, "show_in_front", toggle=True, icon='XRAY')
|
||||
if overlay.show_xray_bone:
|
||||
x_row.prop(overlay, 'show_xray_bone', text="X-Ray Overlay")
|
||||
|
||||
|
||||
registry = [
|
||||
EASYWEIGHT_MT_PIE_easy_weight,
|
||||
]
|
@ -1,23 +0,0 @@
|
||||
## 0.1.4 - 2023-10-31
|
||||
|
||||
### FIXED
|
||||
- Fix a crash in hotkeys.py
|
||||
- Upgrade to Blender 4.0
|
||||
- EasyWeight console warnings & more
|
||||
- Catch an error (not sure of cause yet)
|
||||
- Update hotkey registration code
|
||||
- Use consistent registration pattern
|
||||
|
||||
### REMOVED
|
||||
- Remove hotkeys for painting.
|
||||
|
||||
## 0.1.2 - 2023-08-02
|
||||
|
||||
### FIXED
|
||||
- Fix Changelog Rendering (#125)
|
||||
- Fix Addon Install Instructions
|
||||
|
||||
## 0.1.1 - 2023-06-02
|
||||
|
||||
## DOCUMENTED
|
||||
- Initial release
|
@ -1,66 +0,0 @@
|
||||
# Easy Weights
|
||||
|
||||
|
||||
Easy Weights is an addon focused on quality of life improvements for weight painting in Blender.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Installation](#installation)
|
||||
- [How to Use](#how-to-use)
|
||||
- [Entering Weight Paint Mode](#entering-weight-paint-mode)
|
||||
- [Weight Paint Context Menu](#weight-paint-context-menu)
|
||||
- [Hunting Rogue Weights](#hunting-rogue-weights)
|
||||
- [Vertex Group Operators](#vertex-group-operators)
|
||||
- [Force Apply Mirror Modifier](#force-apply-mirror-modifier)
|
||||
- [Previous Features](#previous-features)
|
||||
|
||||
## Installation
|
||||
Find installation instructions [here](https://studio.blender.org/pipeline/addons/overview).
|
||||
|
||||
## How to Use
|
||||
Read the paragraphs below to find out how to boost your weight painting workflow and comfort.
|
||||
|
||||
### Entering Weight Paint Mode
|
||||
An operator called "Toggle Weight Paint" is added under the "Object" and "Weight" menus in the 3D View. You can right-click the operator in either of these locations to assign a shortcut. I use pie menu object modes on Tab, so my Ctrl+Tab shortcut is available for this.
|
||||
|
||||
The operator will switch into weight paint mode without having to select both the armature and the mesh. Just select a mesh and press the shortcut you assigned. The armature will be un-hidden and put into pose mode if necessary.
|
||||
Press the shortcut again to reset the armature object's visibility state to what it was before, and go back to Object Mode.
|
||||
|
||||
### Weight Paint Context Menu
|
||||
The add-on will override Blender's built-in "W" shortcut for the Context Menu in weight paint mode.
|
||||
Simply enter Weight Paint mode and press W after installing the add-on.
|
||||
|
||||
This pop-up panel provides quick access to commonly needed tools, whether they are part of core Blender or the addon:
|
||||
- Toggles for the Accumulate, Front Faces Only and Falloff Shape brush options. These are normally per-brush, but these buttons will affect ALL Weight Paint brushes.
|
||||
- Weight Paint settings: Auto-Normalize, Multi-Paint, X-Mirror.
|
||||
- A new "Clean Weights" option. When enabled, this will remove 0-weights after every brush stroke.
|
||||
- Commonly used Overlay and Armature display settings.
|
||||
- Commonly used or [new](#vertex-group-operators) operators.
|
||||
|
||||
### Hunting Rogue Weights
|
||||
The addon provides a workflow for hunting down rogue weights efficiently but safely, with just the right amount of automation. This functionality can be found in the Sidebar->EasyWeight->Weight Islands panel.
|
||||
|
||||
- After pressing Calculate Weight Islands and waiting a few seconds, you will see a list of all vertex groups which consist of more than a single island.
|
||||
- Clicking the magnifying glass icon will focus the smallest island in the group, so you can decide what to do with it.
|
||||
- If the island is rogue weights, you can subtract them and go back to the previous step. If not, you can press the checkmark icon next to the magnifying glass, and the vertex group will be hidden from the list.
|
||||
- Continue with this process until all entries are gone from the list.
|
||||
- In the end, you can be 100% sure that you have no rogue weights anywhere on your mesh.
|
||||
|
||||
### Vertex Group Operators
|
||||
The Vertex Groups context menu is re-organized with more icons and better labels, as well as some additional operators:
|
||||
- **Delete Empty Deform Groups**: Delete deforming groups that don't have any weights.
|
||||
- **Delete Unused Non-Deform Groups**: Delete non-deforming groups that aren't used anywhere, even if they do have weights.
|
||||
- **Delete Unselected Deform Groups**: Delete all deforming groups that don't correspond to a selected pose bone. Only in Weight Paint mode.
|
||||
- **Focus Deforming Bones**: Reveal and select all bones deforming this mesh. Only in Weight Paint mode.
|
||||
- **Symmetrize Vertex Groups**: Symmetrizes vertex groups from left to right side, creating missing groups as needed.
|
||||
|
||||
If you have any more suggestions, feel free to open an Issue with a feature request.
|
||||
|
||||
### Force Apply Mirror Modifier
|
||||
In Blender, you cannot apply a mirror modifier to meshes that have shape keys.
|
||||
This operator tries to anyways, by duplicating your mesh, flipping it on the X axis and merging into the original. It will also flip vertex groups, shape keys, shape key masks, and even (attempt) shape key drivers, assuming everything is named with .L/.R suffixes.
|
||||
|
||||
## Previous Features
|
||||
Over time as more things have been fixed on Blender's side, some features have been removed. To avoid confusion, these are listed here:
|
||||
- As of [Blender 3.1](https://projects.blender.org/blender/blender/commit/a215d7e230d3286abbed0108a46359ce57104bc1), holding the Ctrl and Shift buttons in weight painting will use the Subtract and Blur brushes respectively, removing the need for the shortcuts on the 1, 2, 3 keys this addon used to add to provide quick brush switching.
|
||||
- As of [Blender 3.0](https://projects.blender.org/blender/blender/issues/61486), the weight paint overlay is no longer multiplied on top of the underlying colors, removing the need for this addon to change shading or object display settings when using the Toggle Weight Paint mode operator.
|
@ -1,8 +0,0 @@
|
||||
import bpy
|
||||
|
||||
|
||||
class EASYWEIGHT_addon_preferences(bpy.types.AddonPreferences):
|
||||
hotkeys = []
|
||||
|
||||
|
||||
registry = [EASYWEIGHT_addon_preferences]
|
@ -1,282 +0,0 @@
|
||||
import bmesh
|
||||
from bpy.props import EnumProperty, BoolProperty, IntProperty, StringProperty
|
||||
import mathutils
|
||||
import bpy
|
||||
|
||||
bl_info = {
|
||||
"name": "Distance Weighted Weight Transfer",
|
||||
"description": "Smart Transfer Weights operator",
|
||||
"author": "Mets 3D",
|
||||
"version": (2, 0),
|
||||
"blender": (2, 80, 0),
|
||||
"location": "Search -> Smart Weight Transfer",
|
||||
"category": "Object"
|
||||
}
|
||||
|
||||
# This is probably fairly useless and will give roughly the same results as transferring weights with
|
||||
# the Transfer Mesh Data operator set to Nearest Face Interpolated, and then running a Smooth Vertex Weights operator.
|
||||
|
||||
|
||||
def build_weight_dict(obj, vgroups=None, mask_vgroup=None, bone_combine_dict=None):
|
||||
""" Builds and returns a dictionary that matches the vertex indicies of the object to a list of tuples containing the vertex group names that the vertex belongs to, and the weight of the vertex in that group.
|
||||
vgroups: If passed, skip groups that aren't in vgroups.
|
||||
bone_combine_dict: Can be specified if we want some bones to be merged into others, eg. passing in {'Toe_Main' : ['Toe1', 'Toe2', 'Toe3']} will combine the weights in the listed toe bones into Toe_Main. You would do this when transferring weights from a model of actual feet onto shoes.
|
||||
"""
|
||||
if (bone_combine_dict == ""):
|
||||
bone_combine_dict = None
|
||||
# {vert index : [('vgroup_name', vgroup_value), ...], ...}
|
||||
weight_dict = {}
|
||||
|
||||
if (vgroups == None):
|
||||
vgroups = obj.vertex_groups
|
||||
|
||||
for v in obj.data.vertices:
|
||||
# TODO: instead of looking through all vgroups we should be able to get only the groups that this vert is assigned to via v.groups[0].group which gives the group id which we can use to get the group via Object.vertex_groups[id]
|
||||
# With this maybe it's useless altogether to save the weights into a dict? idk.
|
||||
# Although the reason we are doing it this way is because we wanted some bones to be considered the same as others. (eg. toe bones should be considered a single combined bone)
|
||||
for vg in vgroups:
|
||||
w = 0
|
||||
try:
|
||||
w = vg.weight(v.index)
|
||||
except:
|
||||
pass
|
||||
|
||||
if (bone_combine_dict):
|
||||
# Adding the weights from any sub-vertexgroups defined in bone_combine_dict
|
||||
if (vg.name in bone_combine_dict.keys()):
|
||||
for sub_vg_name in bone_combine_dict[vg.name]:
|
||||
sub_vg = obj.vertex_groups.get(sub_vg_name)
|
||||
if (sub_vg == None):
|
||||
continue
|
||||
try:
|
||||
w = w + sub_vg.weight(v.index)
|
||||
except RuntimeError:
|
||||
pass
|
||||
|
||||
if (w == 0):
|
||||
continue
|
||||
|
||||
# Masking transfer influence
|
||||
if (mask_vgroup):
|
||||
try:
|
||||
multiplier = mask_vgroup.weight(v.index)
|
||||
w = w * multiplier
|
||||
except:
|
||||
pass
|
||||
|
||||
# Create or append entry in the dict.
|
||||
if (v.index not in weight_dict):
|
||||
weight_dict[v.index] = [(vg.name, w)]
|
||||
else:
|
||||
weight_dict[v.index].append((vg.name, w))
|
||||
|
||||
return weight_dict
|
||||
|
||||
|
||||
def build_kdtree(obj):
|
||||
kd = mathutils.kdtree.KDTree(len(obj.data.vertices))
|
||||
for i, v in enumerate(obj.data.vertices):
|
||||
kd.insert(v.co, i)
|
||||
kd.balance()
|
||||
return kd
|
||||
|
||||
|
||||
def smart_transfer_weights(obj_from, obj_to, weights, expand=2):
|
||||
""" Smart Vertex Weight Transfer.
|
||||
The number of nearby verts which it searches for depends on how far the nearest vert is. (This is controlled by max_verts, max_dist and dist_multiplier)
|
||||
This means if a very close vert is found, it won't look for any more verts.
|
||||
If the nearest vert is quite far away(or dist_multiplier is set high), it will average the influences of a larger number few verts.
|
||||
The averaging of the influences is also weighted by their distance, so that a vertex which is twice as far away will contribute half as much influence to the final result.
|
||||
weights: a dictionary of vertex weights that needs to be built with build_weight_dict().
|
||||
expand: How many times the "selection" should be expanded around the nearest vert, to collect more verts whose weights will be averaged. 0 is like default weight transfer.
|
||||
"""
|
||||
# TODO: because we normalize at the end, it also means we are expecting the input weighs to be normalized. So we should call a normalize all automatically.
|
||||
|
||||
# Assuming obj_from is at least selected, but probably active. (Shouldn't matter thanks to multi-edit mode?)
|
||||
bpy.ops.object.mode_set(mode='EDIT')
|
||||
bm = bmesh.from_edit_mesh(obj_from.data)
|
||||
|
||||
kd = build_kdtree(obj_from)
|
||||
|
||||
for v in obj_to.data.vertices:
|
||||
# Finding the nearest vertex on source object
|
||||
nearest_co, nearest_idx, nearest_dist = kd.find(v.co)
|
||||
|
||||
# Find neighbouring verts to the nearest vert. Save their index to this list. Will later turn it into a list of (index, distance) tuples.
|
||||
source_vert_indices = [nearest_idx]
|
||||
|
||||
bm.verts.ensure_lookup_table()
|
||||
bmv = bm.verts[nearest_idx]
|
||||
|
||||
for i in range(0, expand):
|
||||
new_indices = []
|
||||
for v_idx in source_vert_indices:
|
||||
cur_bmv = bm.verts[v_idx]
|
||||
for e in cur_bmv.link_edges:
|
||||
v_other = e.other_vert(cur_bmv)
|
||||
if (v_other.index not in source_vert_indices):
|
||||
new_indices.append(v_other.index)
|
||||
source_vert_indices.extend(new_indices)
|
||||
|
||||
source_verts = []
|
||||
for vi in source_vert_indices:
|
||||
distance = (v.co - bm.verts[vi].co).length
|
||||
source_verts.append((vi, distance))
|
||||
|
||||
# Sort valid verts by distance (least to most distance)
|
||||
source_verts.sort(key=lambda tup: tup[1])
|
||||
|
||||
# Iterating through the source verts, from closest to furthest, and accumulating our target weight for each vertex group.
|
||||
vgroup_weights = {} # Dictionary of Vertex Group Name : Weight
|
||||
for i in range(0, len(source_verts)):
|
||||
vert = source_verts[i]
|
||||
# The closest vert's weights are multiplied by the farthest vert's distance, and vice versa. The 2nd closest will use the 2nd farthest, etc.
|
||||
# Note: The magnitude of the distance vectors doesn't matter because at the end they will be normalized anyways.
|
||||
pair_distance = source_verts[-i-1][1]
|
||||
if (vert[0] not in weights):
|
||||
continue
|
||||
for vg_name, vg_weight in weights[vert[0]]:
|
||||
new_weight = vg_weight * pair_distance
|
||||
if (vg_name not in vgroup_weights):
|
||||
vgroup_weights[vg_name] = new_weight
|
||||
else:
|
||||
vgroup_weights[vg_name] = vgroup_weights[vg_name] + new_weight
|
||||
|
||||
# The sum is used to normalize the weights. This is important because otherwise the values would depend on object scale, and in the case of very small or very large objects, stuff could get culled.
|
||||
weights_sum = sum(vgroup_weights.values())
|
||||
|
||||
# Assigning the final, normalized weights of this vertex to the vertex groups.
|
||||
for vg_avg in vgroup_weights.keys():
|
||||
target_vg = obj_to.vertex_groups.get(vg_avg)
|
||||
if (target_vg == None):
|
||||
target_vg = obj_to.vertex_groups.new(name=vg_avg)
|
||||
target_vg.add([v.index], vgroup_weights[vg_avg] /
|
||||
weights_sum, 'REPLACE')
|
||||
|
||||
# bpy.ops.object.mode_set(mode='WEIGHT_PAINT')
|
||||
|
||||
|
||||
w3_bone_dict_str = """{
|
||||
'Toe_Def.L' : ['Toe_Thumb1.L', 'Toe_Thumb2.L', 'Toe_Index1.L', 'Toe_Index2.L', 'Toe_Middle1.L', 'Toe_Middle2.L', 'Toe_Ring1.L', 'Toe_Ring2.L', 'Toe_Pinky1.L', 'Toe_Pinky2.L'],
|
||||
|
||||
'Toe_Def.R' : ['Toe_Thumb1.R', 'Toe_Thumb2.R', 'Toe_Index1.R', 'Toe_Index2.R', 'Toe_Middle1.R', 'Toe_Middle2.R', 'Toe_Ring1.R', 'Toe_Ring2.R', 'Toe_Pinky1.R', 'Toe_Pinky2.R'],
|
||||
|
||||
'Hand_Def.L' : ['l_thumb_roll', 'l_pinky0', 'l_index_knuckleRoll', 'l_middle_knuckleRoll', 'l_ring_knuckleRoll'],
|
||||
|
||||
'Hand_Def.R' : ['r_thumb_roll', 'r_pinky0', 'r_index_knuckleRoll', 'r_middle_knuckleRoll', 'r_ring_knuckleRoll'],
|
||||
}"""
|
||||
|
||||
|
||||
class EASYWEIGHT_OT_smart_weight_transfer(bpy.types.Operator):
|
||||
""" Transfer weights from active to selected objects based on weighted vert distances """
|
||||
bl_idname = "object.smart_weight_transfer"
|
||||
bl_label = "Smart Transfer Weights"
|
||||
bl_options = {'REGISTER', 'UNDO'}
|
||||
|
||||
opt_source_vgroups: EnumProperty(name="Source Groups",
|
||||
items=[("ALL", "All", "All"),
|
||||
("SELECTED", "Selected Bones",
|
||||
"Selected Bones"),
|
||||
("DEFORM", "Deform Bones",
|
||||
"Deform Bones"),
|
||||
],
|
||||
description="Which vertex groups to transfer from the source object",
|
||||
default="ALL")
|
||||
|
||||
opt_wipe_originals: BoolProperty(name="Wipe originals",
|
||||
default=True,
|
||||
description="Wipe original vertex groups before transferring. Recommended. Does not wipe vertex groups that aren't being transferred in the first place")
|
||||
|
||||
opt_expand: IntProperty(name="Expand",
|
||||
default=2,
|
||||
min=0,
|
||||
max=5,
|
||||
description="Expand source vertex pool - Higher values give smoother weights but calculations can take extremely long")
|
||||
|
||||
def get_vgroups(self, context):
|
||||
items = [('None', 'None', 'None')]
|
||||
for vg in context.object.vertex_groups:
|
||||
items.append((vg.name, vg.name, vg.name))
|
||||
return items
|
||||
|
||||
opt_mask_vgroup: EnumProperty(name="Operator Mask",
|
||||
items=get_vgroups,
|
||||
description="The operator's effect will be masked by this vertex group, unless 'None'")
|
||||
|
||||
opt_bone_combine_dict: StringProperty(name='Combine Dict',
|
||||
description="If you want some groups to be considered part of others(eg. to avoid transferring individual toe weights onto shoes), you can enter them here in the form of a valid Python dictionary, where the keys are the parent group name, and values are lists of child group names, eg: {'Toe_Main.L' : ['Toe1.L', 'Toe2.L'], 'Toe_Main.R' : ['Toe1.R', 'Toe2.R']}",
|
||||
default=w3_bone_dict_str
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def poll(cls, context):
|
||||
return context.object # and (context.object.mode=='WEIGHT_PAINT')
|
||||
|
||||
def draw_smart_weight_transfer(self, context):
|
||||
operator = self.layout.operator(
|
||||
EASYWEIGHT_OT_smart_weight_transfer.bl_idname, text=EASYWEIGHT_OT_smart_weight_transfer.bl_label)
|
||||
|
||||
def execute(self, context):
|
||||
assert len(context.selected_objects) > 1, "At least two objects must be selected. Select the source object last, and enter weight paint mode."
|
||||
|
||||
bone_dict = ""
|
||||
if (self.opt_bone_combine_dict != ""):
|
||||
bone_dict = eval(self.opt_bone_combine_dict)
|
||||
|
||||
source_obj = context.object
|
||||
for o in context.selected_objects:
|
||||
if (o == source_obj or o.type != 'MESH'):
|
||||
continue
|
||||
# bpy.ops.object.mode_set(mode='OBJECT')
|
||||
# bpy.ops.object.select_all(action='DESELECT')
|
||||
|
||||
vgroups = []
|
||||
error = ""
|
||||
if (self.opt_source_vgroups == "ALL"):
|
||||
vgroups = source_obj.vertex_groups
|
||||
error = "the source has no vertex groups."
|
||||
elif (self.opt_source_vgroups == "SELECTED"):
|
||||
assert context.selected_pose_bones, "No selected pose bones to transfer from."
|
||||
vgroups = [source_obj.vertex_groups.get(
|
||||
b.name) for b in context.selected_pose_bones]
|
||||
error = "no bones were selected."
|
||||
elif (self.opt_source_vgroups == "DEFORM"):
|
||||
vgroups = [source_obj.vertex_groups.get(
|
||||
b.name) for b in context.pose_object.data.bones if b.use_deform]
|
||||
error = "there are no deform bones"
|
||||
|
||||
# Clean up
|
||||
vgroups = [vg for vg in vgroups if vg != None]
|
||||
assert len(
|
||||
vgroups) > 0, "No transferable Vertex Groups were found, " + error
|
||||
|
||||
# Delete the vertex groups from the destination mesh first...
|
||||
if (self.opt_wipe_originals):
|
||||
for vg in vgroups:
|
||||
if (vg.name in o.vertex_groups):
|
||||
o.vertex_groups.remove(o.vertex_groups.get(vg.name))
|
||||
|
||||
mask_vgroup = o.vertex_groups.get(self.opt_mask_vgroup)
|
||||
|
||||
weights = build_weight_dict(
|
||||
source_obj, vgroups, mask_vgroup, bone_dict)
|
||||
smart_transfer_weights(source_obj, o, weights, self.opt_expand)
|
||||
|
||||
bpy.context.view_layer.objects.active = o
|
||||
bpy.ops.object.mode_set(mode='WEIGHT_PAINT')
|
||||
|
||||
return {'FINISHED'}
|
||||
|
||||
|
||||
registry = [
|
||||
EASYWEIGHT_OT_smart_weight_transfer
|
||||
]
|
||||
|
||||
def register():
|
||||
bpy.types.VIEW3D_MT_paint_weight.append(
|
||||
EASYWEIGHT_OT_smart_weight_transfer.draw_smart_weight_transfer)
|
||||
|
||||
|
||||
def unregister():
|
||||
bpy.types.VIEW3D_MT_paint_weight.remove(
|
||||
EASYWEIGHT_OT_smart_weight_transfer.draw_smart_weight_transfer)
|
@ -1,218 +0,0 @@
|
||||
from typing import Dict, Tuple, List
|
||||
|
||||
import bpy
|
||||
from bpy.props import IntProperty
|
||||
from mathutils import Vector, kdtree
|
||||
|
||||
|
||||
class EASYWEIGHT_OT_transfer_vertex_groups(bpy.types.Operator):
|
||||
"""Transfer vertex groups from active to selected meshes"""
|
||||
|
||||
bl_idname = "object.transfer_vertex_groups"
|
||||
bl_label = "Transfer Vertex Groups"
|
||||
bl_options = {'REGISTER', 'UNDO'}
|
||||
|
||||
expand: IntProperty(
|
||||
name="Expand",
|
||||
default=2,
|
||||
min=0,
|
||||
max=5,
|
||||
description="Expand selection of source vertices from the nearest one. Higher values give smoother weights but pre-calculation takes longer",
|
||||
)
|
||||
|
||||
def draw_transfer_vertex_groups_op(self, context):
|
||||
self.layout.operator(
|
||||
EASYWEIGHT_OT_transfer_vertex_groups.bl_idname,
|
||||
text=EASYWEIGHT_OT_transfer_vertex_groups.bl_label,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def poll(cls, context):
|
||||
if not context.active_object or context.active_object.type != 'MESH':
|
||||
cls.poll_message_set("Active object must be a mesh.")
|
||||
return False
|
||||
selected_meshes = [ob for ob in context.selected_objects if ob.type == 'MESH']
|
||||
if len(selected_meshes) < 2:
|
||||
cls.poll_message_set("At least two meshes must be selected.")
|
||||
return False
|
||||
return True
|
||||
|
||||
def execute(self, context):
|
||||
source_obj = context.object
|
||||
vgroups = source_obj.vertex_groups
|
||||
kd_tree = build_kdtree(source_obj.data)
|
||||
|
||||
for target_obj in context.selected_objects:
|
||||
if target_obj == source_obj or target_obj.type != 'MESH':
|
||||
continue
|
||||
|
||||
# Remove groups from the target obj that we will be transferring.
|
||||
for src_vg in vgroups:
|
||||
tgt_vg = target_obj.vertex_groups.get(src_vg.name)
|
||||
if tgt_vg:
|
||||
target_obj.vertex_groups.remove(tgt_vg)
|
||||
|
||||
vert_influence_map = build_vert_influence_map(
|
||||
source_obj, target_obj, kd_tree, self.expand
|
||||
)
|
||||
transfer_vertex_groups(source_obj, target_obj, vert_influence_map, vgroups)
|
||||
|
||||
return {'FINISHED'}
|
||||
|
||||
|
||||
def precalc_and_transfer_single_group(source_obj, target_obj, vgroup_name, expand=2):
|
||||
"""Convenience function to transfer a single group. For transferring multiple groups,
|
||||
this is very inefficient and shouldn't be used.
|
||||
|
||||
Instead, you should:
|
||||
- build_kd_tree ONCE per source mesh.
|
||||
- build_vert_influence_map and transfer_vertex_groups ONCE per object pair.
|
||||
"""
|
||||
|
||||
# Remove group from the target obj if it already exists.
|
||||
tgt_vg = target_obj.vertex_groups.get(vgroup_name)
|
||||
if tgt_vg:
|
||||
target_obj.vertex_groups.remove(tgt_vg)
|
||||
|
||||
kd_tree = build_kdtree(source_obj.data)
|
||||
vert_influence_map = build_vert_influence_map(
|
||||
source_obj, target_obj, kd_tree, expand
|
||||
)
|
||||
transfer_vertex_groups(
|
||||
source_obj,
|
||||
target_obj,
|
||||
vert_influence_map,
|
||||
vgroups=[source_obj.vertex_groups[vgroup_name]],
|
||||
)
|
||||
|
||||
|
||||
def build_kdtree(mesh):
|
||||
kd = kdtree.KDTree(len(mesh.vertices))
|
||||
for i, v in enumerate(mesh.vertices):
|
||||
kd.insert(v.co, i)
|
||||
kd.balance()
|
||||
return kd
|
||||
|
||||
|
||||
def build_vert_influence_map(obj_from, obj_to, kd_tree, expand=2):
|
||||
verts_of_edge = {
|
||||
i: (e.vertices[0], e.vertices[1]) for i, e in enumerate(obj_from.data.edges)
|
||||
}
|
||||
|
||||
edges_of_vert: Dict[int, List[int]] = {}
|
||||
for edge_idx, edge in enumerate(obj_from.data.edges):
|
||||
for vert_idx in edge.vertices:
|
||||
if vert_idx not in edges_of_vert:
|
||||
edges_of_vert[vert_idx] = []
|
||||
edges_of_vert[vert_idx].append(edge_idx)
|
||||
|
||||
# A mapping from target vertex index to a list of source vertex indicies and
|
||||
# their influence.
|
||||
# This can be pre-calculated once per object pair, to minimize re-calculations
|
||||
# of subsequent transferring of individual vertex groups.
|
||||
vert_influence_map: List[int, List[Tuple[int, float]]] = {}
|
||||
for i, dest_vert in enumerate(obj_to.data.vertices):
|
||||
vert_influence_map[i] = get_source_vert_influences(
|
||||
dest_vert, obj_from, kd_tree, expand, edges_of_vert, verts_of_edge
|
||||
)
|
||||
|
||||
return vert_influence_map
|
||||
|
||||
|
||||
def get_source_vert_influences(
|
||||
target_vert, obj_from, kd_tree, expand=2, edges_of_vert={}, verts_of_edge={}
|
||||
) -> List[Tuple[int, float]]:
|
||||
_coord, idx, dist = get_nearest_vert(target_vert.co, kd_tree)
|
||||
source_vert_indices = [idx]
|
||||
|
||||
if dist == 0:
|
||||
# If the vertex position is a perfect match, just use that one vertex with max influence.
|
||||
return [(idx, 1)]
|
||||
|
||||
for i in range(0, expand):
|
||||
new_indices = []
|
||||
for vert_idx in source_vert_indices:
|
||||
for edge in edges_of_vert[vert_idx]:
|
||||
vert_other = other_vert_of_edge(edge, vert_idx, verts_of_edge)
|
||||
if vert_other not in source_vert_indices:
|
||||
new_indices.append(vert_other)
|
||||
source_vert_indices.extend(new_indices)
|
||||
|
||||
distances: List[Tuple[int, float]] = []
|
||||
distance_total = 0
|
||||
for src_vert_idx in source_vert_indices:
|
||||
distance = (target_vert.co - obj_from.data.vertices[src_vert_idx].co).length
|
||||
distance_total += distance
|
||||
distances.append((src_vert_idx, distance))
|
||||
|
||||
# Calculate influences such that the total of all influences adds up to 1.0,
|
||||
# and the influence is inversely correlated with the distance.
|
||||
parts = [1 / (dist / distance_total) for idx, dist in distances]
|
||||
parts_sum = sum(parts)
|
||||
|
||||
influences = [
|
||||
(idx, 1 if dist == 0 else part / parts_sum)
|
||||
for part, dist in zip(parts, distances)
|
||||
]
|
||||
|
||||
return influences
|
||||
|
||||
|
||||
def get_nearest_vert(
|
||||
coords: Vector, kd_tree: kdtree.KDTree
|
||||
) -> Tuple[Vector, int, float]:
|
||||
"""Return coordinate, index, and distance of nearest vert to coords in kd_tree."""
|
||||
return kd_tree.find(coords)
|
||||
|
||||
|
||||
def other_vert_of_edge(
|
||||
edge: int, vert: int, verts_of_edge: Dict[int, Tuple[int, int]]
|
||||
) -> int:
|
||||
verts = verts_of_edge[edge]
|
||||
assert vert in verts, f"Vert {vert} not part of edge {edge}."
|
||||
return verts[0] if vert == verts[1] else verts[1]
|
||||
|
||||
|
||||
def transfer_vertex_groups(obj_from, obj_to, vert_influence_map, src_vgroups):
|
||||
"""Transfer src_vgroups in obj_from to obj_to using a pre-calculated vert_influence_map."""
|
||||
|
||||
for src_vg in src_vgroups:
|
||||
target_vg = obj_to.vertex_groups.get(src_vg.name)
|
||||
if target_vg == None:
|
||||
target_vg = obj_to.vertex_groups.new(name=src_vg.name)
|
||||
|
||||
for i, dest_vert in enumerate(obj_to.data.vertices):
|
||||
source_verts = vert_influence_map[i]
|
||||
|
||||
# Vertex Group Name : Weight
|
||||
vgroup_weights = {}
|
||||
|
||||
for src_vert_idx, influence in source_verts:
|
||||
for group in obj_from.data.vertices[src_vert_idx].groups:
|
||||
group_idx = group.group
|
||||
vg = obj_from.vertex_groups[group_idx]
|
||||
if vg not in src_vgroups:
|
||||
continue
|
||||
if vg.name not in vgroup_weights:
|
||||
vgroup_weights[vg.name] = 0
|
||||
vgroup_weights[vg.name] += vg.weight(src_vert_idx) * influence
|
||||
|
||||
# Assign final weights of this vertex in the vertex groups.
|
||||
for vg_name in vgroup_weights.keys():
|
||||
target_vg = obj_to.vertex_groups.get(vg_name)
|
||||
target_vg.add([dest_vert.index], vgroup_weights[vg_name], 'REPLACE')
|
||||
|
||||
|
||||
registry = [EASYWEIGHT_OT_transfer_vertex_groups]
|
||||
|
||||
|
||||
def register():
|
||||
bpy.types.VIEW3D_MT_object.append(
|
||||
EASYWEIGHT_OT_transfer_vertex_groups.draw_transfer_vertex_groups_op
|
||||
)
|
||||
|
||||
|
||||
def unregister():
|
||||
bpy.types.VIEW3D_MT_object.remove(
|
||||
EASYWEIGHT_OT_transfer_vertex_groups.draw_transfer_vertex_groups_op
|
||||
)
|
@ -1,618 +0,0 @@
|
||||
from typing import List, Dict, Tuple, Optional
|
||||
import bpy
|
||||
from bpy.types import KeyConfig, KeyMap, KeyMapItem, Operator
|
||||
|
||||
|
||||
def addon_hotkey_register(
|
||||
keymap_name='Window',
|
||||
op_idname='',
|
||||
key_id='A',
|
||||
event_type='PRESS',
|
||||
any=False,
|
||||
ctrl=False,
|
||||
alt=False,
|
||||
shift=False,
|
||||
oskey=False,
|
||||
key_modifier='NONE',
|
||||
direction='ANY',
|
||||
repeat=False,
|
||||
op_kwargs={},
|
||||
add_on_conflict=True,
|
||||
warn_on_conflict=True,
|
||||
error_on_conflict=False,
|
||||
):
|
||||
"""Top-level function for registering a hotkey as conveniently as possible.
|
||||
If you want to better manage the registered hotkey (for example, to be able
|
||||
to un-register it), it's advised to instantiate PyKeyMapItems yourself instead.
|
||||
|
||||
:param str keymap_name: Name of the KeyMap that this hotkey will be created in. Used to define what contexts the hotkey is available in
|
||||
:param str op_idname: bl_idname of the operator this hotkey should execute
|
||||
:param str key_id: Name of the key that must be interacted with to trigger this hotkey
|
||||
:param str event_type: Type of interaction to trigger this hotkey
|
||||
|
||||
:param bool any: If True, all modifier keys will be valid to trigger this hotkey
|
||||
:param bool ctrl: Whether the Ctrl key needs to be pressed in addition to the primary key
|
||||
:param bool alt: Whether the Alt key needs to be pressed in addition to the primary key
|
||||
:param bool shift: Whether the Shift key needs to be pressed in addition to the primary key
|
||||
:param bool oskey: Whether the OS key needs to be pressed in addition to the primary key
|
||||
:param str key_modifier: Another non-modifier key that should be used as a modifier key
|
||||
:param str direction: For interaction methods with a direction, this defines the direction
|
||||
:param bool repeat: Whether the hotkey should repeat its action as long as the keys remain held
|
||||
|
||||
:param op_kwargs: A dictionary of parameters that should be passed as operator parameters
|
||||
|
||||
:return: The PyKeyMapItem that manages this hotkey
|
||||
"""
|
||||
py_kmi = PyKeyMapItem(
|
||||
op_idname=op_idname,
|
||||
key_id=key_id,
|
||||
event_type=event_type,
|
||||
any=any,
|
||||
ctrl=ctrl,
|
||||
alt=alt,
|
||||
shift=shift,
|
||||
oskey=oskey,
|
||||
key_modifier=key_modifier,
|
||||
direction=direction,
|
||||
repeat=repeat,
|
||||
op_kwargs=op_kwargs,
|
||||
)
|
||||
|
||||
py_kmi.register(
|
||||
keymap_name=keymap_name,
|
||||
add_on_conflict=add_on_conflict,
|
||||
warn_on_conflict=warn_on_conflict,
|
||||
error_on_conflict=error_on_conflict,
|
||||
)
|
||||
return py_kmi
|
||||
|
||||
|
||||
class PyKeyMapItem:
|
||||
"""Class to help conveniently manage a single KeyMapItem, independently of
|
||||
any particular KeyMap or any other container or built-in bpy_type."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
op_idname='',
|
||||
key_id='A',
|
||||
event_type='PRESS',
|
||||
any=False,
|
||||
ctrl=False,
|
||||
alt=False,
|
||||
shift=False,
|
||||
oskey=False,
|
||||
key_modifier='NONE',
|
||||
direction='ANY',
|
||||
repeat=False,
|
||||
op_kwargs={},
|
||||
):
|
||||
self.op_idname = op_idname
|
||||
self.key_id = self.type = key_id
|
||||
self.check_key_id()
|
||||
self.event_type = self.value = event_type
|
||||
self.check_event_type()
|
||||
|
||||
self.any = any
|
||||
self.ctrl = ctrl
|
||||
self.alt = alt
|
||||
self.shift = shift
|
||||
self.oskey = oskey
|
||||
self.key_modifier = key_modifier
|
||||
self.direction = direction
|
||||
self.repeat = repeat
|
||||
|
||||
self.op_kwargs = op_kwargs
|
||||
|
||||
@staticmethod
|
||||
def new_from_keymap_item(kmi: KeyMapItem, context=None) -> "PyKeyMapItem":
|
||||
op_kwargs = {}
|
||||
if kmi.properties:
|
||||
op_kwargs = {key: value for key, value in kmi.properties.items()}
|
||||
return PyKeyMapItem(
|
||||
op_idname=kmi.idname,
|
||||
key_id=kmi.type,
|
||||
event_type=kmi.value,
|
||||
any=kmi.any,
|
||||
ctrl=kmi.ctrl,
|
||||
alt=kmi.alt,
|
||||
shift=kmi.shift,
|
||||
oskey=kmi.oskey,
|
||||
key_modifier=kmi.key_modifier,
|
||||
direction=kmi.direction,
|
||||
repeat=kmi.repeat,
|
||||
op_kwargs=op_kwargs,
|
||||
)
|
||||
|
||||
def check_key_id(self):
|
||||
"""Raise a KeyMapException if the keymap_name isn't a valid KeyMap name that
|
||||
actually exists in Blender's keymap system.
|
||||
"""
|
||||
return check_key_id(self.key_id)
|
||||
|
||||
def check_event_type(self):
|
||||
"""Raise a KeyMapException if the event_type isn't one that actually exists
|
||||
in Blender's keymap system."""
|
||||
return check_event_type(self.event_type)
|
||||
|
||||
@property
|
||||
def key_string(self) -> str:
|
||||
return get_kmi_key_string(self)
|
||||
|
||||
def register(
|
||||
self,
|
||||
context=None,
|
||||
keymap_name='Window',
|
||||
*,
|
||||
add_on_conflict=True,
|
||||
warn_on_conflict=True,
|
||||
error_on_conflict=False,
|
||||
) -> Optional[Tuple[KeyMap, KeyMapItem]]:
|
||||
"""Higher-level function for addon dev convenience.
|
||||
The caller doesn't have to worry about the KeyConfig or the KeyMap.
|
||||
The `addon` KeyConfig will be used.
|
||||
"""
|
||||
|
||||
if not context:
|
||||
context = bpy.context
|
||||
|
||||
wm = context.window_manager
|
||||
kconf_addon = wm.keyconfigs.addon
|
||||
if not kconf_addon:
|
||||
# This happens when running Blender in background mode.
|
||||
return
|
||||
|
||||
check_keymap_name(keymap_name)
|
||||
|
||||
# Find conflicts.
|
||||
user_km = get_keymap_of_config(wm.keyconfigs.user, keymap_name)
|
||||
if not user_km:
|
||||
conflicts = []
|
||||
else:
|
||||
conflicts = self.find_in_keymap_conflicts(user_km)
|
||||
|
||||
kmi = None
|
||||
keymap = None
|
||||
if not conflicts or add_on_conflict:
|
||||
# Add the keymap if there is no conflict, or if we are allowed
|
||||
# to add it in spite of a conflict.
|
||||
|
||||
# If this KeyMap already exists, new() will return the existing one,
|
||||
# which is confusing, but ideal.
|
||||
space_type, region_type = get_ui_types_of_keymap(keymap_name)
|
||||
keymap = kconf_addon.keymaps.new(
|
||||
name=keymap_name, space_type=space_type, region_type=region_type
|
||||
)
|
||||
|
||||
kmi = self.register_in_keymap(keymap)
|
||||
|
||||
# Warn or raise error about conflicts.
|
||||
if conflicts and (warn_on_conflict or error_on_conflict):
|
||||
conflict_info = "\n".join(
|
||||
["Conflict: " + kmi_to_str(kmi) for kmi in conflicts]
|
||||
)
|
||||
|
||||
if error_on_conflict:
|
||||
raise KeyMapException(
|
||||
"Failed to register KeyMapItem due to conflicting items:"
|
||||
+ conflict_info
|
||||
)
|
||||
if warn_on_conflict:
|
||||
print(
|
||||
"Warning: Conflicting KeyMapItems: "
|
||||
+ str(self)
|
||||
+ "\n"
|
||||
+ conflict_info
|
||||
)
|
||||
|
||||
return keymap, kmi
|
||||
|
||||
def register_in_keymap(self, keymap: KeyMap) -> Optional[KeyMapItem]:
|
||||
"""Lower-level function, for registering in a specific KeyMap."""
|
||||
|
||||
kmi = keymap.keymap_items.new(
|
||||
self.op_idname,
|
||||
type=self.key_id,
|
||||
value=self.event_type,
|
||||
any=self.any,
|
||||
ctrl=self.ctrl,
|
||||
alt=self.alt,
|
||||
shift=self.shift,
|
||||
oskey=self.oskey,
|
||||
key_modifier=self.key_modifier,
|
||||
direction=self.direction,
|
||||
repeat=self.repeat,
|
||||
)
|
||||
|
||||
for key in self.op_kwargs:
|
||||
value = self.op_kwargs[key]
|
||||
setattr(kmi.properties, key, value)
|
||||
|
||||
return kmi
|
||||
|
||||
def unregister(self, context=None) -> bool:
|
||||
"""Higher-level function for addon dev convenience.
|
||||
The caller doesn't have to worry about the KeyConfig or the KeyMap.
|
||||
The hotkey will be removed from all KeyMaps of both `addon` and 'user' KeyConfigs.
|
||||
"""
|
||||
|
||||
if not context:
|
||||
context = bpy.context
|
||||
|
||||
wm = context.window_manager
|
||||
kconfs = wm.keyconfigs
|
||||
|
||||
success = False
|
||||
for kconf in (kconfs.user, kconfs.addon):
|
||||
if not kconf:
|
||||
# This happens when running Blender in background mode.
|
||||
continue
|
||||
for km in self.find_containing_keymaps(kconf):
|
||||
self.unregister_from_keymap(km)
|
||||
success = True
|
||||
|
||||
return success
|
||||
|
||||
def unregister_from_keymap(self, keymap: KeyMap):
|
||||
"""Lower-level function, for unregistering from a specific KeyMap."""
|
||||
kmi = self.find_in_keymap_exact(keymap)
|
||||
if not kmi:
|
||||
return False
|
||||
keymap.keymap_items.remove(kmi)
|
||||
return True
|
||||
|
||||
def find_containing_keymaps(self, key_config: KeyConfig) -> List[KeyMap]:
|
||||
"""Return list of KeyMaps in a KeyConfig that contain a matching KeyMapItem."""
|
||||
matches: List[KeyMap] = []
|
||||
for km in key_config.keymaps:
|
||||
match = self.find_in_keymap_exact(km)
|
||||
if match:
|
||||
matches.append(km)
|
||||
return matches
|
||||
|
||||
def find_in_keymap_exact(self, keymap: KeyMap) -> Optional[KeyMapItem]:
|
||||
"""Find zero or one KeyMapItem in the given KeyMap that is an exact match
|
||||
with this in its operator, parameters, and key binding.
|
||||
More than one will result in an error.
|
||||
"""
|
||||
matches = self.find_in_keymap_exact_multi(keymap)
|
||||
if len(matches) > 1:
|
||||
# This should happen only if an addon dev or a user creates two keymaps
|
||||
# that are identical in everything except their ``repeat`` flag.
|
||||
raise KeyMapException(
|
||||
"More than one KeyMapItems match this PyKeyMapItem: \n"
|
||||
+ str(self)
|
||||
+ "\n".join([str(match) for match in matches])
|
||||
)
|
||||
if matches:
|
||||
return matches[0]
|
||||
|
||||
def find_in_keymap_exact_multi(self, keymap: KeyMap) -> List[KeyMapItem]:
|
||||
"""Return KeyMapItems in the given KeyMap that are an exact match with
|
||||
this PyKeyMapItem in its operator, parameters, and key binding.
|
||||
"""
|
||||
return [kmi for kmi in keymap.keymap_items if self.compare_to_kmi_exact(kmi)]
|
||||
|
||||
def compare_to_kmi_exact(self, kmi: KeyMapItem) -> bool:
|
||||
"""Return whether we have the same operator, params, and trigger
|
||||
as the passed KeyMapItem.
|
||||
"""
|
||||
return self.compare_to_kmi_by_operator(
|
||||
kmi, match_kwargs=True
|
||||
) and self.compare_to_kmi_by_trigger(kmi)
|
||||
|
||||
def find_in_keymap_by_operator(
|
||||
self, keymap: KeyMap, *, match_kwargs=True
|
||||
) -> List[KeyMapItem]:
|
||||
"""Return all KeyMapItems in the given KeyMap, which triggers the given
|
||||
operator with the given parameters.
|
||||
"""
|
||||
return [
|
||||
kmi
|
||||
for kmi in keymap.keymap_items
|
||||
if self.compare_to_kmi_by_operator(kmi, match_kwargs=match_kwargs)
|
||||
]
|
||||
|
||||
def compare_to_kmi_by_operator(self, kmi: KeyMapItem, *, match_kwargs=True) -> bool:
|
||||
"""Return whether we have the same operator
|
||||
(and optionally operator params) as the passed KMI.
|
||||
"""
|
||||
if kmi.idname != self.op_idname:
|
||||
return False
|
||||
|
||||
if not match_kwargs:
|
||||
return True
|
||||
|
||||
# Check for mismatching default-ness of operator parameters.
|
||||
if set(kmi.properties.keys()) != set(self.op_kwargs.keys()):
|
||||
# This happens when the parameter overrides specified in the KMI
|
||||
# aren't the same as what we're searching for.
|
||||
return False
|
||||
|
||||
# Check for mismatching values of operator parameters.
|
||||
for prop_name in kmi.properties.keys():
|
||||
# It's important to use getattr() instead of dictionary syntax here,
|
||||
# otherwise enum values will be integers instead of identifier strings.
|
||||
value = getattr(kmi.properties, prop_name)
|
||||
|
||||
if value != self.op_kwargs[prop_name]:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def find_in_keymap_conflicts(self, keymap: KeyMap) -> List[KeyMapItem]:
|
||||
"""Return any KeyMapItems in the given KeyMap which are bound to the
|
||||
same key combination.
|
||||
"""
|
||||
return [
|
||||
kmi for kmi in keymap.keymap_items if self.compare_to_kmi_by_trigger(kmi)
|
||||
]
|
||||
|
||||
def compare_to_kmi_by_trigger(self, kmi: KeyMapItem) -> bool:
|
||||
"""Return whether we have the same trigger settings as the passed KMI."""
|
||||
return (
|
||||
kmi.type == self.key_id
|
||||
and kmi.value == self.event_type
|
||||
and kmi.any == self.any
|
||||
and kmi.ctrl == self.ctrl
|
||||
and kmi.alt == self.alt
|
||||
and kmi.shift == self.shift
|
||||
and kmi.oskey == self.oskey
|
||||
and kmi.key_modifier == self.key_modifier
|
||||
and kmi.direction == self.direction
|
||||
)
|
||||
|
||||
def get_user_kmis(self, context=None) -> List[KeyMapItem]:
|
||||
"""Return all matching KeyMapItems in the user keyconfig."""
|
||||
if not context:
|
||||
context = bpy.context
|
||||
user_kconf = context.window_manager.keyconfigs.user
|
||||
matches = []
|
||||
for km in user_kconf.keymaps:
|
||||
for kmi in km.keymap_items:
|
||||
if self.compare_to_kmi_exact(kmi):
|
||||
matches.append(kmi)
|
||||
return matches
|
||||
|
||||
def update(self, **kwargs):
|
||||
"""Update all KeyMapItems with the passed keyword arguments."""
|
||||
for key, value in kwargs.items():
|
||||
for kmi in self.get_user_kmis():
|
||||
setattr(kmi, key, value)
|
||||
|
||||
setattr(self, key, value)
|
||||
|
||||
def __str__(self) -> str:
|
||||
"""Return an informative but compact string representation."""
|
||||
ret = f"PyKeyMapItem: < {self.key_string}"
|
||||
if self.op_idname:
|
||||
op = find_operator_class_by_bl_idname(self.op_idname)
|
||||
if not op:
|
||||
ret += " | " + self.op_idname + " (Unregistered)"
|
||||
else:
|
||||
op_ui_name = op.name if hasattr(op, 'name') else op.bl_label
|
||||
op_class_name = op.bl_rna.identifier
|
||||
ret += " | " + op_ui_name + f" | {self.op_idname} | {op_class_name}"
|
||||
if self.op_kwargs:
|
||||
ret += " | " + str(self.op_kwargs)
|
||||
else:
|
||||
ret += " | (No operator assigned.)"
|
||||
|
||||
return ret + " >"
|
||||
|
||||
def __repr__(self):
|
||||
"""Return a string representation that evaluates back to this object."""
|
||||
pretty_kwargs = str(self.op_kwargs).replace(", ", ",\n")
|
||||
return (
|
||||
"PyKeyMapItem(\n"
|
||||
f" op_idname='{self.op_idname}',\n"
|
||||
f" key_id='{self.key_id}',\n"
|
||||
f" event_type='{self.event_type}',\n"
|
||||
"\n"
|
||||
f" any={self.any},\n"
|
||||
f" ctrl={self.ctrl},\n"
|
||||
f" alt={self.alt},\n"
|
||||
f" shift={self.shift},\n"
|
||||
f" oskey={self.oskey},\n"
|
||||
f" key_modifier='{self.key_modifier}',\n"
|
||||
f" direction='{self.direction}',\n"
|
||||
f" repeat='{self.repeat}',\n"
|
||||
"\n"
|
||||
f" op_kwargs={pretty_kwargs}\n"
|
||||
")"
|
||||
)
|
||||
|
||||
|
||||
def kmi_to_str(kmi: KeyMapItem) -> str:
|
||||
"""Similar to PyKeyMapItem.__str__: Return a compact string representation of this KeyMapItem."""
|
||||
ret = f"KeyMapItem: < {get_kmi_key_string(kmi)}"
|
||||
if kmi.idname:
|
||||
op = find_operator_class_by_bl_idname(kmi.idname)
|
||||
if not op:
|
||||
ret += " | " + kmi.idname + " (Unregistered)"
|
||||
else:
|
||||
op_ui_name = op.name if hasattr(op, 'name') else op.bl_label
|
||||
op_class_name = op.bl_rna.identifier
|
||||
ret += " | " + op_ui_name + f" | {kmi.idname} | {op_class_name}"
|
||||
# if kmi.properties: # TODO: This currently causes a crash: https://projects.blender.org/blender/blender/issues/111702
|
||||
# ret += " | " + str({key:value for key, value in kmi.properties.items()})
|
||||
else:
|
||||
ret += " | (No operator assigned.)"
|
||||
|
||||
return ret + " >"
|
||||
|
||||
|
||||
def get_kmi_key_string(kmi) -> str:
|
||||
"""A user-friendly description string of the keys needed to activate this hotkey.
|
||||
Should be identical to what's displayed in Blender's Keymap preferences.
|
||||
"""
|
||||
key_data = get_enum_values(bpy.types.KeyMapItem, 'type')
|
||||
keys = []
|
||||
if kmi.shift:
|
||||
keys.append("Shift")
|
||||
if kmi.ctrl:
|
||||
keys.append("Ctrl")
|
||||
if kmi.alt:
|
||||
keys.append("Alt")
|
||||
if kmi.oskey:
|
||||
keys.append("OS")
|
||||
if kmi.key_modifier != 'NONE':
|
||||
keys.append(key_data[kmi.key_modifier][0])
|
||||
keys.append(key_data[kmi.type][0])
|
||||
final_string = " ".join(keys)
|
||||
if not final_string:
|
||||
return "Unassigned"
|
||||
return final_string
|
||||
|
||||
|
||||
def get_keymap_of_config(keyconfig: KeyConfig, keymap_name: str) -> Optional[KeyMap]:
|
||||
space_type, region_type = get_ui_types_of_keymap(keymap_name)
|
||||
keymap = keyconfig.keymaps.find(
|
||||
keymap_name, space_type=space_type, region_type=region_type
|
||||
)
|
||||
return keymap
|
||||
|
||||
|
||||
def ensure_keymap_in_config(keyconfig, keymap_name: str) -> KeyMap:
|
||||
space_type, region_type = get_ui_types_of_keymap(keymap_name)
|
||||
keymap = keyconfig.keymaps.new(
|
||||
keymap_name, space_type=space_type, region_type=region_type
|
||||
)
|
||||
return keymap
|
||||
|
||||
|
||||
def get_enum_values(bpy_type, enum_prop_name: str) -> Dict[str, Tuple[str, str]]:
|
||||
"""Given a registered EnumProperty's owner and name, return the enum's
|
||||
possible states as a dictionary, mapping the enum identifiers to a tuple
|
||||
of its name and description.
|
||||
|
||||
:param bpy_type: The RNA type that owns the Enum property
|
||||
:param str enum_prop_name: The name of the Enum property
|
||||
:return: A dictionary mapping the enum's identifiers to its name and description
|
||||
:rtype: dict{str: (str, str)}
|
||||
"""
|
||||
|
||||
# If it's a Python Operator.
|
||||
if isinstance(bpy_type, Operator):
|
||||
try:
|
||||
enum_items = bpy_type.__annotations__[enum_prop_name].keywords['items']
|
||||
return {e[0]: (e[1], e[2]) for e in enum_items}
|
||||
except:
|
||||
return
|
||||
|
||||
# If it's a built-in operator.
|
||||
enum_items = bpy_type.bl_rna.properties[enum_prop_name].enum_items
|
||||
return {e.identifier: (e.name, e.description) for e in enum_items}
|
||||
|
||||
|
||||
def get_all_keymap_names() -> List[str]:
|
||||
"""Returns a list of all keymap names in Blender.
|
||||
|
||||
:return: A list of all valid keymap names
|
||||
:rtype: list[str]
|
||||
"""
|
||||
return bpy.context.window_manager.keyconfigs.default.keymaps.keys()
|
||||
|
||||
|
||||
def get_ui_types_of_keymap(keymap_name: str) -> Tuple[str, str]:
|
||||
# The default KeyConfig contains all the possible valid KeyMap names,
|
||||
# with the correct space_type and region_type already assigned.
|
||||
kc_default = bpy.context.window_manager.keyconfigs.default
|
||||
# This is useful to acquire the correct parameters for new KeyMapItems,
|
||||
# since having the wrong params causes the KeyMapItem to fail silently.
|
||||
check_keymap_name(keymap_name)
|
||||
|
||||
km = kc_default.keymaps.get(keymap_name)
|
||||
assert km, f"Error: KeyMap not found: '{keymap_name}'"
|
||||
|
||||
return km.space_type, km.region_type
|
||||
|
||||
|
||||
def find_operator_class_by_bl_idname(bl_idname: str):
|
||||
"""
|
||||
Returns the class of the operator registered with the given bl_idname.
|
||||
|
||||
:param str bl_idname: Identifier of the operator to find
|
||||
:return: Class of the operator registered with the given bl_idname
|
||||
:rtype: bpy.types.Operator (for Python ops) or bpy_struct (for built-ins)
|
||||
"""
|
||||
|
||||
# Try Python operators first.
|
||||
for cl in Operator.__subclasses__():
|
||||
if not hasattr(cl, 'bl_idname'):
|
||||
# This can happen with mix-in classes.
|
||||
continue
|
||||
if cl.bl_idname == bl_idname:
|
||||
return cl
|
||||
|
||||
# Then built-ins.
|
||||
module_name, op_name = bl_idname.split(".")
|
||||
module = getattr(bpy.ops, module_name)
|
||||
if not module:
|
||||
return
|
||||
op = getattr(module, op_name)
|
||||
if not op:
|
||||
return
|
||||
return op.get_rna_type()
|
||||
|
||||
|
||||
class KeyMapException(Exception):
|
||||
"""Raised when a KeyMapItem cannot (un)register."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
def check_keymap_name(keymap_name: str):
|
||||
"""Raise a KeyMapException if the keymap_name isn't a valid KeyMap name that
|
||||
actually exists in Blender's keymap system.
|
||||
"""
|
||||
all_km_names = get_all_keymap_names()
|
||||
is_valid = keymap_name in all_km_names
|
||||
if not is_valid:
|
||||
print("All valid keymap names:")
|
||||
print("\n".join(all_km_names))
|
||||
raise KeyMapException(
|
||||
f'"{keymap_name}" is not a valid keymap name. Must be one of the above.'
|
||||
)
|
||||
|
||||
|
||||
def check_key_id(key_id: str):
|
||||
"""Raise a KeyMapException if the key_id isn't one that actually exists
|
||||
in Blender's keymap system.
|
||||
"""
|
||||
all_valid_key_identifiers = get_enum_values(KeyMapItem, 'type')
|
||||
is_valid = key_id in all_valid_key_identifiers
|
||||
if not is_valid:
|
||||
print("All valid key identifiers and names:")
|
||||
print("\n".join(list(all_valid_key_identifiers.items())))
|
||||
raise KeyMapException(
|
||||
f'"{key_id}" is not a valid key identifier. Must be one of the above.'
|
||||
)
|
||||
|
||||
|
||||
def check_event_type(event_type: str):
|
||||
"""Raise a KeyMapException if the event_type isn't one that actually exists
|
||||
in Blender's keymap system.
|
||||
"""
|
||||
all_valid_event_types = get_enum_values(KeyMapItem, 'value')
|
||||
is_valid = event_type in all_valid_event_types
|
||||
if not is_valid:
|
||||
print("All valid event names:")
|
||||
print("\n".join(list(all_valid_event_types.keys())))
|
||||
raise KeyMapException(
|
||||
f'"{event_type}" is not a valid event type. Must be one of the above.'
|
||||
)
|
||||
return is_valid
|
||||
|
||||
|
||||
def find_broken_items_of_keymap(keymap: bpy.types.KeyMap):
|
||||
"""I encountered one case where kmi.properties.keys() resulted in an error.
|
||||
If that happens again, use this func to troubleshoot.
|
||||
"""
|
||||
broken = []
|
||||
for kmi in keymap.keymap_items:
|
||||
try:
|
||||
kmi.properties.keys()
|
||||
except:
|
||||
broken.append(kmi)
|
||||
|
||||
return broken
|
@ -1,129 +0,0 @@
|
||||
from typing import Tuple, List, Optional
|
||||
import re
|
||||
from bpy.utils import flip_name
|
||||
|
||||
separators = "-_."
|
||||
|
||||
|
||||
def get_name(thing) -> str:
|
||||
if hasattr(thing, 'name'):
|
||||
return thing.name
|
||||
else:
|
||||
return str(thing)
|
||||
|
||||
|
||||
def make_name(prefixes=[], base="", suffixes=[],
|
||||
prefix_separator="-", suffix_separator=".") -> str:
|
||||
"""Make a name from a list of prefixes, a base, and a list of suffixes."""
|
||||
name = ""
|
||||
for pre in prefixes:
|
||||
if pre == "":
|
||||
continue
|
||||
name += pre + prefix_separator
|
||||
name += base
|
||||
for suf in suffixes:
|
||||
if suf == "":
|
||||
continue
|
||||
name += suffix_separator + suf
|
||||
return name
|
||||
|
||||
|
||||
def slice_name(name, prefix_separator="-", suffix_separator="."):
|
||||
"""Break up a name into its prefix, base, suffix components."""
|
||||
prefixes = name.split(prefix_separator)[:-1]
|
||||
suffixes = name.split(suffix_separator)[1:]
|
||||
base = name.split(prefix_separator)[-1].split(suffix_separator)[0]
|
||||
return [prefixes, base, suffixes]
|
||||
|
||||
|
||||
def has_trailing_zeroes(thing):
|
||||
name = get_name(thing)
|
||||
regex = "\.[0-9][0-9][0-9]$"
|
||||
search = re.search(regex, name)
|
||||
return search != None
|
||||
|
||||
|
||||
def strip_trailing_numbers(name) -> Tuple[str, str]:
|
||||
if "." in name:
|
||||
# Check if there are only digits after the last period
|
||||
slices = name.split(".")
|
||||
after_last_period = slices[-1]
|
||||
before_last_period = ".".join(slices[:-1])
|
||||
|
||||
# If there are only digits after the last period, discard them
|
||||
if all([c in "0123456789" for c in after_last_period]):
|
||||
return before_last_period, "."+after_last_period
|
||||
|
||||
return name, ""
|
||||
|
||||
|
||||
def get_side_lists(with_separators=False) -> Tuple[List[str], List[str], List[str]]:
|
||||
left = ['left', 'Left', 'LEFT', 'l', 'L',]
|
||||
right_placehold = ['*rgt*', '*Rgt*', '*RGT*', '*r*', '*R*']
|
||||
right = ['right', 'Right', 'RIGHT', 'r', 'R']
|
||||
|
||||
# If the name is longer than 2 characters, only swap side identifiers if they
|
||||
# are next to a separator.
|
||||
if with_separators:
|
||||
for l in [left, right_placehold, right]:
|
||||
l_copy = l[:]
|
||||
for side in l_copy:
|
||||
if len(side) < 4:
|
||||
l.remove(side)
|
||||
for sep in separators:
|
||||
l.append(side+sep)
|
||||
l.append(sep+side)
|
||||
|
||||
return left, right_placehold, right
|
||||
|
||||
|
||||
def side_is_left(name) -> Optional[bool]:
|
||||
"""Identify whether a name belongs to the left or right side or neither."""
|
||||
|
||||
flipped_name = flip_name(name)
|
||||
if flipped_name == name:
|
||||
return None # Return None to indicate neither side.
|
||||
|
||||
stripped_name, number_suffix = strip_trailing_numbers(name)
|
||||
|
||||
def check_start_side(side_list, name):
|
||||
for side in side_list:
|
||||
if name.startswith(side):
|
||||
return True
|
||||
return False
|
||||
|
||||
def check_end_side(side_list, name):
|
||||
for side in side_list:
|
||||
if name.endswith(side):
|
||||
return True
|
||||
return False
|
||||
|
||||
left, right_placehold, right = get_side_lists(with_separators=True)
|
||||
|
||||
is_left_prefix = check_start_side(left, stripped_name)
|
||||
is_left_suffix = check_end_side(left, stripped_name)
|
||||
|
||||
is_right_prefix = check_start_side(right, stripped_name)
|
||||
is_right_suffix = check_end_side(right, stripped_name)
|
||||
|
||||
# Prioritize suffix for determining the name's side.
|
||||
if is_left_suffix or is_right_suffix:
|
||||
return is_left_suffix
|
||||
|
||||
# If no relevant suffix found, try prefix.
|
||||
if is_left_prefix or is_right_prefix:
|
||||
return is_left_prefix
|
||||
|
||||
# If no relevant suffix or prefix found, try anywhere.
|
||||
any_left = any([side in name for side in left])
|
||||
any_right = any([side in name for side in right])
|
||||
if not any_left and not any_right:
|
||||
# If neither side found, return None.
|
||||
return None
|
||||
if any_left and not any_right:
|
||||
return True
|
||||
if any_right and not any_left:
|
||||
return False
|
||||
|
||||
# If left and right were both found somewhere, I give up.
|
||||
return None
|
@ -1,255 +0,0 @@
|
||||
import bpy
|
||||
from bpy.props import BoolProperty, EnumProperty
|
||||
from bpy.app.handlers import persistent
|
||||
from .vertex_group_operators import EASYWEIGHTS_OT_delete_empty_deform_groups, EASYWEIGHTS_OT_delete_unused_vertex_groups
|
||||
|
||||
class EASYWEIGHT_OT_wp_context_menu(bpy.types.Operator):
|
||||
""" Custom Weight Paint context menu """
|
||||
bl_idname = "object.custom_weight_paint_context_menu"
|
||||
bl_label = "Custom Weight Paint Context Menu"
|
||||
bl_options = {'REGISTER'}
|
||||
|
||||
def update_clean_weights(self, context):
|
||||
context.scene['clean_weights'] = self.clean_weights
|
||||
WeightCleaner.cleaner_active = context.scene['clean_weights']
|
||||
|
||||
def update_front_faces(self, context):
|
||||
for b in bpy.data.brushes:
|
||||
if not b.use_paint_weight:
|
||||
continue
|
||||
b.use_frontface = self.front_faces
|
||||
|
||||
def update_accumulate(self, context):
|
||||
for b in bpy.data.brushes:
|
||||
if not b.use_paint_weight:
|
||||
continue
|
||||
b.use_accumulate = self.accumulate
|
||||
|
||||
def update_falloff_shape(self, context):
|
||||
for b in bpy.data.brushes:
|
||||
if not b.use_paint_weight:
|
||||
continue
|
||||
b.falloff_shape = self.falloff_shape
|
||||
for i, val in enumerate(b.cursor_color_add):
|
||||
if val > 0:
|
||||
b.cursor_color_add[i] = (
|
||||
0.5 if self.falloff_shape == 'SPHERE' else 2.0)
|
||||
|
||||
clean_weights: BoolProperty(
|
||||
name="Clean Weights", description="Run the Clean Vertex Groups operator after every weight brush stroke", update=update_clean_weights)
|
||||
front_faces: BoolProperty(
|
||||
name="Front Faces Only", description="Toggle the Front Faces Only setting for all weight brushes", update=update_front_faces)
|
||||
accumulate: BoolProperty(
|
||||
name="Accumulate", description="Toggle the Accumulate setting for all weight brushes", update=update_accumulate)
|
||||
falloff_shape: EnumProperty(name="Falloff Type", description="Select the Falloff Shape setting for all weight brushes", update=update_falloff_shape,
|
||||
items=[
|
||||
('SPHERE', 'Sphere', "The brush influence falls off along a sphere whose center is the mesh under the cursor's pointer"),
|
||||
('PROJECTED', 'Projected', "The brush influence falls off in a tube around the cursor. This is useful for painting backfaces, as long as Front Faces Only is off.")
|
||||
]
|
||||
)
|
||||
|
||||
# @classmethod
|
||||
# def poll(cls, context):
|
||||
# return context.mode == 'PAINT_WEIGHT'
|
||||
|
||||
def draw_operators(self, layout, context):
|
||||
layout.label(text="Operators")
|
||||
|
||||
op = layout.operator(
|
||||
'object.vertex_group_normalize_all',
|
||||
text="Normalize Deform",
|
||||
icon='IPO_SINE'
|
||||
)
|
||||
op.group_select_mode = 'BONE_DEFORM'
|
||||
op.lock_active = False
|
||||
|
||||
row = layout.row()
|
||||
row.operator("object.vertex_group_clean", icon='BRUSH_DATA',
|
||||
text="Clean 0").group_select_mode = 'ALL'
|
||||
row.operator(EASYWEIGHTS_OT_delete_empty_deform_groups.bl_idname,
|
||||
text="Wipe Empty", icon='GROUP_BONE')
|
||||
row.operator(EASYWEIGHTS_OT_delete_unused_vertex_groups.bl_idname,
|
||||
text="Wipe Unused", icon='BRUSH_DATA')
|
||||
|
||||
def draw_minimal(self, layout, context):
|
||||
overlay = context.space_data.overlay
|
||||
row = layout.row(heading="Symmetry: ")
|
||||
# Compatibility for versions between rB5502517c3c12086c111a and rBfa9b05149c2ca3915a4fb26.
|
||||
if hasattr(context.weight_paint_object.data, "use_mirror_vertex_group_x"):
|
||||
row.prop(context.weight_paint_object.data,
|
||||
"use_mirror_vertex_group_x", text="X-Mirror", toggle=True)
|
||||
else:
|
||||
row.prop(context.weight_paint_object.data,
|
||||
"use_mirror_x", text="X-Mirror", toggle=True)
|
||||
if hasattr(context.weight_paint_object.data, 'use_mirror_vertex_groups'):
|
||||
row.prop(context.weight_paint_object.data,
|
||||
'use_mirror_vertex_groups', text="Flip Groups", toggle=True)
|
||||
|
||||
row = layout.row(heading="Mesh Display: ")
|
||||
row.prop(overlay, "show_wpaint_contours",
|
||||
text="Weight Contours", toggle=True)
|
||||
row.prop(overlay, "show_paint_wire", text="Wireframe", toggle=True)
|
||||
|
||||
row = layout.row(heading="Bone Display: ")
|
||||
row.prop(overlay, "show_bones", text="Bones", toggle=True)
|
||||
if context.pose_object:
|
||||
row.prop(context.pose_object, "show_in_front", toggle=True)
|
||||
|
||||
self.draw_operators(layout, context)
|
||||
|
||||
def draw_overlay_settings(self, layout, context):
|
||||
overlay = context.space_data.overlay
|
||||
tool_settings = context.tool_settings
|
||||
layout.label(text="Overlay")
|
||||
row = layout.row()
|
||||
row.use_property_split = True
|
||||
row.prop(tool_settings, "vertex_group_user",
|
||||
text="Zero Weights Display", expand=True)
|
||||
if hasattr(context.space_data, "overlay"):
|
||||
row = layout.row()
|
||||
row.prop(overlay, "show_wpaint_contours",
|
||||
text="Weight Contours", toggle=True)
|
||||
row.prop(overlay, "show_paint_wire", text="Wireframe", toggle=True)
|
||||
row.prop(overlay, "show_bones", text="Bones", toggle=True)
|
||||
|
||||
if context.pose_object:
|
||||
layout.label(text="Armature Display")
|
||||
layout.prop(context.pose_object.data, "display_type", expand=True)
|
||||
layout.prop(context.pose_object, "show_in_front", toggle=True)
|
||||
|
||||
def draw_weight_paint_settings(self, layout, context):
|
||||
tool_settings = context.tool_settings
|
||||
layout.label(text="Weight Paint settings")
|
||||
|
||||
row = layout.row()
|
||||
row.prop(tool_settings, "use_auto_normalize",
|
||||
text="Auto Normalize", toggle=True)
|
||||
row.prop(self, "clean_weights", toggle=True)
|
||||
row.prop(tool_settings, "use_multipaint",
|
||||
text="Multi-Paint", toggle=True)
|
||||
row = layout.row()
|
||||
# Compatibility for versions between rB5502517c3c12086c111a and rBfa9b05149c2ca3915a4fb26.
|
||||
if hasattr(context.weight_paint_object.data, "use_mirror_vertex_group_x"):
|
||||
row.prop(context.weight_paint_object.data,
|
||||
"use_mirror_vertex_group_x", text="X-Mirror", toggle=True)
|
||||
else:
|
||||
row.prop(context.weight_paint_object.data,
|
||||
"use_mirror_x", text="X-Mirror", toggle=True)
|
||||
if hasattr(context.weight_paint_object.data, 'use_mirror_vertex_groups'):
|
||||
row.prop(context.weight_paint_object.data,
|
||||
'use_mirror_vertex_groups', text="Flip Groups", toggle=True)
|
||||
|
||||
def draw_brush_settings(self, layout, context):
|
||||
row = layout.row()
|
||||
row.label(text="Brush Settings (Global)")
|
||||
icon = 'HIDE_ON' if context.scene.easyweight_minimal else 'HIDE_OFF'
|
||||
row.prop(context.scene, "easyweight_minimal",
|
||||
icon=icon, toggle=False, text="", emboss=False)
|
||||
layout.prop(self, "accumulate", toggle=True)
|
||||
layout.prop(self, "front_faces", toggle=True)
|
||||
row = layout.row(heading="Falloff Shape: ")
|
||||
row.prop(self, "falloff_shape", expand=True)
|
||||
layout.separator()
|
||||
|
||||
def draw(self, context):
|
||||
layout = self.layout
|
||||
|
||||
self.draw_brush_settings(layout, context)
|
||||
layout.separator()
|
||||
|
||||
if context.scene.easyweight_minimal:
|
||||
self.draw_minimal(layout, context)
|
||||
return
|
||||
|
||||
self.draw_weight_paint_settings(layout, context)
|
||||
layout.separator()
|
||||
self.draw_overlay_settings(layout, context)
|
||||
layout.separator()
|
||||
self.draw_operators(layout, context)
|
||||
|
||||
def invoke(self, context, event):
|
||||
active_brush = context.tool_settings.weight_paint.brush
|
||||
self.front_faces = active_brush.use_frontface
|
||||
self.falloff_shape = active_brush.falloff_shape
|
||||
if 'clean_weights' not in context.scene:
|
||||
context.scene['clean_weights'] = False
|
||||
self.clean_weights = context.scene['clean_weights']
|
||||
|
||||
wm = context.window_manager
|
||||
return wm.invoke_props_dialog(self)
|
||||
|
||||
def execute(self, context):
|
||||
context.scene.tool_settings.vertex_group_user = 'ACTIVE'
|
||||
return {'FINISHED'}
|
||||
|
||||
|
||||
class WeightCleaner:
|
||||
"""Run bpy.ops.object.vertex_group_clean on every depsgraph update while in weight paint mode (ie. every brush stroke)."""
|
||||
# Most of the code is simply responsible for avoiding infinite looping depsgraph updates.
|
||||
# Flag set by the user via the custom WP context menu.
|
||||
cleaner_active = False
|
||||
|
||||
# Flag set in post_depsgraph_update, to indicate to pre_depsgraph_update that the depsgraph update has indeed completed.
|
||||
can_clean = True
|
||||
# Flag set by pre_depsgraph_update to indicate to post_depsgraph_update that the cleanup operator is still running (in a different thread).
|
||||
cleaning_in_progress = False
|
||||
|
||||
@classmethod
|
||||
def clean_weights(cls, scene, depsgraph):
|
||||
if bpy.context.mode != 'PAINT_WEIGHT':
|
||||
return
|
||||
if not bpy.context or not hasattr(bpy.context, 'object') or not bpy.context.object:
|
||||
return
|
||||
if not cls.cleaner_active:
|
||||
return
|
||||
if cls.can_clean:
|
||||
cls.can_clean = False
|
||||
cls.cleaning_in_progress = True
|
||||
# This will trigger a depsgraph update, and therefore clean_weights, again.
|
||||
bpy.ops.object.vertex_group_clean(
|
||||
group_select_mode='ALL', limit=0.001)
|
||||
cls.cleaning_in_progress = False
|
||||
|
||||
@classmethod
|
||||
def reset_flag(cls, scene, depsgraph):
|
||||
if bpy.context.mode != 'PAINT_WEIGHT':
|
||||
return
|
||||
if not bpy.context or not hasattr(bpy.context, 'object') or not bpy.context.object:
|
||||
return
|
||||
if cls.cleaning_in_progress:
|
||||
return
|
||||
if not cls.cleaner_active:
|
||||
return
|
||||
cls.can_clean = True
|
||||
|
||||
|
||||
def draw_menu_entry(self, context):
|
||||
self.layout.operator(EASYWEIGHT_OT_wp_context_menu.bl_idname)
|
||||
|
||||
|
||||
@persistent
|
||||
def start_cleaner(scene, depsgraph):
|
||||
bpy.app.handlers.depsgraph_update_pre.append(WeightCleaner.clean_weights)
|
||||
bpy.app.handlers.depsgraph_update_post.append(WeightCleaner.reset_flag)
|
||||
|
||||
registry = [
|
||||
EASYWEIGHT_OT_wp_context_menu
|
||||
]
|
||||
|
||||
|
||||
def register():
|
||||
bpy.types.Scene.easyweight_minimal = BoolProperty(
|
||||
name="Minimal",
|
||||
description="Hide options that are less frequently used",
|
||||
default=False
|
||||
)
|
||||
start_cleaner(None, None)
|
||||
bpy.app.handlers.load_post.append(start_cleaner)
|
||||
|
||||
bpy.types.VIEW3D_MT_paint_weight.append(draw_menu_entry)
|
||||
|
||||
def unregister():
|
||||
del bpy.types.Scene.easyweight_minimal
|
||||
bpy.app.handlers.load_post.remove(start_cleaner)
|
||||
|
||||
bpy.types.VIEW3D_MT_paint_weight.remove(draw_menu_entry)
|
Loading…
Reference in New Issue
Block a user