новая структура проекта

This commit is contained in:
2026-04-20 21:04:25 +04:00
parent 1fe2a72ef1
commit 1a56b22e38
1932 changed files with 1886 additions and 22779 deletions
+7
View File
@@ -0,0 +1,7 @@
Reference-only sources and tools.
This directory contains external projects used to compare WoW file-format behavior and editor pipelines while implementing OpenWC. Runtime code should not depend on anything in this directory.
- `blender-wow-studio-3.4-1.1.0_Experimental/` - Blender add-on sources for M2/WMO import/export reference.
- `wow.export/` - wow.export source tree and Blender OBJ importer reference.
- `noggit-red/` - Noggit RED source tree from `https://gitlab.com/dirtbikercj/noggit-red`, used as a reference for WoW 3.3.5 map editing, ADT/WMO/M2 placement behavior, UID handling and editor workflows.
@@ -0,0 +1,14 @@
*.pyc
io_scene_wmo/.idea/
io_scene_wmo/third_party/
.idea/
.vscode/
io_scene_wmo/bpy_boost/
io_scene_wmo/wbs_kernel/build/
io_scene_wmo/wbs_kernel/src/wbs_kernel.cpp
build/
*.pyd
/io_scene_wmo/.vscode/settings.json
/io_scene_wmo/wbs_kernel/src/render.cpp
/io_scene_wmo/wbs_kernel/src/wmo_utils.cpp
@@ -0,0 +1,35 @@
stages:
- build
windows:
stage: build
only:
- schedules
variables:
GIT_SUBMODULE_STRATEGY: recursive
tags:
- shared-windows
- windows
- windows-1809
before_script:
- choco install python --version=3.10.2 -y -f
- choco install cmake --installargs 'ADD_CMAKE_TO_PATH=System' -y -f
- $env:Path += ';C:\Program Files\CMake\bin'
script:
- C:\Python310\python.exe -m pip install --upgrade pip
- C:\Python310\python.exe -m pip install Cython
- C:\Python310\python.exe -m pip install numpy
- mkdir C:\\GitLab-Runner\\builds\\skarnproject\\blender-wow-studio\\dist
- C:\Python310\python.exe io_scene_wmo/build.py --dist=C:\\GitLab-Runner\\builds\\skarnproject\\blender-wow-studio\\dist
artifacts:
name: "$CI_JOB_NAME-$CI_COMMIT_REF_NAME"
paths:
- C:\\GitLab-Runner\\builds\\skarnproject\\blender-wow-studio\\dist
@@ -0,0 +1,7 @@
[submodule "io_scene_wmo/pywowlib"]
path = io_scene_wmo/pywowlib
url = https://github.com/wowdev/pywowlib.git
[submodule "io_scene_wmo/wbs_kernel/src/bl_src"]
path = io_scene_wmo/wbs_kernel/src/bl_src
url = https://github.com/blender/blender
branch = blender-v3.1-release
@@ -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.
WoW Blender Studio
Copyright (C) 2022 Skarn
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) 2022 Skarn
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>.
@@ -0,0 +1,6 @@
- Supported Blender version : 3.4
- Supported WoW versions : 3.3.5 and 7.3(not stable)
- M2 exporting doesn't work for animated models and is also unstable for static models. (Beta build for animated M2 available in discord)
- The addon needs to be built by running build.py with a python version matching blender's, or grab a pre compiled build at https://gitlab.com/skarnproject/blender-wow-studio/-/jobs
- To enable the addon, search "WoW" in the addons list, fill the WoW Client path, WMV log path (select log.txt), cache and project paths (use empty folders)
- Discord : https://discord.gg/SBEDRXrSnd
@@ -0,0 +1,21 @@
wbs_kernel/build
wbs_kernel/cmake-build-debug
wbs_kernel/cmake-build-release
wbs_kernel/src/cmake-build-debug
wbs_kernel/src/cmake-build-release
wbs_kernel/.idea
.vscode/
build/
venv/
__pycache__/
*.so
*.pyd
*.lib
*.a
*.dylib
*.dll
*.pdb
wbs_kernel/CMakeLists.txt
wbs_kernel/wmo_utils.cpp
wbs_kernel/render.cpp
@@ -0,0 +1,93 @@
# ##### BEGIN GPL LICENSE BLOCK #####
#
# 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 2
# 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, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
# <pep8-80 compliant>
bl_info = {
"name": "WoW Blender Studio",
"author": "Skarn",
"version": (1, 1, 0),
"blender": (3, 4, 0),
"description": "Import-Export WoW M2-WMO",
"category": "Import-Export"
}
import os
import sys
import traceback
import bpy
import bpy.utils.previews
from bpy.props import StringProperty
from . import auto_load
PACKAGE_NAME = __package__
# include custom lib vendoring dir
parent_dir = os.path.abspath(os.path.dirname(__file__))
vendor_dir = os.path.join(parent_dir, 'third_party')
sys.path.append(vendor_dir)
# load custom icons
ui_icons = {}
pcoll = None
def register():
global pcoll
global ui_icons
pcoll = bpy.utils.previews.new()
icons_dir = os.path.join(os.path.dirname(__file__), "icons")
for file in os.listdir(icons_dir):
pcoll.load(os.path.splitext(file)[0].upper(), os.path.join(icons_dir, file), 'IMAGE')
for name, icon_file in pcoll.items():
ui_icons[name] = icon_file.icon_id
auto_load.init()
try:
auto_load.register()
print("Registered WoW Blender Studio")
except:
traceback.print_exc()
def unregister():
try:
auto_load.unregister()
print("Unregistered WoW Blender Studio")
except:
traceback.print_exc()
global pcoll
bpy.utils.previews.remove(pcoll)
global ui_icons
ui_icons = {}
if __name__ == "__main__":
register()
@@ -0,0 +1,108 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
# addon updater temp folder
common/updater_tmp/*
!common/updater_tmp/.gitignore
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
@@ -0,0 +1,11 @@
# addon_common
This repo contains the CookieCutter Blender add-on framework.
## Example Add-on
As an example add-on, see the [ExtruCut](https://github.com/CGCookie/ExtruCut) project.
## resources
- Blender Conference 2018 workshop [slides](https://gfx.cse.taylor.edu/courses/bcon18/index.md.html?scale) and [presentation](https://www.youtube.com/watch?v=YSHdSNhMO1c)
@@ -0,0 +1,51 @@
'''
Copyright (C) 2020 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson, Patrick Moore
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/>.
'''
__all__ = [
'bezier',
'blender',
'bmesh_render',
'bmesh_utils',
'debug',
'decorators',
'drawing',
'fontmanager',
'globals',
'hasher',
'irc',
'logger',
'maths',
'metaclasses',
'parse',
'profiler',
'shaders',
'ui',
'useractions',
'utils',
'xmesh',
]
# import the following only to populate the globals
from . import debug as _
from . import drawing as _
from . import logger as _
from . import profiler as _
from . import ui_core as _
@@ -0,0 +1,636 @@
'''
Copyright (C) 2020 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson
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/>.
'''
import math
from mathutils import Vector, Matrix
from .blender import matrix_vector_mult
from .maths import Point, Vec
from .utils import iter_running_sum
def compute_quadratic_weights(t):
t0, t1 = t, (1-t)
return (t1**2, 2*t0*t1, t0**2)
def compute_cubic_weights(t):
t0, t1 = t, (1-t)
return (t1**3, 3*t0*t1**2, 3*t0**2*t1, t0**3)
def interpolate_cubic(v0, v1, v2, v3, t):
b0, b1, b2, b3 = compute_cubic_weights(t)
return v0*b0 + v1*b1 + v2*b2 + v3*b3
def compute_cubic_error(v0, v1, v2, v3, l_v, l_t):
return math.sqrt(sum(
(interpolate_cubic(v0, v1, v2, v3, t) - v)**2
for v, t in zip(l_v, l_t)
))
def fit_cubicbezier(l_v, l_t):
#########################################################
# http://nbviewer.ipython.org/gist/anonymous/5688579
# make the summation functions for A (16 of them)
A_fns = [
lambda l_t: sum([2*t**0*(t-1)**6 for t in l_t]),
lambda l_t: sum([-6*t**1*(t-1)**5 for t in l_t]),
lambda l_t: sum([6*t**2*(t-1)**4 for t in l_t]),
lambda l_t: sum([-2*t**3*(t-1)**3 for t in l_t]),
lambda l_t: sum([-6*t**1*(t-1)**5 for t in l_t]),
lambda l_t: sum([18*t**2*(t-1)**4 for t in l_t]),
lambda l_t: sum([-18*t**3*(t-1)**3 for t in l_t]),
lambda l_t: sum([6*t**4*(t-1)**2 for t in l_t]),
lambda l_t: sum([6*t**2*(t-1)**4 for t in l_t]),
lambda l_t: sum([-18*t**3*(t-1)**3 for t in l_t]),
lambda l_t: sum([18*t**4*(t-1)**2 for t in l_t]),
lambda l_t: sum([-6*t**5*(t-1)**1 for t in l_t]),
lambda l_t: sum([-2*t**3*(t-1)**3 for t in l_t]),
lambda l_t: sum([6*t**4*(t-1)**2 for t in l_t]),
lambda l_t: sum([-6*t**5*(t-1)**1 for t in l_t]),
lambda l_t: sum([2*t**6*(t-1)**0 for t in l_t])
]
# make the summation functions for b (4 of them)
b_fns = [
lambda l_t, l_v: sum(v * (-2 * (t**0) * ((t-1)**3))
for t, v in zip(l_t, l_v)),
lambda l_t, l_v: sum(v * (6 * (t**1) * ((t-1)**2))
for t, v in zip(l_t, l_v)),
lambda l_t, l_v: sum(v * (-6 * (t**2) * ((t-1)**1))
for t, v in zip(l_t, l_v)),
lambda l_t, l_v: sum(v * (2 * (t**3) * ((t-1)**0))
for t, v in zip(l_t, l_v)),
]
# compute the data we will put into matrix A
A_values = [fn(l_t) for fn in A_fns]
# fill the A matrix with data
A_matrix = Matrix(tuple(zip(*[iter(A_values)]*4)))
try:
A_inv = A_matrix.inverted()
except:
return (float('inf'), l_v[0], l_v[0], l_v[0], l_v[0])
# compute the data we will put into the b vector
b_values = [fn(l_t, l_v) for fn in b_fns]
# fill the b vector with data
b_vector = Vector(b_values)
# solve for the unknowns in vector x
v0, v1, v2, v3 = matrix_vector_mult(A_inv, b_vector)
err = compute_cubic_error(v0, v1, v2, v3, l_v, l_t) / len(l_v)
return (err, v0, v1, v2, v3)
def fit_cubicbezier_spline(
l_co, error_scale, depth=0,
t0=0, t3=-1, allow_split=True, force_split=False
):
'''
fits cubic bezier to given points
returns list of tuples of (t0,t3,p0,p1,p2,p3)
that best fits the given points l_co
where t0 and t3 are the passed-in t0 and t3
and p0,p1,p2,p3 are the control points of bezier
'''
count = len(l_co)
if t3 == -1:
t3 = count-1
# spc = ' ' * depth
# print(spc + 'count = %d' % count)
if count == 0:
assert False
if count == 1:
assert False
if count == 2:
p0, p3 = l_co[0], l_co[-1]
diff = p3-p0
return [(t0, t3, p0, p0+diff*0.33, p0+diff*0.66, p3)]
if count == 3:
new_co = [l_co[0], (l_co[0]+l_co[1])/2, l_co[1],
(l_co[1]+l_co[2])/2, l_co[2]]
return fit_cubicbezier_spline(
new_co, error_scale,
depth=depth,
t0=t0, t3=t3,
allow_split=allow_split, force_split=force_split
)
l_d = [0] + [(v0-v1).length for v0, v1 in zip(l_co[:-1], l_co[1:])]
l_ad = [s for d, s in iter_running_sum(l_d)]
dist = sum(l_d)
if dist <= 0:
# print(spc + 'fit_cubicbezier_spline: returning []')
return [] # [(t0,t3,l_co[0],l_co[0],l_co[0],l_co[0])]
l_t = [ad/dist for ad in l_ad]
ex, x0, x1, x2, x3 = fit_cubicbezier([co[0] for co in l_co], l_t)
ey, y0, y1, y2, y3 = fit_cubicbezier([co[1] for co in l_co], l_t)
ez, z0, z1, z2, z3 = fit_cubicbezier([co[2] for co in l_co], l_t)
tot_error = ex+ey+ez
# print(spc + 'total error = %f (%f)' % (tot_error,error_scale)) #, l=4)
if not force_split:
do_not_split = tot_error < error_scale
do_not_split |= depth == 4
do_not_split |= len(l_co) <= 15
do_not_split |= not allow_split
if do_not_split:
p0, p1 = Point((x0, y0, z0)), Point((x1, y1, z1))
p2, p3 = Point((x2, y2, z2)), Point((x3, y3, z3))
return [(t0, t3, p0, p1, p2, p3)]
# too much error in fit. split sequence in two, and fit each sub-sequence
# find a good split point
ind_split = -1
mindot = 1.0
for ind in range(5, len(l_co)-5):
if l_t[ind] < 0.4:
continue
if l_t[ind] > 0.6:
break
# if l_ad[ind] < 0.1: continue
# if l_ad[ind] > dist-0.1: break
v0 = l_co[ind-4]
v1 = l_co[ind+0]
v2 = l_co[ind+4]
d0 = (v1-v0).normalized()
d1 = (v2-v1).normalized()
dot01 = d0.dot(d1)
if ind_split == -1 or dot01 < mindot:
ind_split = ind
mindot = dot01
if ind_split == -1:
# did not find a good splitting point!
p0, p1, p2, p3 = Point((x0, y0, z0)), Point(
(x1, y1, z1)), Point((x2, y2, z2)), Point((x3, y3, z3))
#p0,p3 = Point(l_co[0]),Point(l_co[-1])
return [(t0, t3, p0, p1, p2, p3)]
#print(spc + 'splitting at %d' % ind_split)
l_co0, l_co1 = l_co[:ind_split+1], l_co[ind_split:] # share split point
tsplit = ind_split # / (len(l_co)-1)
bezier0 = fit_cubicbezier_spline(
l_co0, error_scale, depth=depth+1, t0=t0, t3=tsplit)
bezier1 = fit_cubicbezier_spline(
l_co1, error_scale, depth=depth+1, t0=tsplit, t3=t3)
return bezier0 + bezier1
class CubicBezier:
split_default = 100
segments_default = 100
@staticmethod
def create_from_points(pts_list):
'''
Estimates best spline to fit given points
'''
count = len(pts_list)
if count == 0:
assert False
if count == 1:
assert False
if count == 2:
p0, p3 = pts_list
diff = p3-p0
p1, p2 = p0+diff*0.33, p0+diff*0.66
return CubicBezier(p0, p1, p2, p3)
if count == 3:
p0, p03, p3 = pts_list
d003, d303 = (p03-p0), (p03-p3)
p1, p2 = p0+d003*0.5, p3+d303*0.5
return CubicBezier(p0, p1, p2, p3)
l_d = [0] + [(p0-p1).length for p0,
p1 in zip(pts_list[:-1], pts_list[1:])]
l_ad = [s for d, s in iter_running_sum(l_d)]
dist = sum(l_d)
if dist <= 0:
p0 = pts_list[0]
return CubicBezier(p0, p0, p0, p0)
l_t = [ad/dist for ad in l_ad]
ex, x0, x1, x2, x3 = fit_cubicbezier([pt[0] for pt in pts_list], l_t)
ey, y0, y1, y2, y3 = fit_cubicbezier([pt[1] for pt in pts_list], l_t)
ez, z0, z1, z2, z3 = fit_cubicbezier([pt[2] for pt in pts_list], l_t)
p0 = Point((x0, y0, z0))
p1 = Point((x1, y1, z1))
p2 = Point((x2, y2, z2))
p3 = Point((x3, y3, z3))
return CubicBezier(p0, p1, p2, p3)
def __init__(self, p0, p1, p2, p3):
self.p0, self.p1, self.p2, self.p3 = p0, p1, p2, p3
self.tessellation = []
def __iter__(self): return iter([self.p0, self.p1, self.p2, self.p3])
def points(self): return (self.p0, self.p1, self.p2, self.p3)
def copy(self):
''' shallow copy '''
return CubicBezier(self.p0, self.p1, self.p2, self.p3)
def eval(self, t):
p0, p1, p2, p3 = self.p0, self.p1, self.p2, self.p3
b0, b1, b2, b3 = compute_cubic_weights(t)
return Point.weighted_average([
(b0, p0), (b1, p1), (b2, p2), (b3, p3)
])
def eval_derivative(self, t):
p0, p1, p2, p3 = self.p0, self.p1, self.p2, self.p3
q0, q1, q2 = 3*(p1-p0), 3*(p2-p1), 3*(p3-p2)
b0, b1, b2 = compute_quadratic_weights(t)
return q0*b0 + q1*b1 + q2*b2
def subdivide(self, iters=1):
if iters == 0:
return [self]
# de casteljau subdivide
p0, p1, p2, p3 = self.p0, self.p1, self.p2, self.p3
q0, q1, q2 = (p0+p1)/2, (p1+p2)/2, (p2+p3)/2
r0, r1 = (q0+q1)/2, (q1+q2)/2
s = (r0+r1)/2
cb0, cb1 = CubicBezier(p0, q0, r0, s), CubicBezier(s, r1, q2, p3)
if iters == 1:
return [cb0, cb1]
return cb0.subdivide(iters=iters-1) + cb1.subdivide(iters=iters-1)
def compute_linearity(self, fn_dist):
'''
Estimating measure of linearity as ratio of distances
of curve mid-point and mid-point of end control points
over half the distance between end control points
p1 _
/
|
p0 * * p3
_/
p2
'''
p0, p1, p2, p3 = Vector(self.p0), Vector(
self.p1), Vector(self.p2), Vector(self.p3)
q0, q1, q2 = (p0+p1)/2, (p1+p2)/2, (p2+p3)/2
r0, r1 = (q0+q1)/2, (q1+q2)/2
s = (r0+r1)/2
m = (p0+p3)/2
d03 = fn_dist(p0, p3)
dsm = fn_dist(s, m)
return 2 * dsm / d03
def subdivide_linesegments(self, fn_dist, max_linearity=None):
if self.compute_linearity(fn_dist) < (max_linearity or 0.1):
return [self]
# de casteljau subdivide:
p0, p1, p2, p3 = Vector(self.p0), Vector(
self.p1), Vector(self.p2), Vector(self.p3)
q0, q1, q2 = (p0+p1)/2, (p1+p2)/2, (p2+p3)/2
r0, r1 = (q0+q1)/2, (q1+q2)/2
s = (r0+r1)/2
cbs = CubicBezier(p0, q0, r0, s), CubicBezier(s, r1, q2, p3)
segs0, segs1 = [cb.subdivide_linesegments(
fn_dist, max_linearity=max_linearity) for cb in cbs]
return segs0 + segs1
def length(self, fn_dist, max_linearity=None):
l = self.subdivide_linesegments(fn_dist, max_linearity=max_linearity)
return sum(fn_dist(cb.p0, cb.p3) for cb in l)
def approximate_length_uniform(self, fn_dist, split=None):
split = split or self.split_default
p = self.p0
d = 0
for i in range(split):
q = self.eval((i+1) / split)
d += fn_dist(p, q)
p = q
return d
def approximate_t_at_interval_uniform(self, interval, fn_dist, split=None):
split = split or self.split_default
p = self.p0
d = 0
for i in range(split):
percent = (i+1) / split
q = self.eval(percent)
d += fn_dist(p, q)
if interval <= d:
return percent
p = q
return 1
def approximate_ts_at_intervals_uniform(
self, intervals, fn_dist, split=None
):
a = self.approximate_t_at_interval_uniform
def approx(i): return a(i, fn_dist, split=None)
return [approx(interval) for interval in intervals]
def get_tessellate_uniform(self, fn_dist, split=None):
split = split or self.split_default
ts = [i/(split-1) for i in range(split)]
ps = [self.eval(t) for t in ts]
ds = [0] + [fn_dist(p, q) for p, q in zip(ps[:-1], ps[1:])]
return [(t, p, d) for t, p, d in zip(ts, ps, ds)]
def tessellate_uniform_points(self, segments=None):
segments = segments or self.segments_default
ts = [i/(segments-1) for i in range(segments)]
ps = [self.eval(t) for t in ts]
return ps
#########################################
# #
# the following code **requires** that #
# self.tessellate_uniform() is called #
# beforehand! #
# #
#########################################
def tessellate_uniform(self, fn_dist, split=None):
self.tessellation = self.get_tessellate_uniform(fn_dist, split=split)
def approximate_t_at_point_tessellation(self, point, fn_dist):
bd, bt = None, None
for t, q, _ in self.tessellation:
d = fn_dist(point, q)
if bd is None or d < bd:
bd, bt = d, t
return bt
def approximate_totlength_tessellation(self):
return sum(self.approximate_lengths_tessellation())
def approximate_lengths_tessellation(self):
return [d for _, _, d in self.tessellation]
class CubicBezierSpline:
@staticmethod
def create_from_points(pts_list, max_error):
'''
Estimates best spline to fit given points
'''
cbs = []
inds = []
for pts in pts_list:
cbs_pts = fit_cubicbezier_spline(pts, max_error)
cbs += [CubicBezier(p0, p1, p2, p3)
for _, _, p0, p1, p2, p3 in cbs_pts]
inds += [(ind0, ind1) for ind0, ind1, _, _, _, _ in cbs_pts]
return CubicBezierSpline(cbs=cbs, inds=inds)
def __init__(self, cbs=None, inds=None):
if cbs is None:
cbs = []
if inds is None:
inds = []
if type(cbs) is CubicBezierSpline:
cbs = [cb.copy() for cb in cbs.cbs]
assert type(cbs) is list, "expected list"
self.cbs = cbs
self.inds = inds
self.tessellation = []
def copy(self):
return CubicBezierSpline(
cbs=[cb.copy() for cb in self.cbs],
inds=list(self.inds)
)
def __add__(self, other):
t = type(other)
if t is CubicBezierSpline:
return CubicBezierSpline(
self.cbs + other.cbs,
self.inds + other.inds
)
if t is CubicBezier:
return CubicBezierSpline(self.cbs + [other])
if t is list:
return CubicBezierSpline(self.cbs + other)
assert False, "unhandled type: %s (%s)" % (str(other), str(t))
def __iadd__(self, other):
t = type(other)
if t is CubicBezierSpline:
self.cbs += other.cbs
self.inds += other.inds
elif t is CubicBezier:
self.cbs += [other]
self.inds = []
elif t is list:
self.cbs += other
self.inds = []
else:
assert False, "unhandled type: %s (%s)" % (str(other), str(t))
def __len__(self): return len(self.cbs)
def __iter__(self): return self.cbs.__iter__()
def __getitem__(self, idx): return self.cbs[idx]
def eval(self, t):
if t < 0.0:
t = 0
idx = 0
elif t >= len(self):
t = 1
idx = len(self)-1
else:
idx = int(t)
t = t - idx
return self.cbs[idx].eval(t)
def eval_derivative(self, t):
if t < 0.0:
t = 0
idx = 0
elif t >= len(self):
t = 1
idx = len(self)-1
else:
idx = int(t)
t = t - idx
return self.cbs[idx].eval_derivative(t)
def approximate_totlength_uniform(self, fn_dist, split=None):
return sum(self.approximate_lengths_uniform(fn_dist, split=split))
def approximate_lengths_uniform(self, fn_dist, split=None):
return [
cb.approximate_length_uniform(fn_dist, split=split)
for cb in self.cbs
]
def approximate_ts_at_intervals_uniform(
self, intervals, fn_dist, split=None
):
lengths = self.approximate_lengths_uniform(fn_dist, split=split)
totlength = sum(lengths)
ts = []
for interval in intervals:
if interval < 0:
ts.append(0)
continue
if interval >= totlength:
ts.append(len(self.cbs))
continue
for i, length in enumerate(lengths):
if interval <= length:
t = self.cbs[i].approximate_t_at_interval_uniform(
interval, fn_dist, split=split)
ts.append(i + t)
break
interval -= length
else:
assert False
return ts
def subdivide_linesegments(self, fn_dist, max_linearity=None):
return CubicBezierSpline(cbi
for cb in self.cbs
for cbi in cb.subdivide_linesegments(
fn_dist,
max_linearity=max_linearity
))
#########################################
# #
# the following code **requires** that #
# self.tessellate_uniform() is called #
# beforehand! #
# #
#########################################
def tessellate_uniform(self, fn_dist, split=None):
self.tessellation.clear()
for i, cb in enumerate(self.cbs):
cb_tess = cb.get_tessellate_uniform(fn_dist, split=split)
self.tessellation.append(cb_tess)
def approximate_totlength_tessellation(self):
return sum(self.approximate_lengths_tessellation())
def approximate_lengths_tessellation(self):
return [sum(d for _, _, d in cb_tess) for cb_tess in self.tessellation]
def approximate_ts_at_intervals_tessellation(self, intervals):
lengths = self.approximate_lengths_tessellation()
totlength = sum(lengths)
ts = []
for interval in intervals:
if interval < 0:
ts.append(0)
continue
if interval >= totlength:
ts.append(len(self.cbs))
continue
for i, length in enumerate(lengths):
if interval > length:
interval -= length
continue
cb_tess = self.tessellation[i]
for t, p, d in cb_tess:
if interval > d:
interval -= d
continue
ts.append(i+t)
break
else:
assert False
break
else:
assert False
return ts
def approximate_ts_at_points_tessellation(self, points, fn_dist):
ts = []
for p in points:
bd, bt = None, None
for i, cb_tess in enumerate(self.tessellation):
for t, q, _ in cb_tess:
d = fn_dist(p, q)
if bd is None or d < bd:
bd, bt = d, i+t
ts.append(bt)
return ts
def approximate_t_at_point_tessellation(self, point, fn_dist):
bd, bt = None, None
for i, cb_tess in enumerate(self.tessellation):
for t, q, _ in cb_tess:
d = fn_dist(point, q)
if bd is None or d < bd:
bd, bt = d, i+t
return bt
class GenVector(list):
'''
Generalized Vector, allows for some simple ordered items to be linearly combined
which is useful for interpolating arbitrary points of Bezier Spline.
'''
def __mul__(self, scalar: float): # ->GVector:
for idx in range(len(self)):
self[idx] *= scalar
return self
def __rmul__(self, scalar: float): # ->GVector:
return self.__mul__(scalar)
def __add__(self, other: list): # ->GVector:
for idx in range(len(self)):
self[idx] += other[idx]
return self
if __name__ == '__main__':
# run tests
print('-'*50)
l = GenVector([Vector((1, 2, 3)), 23])
print(l)
print(l * 2)
print(4 * l)
l2 = GenVector([Vector((0, 0, 1)), 10])
print(l + l2)
print(2 * l + l2 * 4)
@@ -0,0 +1,332 @@
'''
Copyright (C) 2020 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson
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/>.
'''
import bpy
from .decorators import blender_version_wrapper
@blender_version_wrapper("<=", "2.79")
def get_preferences(ctx=None):
return (ctx if ctx else bpy.context).user_preferences
@blender_version_wrapper(">=", "2.80")
def get_preferences(ctx=None):
return (ctx if ctx else bpy.context).preferences
#############################################################
class ModifierWrapper_Mirror:
'''
normalize the mirror modifier API across 2.79 and 2.80
'''
@staticmethod
def create_new(obj):
bpy.ops.object.modifier_add(type='MIRROR')
mod = ModifierWrapper_Mirror(obj, obj.modifiers[-1])
mod.set_defaults()
return mod
@staticmethod
def get_from_object(obj):
for mod in obj.modifiers:
if mod.type != 'MIRROR': continue
return ModifierWrapper_Mirror(obj, mod)
return None
def __init__(self, obj, modifier):
self._reading = True
self.obj = obj
self.mod = modifier
self.read()
@property
def x(self):
return 'x' in self._symmetry
@x.setter
def x(self, v):
if v: self._symmetry.add('x')
else: self._symmetry.discard('x')
self.write()
@property
def y(self):
return 'y' in self._symmetry
@y.setter
def y(self, v):
if v: self._symmetry.add('y')
else: self._symmetry.discard('y')
self.write()
@property
def z(self):
return 'z' in self._symmetry
@z.setter
def z(self, v):
if v: self._symmetry.add('z')
else: self._symmetry.discard('z')
self.write()
@property
def xyz(self):
return set(self._symmetry)
@property
def symmetry_threshold(self):
return self._symmetry_threshold
@symmetry_threshold.setter
def symmetry_threshold(self, v):
self._symmetry_threshold = max(0, float(v))
self.write()
def enable_axis(self, axis):
self._symmetry.add(axis)
self.write()
def disable_axis(self, axis):
self._symmetry.discard(axis)
self.write()
def disable_all(self):
self._symmetry.clear()
self.write()
def is_enabled_axis(self, axis):
return axis in self._symmetry
def set_defaults(self):
self.mod.merge_threshold = 0.001
self.mod.show_expanded = False
self.mod.show_on_cage = True
self.mod.use_mirror_merge = True
self.mod.show_viewport = True
self.disable_all()
@blender_version_wrapper('<', '2.80')
def read(self):
self._reading = True
self._symmetry = set()
if self.mod.use_x: self._symmetry.add('x')
if self.mod.use_y: self._symmetry.add('y')
if self.mod.use_z: self._symmetry.add('z')
self._symmetry_threshold = self.mod.merge_threshold
self.show_viewport = self.mod.show_viewport
self._reading = False
@blender_version_wrapper('>=', '2.80')
def read(self):
self._reading = True
self._symmetry = set()
if self.mod.use_axis[0]: self._symmetry.add('x')
if self.mod.use_axis[1]: self._symmetry.add('y')
if self.mod.use_axis[2]: self._symmetry.add('z')
self._symmetry_threshold = self.mod.merge_threshold
self.show_viewport = self.mod.show_viewport
self._reading = False
@blender_version_wrapper('<', '2.80')
def write(self):
if self._reading: return
self.mod.use_x = self.x
self.mod.use_y = self.y
self.mod.use_z = self.z
self.mod.merge_threshold = self._symmetry_threshold
self.mod.show_viewport = self.show_viewport
@blender_version_wrapper('>=', '2.80')
def write(self):
if self._reading: return
self.mod.use_axis[0] = self.x
self.mod.use_axis[1] = self.y
self.mod.use_axis[2] = self.z
self.mod.merge_threshold = self._symmetry_threshold
self.mod.show_viewport = self.show_viewport
#############################################################
@blender_version_wrapper('<', '2.80')
def matrix_vector_mult(mat, vec): return mat * vec
@blender_version_wrapper('>=', '2.80')
def matrix_vector_mult(mat, vec): return mat @ vec
@blender_version_wrapper('<', '2.80')
def quat_vector_mult(quat, vec): return quat * vec
@blender_version_wrapper('>=', '2.80')
def quat_vector_mult(quat, vec): return quat @ vec
#############################################################
# TODO: generalize these functions to be add_object, etc.
@blender_version_wrapper('<=','2.79')
def set_object_layers(o): o.layers = list(bpy.context.scene.layers)
@blender_version_wrapper('>=','2.80')
def set_object_layers(o): print('unhandled: set_object_layers')
@blender_version_wrapper('<=','2.79')
def set_object_selection(o, sel): o.select = sel
@blender_version_wrapper('>=','2.80')
def set_object_selection(o, sel): o.select_set(sel)
@blender_version_wrapper('<=','2.79')
def link_object(o): bpy.context.scene.objects.link(o)
@blender_version_wrapper('>=','2.80')
def link_object(o): bpy.context.scene.collection.objects.link(o)
@blender_version_wrapper('<=','2.79')
def set_active_object(o): bpy.context.scene.objects.active = o
@blender_version_wrapper('>=','2.80')
def set_active_object(o): bpy.context.window.view_layer.objects.active = o
# use this, because bpy.context might not Screen context!
# see https://docs.blender.org/api/current/bpy.context.html
def get_active_object(): return bpy.context.view_layer.objects.active
@blender_version_wrapper('<=', '2.79')
def toggle_screen_header(ctx): bpy.ops.screen.header(ctx)
@blender_version_wrapper('>=', '2.80')
def toggle_screen_header(ctx):
space = ctx['space_data'] if type(ctx) is dict else ctx.space_data
space.show_region_header = not space.show_region_header
@blender_version_wrapper('<=', '2.79')
def toggle_screen_toolbar(ctx):
bpy.ops.view3d.toolshelf(ctx)
@blender_version_wrapper('>=', '2.80')
def toggle_screen_toolbar(ctx):
space = ctx['space_data'] if type(ctx) is dict else ctx.space_data
space.show_region_toolbar = not space.show_region_toolbar
@blender_version_wrapper('<=', '2.79')
def toggle_screen_properties(ctx):
bpy.ops.view3d.properties(ctx)
@blender_version_wrapper('>=', '2.80')
def toggle_screen_properties(ctx):
space = ctx['space_data'] if type(ctx) is dict else ctx.space_data
space.show_region_ui = not space.show_region_ui
@blender_version_wrapper('<=', '2.79')
def toggle_screen_lastop(ctx):
# Blender 2.79 does not have a last operation region
pass
@blender_version_wrapper('>=', '2.80')
def toggle_screen_lastop(ctx):
space = ctx['space_data'] if type(ctx) is dict else ctx.space_data
space.show_region_hud = not space.show_region_hud
tagged_redraw_all = False
tag_reasons = set()
def tag_redraw_all(reason, only_tag=True):
global tagged_redraw_all, tag_reasons
tagged_redraw_all = True
tag_reasons.add(reason)
if not only_tag: perform_redraw_all()
def perform_redraw_all():
global tagged_redraw_all, tag_reasons
if not tagged_redraw_all: return
# print('Redrawing:', tag_reasons)
tag_reasons.clear()
tagged_redraw_all = False
for wm in bpy.data.window_managers:
for win in wm.windows:
for ar in win.screen.areas:
ar.tag_redraw()
def show_blender_popup(message, title="Message", icon="INFO", wrap=80):
'''
icons: NONE, QUESTION, ERROR, CANCEL,
TRIA_RIGHT, TRIA_DOWN, TRIA_LEFT, TRIA_UP,
ARROW_LEFTRIGHT, PLUS,
DISCLOSURE_TRI_DOWN, DISCLOSURE_TRI_RIGHT,
RADIOBUT_OFF, RADIOBUT_ON,
MENU_PANEL, BLENDER, GRIP, DOT, COLLAPSEMENU, X,
GO_LEFT, PLUG, UI, NODE, NODE_SEL,
FULLSCREEN, SPLITSCREEN, RIGHTARROW_THIN, BORDERMOVE,
VIEWZOOM, ZOOMIN, ZOOMOUT, ...
see: https://git.blender.org/gitweb/gitweb.cgi/blender.git/blob/HEAD:/source/blender/editors/include/UI_icons.h
''' # noqa
if not message: return
lines = message.splitlines()
if wrap > 0:
nlines = []
for line in lines:
spc = len(line) - len(line.lstrip())
while len(line) > wrap:
i = line.rfind(' ',0,wrap)
if i == -1:
nlines += [line[:wrap]]
line = line[wrap:]
else:
nlines += [line[:i]]
line = line[i+1:]
if line:
line = ' '*spc + line
nlines += [line]
lines = nlines
def draw(self,context):
for line in lines:
self.layout.label(line)
bpy.context.window_manager.popup_menu(draw, title=title, icon=icon)
return
def show_error_message(message, title="Error", wrap=80):
show_blender_popup(message, title, "ERROR", wrap)
def create_and_show_blender_text(text, name='A Report', hide_header=True, goto_top=True):
# create a new textblock for reporting
bpy.ops.text.new() # create new text block, which is appended to list
bpy.data.texts[-1].name = name # set name, but if another object exists with the
name = bpy.data.texts[-1].name # same name, blender will append .001 (or similar)
bpy.data.texts[name].text = text # set text of text block
show_blender_text(name, hide_header=hide_header, goto_top=goto_top)
def show_blender_text(textblock_name, hide_header=True, goto_top=True):
if textblock_name not in bpy.data.texts:
# no textblock to show
return
txt = bpy.data.texts[textblock_name]
if goto_top:
txt.current_line_index = 0
txt.select_end_line_index = 0
# duplicate the current area then change it to a text editor
area_dupli = bpy.ops.screen.area_dupli('INVOKE_DEFAULT')
win = bpy.context.window_manager.windows[-1]
area = win.screen.areas[-1]
area.type = 'TEXT_EDITOR'
# load the text file into the correct space
for space in area.spaces:
if space.type == 'TEXT_EDITOR':
space.text = txt
space.show_word_wrap = True
space.show_syntax_highlight = False
space.top = 0
if hide_header and area.regions[0].height != 1:
# hide header
toggle_screen_header({'window':win, 'region':area.regions[2], 'area':area, 'space_data':space})
def bversion(short=True):
major,minor,rev = bpy.app.version
bver_long = '%03d.%03d.%03d' % (major,minor,rev)
bver_short = '%d.%02d' % (major, minor)
return bver_short if short else bver_long
@@ -0,0 +1,394 @@
'''
Copyright (C) 2020 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson, and Patrick Moore
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/>.
'''
'''
notes: something is really wrong here to have such poor performance
Below are some related, interesting links
- https://machinesdontcare.wordpress.com/2008/02/02/glsl-discard-z-fighting-supersampling/
- https://developer.apple.com/library/archive/documentation/3DDrawing/Conceptual/OpenGLES_ProgrammingGuide/BestPracticesforShaders/BestPracticesforShaders.html
- https://stackoverflow.com/questions/16415037/opengl-core-profile-incredible-slowdown-on-os-x
'''
import os
import re
import math
import ctypes
import random
import traceback
import bmesh
import bgl
import bpy
from bpy_extras.view3d_utils import (
location_3d_to_region_2d, region_2d_to_vector_3d
)
from bpy_extras.view3d_utils import (
region_2d_to_location_3d, region_2d_to_origin_3d
)
from mathutils import Vector, Matrix, Quaternion
from mathutils.bvhtree import BVHTree
from .debug import dprint
from .shaders import Shader
from .utils import shorten_floats
from .maths import Point, Direction, Frame, XForm
from .maths import invert_matrix, matrix_normal
from .profiler import profiler
from .decorators import blender_version_wrapper
# note: not all supported by user system, but we don't need full functionality
# https://en.wikipedia.org/wiki/OpenGL_Shading_Language#Versions
# OpenGL GLSL OpenGL GLSL
# 2.0 110 4.0 400
# 2.1 120 4.1 410
# 3.0 130 4.2 420
# 3.1 140 4.3 430
# 3.2 150 4.4 440
# 3.3 330 4.5 450
# 4.6 460
print('(bmesh_render) GLSL Version:', bgl.glGetString(bgl.GL_SHADING_LANGUAGE_VERSION))
def glCheckError(title):
if not glCheckError.CHECK_ERROR: return
err = bgl.glGetError()
if err == bgl.GL_NO_ERROR: return
print('ERROR (%s): %s' % (title, glCheckError.ERROR_MAP.get(err, 'code %d' % err)))
traceback.print_stack()
glCheckError.CHECK_ERROR = True
glCheckError.ERROR_MAP = {
getattr(bgl, k): s
for (k,s) in [
# https://www.khronos.org/opengl/wiki/OpenGL_Error#Meaning_of_errors
('GL_INVALID_ENUM', 'invalid enum'),
('GL_INVALID_VALUE', 'invalid value'),
('GL_INVALID_OPERATION', 'invalid operation'),
('GL_STACK_OVERFLOW', 'stack overflow'), # does not exist in b3d 2.8x for OSX??
('GL_STACK_UNDERFLOW', 'stack underflow'), # does not exist in b3d 2.8x for OSX??
('GL_OUT_OF_MEMORY', 'out of memory'),
('GL_INVALID_FRAMEBUFFER_OPERATION', 'invalid framebuffer operation'),
('GL_CONTEXT_LOST', 'context lost'),
('GL_TABLE_TOO_LARGE', 'table too large'), # deprecated in OpenGL 3.0, removed in 3.1 core and above
]
if hasattr(bgl, k)
}
@blender_version_wrapper('<', '2.80')
def glSetDefaultOptions():
bgl.glDisable(bgl.GL_LIGHTING)
bgl.glEnable(bgl.GL_MULTISAMPLE)
bgl.glEnable(bgl.GL_BLEND)
bgl.glEnable(bgl.GL_DEPTH_TEST)
bgl.glEnable(bgl.GL_POINT_SMOOTH)
bgl.glEnable(bgl.GL_LINE_SMOOTH)
bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)
@blender_version_wrapper('>=', '2.80')
def glSetDefaultOptions():
bgl.glEnable(bgl.GL_MULTISAMPLE)
bgl.glEnable(bgl.GL_BLEND)
bgl.glEnable(bgl.GL_DEPTH_TEST)
bgl.glEnable(bgl.GL_LINE_SMOOTH)
bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)
@blender_version_wrapper('<', '2.80')
def glEnableStipple(enable=True):
if enable:
bgl.glLineStipple(4, 0x5555)
bgl.glEnable(bgl.GL_LINE_STIPPLE)
else:
bgl.glDisable(bgl.GL_LINE_STIPPLE)
@blender_version_wrapper('>=', '2.80')
def glEnableStipple(enable=True):
pass
# if enable:
# bgl.glLineStipple(4, 0x5555)
# bgl.glEnable(bgl.GL_LINE_STIPPLE)
# else:
# bgl.glDisable(bgl.GL_LINE_STIPPLE)
# def glEnableBackfaceCulling(enable=True):
# if enable:
# bgl.glDisable(bgl.GL_CULL_FACE)
# bgl.glDepthFunc(bgl.GL_GEQUAL)
# else:
# bgl.glDepthFunc(bgl.GL_LEQUAL)
# bgl.glEnable(bgl.GL_CULL_FACE)
def glSetOptions(prefix, opts):
if not opts: return
prefix = '%s ' % prefix if prefix else ''
def set_if_set(opt, cb):
opt = '%s%s' % (prefix, opt)
if opt not in opts: return
cb(opts[opt])
glCheckError('setting %s to %s' % (str(opt), str(opts[opt])))
def set_linewidth(v):
dpi_mult = opts.get('dpi mult', 1.0)
#bgl.glLineWidth(v*dpi_mult)
glCheckError('setting line width to %s' % (str(v*dpi_mult)))
def set_pointsize(v):
dpi_mult = opts.get('dpi mult', 1.0)
bgl.glPointSize(v*dpi_mult)
glCheckError('setting point size to %s' % (str(v*dpi_mult)))
def set_stipple(v):
glEnableStipple(v)
glCheckError('setting stipple to %s' % (str(v)))
set_if_set('offset', lambda v: bmeshShader.assign('offset', v))
set_if_set('dotoffset', lambda v: bmeshShader.assign('dotoffset', v))
set_if_set('color', lambda v: bmeshShader.assign('color', v))
set_if_set('color selected', lambda v: bmeshShader.assign('color_selected', v))
set_if_set('hidden', lambda v: bmeshShader.assign('hidden', v))
set_if_set('width', set_linewidth)
set_if_set('size', set_pointsize)
set_if_set('stipple', set_stipple)
def glSetMirror(symmetry=None, view=None, effect=0.0, frame: Frame=None):
mirroring = (0, 0, 0)
if symmetry and frame:
mx = 1.0 if 'x' in symmetry else 0.0
my = 1.0 if 'y' in symmetry else 0.0
mz = 1.0 if 'z' in symmetry else 0.0
mirroring = (mx, my, mz)
bmeshShader.assign('mirror_o', frame.o)
bmeshShader.assign('mirror_x', frame.x)
bmeshShader.assign('mirror_y', frame.y)
bmeshShader.assign('mirror_z', frame.z)
bmeshShader.assign('mirror_view', {'Edge': 1, 'Face': 2}.get(view, 0))
bmeshShader.assign('mirror_effect', effect)
bmeshShader.assign('mirroring', mirroring)
def triangulateFace(verts):
l = len(verts)
if l < 3: return
if l == 3:
yield verts
return
if l == 4:
v0,v1,v2,v3 = verts
yield (v0,v1,v2)
yield (v0,v2,v3)
return
iv = iter(verts)
v0, v2 = next(iv), next(iv)
for v3 in iv:
v1, v2 = v2, v3
yield (v0, v1, v2)
#############################################################################################################
#############################################################################################################
#############################################################################################################
import gpu
from gpu_extras.batch import batch_for_shader
from .shaders import Shader
verts_vs, verts_fs = Shader.parse_file('bmesh_render_verts.glsl', includeVersion=False)
verts_shader = gpu.types.GPUShader(verts_vs, verts_fs)
edges_vs, edges_fs = Shader.parse_file('bmesh_render_edges.glsl', includeVersion=False)
edges_shader = gpu.types.GPUShader(edges_vs, edges_fs)
faces_vs, faces_fs = Shader.parse_file('bmesh_render_faces.glsl', includeVersion=False)
faces_shader = gpu.types.GPUShader(faces_vs, faces_fs)
class BufferedRender_Batch:
_quarantine = {}
def __init__(self, gltype):
global faces_shader, edges_shader, verts_shader
self.count = 0
self.gltype = gltype
self.shader, self.shader_type, self.gltype_name, self.gl_count, self.options_prefix = {
bgl.GL_POINTS: (verts_shader, 'POINTS', 'points', 1, 'point'),
bgl.GL_LINES: (edges_shader, 'LINES', 'lines', 2, 'line'),
bgl.GL_TRIANGLES: (faces_shader, 'TRIS', 'triangles', 3, 'poly'),
}[self.gltype]
self.batch = None
self._quarantine.setdefault(self.shader, set())
def buffer(self, pos, norm, sel):
if self.shader == None: return
if self.shader_type == 'POINTS':
data = {
'vert_pos': [p for p in pos for __ in range(6)],
'vert_norm': [n for n in norm for __ in range(6)],
'selected': [s for s in sel for __ in range(6)],
'vert_offset': [o for _ in pos for o in [(0,0), (1,0), (0,1), (0,1), (1,0), (1,1)]],
}
elif self.shader_type == 'LINES':
data = {
'vert_pos0': [p0 for (p0,p1) in zip(pos[0::2], pos[1::2] ) for __ in range(6)],
'vert_pos1': [p1 for (p0,p1) in zip(pos[0::2], pos[1::2] ) for __ in range(6)],
'vert_norm': [n0 for (n0,n1) in zip(norm[0::2],norm[1::2]) for __ in range(6)],
'selected': [s0 for (s0,s1) in zip(sel[0::2], sel[1::2] ) for __ in range(6)],
'vert_offset': [o for _ in pos[0::2] for o in [(0,0), (0,1), (1,1), (0,0), (1,1), (1,0)]],
}
elif self.shader_type == 'TRIS':
data = {
'vert_pos': pos,
'vert_norm': norm,
'selected': sel,
}
else: assert False, 'BufferedRender_Batch.buffer: Unhandled type: ' + self.shader_type
self.batch = batch_for_shader(self.shader, 'TRIS', data) # self.shader_type, data)
self.count = len(pos)
def set_options(self, prefix, opts):
if not opts: return
shader = self.shader
prefix = '%s ' % prefix if prefix else ''
def set_if_set(opt, cb):
opt = '%s%s' % (prefix, opt)
if opt not in opts: return
cb(opts[opt])
glCheckError('setting %s to %s' % (str(opt), str(opts[opt])))
dpi_mult = opts.get('dpi mult', 1.0)
set_if_set('color', lambda v: self.uniform_float('color', v))
set_if_set('color selected', lambda v: self.uniform_float('color_selected', v))
set_if_set('hidden', lambda v: self.uniform_float('hidden', v))
set_if_set('offset', lambda v: self.uniform_float('offset', v))
set_if_set('dotoffset', lambda v: self.uniform_float('dotoffset', v))
if self.shader_type == 'POINTS':
set_if_set('size', lambda v: self.uniform_float('radius', v*dpi_mult))
elif self.shader_type == 'LINES':
set_if_set('width', lambda v: self.uniform_float('radius', v*dpi_mult))
def _draw(self, sx, sy, sz):
self.uniform_float('vert_scale', (sx, sy, sz))
self.batch.draw(self.shader)
#glCheckError('_draw: glDrawArrays (%d)' % self.count)
def is_quarantined(self, k):
return k in self._quarantine[self.shader]
def quarantine(self, k):
dprint('BufferedRender_Batch: quarantining %s for %s' % (str(k), str(self.shader)))
self._quarantine[self.shader].add(k)
def uniform_float(self, k, v):
if self.is_quarantined(k): return
try: self.shader.uniform_float(k, v)
except Exception as e: self.quarantine(k)
def uniform_int(self, k, v):
if self.is_quarantined(k): return
try: self.shader.uniform_int(k, v)
except Exception as e: self.quarantine(k)
def uniform_bool(self, k, v):
if self.is_quarantined(k): return
try: self.shader.uniform_bool(k, v)
except Exception as e: self.quarantine(k)
def draw(self, opts):
if self.shader == None or self.count == 0: return
if self.gltype == bgl.GL_LINES and opts.get('line width', 1.0) <= 0: return
if self.gltype == bgl.GL_POINTS and opts.get('point size', 1.0) <= 0: return
shader = self.shader
shader.bind()
# set defaults
self.uniform_float('color', (1,1,1,0.5))
self.uniform_float('color_selected', (0.5,1,0.5,0.5))
self.uniform_float('hidden', 0.9)
self.uniform_float('offset', 0)
self.uniform_float('dotoffset', 0)
self.uniform_float('vert_scale', (1, 1, 1))
self.uniform_float('radius', 1) #random.random()*10)
nosel = opts.get('no selection', False)
self.uniform_bool('use_selection', [not nosel]) # must be a sequence!?
self.uniform_bool('use_rounding', [self.gltype == bgl.GL_POINTS]) # must be a sequence!?
self.uniform_float('matrix_m', opts['matrix model'])
self.uniform_float('matrix_mn', opts['matrix normal'])
self.uniform_float('matrix_t', opts['matrix target'])
self.uniform_float('matrix_ti', opts['matrix target inverse'])
self.uniform_float('matrix_v', opts['matrix view'])
self.uniform_float('matrix_vn', opts['matrix view normal'])
self.uniform_float('matrix_p', opts['matrix projection'])
self.uniform_float('dir_forward', opts['forward direction'])
self.uniform_float('unit_scaling_factor', opts['unit scaling factor'])
mx, my, mz = opts.get('mirror x', False), opts.get('mirror y', False), opts.get('mirror z', False)
symmetry = opts.get('symmetry', None)
symmetry_frame = opts.get('symmetry frame', None)
symmetry_view = opts.get('symmetry view', None)
symmetry_effect = opts.get('symmetry effect', 0.0)
mirroring = (False, False, False)
if symmetry and symmetry_frame:
mx = 'x' in symmetry
my = 'y' in symmetry
mz = 'z' in symmetry
mirroring = (mx, my, mz)
self.uniform_float('mirror_o', symmetry_frame.o)
self.uniform_float('mirror_x', symmetry_frame.x)
self.uniform_float('mirror_y', symmetry_frame.y)
self.uniform_float('mirror_z', symmetry_frame.z)
self.uniform_int('mirror_view', [{'Edge': 1, 'Face': 2}.get(symmetry_view, 0)])
self.uniform_float('mirror_effect', symmetry_effect)
self.uniform_bool('mirroring', mirroring)
self.uniform_float('normal_offset', opts.get('normal offset', 0.0))
self.uniform_bool('constrain_offset', [opts.get('constrain offset', True)]) # must be a sequence!?
ctx = bpy.context
area, spc, r3d = ctx.area, ctx.space_data, ctx.space_data.region_3d
self.uniform_bool('perspective', [r3d.view_perspective != 'ORTHO']) # must be a sequence!?
self.uniform_float('clip_start', spc.clip_start)
self.uniform_float('clip_end', spc.clip_end)
self.uniform_float('view_distance', r3d.view_distance)
self.uniform_float('screen_size', Vector((area.width, area.height)))
focus = opts.get('focus mult', 1.0)
self.uniform_float('focus_mult', focus)
self.uniform_bool('cull_backfaces', [opts.get('cull backfaces', False)])
self.uniform_float('alpha_backface', opts.get('alpha backface', 0.5))
self.set_options(self.options_prefix, opts)
self._draw(1, 1, 1)
if mx or my or mz:
self.set_options('%s mirror' % self.options_prefix, opts)
if mx: self._draw(-1, 1, 1)
if my: self._draw( 1, -1, 1)
if mz: self._draw( 1, 1, -1)
if mx and my: self._draw(-1, -1, 1)
if mx and mz: self._draw(-1, 1, -1)
if my and mz: self._draw( 1, -1, -1)
if mx and my and mz: self._draw(-1, -1, -1)
gpu.shader.unbind()
@@ -0,0 +1,485 @@
'''
Copyright (C) 2020 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson, and Patrick Moore
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/>.
'''
'''
notes: something is really wrong here to have such poor performance
Below are some related, interesting links
- https://machinesdontcare.wordpress.com/2008/02/02/glsl-discard-z-fighting-supersampling/
- https://developer.apple.com/library/archive/documentation/3DDrawing/Conceptual/OpenGLES_ProgrammingGuide/BestPracticesforShaders/BestPracticesforShaders.html
- https://stackoverflow.com/questions/16415037/opengl-core-profile-incredible-slowdown-on-os-x
'''
import os
import re
import math
import ctypes
import traceback
import bmesh
import bgl
import bpy
from bpy_extras.view3d_utils import (
location_3d_to_region_2d, region_2d_to_vector_3d
)
from bpy_extras.view3d_utils import (
region_2d_to_location_3d, region_2d_to_origin_3d
)
from mathutils import Vector, Matrix, Quaternion
from mathutils.bvhtree import BVHTree
from .debug import dprint
from .shaders import Shader
from .utils import shorten_floats
from .maths import Point, Direction, Frame, XForm
from .maths import invert_matrix, matrix_normal
from .profiler import profiler
from .decorators import blender_version_wrapper
def glColor(color):
if len(color) == 3:
bgl.glColor3f(*color)
else:
bgl.glColor4f(*color)
def glDrawBMFace(bmf, opts=None, enableShader=True):
glDrawBMFaces([bmf], opts=opts, enableShader=enableShader)
@profiler.function
def glDrawBMFaces(lbmf, opts=None, enableShader=True):
opts_ = opts or {}
nosel = opts_.get('no selection', False)
mx = opts_.get('mirror x', False)
my = opts_.get('mirror y', False)
mz = opts_.get('mirror z', False)
dn = opts_.get('normal', 0.0)
vdict = opts_.get('vertex dict', {})
bmeshShader.assign('focus_mult', opts_.get('focus mult', 1.0))
bmeshShader.assign('use_selection', 0.0 if nosel else 1.0)
@profiler.function
def render_general(sx, sy, sz):
bmeshShader.assign('vert_scale', (sx, sy, sz))
bmeshShader.assign('selected', 0.0)
for bmf in lbmf:
bmeshShader.assign('selected', 1.0 if bmf.select else 0.0)
if bmf.smooth:
for v0, v1, v2 in triangulateFace(bmf.verts):
if v0 not in vdict:
vdict[v0] = (v0.co, v0.normal)
if v1 not in vdict:
vdict[v1] = (v1.co, v1.normal)
if v2 not in vdict:
vdict[v2] = (v2.co, v2.normal)
(c0, n0), (c1, n1), (c2,
n2) = vdict[v0], vdict[v1], vdict[v2]
bmeshShader.assign('vert_norm', n0)
bmeshShader.assign('vert_pos', c0)
bmeshShader.assign('vert_norm', n1)
bmeshShader.assign('vert_pos', c1)
bmeshShader.assign('vert_norm', n2)
bmeshShader.assign('vert_pos', c2)
else:
bgl.glNormal3f(*bmf.normal)
bmeshShader.assign('vert_norm', bmf.normal)
for v0, v1, v2 in triangulateFace(bmf.verts):
if v0 not in vdict:
vdict[v0] = (v0.co, v0.normal)
if v1 not in vdict:
vdict[v1] = (v1.co, v1.normal)
if v2 not in vdict:
vdict[v2] = (v2.co, v2.normal)
(c0, n0), (c1, n1), (c2,
n2) = vdict[v0], vdict[v1], vdict[v2]
bmeshShader.assign('vert_pos', c0)
bmeshShader.assign('vert_pos', c1)
bmeshShader.assign('vert_pos', c2)
@profiler.function
def render_triangles(sx, sy, sz):
# optimized for triangle-only meshes
# (source meshes that have been triangulated)
bmeshShader.assign('vert_scale', (sx, sy, sz))
bmeshShader.assign('selected', 0.0)
for bmf in lbmf:
bmeshShader.assign('selected', 1.0 if bmf.select else 0.0)
if bmf.smooth:
v0, v1, v2 = bmf.verts
if v0 not in vdict:
vdict[v0] = (v0.co, v0.normal)
if v1 not in vdict:
vdict[v1] = (v1.co, v1.normal)
if v2 not in vdict:
vdict[v2] = (v2.co, v2.normal)
(c0, n0), (c1, n1), (c2, n2) = vdict[v0], vdict[v1], vdict[v2]
bmeshShader.assign('vert_norm', n0)
bmeshShader.assign('vert_pos', c0)
# bgl.glNormal3f(*n0)
# bgl.glVertex3f(*c0)
bmeshShader.assign('vert_norm', n1)
bmeshShader.assign('vert_pos', c1)
# bgl.glNormal3f(*n1)
# bgl.glVertex3f(*c1)
bmeshShader.assign('vert_norm', n2)
bmeshShader.assign('vert_pos', c2)
# bgl.glNormal3f(*n2)
# bgl.glVertex3f(*c2)
else:
bgl.glNormal3f(*bmf.normal)
v0, v1, v2 = bmf.verts
if v0 not in vdict:
vdict[v0] = (v0.co, v0.normal)
if v1 not in vdict:
vdict[v1] = (v1.co, v1.normal)
if v2 not in vdict:
vdict[v2] = (v2.co, v2.normal)
(c0, n0), (c1, n1), (c2, n2) = vdict[v0], vdict[v1], vdict[v2]
bmeshShader.assign('vert_pos', c0)
# bgl.glVertex3f(*c0)
bmeshShader.assign('vert_pos', c1)
# bgl.glVertex3f(*c1)
bmeshShader.assign('vert_pos', c2)
# bgl.glVertex3f(*c2)
render = render_triangles if opts_.get(
'triangles only', False) else render_general
if enableShader:
bmeshShader.enable()
glSetOptions('poly', opts)
bgl.glBegin(bgl.GL_TRIANGLES)
render(1, 1, 1)
bgl.glEnd()
bgl.glDisable(bgl.GL_LINE_STIPPLE)
if mx or my or mz:
glSetOptions('poly mirror', opts)
bgl.glBegin(bgl.GL_TRIANGLES)
if mx:
render(-1, 1, 1)
if my:
render(1, -1, 1)
if mz:
render(1, 1, -1)
if mx and my:
render(-1, -1, 1)
if mx and mz:
render(-1, 1, -1)
if my and mz:
render(1, -1, -1)
if mx and my and mz:
render(-1, -1, -1)
bgl.glEnd()
bgl.glDisable(bgl.GL_LINE_STIPPLE)
if enableShader:
bmeshShader.disable()
@profiler.function
def glDrawSimpleFaces(lsf, opts=None, enableShader=True):
opts_ = opts or {}
nosel = opts_.get('no selection', False)
mx = opts_.get('mirror x', False)
my = opts_.get('mirror y', False)
mz = opts_.get('mirror z', False)
dn = opts_.get('normal', 0.0)
bmeshShader.assign('focus_mult', opts_.get('focus mult', 1.0))
bmeshShader.assign('use_selection', 0.0 if nosel else 1.0)
bmeshShader.assign('selected', 0.0)
@profiler.function
def render(sx, sy, sz):
bmeshShader.assign('vert_scale', (sx, sy, sz))
for sf in lsf:
for v0, v1, v2 in triangulateFace(sf):
(c0, n0), (c1, n1), (c2, n2) = v0, v1, v2
bgl.glNormal3f(*n0)
bgl.glVertex3f(*c0)
bgl.glNormal3f(*n1)
bgl.glVertex3f(*c1)
bgl.glNormal3f(*n2)
bgl.glVertex3f(*c2)
if enableShader:
bmeshShader.enable()
glSetOptions('poly', opts)
bgl.glBegin(bgl.GL_TRIANGLES)
render(1, 1, 1)
bgl.glEnd()
bgl.glDisable(bgl.GL_LINE_STIPPLE)
if mx or my or mz:
glSetOptions('poly mirror', opts)
bgl.glBegin(bgl.GL_TRIANGLES)
if mx:
render(-1, 1, 1)
if my:
render(1, -1, 1)
if mz:
render(1, 1, -1)
if mx and my:
render(-1, -1, 1)
if mx and mz:
render(-1, 1, -1)
if my and mz:
render(1, -1, -1)
if mx and my and mz:
render(-1, -1, -1)
bgl.glEnd()
bgl.glDisable(bgl.GL_LINE_STIPPLE)
if enableShader:
bmeshShader.disable()
def glDrawBMFaceEdges(bmf, opts=None, enableShader=True):
glDrawBMEdges(bmf.edges, opts=opts, enableShader=enableShader)
def glDrawBMFaceVerts(bmf, opts=None, enableShader=True):
glDrawBMVerts(bmf.verts, opts=opts, enableShader=enableShader)
def glDrawBMEdge(bme, opts=None, enableShader=True):
glDrawBMEdges([bme], opts=opts, enableShader=enableShader)
@profiler.function
def glDrawBMEdges(lbme, opts=None, enableShader=True):
opts_ = opts or {}
if opts_.get('line width', 1.0) <= 0.0:
return
nosel = opts_.get('no selection', False)
mx = opts_.get('mirror x', False)
my = opts_.get('mirror y', False)
mz = opts_.get('mirror z', False)
dn = opts_.get('normal', 0.0)
vdict = opts_.get('vertex dict', {})
bmeshShader.assign('use_selection', 0.0 if nosel else 1.0)
@profiler.function
def render(sx, sy, sz):
bmeshShader.assign('vert_scale', (sx, sy, sz))
for bme in lbme:
bmeshShader.assign('selected', 1.0 if bme.select else 0.0)
v0, v1 = bme.verts
if v0 not in vdict:
vdict[v0] = (v0.co, v0.normal)
if v1 not in vdict:
vdict[v1] = (v1.co, v1.normal)
(c0, n0), (c1, n1) = vdict[v0], vdict[v1]
c0, c1 = c0+n0*dn, c1+n1*dn
bmeshShader.assign('vert_norm', n0)
bmeshShader.assign('vert_pos', c0)
# bgl.glVertex3f(0,0,0)
bmeshShader.assign('vert_norm', n1)
bmeshShader.assign('vert_pos', c1)
# bgl.glVertex3f(0,0,0)
if enableShader:
bmeshShader.enable()
glSetOptions('line', opts)
bgl.glBegin(bgl.GL_LINES)
render(1, 1, 1)
bgl.glEnd()
bgl.glDisable(bgl.GL_LINE_STIPPLE)
if mx or my or mz:
glSetOptions('line mirror', opts)
bgl.glBegin(bgl.GL_LINES)
if mx:
render(-1, 1, 1)
if my:
render(1, -1, 1)
if mz:
render(1, 1, -1)
if mx and my:
render(-1, -1, 1)
if mx and mz:
render(-1, 1, -1)
if my and mz:
render(1, -1, -1)
if mx and my and mz:
render(-1, -1, -1)
bgl.glEnd()
bgl.glDisable(bgl.GL_LINE_STIPPLE)
if enableShader:
bmeshShader.disable()
def glDrawBMEdgeVerts(bme, opts=None, enableShader=True):
glDrawBMVerts(bme.verts, opts=opts, enableShader=enableShader)
def glDrawBMVert(bmv, opts=None, enableShader=True):
glDrawBMVerts([bmv], opts=opts, enableShader=enableShader)
@profiler.function
def glDrawBMVerts(lbmv, opts=None, enableShader=True):
opts_ = opts or {}
if opts_.get('point size', 1.0) <= 0.0:
return
nosel = opts_.get('no selection', False)
mx = opts_.get('mirror x', False)
my = opts_.get('mirror y', False)
mz = opts_.get('mirror z', False)
dn = opts_.get('normal', 0.0)
vdict = opts_.get('vertex dict', {})
if enableShader:
bmeshShader.enable()
bmeshShader.assign('use_selection', 0.0 if nosel else 1.0)
@profiler.function
def render(sx, sy, sz):
bmeshShader.assign('vert_scale', Vector((sx, sy, sz)))
for bmv in lbmv:
bmeshShader.assign('selected', 1.0 if bmv.select else 0.0)
if bmv not in vdict:
vdict[bmv] = (bmv.co, bmv.normal)
c, n = vdict[bmv]
c = c + dn * n
bmeshShader.assign('vert_norm', n)
bmeshShader.assign('vert_pos', c)
# bgl.glNormal3f(*n)
# bgl.glVertex3f(*c)
glSetOptions('point', opts)
bgl.glBegin(bgl.GL_POINTS)
glCheckError('something broke before rendering bmverts')
render(1, 1, 1)
glCheckError('something broke after rendering bmverts')
bgl.glEnd()
glCheckError('something broke after glEnd')
bgl.glDisable(bgl.GL_LINE_STIPPLE)
glCheckError('something broke after glDisable(bgl.GL_LINE_STIPPLE')
if mx or my or mz:
glSetOptions('point mirror', opts)
bgl.glBegin(bgl.GL_POINTS)
if mx:
render(-1, 1, 1)
if my:
render(1, -1, 1)
if mz:
render(1, 1, -1)
if mx and my:
render(-1, -1, 1)
if mx and mz:
render(-1, 1, -1)
if my and mz:
render(1, -1, -1)
if mx and my and mz:
render(-1, -1, -1)
bgl.glEnd()
bgl.glDisable(bgl.GL_LINE_STIPPLE)
if enableShader:
glCheckError('before disabling shader')
bmeshShader.disable()
class BMeshRender():
@profiler.function
def __init__(self, obj, xform=None):
self.calllist = None
if type(obj) is bpy.types.Object:
print('Creating BMeshRender for ' + obj.name)
self.bme = bmesh.new()
self.bme.from_object(obj, bpy.context.scene, deform=True)
self.xform = xform or XForm(obj.matrix_world)
elif type(obj) is bmesh.types.BMesh:
self.bme = obj
self.xform = xform or XForm()
else:
assert False, 'Unhandled type: ' + str(type(obj))
self.buf_matrix_model = self.xform.to_bglMatrix_Model()
self.buf_matrix_normal = self.xform.to_bglMatrix_Normal()
self.is_dirty = True
self.calllist = bgl.glGenLists(1)
def replace_bmesh(self, bme):
self.bme = bme
self.is_dirty = True
def __del__(self):
if not self.calllist: return
bgl.glDeleteLists(self.calllist, 1)
self.calllist = None
def dirty(self):
self.is_dirty = True
@profiler.function
def clean(self, opts=None):
if not self.is_dirty: return
# make not dirty first in case bad things happen while drawing
self.is_dirty = False
bgl.glNewList(self.calllist, bgl.GL_COMPILE)
# do not change attribs if they're not set
glSetDefaultOptions(opts=opts)
glDrawBMFaces(self.bme.faces, opts=opts, enableShader=False)
glDrawBMEdges(self.bme.edges, opts=opts, enableShader=False)
glDrawBMVerts(self.bme.verts, opts=opts, enableShader=False)
bgl.glDepthRange(0, 1)
bgl.glEndList()
@profiler.function
def draw(self, opts=None):
try:
self.clean(opts=opts)
bmeshShader.enable()
#bmeshShader.assign('matrix_m', self.buf_matrix_model)
#bmeshShader.assign('matrix_mn', self.buf_matrix_normal)
#bmeshShader.assign('matrix_t', buf_matrix_target)
#bmeshShader.assign('matrix_ti', buf_matrix_target_inv)
#bmeshShader.assign('matrix_v', buf_matrix_view)
#bmeshShader.assign('matrix_vn', buf_matrix_view_invtrans)
#bmeshShader.assign('matrix_p', buf_matrix_proj)
#bmeshShader.assign('dir_forward', view_forward)
bgl.glCallList(self.calllist)
except:
pass
finally:
bmeshShader.disable()
@@ -0,0 +1,55 @@
'''
Copyright (C) 2020 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning and Jonathan Williamson
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/>.
'''
class BMeshState:
def __init__(self, bmesh, property, default_value=False):
self.bmesh = bmesh
self.property = property
self.default_value = default_value
self.vert_state = { bmv:getattr(bmv, property) for bmv in bmesh.verts }
self.edge_state = { bme:getattr(bme, property) for bme in bmesh.edges }
self.face_state = { bmf:getattr(bmf, property) for bmf in bmesh.faces }
def restore(self, verts=True, edges=True, faces=True):
if faces:
for bmf in self.bmesh.faces:
setattr(bmf, self.property, self.face_state.get(bmf, self.default_value))
if edges:
for bme in self.bmesh.edges:
setattr(bme, self.property, self.edge_state.get(bme, self.default_value))
if verts:
for bmv in self.bmesh.verts:
setattr(bmv, self.property, self.vert_state.get(bmv, self.default_value))
class BMeshSelectState(BMeshState):
''' Saves selection state of BMesh, allowing to restore '''
def __init__(self, bmesh):
super().__init__(bmesh, 'select')
class BMeshHideState(BMeshState):
''' Saves hide state of BMesh, allowing to restore '''
def __init__(self, bmesh):
super().__init__(bmesh, 'hide')
@@ -0,0 +1,144 @@
'''
Copyright (C) 2020 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson
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/>.
'''
import re
import inspect
class IgnoreChange(Exception): pass
class BoundVar:
def __init__(self, value_str, *, on_change=None, frame_depth=1):
assert type(value_str) is str, 'BoundVar: constructor needs value as string!'
frame = inspect.currentframe()
for i in range(frame_depth): frame = frame.f_back
self._f_globals = frame.f_globals
self._f_locals = dict(frame.f_locals)
try:
exec(value_str, self._f_globals, self._f_locals)
except Exception as e:
print('Caught exception when trying to bind to variable')
print(e)
assert False, 'BoundVar: value string ("%s") must be a valid variable!' % (value_str)
self._f_locals.update({'boundvar_interface': self._boundvar_interface})
self._value_str = value_str
self._callbacks = []
self._validators = []
self._disabled = False
if on_change: self.on_change(on_change)
def _boundvar_interface(self, v): self._v = v
def _call_callbacks(self):
for cb in self._callbacks: cb()
def __str__(self): return str(self.value)
def get(self):
return self.value
def set(self, value):
self.value = value
@property
def disabled(self):
return self._disabled
@disabled.setter
def disabled(self, v):
self._disabled = bool(v)
self._call_callbacks()
@property
def value(self):
exec('boundvar_interface(' + self._value_str + ')', self._f_globals, self._f_locals)
return self._v
@value.setter
def value(self, value):
try:
for validator in self._validators: value = validator(value)
except IgnoreChange:
return
if self.value == value: return
exec(self._value_str + ' = ' + str(value), self._f_globals, self._f_locals)
self._call_callbacks()
@property
def value_as_str(self): return str(self)
def on_change(self, fn):
self._callbacks.append(fn)
def add_validator(self, fn):
self._validators.append(fn)
class BoundBool(BoundVar):
def __init__(self, value_str, **kwargs):
super().__init__(value_str, frame_depth=2, **kwargs)
@property
def checked(self): return self.value
@checked.setter
def checked(self,v): self.value = v
class BoundInt(BoundVar):
def __init__(self, value_str, *, min_value=None, max_value=None, **kwargs):
super().__init__(value_str, frame_depth=2, **kwargs)
self._min_value = min_value
self._max_value = max_value
self.add_validator(self.int_validator)
def int_validator(self, value):
try:
t = type(value)
if t is str: nv = int(re.sub(r'\D', '', value))
elif t is int: nv = value
elif t is float: nv = int(value)
else: assert False, 'Unhandled type of value: %s (%s)' % (str(value), str(t))
if self._min_value is not None: nv = max(nv, self._min_value)
if self._max_value is not None: nv = min(nv, self._max_value)
return nv
except ValueError as e:
raise IgnoreChange()
except Exception:
# ignoring all exceptions?
raise IgnoreChange()
class BoundFloat(BoundVar):
def __init__(self, value_str, *, min_value=None, max_value=None, **kwargs):
super().__init__(value_str, frame_depth=2, **kwargs)
self._min_value = min_value
self._max_value = max_value
self.add_validator(self.float_validator)
def float_validator(self, value):
try:
t = type(value)
if t is str: nv = float(re.sub(r'[^\d.]', '', value))
elif t is int: nv = float(value)
elif t is float: nv = value
else: assert False, 'Unhandled type of value: %s (%s)' % (str(value), str(t))
if self._min_value is not None: nv = max(nv, self._min_value)
if self._max_value is not None: nv = min(nv, self._max_value)
return nv
except ValueError as e:
raise IgnoreChange()
except Exception:
# ignoring all exceptions?
raise IgnoreChange()
@@ -0,0 +1,181 @@
'''
Copyright (C) 2020 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson
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/>.
'''
#####################################################################################
# below are various token converters
# dictionary to convert color name to color values, either (R,G,B) or (R,G,B,a)
# https://www.quackit.com/css/css_color_codes.cfm
colorname_to_color = {
'transparent': (255, 0, 255, 0),
# https://www.quackit.com/css/css_color_codes.cfm
'indianred': (205,92,92),
'lightcoral': (240,128,128),
'salmon': (250,128,114),
'darksalmon': (233,150,122),
'lightsalmon': (255,160,122),
'crimson': (220,20,60),
'red': (255,0,0),
'firebrick': (178,34,34),
'darkred': (139,0,0),
'pink': (255,192,203),
'lightpink': (255,182,193),
'hotpink': (255,105,180),
'deeppink': (255,20,147),
'mediumvioletred': (199,21,133),
'palevioletred': (219,112,147),
'coral': (255,127,80),
'tomato': (255,99,71),
'orangered': (255,69,0),
'darkorange': (255,140,0),
'orange': (255,165,0),
'gold': (255,215,0),
'yellow': (255,255,0),
'lightyellow': (255,255,224),
'lemonchiffon': (255,250,205),
'lightgoldenrodyellow': (250,250,210),
'papayawhip': (255,239,213),
'moccasin': (255,228,181),
'peachpuff': (255,218,185),
'palegoldenrod': (238,232,170),
'khaki': (240,230,140),
'darkkhaki': (189,183,107),
'lavender': (230,230,250),
'thistle': (216,191,216),
'plum': (221,160,221),
'violet': (238,130,238),
'orchid': (218,112,214),
'fuchsia': (255,0,255),
'magenta': (255,0,255),
'mediumorchid': (186,85,211),
'mediumpurple': (147,112,219),
'blueviolet': (138,43,226),
'darkviolet': (148,0,211),
'darkorchid': (153,50,204),
'darkmagenta': (139,0,139),
'purple': (128,0,128),
'rebeccapurple': (102,51,153),
'indigo': (75,0,130),
'mediumslateblue': (123,104,238),
'slateblue': (106,90,205),
'darkslateblue': (72,61,139),
'greenyellow': (173,255,47),
'chartreuse': (127,255,0),
'lawngreen': (124,252,0),
'lime': (0,255,0),
'limegreen': (50,205,50),
'palegreen': (152,251,152),
'lightgreen': (144,238,144),
'mediumspringgreen': (0,250,154),
'springgreen': (0,255,127),
'mediumseagreen': (60,179,113),
'seagreen': (46,139,87),
'forestgreen': (34,139,34),
'green': (0,128,0),
'darkgreen': (0,100,0),
'yellowgreen': (154,205,50),
'olivedrab': (107,142,35),
'olive': (128,128,0),
'darkolivegreen': (85,107,47),
'mediumaquamarine': (102,205,170),
'darkseagreen': (143,188,143),
'lightseagreen': (32,178,170),
'darkcyan': (0,139,139),
'teal': (0,128,128),
'aqua': (0,255,255),
'cyan': (0,255,255),
'lightcyan': (224,255,255),
'paleturquoise': (175,238,238),
'aquamarine': (127,255,212),
'turquoise': (64,224,208),
'mediumturquoise': (72,209,204),
'darkturquoise': (0,206,209),
'cadetblue': (95,158,160),
'steelblue': (70,130,180),
'lightsteelblue': (176,196,222),
'powderblue': (176,224,230),
'lightblue': (173,216,230),
'skyblue': (135,206,235),
'lightskyblue': (135,206,250),
'deepskyblue': (0,191,255),
'dodgerblue': (30,144,255),
'cornflowerblue': (100,149,237),
'royalblue': (65,105,225),
'blue': (0,0,255),
'mediumblue': (0,0,205),
'darkblue': (0,0,139),
'navy': (0,0,128),
'midnightblue': (25,25,112),
'cornsilk': (255,248,220),
'blanchedalmond': (255,235,205),
'bisque': (255,228,196),
'navajowhite': (255,222,173),
'wheat': (245,222,179),
'burlywood': (222,184,135),
'tan': (210,180,140),
'rosybrown': (188,143,143),
'sandybrown': (244,164,96),
'goldenrod': (218,165,32),
'darkgoldenrod': (184,134,11),
'peru': (205,133,63),
'chocolate': (210,105,30),
'saddlebrown': (139,69,19),
'sienna': (160,82,45),
'brown': (165,42,42),
'maroon': (128,0,0),
'white': (255,255,255),
'snow': (255,250,250),
'honeydew': (240,255,240),
'mintcream': (245,255,250),
'azure': (240,255,255),
'aliceblue': (240,248,255),
'ghostwhite': (248,248,255),
'whitesmoke': (245,245,245),
'seashell': (255,245,238),
'beige': (245,245,220),
'oldlace': (253,245,230),
'floralwhite': (255,250,240),
'ivory': (255,255,240),
'antiquewhite': (250,235,215),
'linen': (250,240,230),
'lavenderblush': (255,240,245),
'mistyrose': (255,228,225),
'gainsboro': (220,220,220),
'lightgray': (211,211,211),
'lightgrey': (211,211,211),
'silver': (192,192,192),
'darkgray': (169,169,169),
'darkgrey': (169,169,169),
'gray': (128,128,128),
'grey': (128,128,128),
'dimgray': (105,105,105),
'dimgrey': (105,105,105),
'lightslategray': (119,136,153),
'lightslategrey': (119,136,153),
'slategray': (112,128,144),
'slategrey': (112,128,144),
'darkslategray': (47,79,79),
'darkslategrey': (47,79,79),
'black': (0,0,0),
}
@@ -0,0 +1,687 @@
/*
https://en.wikipedia.org/wiki/Flat_design#/media/File:Flat_widgets.png
https://bulma.io/documentation/elements/button/
*/
* {
margin: 2px 2px;
padding: 4px 8px;
width: auto;
height: auto;
min-width: 0;
min-height: 0;
max-width: auto;
max-height: auto;
background-color: transparent;
border-width: 1px;
border-color: rgba(0, 0, 0, 0.75);
border-radius: 4px;
overflow: hidden;
font: normal normal 12pt sans-serif;
}
body {
position: fixed;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
border: 4px rgba(0,0,0,0.25);
border-radius: 8px;
cursor: default;
overflow: hidden;
}
button {
white-space: normal;
cursor: default;
display: inline;
border-width: 0px;
border-radius: 4px;
border-color: white rgb(96,96,96) rgb(32,32,32) rgb(224,224,224);
background: rgba(160,160,160, 0.50);
color: black;
}
button:focus {
/*background: yellow;*/
/*background: lightcyan;*/
background: rgba(160,160,160, 1.00);
}
button:active {
/*background: rgb(192,128,128);*/
background: hsla(200, 100%, 62.5%, 1.0); /* rgba(128,224,255,0.5); */
}
button:hover {
background: rgba(160, 160, 160, 1.00); /* hsla(200, 100%, 62.5%, 1.0); /* rgb(64,192,255); */
}
button:active:hover {
background: hsla(200, 100%, 62.5%, 1.0); /*rgb(128,224,255);*/
}
button:disabled {
background-color: rgb(128,128,128);
color: rgb(192,192,192);
/*border-width: 1px;*/
border-color: rgb(96,96,96);
cursor: default;
}
p {
display: block;
width: 100%;
/*margin: 2px 0px;*/
padding: 2px;
border-width: 0px;
color: white;
}
p span {
margin: 0;
padding: 0;
border-width: 0;
}
code {
font-family: monospace;
white-space: pre;
}
pre {
width: 100%;
display: block;
font-family: monospace;
background-color: rgba(128, 128, 128, 0.5);
font-size: 10pt;
white-space: pre-wrap;
}
textarea {
display: block;
width: 100%;
/*margin: 2px 0px;*/
padding: 4px;
background-color: rgba(255,255,255,0.9);
border: 1px black;
border-radius: 4px;
color: black;
cursor: text;
}
div {
background-color: rgba(0,0,0,0.25);
display: block;
width: 100%;
margin: 2px 0px;
padding: 2px;
}
br {
display: block;
width: 0px;
height: 0px;
margin: 0px;
padding: 0px;
border-width: 0px;
}
img {
/*max-width: 100%;*/
object-fit: contain;
border-width: 1px;
border-color: rgba(0,0,0,0.25);
background-color: hsla(200, 100%, 62.5%, 0.0); /* rgba(255,0,0,0); */
padding: 2px;
}
span {
color: white;
border-width: 0px;
}
/* make sure we handle cases correctly! */
input {
background: red;
}
dialog {
position: fixed;
border-radius: 4px;
border: 1px black;
background: rgba(32, 32, 32, 0.75);
/*overflow-x: scroll;*/
overflow-y: scroll;
color: white;
width: 500px;
/*max-width: 750px;*/
min-width: 200px;
}
dialog.framed {
border: 2px rgba(0,0,0,0.75);
border-radius: 5px;
overflow: hidden;
padding: 0px;
margin: 5px;
}
div.dialog-header {
background: hsla(200, 0%, 25%, 0.75); /* hsla(0, 0%, 25%, 0.75); */
margin: 0px;
padding: 2px;
border: 1px rgba(0,0,0,0.25) rgba(0,0,0,0.25) rgba(0,0,0,1) rgba(0,0,0,0.25);
border-radius: 0px;
}
dialog.framed.moveable div.dialog-header {
cursor: grab;
}
dialog.framed.moveable div.dialog-header:hover {
background-color: hsla(200, 25%, 40%, 0.75); /* hsla(0,0%,40%,0.75);*/
}
dialog.framed.moveable div.dialog-header:active {
background-color: hsla(200, 100%, 60%, 0.75); /*hsla(0,0%,40%,0.5);*/
}
span.dialog-title {
margin: 0px;
border: 0px white;
padding: 2px;
color: white;
/*font-weight: bold;*/
white-space: pre;
cursor: grab;
text-shadow: 2px 2px rgba(0,0,0,0.25);
}
button.dialog-close {
margin: 0px;
padding: 2px;
border: 0px;
display: inline;
width: 16px;
height: 16px;
background: url('close.png');
}
dialog.framed > div.inside {
margin: 0px;
border-width: 1px;
border-radius: 0px;
border-color: rgba(0,0,0,1.0) rgba(0,0,0,0.25) rgba(0,0,0,0.25) rgba(0,0,0,0.25);
padding: 5px 2px 2px 2px;
}
div.dialog-footer {
position: absolute;
left: auto;
right: 50px;
top: -200px;
width: 100%;
/*bottom: 0px;*/
background: hsla(200, 0%, 25%, 0.75); /* hsla(0, 0%, 25%, 0.75); */
margin: 0px;
padding: 2px;
border: 1px rgba(0,0,0,1) rgba(0,0,0,0.25) rgba(0,0,0,0.25) rgba(0,0,0,0.25);
border-radius: 0px;
}
div.dialog-footer > * {
margin: 0px;
border: 0px white;
padding: 2px;
}
/**********************/
/* INPUT CHECKBOX */
input[type="checkbox"] {
background-color: transparent;
border-width: 0px;
padding: 0px;
}
input[type="checkbox"] > img.checkbox {
margin: 0;
padding: 4px;
margin-right: 5px;
border-width: 0px;
width: 29px;
height: 24px;
background-color: rgba(160, 160, 160, 0.50); /* hsla(200, 0%, 62.5%, 1.0);*/
background-image: none;
}
input[type="checkbox"]:hover > img.checkbox {
background-color: rgba(160, 160, 160, 1.00); /* hsla(200, 0%, 75%, 1.0); */
}
input[type="checkbox"][checked] > img.checkbox {
background-color: hsla(200, 100%, 62.5%, 1.0);
background-image: url('checkmark.png');
}
input[type="checkbox"]:active > img.checkbox {
background-color: hsla(200, 100%, 75%, 1.0);
}
input[type="checkbox"] > label {
color: rgba(255, 255, 255, 0.50);
margin: 0px;
padding: 0px;
padding-top: 3px;
padding-right: 10px;
border-width: 0px;
}
input[type="checkbox"]:hover > label {
color: rgba(255, 255, 255, 1.00);
}
input[type="checkbox"][checked] > label {
color: rgba(255, 255, 255, 1.00);
}
/*******************/
/* INPUT RADIO */
input[type="radio"] {
background-color: transparent;
border-width: 0px;
padding: 0px;
}
input[type="radio"] > img.radio {
margin: 0;
padding: 4px;
margin-right: 5px;
border: 0px;
border-radius: 12px;
width: 29px;
height: 24px;
background-color: rgba(160, 160, 160, 0.50); /* hsla(200, 0%, 62.5%, 1.0);*/
background-image: none;
}
input[type="radio"]:hover > img.radio {
background-color: rgba(160, 160, 160, 1.00); /* hsla(200, 0%, 75%, 1.0); */
}
input[type="radio"]:active > img.radio {
background-color: hsla(200, 100%, 75%, 1.0);
}
input[type="radio"][checked] > img.radio {
background: hsla(200, 100%, 62.5%, 1.0) url('radio.png');
}
input[type="radio"] > label {
color: rgba(255, 255, 255, 0.50);
margin: 0px;
padding: 0px;
padding-top: 3px;
padding-right: 10px;
border-width: 0px;
}
input[type="radio"]:hover > label {
color: rgba(255, 255, 255, 1.00);
}
input[type="radio"][checked] > label {
color: rgba(255, 255, 255, 1.00);
}
div.collapsible > input.header {
display: block;
width: 100%;
}
div.collapsible > input.header > img {
background: transparent url('collapse_open.png');
}
div.collapsible > input.header[checked] > img {
background: transparent url('collapse_close.png');
}
div.collapsible > div.inside {
display: block;
margin-top: 2px;
margin-left: 16px;
}
div.collapsible > div.inside.collapsed {
display: none;
}
/*******************/
/* MARKDOWN */
div.mdown {
margin: 2px;
border: 1px rgba(0,0,0,0.5);
padding: 4px 4px 4px 4px;
/*padding: 4px 4px 16px 4px;*/
background: rgba(0,0,0,0.25);
}
div.mdown div {
margin: 0;
padding: 0;
border: 0;
}
div.mdown span {
margin: 0;
padding: 0;
border: 0;
}
table {
width: 100%;
display: table;
background: rgba(0,0,0,0.2);
border: 1px rgba(0,0,0,1);
margin: 0px 10px;
padding: 4px;
}
tr {
width: 100%;
display: table-row;
margin: 0px 0px;
border: 0px;
padding: 0px 2px;
}
th {
display: table-cell;
margin: 0px;
border: 0px;
padding: 2px;
}
td {
display: table-cell;
margin: 0px;
border: 0px;
padding: 2px;
}
div.mdown h1 {
width: 100%;
margin: 0px 4px 4px 4px;
padding: 4px 4px 4px 12px;
border: 0px;
}
div.mdown h1 > span {
font-size: 24;
font-weight: bold;
text-shadow: 2px 2px rgba(0,0,0,0.5);
}
div.mdown h2 {
width: 100%;
margin: 8px 4px 4px 4px;
padding: 4px 4px 4px 12px;
border: 1px transparent;
border-bottom-color: rgba(255, 255, 255, 0.25);
border-radius: 0px;
}
div.mdown h2 > span {
font-size: 18;
font-weight: bold;
text-shadow: 2px 2px rgba(0,0,0,0.5);
}
div.mdown h3 {
width: 100%;
margin: 8px 4px 4px 4px;
padding: 4px 4px 4px 12px;
border: 1px transparent;
border-bottom-color: rgba(255, 255, 255, 0.125);
border-radius: 0px;
}
div.mdown h3 > span {
font-size: 15;
font-weight: bold;
text-shadow: 2px 2px rgba(0,0,0,0.5);
}
div.mdown img {
display: block;
width: 100%;
border: 0px rgba(0, 0, 0, 0.25);
border-radius: 4px;
padding: 0px;
}
div.mdown p { }
div.mdown i {
margin: 0px;
padding: 0px;
border: 0px;
font-style: italic;
}
div.mdown b {
margin: 0px;
padding: 0px;
border: 0px;
font-weight: bold;
}
div.mdown pre {
font-family: monospace;
white-space: pre;
margin: 0px;
padding: 0px 4px;
background-color: rgba(255, 255, 255, 0.25);
}
div.mdown code {
font-family: monospace;
white-space: pre;
margin: 0px;
padding: 0px 4px;
background-color: rgba(255, 255, 255, 0.25);
}
div.mdown ul {
margin: 0px;
border: 0px;
padding: 0px;
display: block;
}
div.mdown ul > li {
/*margin: 8px 0px;*/
margin: 0px;
border: 0px;
padding: 0px;
padding: 0px 0px 0px 8px;
display: block;
}
div.mdown ul > li > img.dot {
display: inline;
margin: 5px 10px 0px 5px;
border: 0px;
padding: 0px;
width: 20px;
height: 10px;
}
div.mdown ul > li > span.text {
margin: 0px;
border: 0px;
padding: 0px;
display: inline;
}
div.mdown ol {
margin: 0px;
border: 0px;
padding: 0px;
display: block;
}
div.mdown ol > li {
/*margin: 8px 0px;*/
margin: 0px;
border: 0px;
padding: 0px;
padding: 0px 0px 0px 8px;
display: block;
}
div.mdown ol > li > span.number {
display: inline;
margin: 0px;
border: 0px;
padding: 0px;
width: 20px;
/*height: 10px;*/
}
div.mdown ol > li > span.text {
margin: 0px 0px 0px 8px;
border: 0px;
padding: 0px;
display: inline;
}
div.mdown a {
padding: -1px;
margin: 0px;
border: 1px transparent;
border-radius: 0px;
border-bottom-color: rgba(255,255,255,0.5);
cursor: pointer;
}
div.mdown img.inline {
display: inline;
border: 0px;
}
/**********************/
/* INPUT TEXT */
*.inputtext-container {
margin: 0px;
position: relative; /*relative;*/
left: 0px;
top: 0px;
width: 100%;
min-height: 28px;
padding: 0px;
display: block;
background: rgba(160,160,160, 0.50);
/*background-color: rgba(255,255,255,0.5);*/
border-width: 1px;
border-radius: 4px;
border-color: black;
}
*.inputtext-container:hover {
background-color: rgba(160,160,160,1.00);
}
*.inputtext-container > *.inputtext-input {
position: relative; /* necessary for cursor! */
left: 0px;
top: 0px;
background-color: transparent;
white-space: pre;
display: block;
width: 100%;
min-height: 26px;
margin: 0px;
padding: 3px;
border-width: 2px;
border-color: transparent;
color: black;
overflow-x: scroll;
cursor: text;
}
*.inputtext-container > *.inputtext-input:focus {
background-color: rgba(255, 255, 255, 1.0);
border-color: hsla(200, 100%, 62.5%, 1.0);
}
*.inputtext-cursor {
position: absolute;
margin: 0px;
padding: 0px;
border-width: 0px;
left: 0px;
top: 0px;
display: none;
color: hsla(200, 100%, 12.5%, 1.0); /* l=62.5% */
}
*.inputtext-input:focus > *.inputtext-cursor {
display: inline;
}
*.labeledinputtext-container {
margin: 2px;
border: 0px;
padding: 0px;
display: block;
width: 100%;
background: transparent;
}
*.labeledinputtext-container > *.labeledinputtext-label-container {
margin: 0px;
border: 0px;
padding: 4px 0px 0px 0px;
display: inline;
width: 50%;
background: transparent;
}
*.labeledinputtext-container > *.labeledinputtext-label-container > *.labeledinputtext-label {
margin: 0px;
border: 0px;
padding: 0px;
display: block;
width: 100%;
background: transparent;
}
*.labeledinputtext-container > *.labeledinputtext-input-container {
margin: 0px;
border: 0px;
padding: 0px;
display: inline;
width: 50%;
}
*.labeledinputtext-container > *.labeledinputtext-input-container > *.inputtext-container {
margin: 0px;
border: 0px;
padding: 0px;
display: block;
width: 100%;
/*max-height: 22px;*/
height: 26px;
}
*.labeledinputtext-container > *.labeledinputtext-input-container > *.inputtext-container > *.inputtext-input {
margin: 0px;
white-space: pre;
}
body > dialog.tooltip {
z-index: 100000;
position: fixed;
/*display: block;*/
border: 1px black;
background: rgba(64,64,64, 0.95);
color: white;
margin: 2px;
padding: 4px;
width: auto;
min-width: 0px;
max-width: 300px;
}
@@ -0,0 +1,207 @@
'''
Copyright (C) 2014 Plasmasolutions
software@plasmasolutions.de
Created by Thomas Beck
Donated to CGCookie and the world
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/>.
'''
'''
Note: not all of the following code was provided by Plasmasolutions
TODO: split into separate files?
'''
# System imports
import os
import sys
import time
import inspect
import itertools
import linecache
import traceback
from datetime import datetime
from hashlib import md5
from .globals import Globals
from .blender import show_blender_popup
from .hasher import Hasher
class Debugger:
_error_level = 1
_exception_count = 0
def __init__(self):
pass
@staticmethod
def set_error_level(l):
Debugger._error_level = max(0, min(5, int(l)))
@staticmethod
def get_error_level():
return Debugger._error_level
@staticmethod
def dprint(*objects, sep=' ', end='\n', file=sys.stdout, flush=True, l=2):
if Debugger._error_level < l: return
sobjects = sep.join(str(o) for o in objects)
print(
'DEBUG(%i): %s' % (l, sobjects),
end=end, file=file, flush=flush
)
@staticmethod
def dcallstack(l=2):
''' print out the calling stack, skipping the first (call to dcallstack) '''
Debugger.dprint('Call Stack Dump:', l=l)
for i, entry in enumerate(inspect.stack()):
if i > 0:
Debugger.dprint(' %s' % str(entry), l=l)
# http://stackoverflow.com/questions/14519177/python-exception-handling-line-number
@staticmethod
def get_exception_info_and_hash():
'''
this function is a duplicate of the one above, but this will attempt
to create a hash to make searching for duplicate bugs on github easier (?)
'''
exc_type, exc_obj, tb = sys.exc_info()
pathabs, pathdir = os.path.abspath, os.path.dirname
pathjoin, pathsplit = os.path.join, os.path.split
base_path = pathabs(pathjoin(pathdir(__file__), '..'))
hasher = Hasher()
errormsg = ['EXCEPTION (%s): %s' % (exc_type, exc_obj)]
hasher.add(errormsg[0])
# errormsg += ['Base: %s' % base_path]
etb = traceback.extract_tb(tb)
pfilename = None
for i,entry in enumerate(reversed(etb)):
filename,lineno,funcname,line = entry
if pfilename is None:
# only hash in details of where the exception occurred
hasher.add(os.path.split(filename)[1])
# hasher.add(lineno)
hasher.add(funcname)
hasher.add(line.strip())
if filename != pfilename:
pfilename = filename
if filename.startswith(base_path):
filename = '.../%s' % filename[len(base_path)+1:]
errormsg += [' %s' % (filename, )]
errormsg += ['%03d %04d:%s() %s' % (i, lineno, funcname, line.strip())]
return ('\n'.join(errormsg), hasher.get_hash())
@staticmethod
def print_exception():
Debugger._exception_count += 1
errormsg, errorhash = Debugger.get_exception_info_and_hash()
message = []
message += ['Exception Info']
message += ['- Time: %s' % datetime.today().isoformat(' ')]
message += ['- Count: %d' % Debugger._exception_count]
message += ['- Hash: %s' % str(errorhash)]
message += ['- Info:']
message += [' - %s' % s for s in errormsg.splitlines()]
message = '\n'.join(message)
print('%s\n%s\n%s' % ('_' * 100, message, '^' * 100))
logger = Globals.logger
if logger: logger.add(message) # write error to log text object
# if Debugger._exception_count < 10:
# show_blender_popup(
# message,
# title='Exception Info',
# icon='ERROR',
# wrap=240
# )
return message
# @staticmethod
# def print_exception2():
# exc_type, exc_value, exc_traceback = sys.exc_info()
# print("*** print_tb:")
# traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
# print("*** print_exception:")
# traceback.print_exception(exc_type, exc_value, exc_traceback,
# limit=2, file=sys.stdout)
# print("*** print_exc:")
# traceback.print_exc()
# print("*** format_exc, first and last line:")
# formatted_lines = traceback.format_exc().splitlines()
# print(formatted_lines[0])
# print(formatted_lines[-1])
# print("*** format_exception:")
# print(repr(traceback.format_exception(exc_type, exc_value,exc_traceback)))
# print("*** extract_tb:")
# print(repr(traceback.extract_tb(exc_traceback)))
# print("*** format_tb:")
# print(repr(traceback.format_tb(exc_traceback)))
# if exc_traceback:
# print("*** tb_lineno:", exc_traceback.tb_lineno)
class ExceptionHandler:
_universal = []
def __init__(self, universal=False):
self._single = []
self._universal_only = universal
@staticmethod
def add_universal_callback(fn):
ExceptionHandler._universal += [fn]
def add_callback(self, fn, universal=None):
if universal:
self._universal += [fn]
if universal is None and self._universal_only:
self._universal += [fn]
else:
self._single += [fn]
def wrap(self, def_val, only=Exception):
def wrapper(fn):
def wrapped(*args, **kwargs):
ret = def_val
try:
ret = fn(*args, **kwargs)
except only as e:
self.handle_exception(e)
return ret
return wrapped
return wrapper
def handle_exception(self, e):
for fn in itertools.chain(self._universal, self._single):
try:
fn(e)
except Exception as e2:
print('Caught exception while calling back exception callbacks: %s' % fn.__name__)
print('original: %s' % str(e))
print('additional: %s' % str(e2))
debugger.print_exception()
debugger = Debugger()
dprint = debugger.dprint
exceptionhandler = ExceptionHandler(universal=True)
Globals.set(debugger)
Globals.dprint = dprint
Globals.exceptionhandler = exceptionhandler
@@ -0,0 +1,308 @@
'''
Copyright (C) 2020 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson
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/>.
'''
import os
import json
import time
import inspect
import bpy
debug_run_test_calls = False
def debug_test_call(*args, **kwargs):
def wrapper(fn):
if debug_run_test_calls:
ret = str(fn(*args,*kwargs))
print('TEST: %s()' % fn.__name__)
if args:
print(' arg:', args)
if kwargs:
print(' kwa:', kwargs)
print(' ret:', ret)
return fn
return wrapper
def stats_wrapper(fn):
return fn
if not hasattr(stats_report, 'stats'):
stats_report.stats = dict()
frame = inspect.currentframe().f_back
f_locals = frame.f_locals
filename = os.path.basename(frame.f_code.co_filename)
clsname = f_locals['__qualname__'] if '__qualname__' in f_locals else ''
linenum = frame.f_lineno
fnname = fn.__name__
key = '%s%s (%s:%d)' % (
clsname + ('.' if clsname else ''),
fnname, filename, linenum
)
stats = stats_report.stats
stats[key] = {
'filename': filename,
'clsname': clsname,
'linenum': linenum,
'fileline': '%s:%d' % (filename, linenum),
'fnname': fnname,
'count': 0,
'total time': 0,
'average time': 0,
}
def wrapped(*args, **kwargs):
time_beg = time.time()
ret = fn(*args, **kwargs)
time_end = time.time()
time_delta = time_end - time_beg
d = stats[key]
d['count'] += 1
d['total time'] += time_delta
d['average time'] = d['total time'] / d['count']
return ret
return wrapped
def stats_report():
return
stats = stats_report.stats if hasattr(stats_report, 'stats') else dict()
l = max(len(k) for k in stats)
def fmt(s):
return s + ' ' * (l - len(s))
print()
print('Call Statistics Report')
cols = [
('class', 'clsname', '%s'),
('func', 'fnname', '%s'),
('location', 'fileline', '%s'),
# ('line','linenum','% 10d'),
('count', 'count', '% 8d'),
('total (sec)', 'total time', '% 10.4f'),
('avg (sec)', 'average time', '% 10.6f'),
]
data = [stats[k] for k in sorted(stats)]
data = [[h] + [f % row[c] for row in data] for (h, c, f) in cols]
colwidths = [max(len(d) for d in col) for col in data]
totwidth = sum(colwidths) + len(colwidths) - 1
def rpad(s, l):
return '%s%s' % (s, ' ' * (l - len(s)))
def printrow(i_row):
row = [col[i_row] for col in data]
print(' '.join(rpad(d, w) for (d, w) in zip(row, colwidths)))
printrow(0)
print('-' * totwidth)
for i in range(1, len(data[0])):
printrow(i)
class LimitRecursion:
def __init__(self, count, def_ret):
self.count = count
self.def_ret = def_ret
self.calls = 0
def __call__(self, fn):
def wrapped(*args, **kwargs):
ret = self.def_ret
if self.calls < self.count:
try:
self.calls += 1
ret = fn(*args, **kwargs)
finally:
self.calls -= 1
return ret
return wrapped
def timed_call(label):
def wrapper(fn):
def wrapped(*args, **kwargs):
time_beg = time.time()
ret = fn(*args, **kwargs)
time_end = time.time()
time_delta = time_end - time_beg
print('Timing: %0.4fs, %s' % (time_delta, label))
return ret
return wrapped
return wrapper
# corrected bug in previous version of blender_version fn wrapper
# https://github.com/CGCookie/retopoflow/commit/135746c7b4ee0052ad0c1842084b9ab983726b33#diff-d4260a97dcac93f76328dfaeb5c87688
def blender_version_wrapper(op, ver):
self = blender_version_wrapper
if not hasattr(self, 'fns'):
major, minor, rev = bpy.app.version
self.blenderver = '%d.%02d' % (major, minor)
self.fns = fns = {}
self.ops = {
'<': lambda v: self.blenderver < v,
'>': lambda v: self.blenderver > v,
'<=': lambda v: self.blenderver <= v,
'==': lambda v: self.blenderver == v,
'>=': lambda v: self.blenderver >= v,
'!=': lambda v: self.blenderver != v,
}
update_fn = self.ops[op](ver)
def wrapit(fn):
nonlocal self, update_fn
fn_name = fn.__name__
fns = self.fns
error_msg = "Could not find appropriate function named %s for version Blender %s" % (fn_name, self.blenderver)
if update_fn: fns[fn_name] = fn
def callit(*args, **kwargs):
nonlocal fns, fn_name, error_msg
fn = fns.get(fn_name, None)
assert fn, error_msg
ret = fn(*args, **kwargs)
return ret
return callit
return wrapit
class PersistentOptions:
class WrappedDict:
def __init__(self, cls, filename, version, defaults, update_external):
self._dirty = False
self._last_save = time.time()
self._write_delay = 2.0
self._defaults = defaults
self._update_external = update_external
self._defaults['persistent options version'] = version
self._dict = {}
if filename:
src = inspect.getsourcefile(cls)
path = os.path.split(os.path.abspath(src))[0]
self._fndb = os.path.join(path, filename)
else:
self._fndb = None
self.read()
if self._dict.get('persistent options version', None) != version:
self.reset()
self.update_external()
def update_external(self):
upd = self._update_external
if upd:
upd()
def dirty(self):
self._dirty = True
self.update_external()
def clean(self, force=False):
if not force:
if not self._dirty:
return
if time.time() < self._last_save + self._write_delay:
return
if self._fndb:
json.dump(self._dict, open(self._fndb, 'wt'), indent=2, sort_keys=True)
self._dirty = False
self._last_save = time.time()
def read(self):
self._dict = {}
if self._fndb and os.path.exists(self._fndb):
try:
self._dict = json.load(open(self._fndb, 'rt'))
except Exception as e:
print('Exception caught while trying to read options from "%s"' % self._fndb)
print(str(e))
for k in set(self._dict.keys()) - set(self._defaults.keys()):
print('Deleting extraneous key "%s" from options' % k)
del self._dict[k]
self.update_external()
self._dirty = False
def keys(self):
return self._defaults.keys()
def reset(self):
keys = list(self._dict.keys())
for k in keys:
del self._dict[k]
self._dict['persistent options version'] = self['persistent options version']
self.dirty()
self.clean()
def __getitem__(self, key):
return self._dict[key] if key in self._dict else self._defaults[key]
def __setitem__(self, key, val):
assert key in self._defaults, 'Attempting to write "%s":"%s" to options, but key does not exist in defaults' % (str(key), str(val))
if self[key] == val: return
self._dict[key] = val
self.dirty()
self.clean()
def gettersetter(self, key, fn_get_wrap=None, fn_set_wrap=None):
if not fn_get_wrap: fn_get_wrap = lambda v: v
if not fn_set_wrap: fn_set_wrap = lambda v: v
oself = self
class GetSet:
def get(self):
return fn_get_wrap(oself[key])
def set(self, v):
v = fn_set_wrap(v)
if oself[key] != v:
oself[key] = v
return GetSet()
def __init__(self, filename=None, version=None):
self._filename = filename
self._version = version
self._db = None
def __call__(self, cls):
upd = getattr(cls, 'update', None)
if upd:
u = upd
def wrap():
def upd_wrap(*args, **kwargs):
u(None)
return upd_wrap
upd = wrap()
self._db = PersistentOptions.WrappedDict(cls, self._filename, self._version, cls.defaults, upd)
db = self._db
class WrappedClass:
def __init__(self, *args, **kwargs):
self._db = db
self._def = cls.defaults
def __getitem__(self, key):
return self._db[key]
def __setitem__(self, key, val):
self._db[key] = val
def keys(self):
return self._db.keys()
def reset(self):
self._db.reset()
def clean(self):
self._db.clean()
def gettersetter(self, key, fn_get_wrap=None, fn_set_wrap=None):
return self._db.gettersetter(key, fn_get_wrap=fn_get_wrap, fn_set_wrap=fn_set_wrap)
return WrappedClass
@@ -0,0 +1,191 @@
'''
Copyright (C) 2020 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson
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/>.
'''
import bpy
import blf
from .debug import dprint
from .blender import get_preferences
from .profiler import profiler
# https://docs.blender.org/api/current/blf.html
class FontManager:
_cache = {0:0}
_last_fontid = 0
_prefs = get_preferences()
@staticmethod
@property
def last_fontid(): return FontManager._last_fontid
@staticmethod
def get_dpi():
ui_scale = FontManager._prefs.view.ui_scale
pixel_size = FontManager._prefs.system.pixel_size
dpi = 72 # FontManager._prefs.system.dpi
return int(dpi * ui_scale * pixel_size)
@staticmethod
@profiler.function
def load(val, load_callback=None):
if val is None:
fontid = FontManager._last_fontid
else:
if val not in FontManager._cache:
# note: loading the same file multiple times is not a problem.
# blender is smart enough to cache
fontid = blf.load(val)
print('Loaded font "%s" as id %d' % (val, fontid))
FontManager._cache[val] = fontid
FontManager._cache[fontid] = fontid
if load_callback: load_callback(fontid)
fontid = FontManager._cache[val]
FontManager._last_fontid = fontid
return fontid
@staticmethod
def unload_fontids():
for name,fontid in FontManager._cache.items():
print('Unloading font "%s" as id %d' % (name, fontid))
blf.unload(name)
FontManager._cache = {}
FontManager._last_fontid = 0
@staticmethod
def unload(filename):
assert filename in FontManager._cache
fontid = FontManager._cache[filename]
dprint('Unloading font "%s" as id %d' % (filename, fontid))
blf.unload(filename)
del FontManager._cache[filename]
if fontid == FontManager._last_fontid:
FontManager._last_fontid = 0
@staticmethod
def aspect(aspect, fontid=None):
return blf.aspect(FontManager.load(fontid), aspect)
@staticmethod
def blur(radius, fontid=None):
return blf.blur(FontManager.load(fontid), radius)
@staticmethod
def clipping(xymin, xymax, fontid=None):
return blf.clipping(FontManager.load(fontid), *xymin, *xymax)
@staticmethod
def color(color, fontid=None):
blf.color(FontManager.load(fontid), *color)
@staticmethod
def dimensions(text, fontid=None):
return blf.dimensions(FontManager.load(fontid), text)
@staticmethod
def disable(option, fontid=None):
return blf.disable(FontManager.load(fontid), option)
@staticmethod
def disable_rotation(fontid=None):
return blf.disable(FontManager.load(fontid), blf.ROTATION)
@staticmethod
def disable_clipping(fontid=None):
return blf.disable(FontManager.load(fontid), blf.CLIPPING)
@staticmethod
def disable_shadow(fontid=None):
return blf.disable(FontManager.load(fontid), blf.SHADOW)
@staticmethod
def disable_kerning_default(fontid=None):
# note: not a listed option in docs for `blf.disable`, but see `blf.word_wrap`
return blf.disable(FontManager.load(fontid), blf.KERNING_DEFAULT)
@staticmethod
def disable_word_wrap(fontid=None):
return blf.disable(FontManager.load(fontid), blf.WORD_WRAP)
@staticmethod
def draw(text, xyz=None, fontsize=None, dpi=None, fontid=None):
fontid = FontManager.load(fontid)
if xyz: blf.position(fontid, *xyz)
if fontsize: FontManager.size(fontsize, dpi=dpi, fontid=fontid)
return blf.draw(fontid, text)
@staticmethod
def draw_simple(text, xyz):
fontid = FontManager._last_fontid
blf.position(fontid, *xyz)
return blf.draw(fontid, text)
@staticmethod
def enable(option, fontid=None):
return blf.enable(FontManager.load(fontid), option)
@staticmethod
def enable_rotation(fontid=None):
return blf.enable(FontManager.load(fontid), blf.ROTATION)
@staticmethod
def enable_clipping(fontid=None):
return blf.enable(FontManager.load(fontid), blf.CLIPPING)
@staticmethod
def enable_shadow(fontid=None):
return blf.enable(FontManager.load(fontid), blf.SHADOW)
@staticmethod
def enable_kerning_default(fontid=None):
return blf.enable(FontManager.load(fontid), blf.KERNING_DEFAULT)
@staticmethod
def enable_word_wrap(fontid=None):
# note: not a listed option in docs for `blf.enable`, but see `blf.word_wrap`
return blf.enable(FontManager.load(fontid), blf.WORD_WRAP)
@staticmethod
def position(xyz, fontid=None):
return blf.position(FontManager.load(fontid), *xyz)
@staticmethod
def rotation(angle, fontid=None):
return blf.rotation(FontManager.load(fontid), angle)
@staticmethod
def shadow(level, rgba, fontid=None):
return blf.shadow(FontManager.load(fontid), level, *rgba)
@staticmethod
def shadow_offset(xy, fontid=None):
return blf.shadow_offset(FontManager.load(fontid), *xy)
@staticmethod
def size(size, dpi=None, fontid=None):
if not dpi: dpi = FontManager.get_dpi()
return blf.size(FontManager.load(fontid), size, dpi)
@staticmethod
def word_wrap(wrap_width, fontid=None):
return blf.word_wrap(FontManager.load(fontid), wrap_width)
@@ -0,0 +1,187 @@
Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
Glyphs imported from Arev fonts are (c) Tavmjong Bah (see below)
Bitstream Vera Fonts Copyright
------------------------------
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is
a trademark of Bitstream, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of the fonts accompanying this license ("Fonts") and associated
documentation files (the "Font Software"), to reproduce and distribute the
Font Software, including without limitation the rights to use, copy, merge,
publish, distribute, and/or sell copies of the Font Software, and to permit
persons to whom the Font Software is furnished to do so, subject to the
following conditions:
The above copyright and trademark notices and this permission notice shall
be included in all copies of one or more of the Font Software typefaces.
The Font Software may be modified, altered, or added to, and in particular
the designs of glyphs or characters in the Fonts may be modified and
additional glyphs or characters may be added to the Fonts, only if the fonts
are renamed to names not containing either the words "Bitstream" or the word
"Vera".
This License becomes null and void to the extent applicable to Fonts or Font
Software that has been modified and is distributed under the "Bitstream
Vera" names.
The Font Software may be sold as part of a larger software package but no
copy of one or more of the Font Software typefaces may be sold by itself.
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING
ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE
FONT SOFTWARE.
Except as contained in this notice, the names of Gnome, the Gnome
Foundation, and Bitstream Inc., shall not be used in advertising or
otherwise to promote the sale, use or other dealings in this Font Software
without prior written authorization from the Gnome Foundation or Bitstream
Inc., respectively. For further information, contact: fonts at gnome dot
org.
Arev Fonts Copyright
------------------------------
Copyright (c) 2006 by Tavmjong Bah. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining
a copy of the fonts accompanying this license ("Fonts") and
associated documentation files (the "Font Software"), to reproduce
and distribute the modifications to the Bitstream Vera Font Software,
including without limitation the rights to use, copy, merge, publish,
distribute, and/or sell copies of the Font Software, and to permit
persons to whom the Font Software is furnished to do so, subject to
the following conditions:
The above copyright and trademark notices and this permission notice
shall be included in all copies of one or more of the Font Software
typefaces.
The Font Software may be modified, altered, or added to, and in
particular the designs of glyphs or characters in the Fonts may be
modified and additional glyphs or characters may be added to the
Fonts, only if the fonts are renamed to names not containing either
the words "Tavmjong Bah" or the word "Arev".
This License becomes null and void to the extent applicable to Fonts
or Font Software that has been modified and is distributed under the
"Tavmjong Bah Arev" names.
The Font Software may be sold as part of a larger software package but
no copy of one or more of the Font Software typefaces may be sold by
itself.
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL
TAVMJONG BAH BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Except as contained in this notice, the name of Tavmjong Bah shall not
be used in advertising or otherwise to promote the sale, use or other
dealings in this Font Software without prior written authorization
from Tavmjong Bah. For further information, contact: tavmjong @ free
. fr.
TeX Gyre DJV Math
-----------------
Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
Math extensions done by B. Jackowski, P. Strzelczyk and P. Pianowski
(on behalf of TeX users groups) are in public domain.
Letters imported from Euler Fraktur from AMSfonts are (c) American
Mathematical Society (see below).
Bitstream Vera Fonts Copyright
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera
is a trademark of Bitstream, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of the fonts accompanying this license (“Fonts”) and associated
documentation
files (the “Font Software”), to reproduce and distribute the Font Software,
including without limitation the rights to use, copy, merge, publish,
distribute,
and/or sell copies of the Font Software, and to permit persons to whom
the Font Software is furnished to do so, subject to the following
conditions:
The above copyright and trademark notices and this permission notice
shall be
included in all copies of one or more of the Font Software typefaces.
The Font Software may be modified, altered, or added to, and in particular
the designs of glyphs or characters in the Fonts may be modified and
additional
glyphs or characters may be added to the Fonts, only if the fonts are
renamed
to names not containing either the words “Bitstream” or the word “Vera”.
This License becomes null and void to the extent applicable to Fonts or
Font Software
that has been modified and is distributed under the “Bitstream Vera”
names.
The Font Software may be sold as part of a larger software package but
no copy
of one or more of the Font Software typefaces may be sold by itself.
THE FONT SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
FOUNDATION
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL,
SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN
ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR
INABILITY TO USE
THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
Except as contained in this notice, the names of GNOME, the GNOME
Foundation,
and Bitstream Inc., shall not be used in advertising or otherwise to promote
the sale, use or other dealings in this Font Software without prior written
authorization from the GNOME Foundation or Bitstream Inc., respectively.
For further information, contact: fonts at gnome dot org.
AMSFonts (v. 2.2) copyright
The PostScript Type 1 implementation of the AMSFonts produced by and
previously distributed by Blue Sky Research and Y&Y, Inc. are now freely
available for general use. This has been accomplished through the
cooperation
of a consortium of scientific publishers with Blue Sky Research and Y&Y.
Members of this consortium include:
Elsevier Science IBM Corporation Society for Industrial and Applied
Mathematics (SIAM) Springer-Verlag American Mathematical Society (AMS)
In order to assure the authenticity of these fonts, copyright will be
held by
the American Mathematical Society. This is not meant to restrict in any way
the legitimate use of the fonts, such as (but not limited to) electronic
distribution of documents containing these fonts, inclusion of these fonts
into other public domain or commercial font collections or computer
applications, use of the outline data to create derivative fonts and/or
faces, etc. However, the AMS does require that the AMS copyright notice be
removed from any derivative versions of the fonts which have been altered in
any way. In addition, to ensure the fidelity of TeX documents using Computer
Modern fonts, Professor Donald Knuth, creator of the Computer Modern faces,
has requested that any alterations which yield different font metrics be
given a different name.
$Id$
@@ -0,0 +1,36 @@
[remap]
importer="font_data_dynamic"
type="FontFile"
uid="uid://bmmgqg7nbr8s1"
path="res://.godot/imported/DejaVuSansMono.ttf-9473a9afeb5256655db966735ffe8a36.fontdata"
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/fonts/DejaVuSansMono.ttf"
dest_files=["res://.godot/imported/DejaVuSansMono.ttf-9473a9afeb5256655db966735ffe8a36.fontdata"]
[params]
Rendering=null
antialiasing=1
generate_mipmaps=false
disable_embedded_bitmaps=true
multichannel_signed_distance_field=false
msdf_pixel_range=8
msdf_size=48
allow_system_fallback=true
force_autohinter=false
modulate_color_glyphs=false
hinting=1
subpixel_positioning=4
keep_rounding_remainders=true
oversampling=0.0
Fallbacks=null
fallbacks=[]
Compress=null
compress=true
preload=[]
language_support={}
script_support={}
opentype_features={}
@@ -0,0 +1,36 @@
[remap]
importer="font_data_dynamic"
type="FontFile"
uid="uid://ds727vulau017"
path="res://.godot/imported/DroidSans-Blender.ttf-cc77a71279c3297693dfda8e50c4884b.fontdata"
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/fonts/DroidSans-Blender.ttf"
dest_files=["res://.godot/imported/DroidSans-Blender.ttf-cc77a71279c3297693dfda8e50c4884b.fontdata"]
[params]
Rendering=null
antialiasing=1
generate_mipmaps=false
disable_embedded_bitmaps=true
multichannel_signed_distance_field=false
msdf_pixel_range=8
msdf_size=48
allow_system_fallback=true
force_autohinter=false
modulate_color_glyphs=false
hinting=1
subpixel_positioning=4
keep_rounding_remainders=true
oversampling=0.0
Fallbacks=null
fallbacks=[]
Compress=null
compress=true
preload=[]
language_support={}
script_support={}
opentype_features={}
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -0,0 +1,36 @@
[remap]
importer="font_data_dynamic"
type="FontFile"
uid="uid://b8tr0wisw4krr"
path="res://.godot/imported/DroidSerif-Bold.ttf-ef32e6fb45bb6c05d157fff9bfde1b5f.fontdata"
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/fonts/DroidSerif-Bold.ttf"
dest_files=["res://.godot/imported/DroidSerif-Bold.ttf-ef32e6fb45bb6c05d157fff9bfde1b5f.fontdata"]
[params]
Rendering=null
antialiasing=1
generate_mipmaps=false
disable_embedded_bitmaps=true
multichannel_signed_distance_field=false
msdf_pixel_range=8
msdf_size=48
allow_system_fallback=true
force_autohinter=false
modulate_color_glyphs=false
hinting=1
subpixel_positioning=4
keep_rounding_remainders=true
oversampling=0.0
Fallbacks=null
fallbacks=[]
Compress=null
compress=true
preload=[]
language_support={}
script_support={}
opentype_features={}
@@ -0,0 +1,36 @@
[remap]
importer="font_data_dynamic"
type="FontFile"
uid="uid://fw383rqv41a8"
path="res://.godot/imported/DroidSerif-BoldItalic.ttf-ad2d338c3ffb1a735fd68773d3495290.fontdata"
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/fonts/DroidSerif-BoldItalic.ttf"
dest_files=["res://.godot/imported/DroidSerif-BoldItalic.ttf-ad2d338c3ffb1a735fd68773d3495290.fontdata"]
[params]
Rendering=null
antialiasing=1
generate_mipmaps=false
disable_embedded_bitmaps=true
multichannel_signed_distance_field=false
msdf_pixel_range=8
msdf_size=48
allow_system_fallback=true
force_autohinter=false
modulate_color_glyphs=false
hinting=1
subpixel_positioning=4
keep_rounding_remainders=true
oversampling=0.0
Fallbacks=null
fallbacks=[]
Compress=null
compress=true
preload=[]
language_support={}
script_support={}
opentype_features={}
@@ -0,0 +1,36 @@
[remap]
importer="font_data_dynamic"
type="FontFile"
uid="uid://dgaib2r77e71v"
path="res://.godot/imported/DroidSerif-Italic.ttf-0300d734521c33629cf34234e1897171.fontdata"
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/fonts/DroidSerif-Italic.ttf"
dest_files=["res://.godot/imported/DroidSerif-Italic.ttf-0300d734521c33629cf34234e1897171.fontdata"]
[params]
Rendering=null
antialiasing=1
generate_mipmaps=false
disable_embedded_bitmaps=true
multichannel_signed_distance_field=false
msdf_pixel_range=8
msdf_size=48
allow_system_fallback=true
force_autohinter=false
modulate_color_glyphs=false
hinting=1
subpixel_positioning=4
keep_rounding_remainders=true
oversampling=0.0
Fallbacks=null
fallbacks=[]
Compress=null
compress=true
preload=[]
language_support={}
script_support={}
opentype_features={}
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -0,0 +1,36 @@
[remap]
importer="font_data_dynamic"
type="FontFile"
uid="uid://dum8i52r5h8w8"
path="res://.godot/imported/DroidSerif-Regular.ttf-8f6ab78663a71ae56017e987555e359b.fontdata"
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/fonts/DroidSerif-Regular.ttf"
dest_files=["res://.godot/imported/DroidSerif-Regular.ttf-8f6ab78663a71ae56017e987555e359b.fontdata"]
[params]
Rendering=null
antialiasing=1
generate_mipmaps=false
disable_embedded_bitmaps=true
multichannel_signed_distance_field=false
msdf_pixel_range=8
msdf_size=48
allow_system_fallback=true
force_autohinter=false
modulate_color_glyphs=false
hinting=1
subpixel_positioning=4
keep_rounding_remainders=true
oversampling=0.0
Fallbacks=null
fallbacks=[]
Compress=null
compress=true
preload=[]
language_support={}
script_support={}
opentype_features={}
@@ -0,0 +1,36 @@
[remap]
importer="font_data_dynamic"
type="FontFile"
uid="uid://f2met102d8kf"
path="res://.godot/imported/OpenSans-Bold.ttf-26a83e22ca716592c6214beb2b32f98b.fontdata"
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/fonts/OpenSans-Bold.ttf"
dest_files=["res://.godot/imported/OpenSans-Bold.ttf-26a83e22ca716592c6214beb2b32f98b.fontdata"]
[params]
Rendering=null
antialiasing=1
generate_mipmaps=false
disable_embedded_bitmaps=true
multichannel_signed_distance_field=false
msdf_pixel_range=8
msdf_size=48
allow_system_fallback=true
force_autohinter=false
modulate_color_glyphs=false
hinting=1
subpixel_positioning=4
keep_rounding_remainders=true
oversampling=0.0
Fallbacks=null
fallbacks=[]
Compress=null
compress=true
preload=[]
language_support={}
script_support={}
opentype_features={}
@@ -0,0 +1,36 @@
[remap]
importer="font_data_dynamic"
type="FontFile"
uid="uid://cf10mnibtohxv"
path="res://.godot/imported/OpenSans-BoldItalic.ttf-de4b83fd85b8c2809b5e602bca653d95.fontdata"
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/fonts/OpenSans-BoldItalic.ttf"
dest_files=["res://.godot/imported/OpenSans-BoldItalic.ttf-de4b83fd85b8c2809b5e602bca653d95.fontdata"]
[params]
Rendering=null
antialiasing=1
generate_mipmaps=false
disable_embedded_bitmaps=true
multichannel_signed_distance_field=false
msdf_pixel_range=8
msdf_size=48
allow_system_fallback=true
force_autohinter=false
modulate_color_glyphs=false
hinting=1
subpixel_positioning=4
keep_rounding_remainders=true
oversampling=0.0
Fallbacks=null
fallbacks=[]
Compress=null
compress=true
preload=[]
language_support={}
script_support={}
opentype_features={}
@@ -0,0 +1,36 @@
[remap]
importer="font_data_dynamic"
type="FontFile"
uid="uid://bsfmfmc4au5i0"
path="res://.godot/imported/OpenSans-Italic.ttf-64c93be2542a4168277c84ad9401c400.fontdata"
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/fonts/OpenSans-Italic.ttf"
dest_files=["res://.godot/imported/OpenSans-Italic.ttf-64c93be2542a4168277c84ad9401c400.fontdata"]
[params]
Rendering=null
antialiasing=1
generate_mipmaps=false
disable_embedded_bitmaps=true
multichannel_signed_distance_field=false
msdf_pixel_range=8
msdf_size=48
allow_system_fallback=true
force_autohinter=false
modulate_color_glyphs=false
hinting=1
subpixel_positioning=4
keep_rounding_remainders=true
oversampling=0.0
Fallbacks=null
fallbacks=[]
Compress=null
compress=true
preload=[]
language_support={}
script_support={}
opentype_features={}
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -0,0 +1,191 @@
'''
Copyright (C) 2020 CG Cookie
https://github.com/CGCookie/retopoflow
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/>.
'''
import inspect
from .debug import ExceptionHandler
from .debug import debugger
from .utils import find_fns
def get_state(state, substate):
return '%s__%s' % (str(state), str(substate))
class FSM:
def __init__(self):
self.wrapper = self._create_wrapper()
self.onlyinstate_wrapper = self._create_onlyinstate_wrapper()
self._exceptionhandler = ExceptionHandler()
def add_exception_callback(self, fn, universal=True):
self._exceptionhandler.add_callback(fn, universal=universal)
def _create_wrapper(self):
fsm = self
seen = set()
class FSM_State:
def __init__(self, state, substate='main'):
self.state = state
self.substate = substate
def __call__(self, fn):
self.fn = fn
self.fnname = fn.__name__
if self.fnname in seen:
print('FSM Warning: detected multiple functions with same name: "%s"' % self.fnname)
st = inspect.stack()
f = st[1]
print(' %s:%d' % (f.filename, f.lineno))
seen.add(self.fnname)
def run(*args, **kwargs):
try:
return fn(*args, **kwargs)
except Exception as e:
print('Caught exception in function "%s" ("%s", "%s")' % (
self.fnname, self.state, self.substate
))
debugger.print_exception()
print(e)
fsm._exceptionhandler.handle_exception(e)
fsm.force_set_state(fsm._reset_state, call_exit=False, call_enter=True)
return
run.fnname = self.fnname
run.fsmstate = self.state
run.fsmstate_full = get_state(self.state, self.substate)
# print('%s: registered %s as %s' % (str(fsm), self.fnname, run.fsmstate_full))
return run
return FSM_State
def _create_onlyinstate_wrapper(self):
fsm = self
class FSM_OnlyInState:
def __init__(self, states, default=None):
if type(states) is str: states = {states}
else: states = set(states)
self.states = states
self.default = default
def __call__(self, fn):
self.fn = fn
self.fnname = fn.__name__
def run(*args, **kwargs):
if fsm.state not in self.states:
return self.default
try:
return fn(*args, **kwargs)
except Exception as e:
print('Caught exception in function "%s" ("%s")' % (
self.fnname, fsm.state
))
debugger.print_exception()
print(e)
fsm._exceptionhandler.handle_exception(e)
fsm.force_set_state(fsm._reset_state, call_exit=False, call_enter=True)
return self.default
run.fnname = self.fnname
run.fsmstate = ' '.join(self.states)
return run
return FSM_OnlyInState
def init(self, obj, start='main', reset_state='main'):
self._obj = obj
self._state_next = start
self._state = None
self._reset_state = reset_state
self._fsm_states = {}
self._fsm_states_handled = { st for (st,fn) in find_fns(self._obj, 'fsmstate') }
for (m,fn) in find_fns(self._obj, 'fsmstate_full'):
assert m not in self._fsm_states, 'Duplicate states registered!'
self._fsm_states[m] = fn
# print('%s: found fn %s as %s' % (str(self), str(fn), m))
def _call(self, state, substate='main', fail_if_not_exist=False):
s = get_state(state, substate)
if s not in self._fsm_states:
assert not fail_if_not_exist, 'Could not find state "%s" with substate "%s" (%s)' % (state, substate, str(s))
return
try:
return self._fsm_states[s](self._obj)
except Exception as e:
print('Caught exception in state ("%s")' % (s))
debugger.print_exception()
self._exceptionhandler.hondle_exception(e)
return
def update(self):
if self._state_next is not None and self._state_next != self._state:
if self._call(self._state, substate='can exit') == False:
# print('Cannot exit %s' % str(self._state))
self._state_next = None
return
if self._call(self._state_next, substate='can enter') == False:
# print('Cannot enter %s' % str(self._state_next))
self._state_next = None
return
# print('%s -> %s' % (str(self._state), str(self._state_next)))
self._call(self._state, substate='exit')
self._state = self._state_next
self._call(self._state, substate='enter')
ret = self._call(self._state, fail_if_not_exist=True)
if ret is None:
self._state_next = ret
ret = None
elif type(ret) is str:
if self.is_state(ret):
self._state_next = ret
ret = None
else:
self._state_next = None
ret = ret
elif type(ret) is tuple:
st = {s for s in ret if self.is_state(s)}
if len(st) == 0:
self._state_next = None
ret = ret
elif len(st) == 1:
self._state_next = next(st)
ret = ret - st
else:
assert False, 'unhandled FSM return value "%s"' % str(ret)
else:
assert False, 'unhandled FSM return value "%s"' % str(ret)
return ret
def is_state(self, state):
return state in self._fsm_states_handled
@property
def state(self):
return self._state
def force_set_state(self, state, call_exit=False, call_enter=True):
if call_exit: self._call(self._state, substate='exit')
self._state = state
self._state_next = state
if call_enter: self._call(self._state, substate='enter')
def FSMClass(cls):
cls.fsm = FSM()
cls.FSM_State = cls.fsm.wrapper
return cls
# https://krzysztofzuraw.com/blog/2016/python-class-decorators.html
# class Wrapper(object):
# def __init__(self, *args, **kwargs):
# self._wrapped = cls(*args, **kwargs)
@@ -0,0 +1,52 @@
'''
Copyright (C) 2020 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson
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/>.
'''
'''
This code helps prevent circular importing.
Each of the main common objects are referenced here.
'''
class GlobalsMeta(type):
# allows for `Globals.drawing` instead of `Globals.get('drawing')`
def __setattr__(self, name, value):
self.set(value, objtype=name)
def __getattr__(self, objtype):
return self.get(objtype)
class Globals(metaclass=GlobalsMeta):
__vars = {}
@staticmethod
def set(obj, objtype=None):
Globals.__vars[objtype or type(obj).__name__.lower()] = obj
return obj
@staticmethod
def is_set(objtype):
return Globals.__vars.get(objtype, None) is not None
@staticmethod
def get(objtype):
return Globals.__vars.get(objtype, None)
@staticmethod
def __getattr__(objtype):
return Globals.get(objtype)
@@ -0,0 +1,136 @@
'''
Copyright (C) 2020 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson
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/>.
'''
import time
from hashlib import md5
import bpy
from bmesh.types import BMesh, BMVert, BMEdge, BMFace
from mathutils import Vector, Matrix
from .maths import (
Point, Direction, Normal, Frame,
Point2D, Vec2D, Direction2D,
Ray, XForm, BBox, Plane
)
class Hasher:
def __init__(self, *args):
self._hasher = md5()
self._digest = None
self.add(args)
def __iadd__(self, other):
self.add(other)
return self
def __str__(self):
return '<Hasher %s>' % str(self.get_hash())
def __hash__(self):
return hash(self.get_hash())
def add(self, *args):
self._digest = None
for arg in args:
t = type(arg)
if t is list:
self._hasher.update(bytes('list %d' % len(arg), 'utf8'))
for a in arg: self.add(a)
elif t is tuple:
self._hasher.update(bytes('tuple %d' % len(arg), 'utf8'))
for a in arg: self.add(a)
elif t is set:
self._hasher.update(bytes('set %d' % len(arg), 'utf8'))
for a in arg: self.add(a)
elif t is Matrix:
self._hasher.update(bytes('matrix', 'utf8'))
self.add([v for r in arg for v in r])
elif t is Vector:
self._hasher.update(bytes('vector %d' % len(arg), 'utf8'))
self.add([v for v in arg])
else:
self._hasher.update(bytes(str(arg), 'utf8'))
def get_hash(self):
if self._digest is None:
self._digest = self._hasher.hexdigest()
return self._digest
def __eq__(self, other):
if type(other) is not Hasher: return False
return self.get_hash() == other.get_hash()
def hash_cycle(cycle):
l = len(cycle)
h = [hash(v) for v in cycle]
m = min(h)
mi = h.index(m)
h = rotate_cycle(h, -mi)
if h[1] > h[-1]:
h.reverse()
h = rotate_cycle(h, 1)
return ' '.join(str(c) for c in h)
def hash_object(obj:bpy.types.Object):
if obj is None: return None
assert type(obj) is bpy.types.Object, "Only call hash_object on mesh objects!"
assert type(obj.data) is bpy.types.Mesh, "Only call hash_object on mesh objects!"
# get object data to act as a hash
me = obj.data
counts = (len(me.vertices), len(me.edges), len(me.polygons), len(obj.modifiers))
if me.vertices:
bbox = (tuple(min(v.co for v in me.vertices)), tuple(max(v.co for v in me.vertices)))
else:
bbox = (None, None)
vsum = tuple(sum((v.co for v in me.vertices), Vector((0,0,0))))
xform = tuple(e for l in obj.matrix_world for e in l)
mods = []
for mod in obj.modifiers:
if mod.type == 'SUBSURF':
mods += [('SUBSURF', mod.levels)]
elif mod.type == 'DECIMATE':
mods += [('DECIMATE', mod.ratio)]
else:
mods += [(mod.type)]
hashed = (counts, bbox, vsum, xform, hash(obj), str(mods)) # ob.name???
return hashed
def hash_bmesh(bme:BMesh):
if bme is None: return None
assert type(bme) is BMesh, 'Only call hash_bmesh on BMesh objects!'
# bme.verts.ensure_lookup_table()
# bme.edges.ensure_lookup_table()
# bme.faces.ensure_lookup_table()
# return Hasher(
# [list(v.co) + list(v.normal) + [v.select] for v in bme.verts],
# [[v.index for v in e.verts] + [e.select] for e in bme.edges],
# [[v.index for v in f.verts] + [f.select] for f in bme.faces],
# )
counts = (len(bme.verts), len(bme.edges), len(bme.faces))
bbox = BBox(from_bmverts=bme.verts)
vsum = tuple(sum((v.co for v in bme.verts), Vector((0,0,0))))
hashed = (counts, tuple(bbox.min) if bbox.min else None, tuple(bbox.max) if bbox.max else None, vsum)
return hashed
Binary file not shown.

After

Width:  |  Height:  |  Size: 525 B

@@ -0,0 +1,40 @@
[remap]
importer="texture"
type="CompressedTexture2D"
uid="uid://b6y712uxg7d08"
path="res://.godot/imported/checkmark.png-fe94393b15034676e007e220420c48c9.ctex"
metadata={
"vram_texture": false
}
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/images/checkmark.png"
dest_files=["res://.godot/imported/checkmark.png-fe94393b15034676e007e220420c48c9.ctex"]
[params]
compress/mode=0
compress/high_quality=false
compress/lossy_quality=0.7
compress/uastc_level=0
compress/rdo_quality_loss=0.0
compress/hdr_compression=1
compress/normal_map=0
compress/channel_pack=0
mipmaps/generate=false
mipmaps/limit=-1
roughness/mode=0
roughness/src_normal=""
process/channel_remap/red=0
process/channel_remap/green=1
process/channel_remap/blue=2
process/channel_remap/alpha=3
process/fix_alpha_border=true
process/premult_alpha=false
process/normal_map_invert_y=false
process/hdr_as_srgb=false
process/hdr_clamp_exposure=false
process/size_limit=0
detect_3d/compress_to=1
Binary file not shown.

After

Width:  |  Height:  |  Size: 437 B

@@ -0,0 +1,40 @@
[remap]
importer="texture"
type="CompressedTexture2D"
uid="uid://07pxn53728bg"
path="res://.godot/imported/close.png-95af66ad4aee53dcc2c5f06508c5818e.ctex"
metadata={
"vram_texture": false
}
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/images/close.png"
dest_files=["res://.godot/imported/close.png-95af66ad4aee53dcc2c5f06508c5818e.ctex"]
[params]
compress/mode=0
compress/high_quality=false
compress/lossy_quality=0.7
compress/uastc_level=0
compress/rdo_quality_loss=0.0
compress/hdr_compression=1
compress/normal_map=0
compress/channel_pack=0
mipmaps/generate=false
mipmaps/limit=-1
roughness/mode=0
roughness/src_normal=""
process/channel_remap/red=0
process/channel_remap/green=1
process/channel_remap/blue=2
process/channel_remap/alpha=3
process/fix_alpha_border=true
process/premult_alpha=false
process/normal_map_invert_y=false
process/hdr_as_srgb=false
process/hdr_clamp_exposure=false
process/size_limit=0
detect_3d/compress_to=1
@@ -0,0 +1,40 @@
[remap]
importer="texture"
type="CompressedTexture2D"
uid="uid://bjebl6r0eslse"
path="res://.godot/imported/collapse_close.png-e57e5a7b1f351b84b7b20b55ac9dc967.ctex"
metadata={
"vram_texture": false
}
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/images/collapse_close.png"
dest_files=["res://.godot/imported/collapse_close.png-e57e5a7b1f351b84b7b20b55ac9dc967.ctex"]
[params]
compress/mode=0
compress/high_quality=false
compress/lossy_quality=0.7
compress/uastc_level=0
compress/rdo_quality_loss=0.0
compress/hdr_compression=1
compress/normal_map=0
compress/channel_pack=0
mipmaps/generate=false
mipmaps/limit=-1
roughness/mode=0
roughness/src_normal=""
process/channel_remap/red=0
process/channel_remap/green=1
process/channel_remap/blue=2
process/channel_remap/alpha=3
process/fix_alpha_border=true
process/premult_alpha=false
process/normal_map_invert_y=false
process/hdr_as_srgb=false
process/hdr_clamp_exposure=false
process/size_limit=0
detect_3d/compress_to=1
Binary file not shown.

After

Width:  |  Height:  |  Size: 436 B

@@ -0,0 +1,40 @@
[remap]
importer="texture"
type="CompressedTexture2D"
uid="uid://0glqvak5eyjd"
path="res://.godot/imported/collapse_open.png-80285e72017a6b0a5d7efaee453876f6.ctex"
metadata={
"vram_texture": false
}
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/images/collapse_open.png"
dest_files=["res://.godot/imported/collapse_open.png-80285e72017a6b0a5d7efaee453876f6.ctex"]
[params]
compress/mode=0
compress/high_quality=false
compress/lossy_quality=0.7
compress/uastc_level=0
compress/rdo_quality_loss=0.0
compress/hdr_compression=1
compress/normal_map=0
compress/channel_pack=0
mipmaps/generate=false
mipmaps/limit=-1
roughness/mode=0
roughness/src_normal=""
process/channel_remap/red=0
process/channel_remap/green=1
process/channel_remap/blue=2
process/channel_remap/alpha=3
process/fix_alpha_border=true
process/premult_alpha=false
process/normal_map_invert_y=false
process/hdr_as_srgb=false
process/hdr_clamp_exposure=false
process/size_limit=0
detect_3d/compress_to=1
Binary file not shown.

After

Width:  |  Height:  |  Size: 380 B

@@ -0,0 +1,40 @@
[remap]
importer="texture"
type="CompressedTexture2D"
uid="uid://x012unpqc1qg"
path="res://.godot/imported/radio.png-1c06939af668c895e24e10d3101c8813.ctex"
metadata={
"vram_texture": false
}
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/images/radio.png"
dest_files=["res://.godot/imported/radio.png-1c06939af668c895e24e10d3101c8813.ctex"]
[params]
compress/mode=0
compress/high_quality=false
compress/lossy_quality=0.7
compress/uastc_level=0
compress/rdo_quality_loss=0.0
compress/hdr_compression=1
compress/normal_map=0
compress/channel_pack=0
mipmaps/generate=false
mipmaps/limit=-1
roughness/mode=0
roughness/src_normal=""
process/channel_remap/red=0
process/channel_remap/green=1
process/channel_remap/blue=2
process/channel_remap/alpha=3
process/fix_alpha_border=true
process/premult_alpha=false
process/normal_map_invert_y=false
process/hdr_as_srgb=false
process/hdr_clamp_exposure=false
process/size_limit=0
detect_3d/compress_to=1
@@ -0,0 +1,80 @@
'''
Copyright (C) 2020 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson
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/>.
'''
import socket
import sys
'''
Note: this is a work in progress only!
'''
# https://pythonspot.com/building-an-irc-bot/
class IRC:
def __init__(self):
self.done = False
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def __del__(self):
self.close()
def send_text(self, text):
if not text.endswith('\n'): text += '\n'
self.socket.send(bytes(text, encoding='utf-8'))
def send(self, chan, msg):
self.socket.send(bytes("PRIVMSG " + chan + " :" + msg + "\n", encoding='utf-8'))
def connect(self, server, channel, nickname):
#defines the socket
print("connecting to:", server)
self.socket.connect((server, 6667)) #connects to the server
self.socket.send(bytes("USER " + nickname + " " + nickname +" " + nickname + " :This is a fun bot!\n", encoding='utf-8')) #user authentication
self.socket.send(bytes("NICK " + nickname + "\n", encoding='utf-8'))
self.socket.send(bytes("JOIN " + channel + "\n", encoding='utf-8')) #join the chan
def get_text(self, blocking=True):
self.socket.setblocking(blocking)
try:
text = str(self.socket.recv(4096), encoding='utf-8') #receive the text
except socket.error:
text = None
return text
def close(self):
if self.done: return
self.socket.close()
self.done = True
if __name__ == '__main__':
channel = "#retopoflow"
server = "irc.freenode.net"
nickname = "rftester"
irc = IRC()
irc.connect(server, channel, nickname)
while 1:
text = irc.get_text()
if text: print(text)
if "PRIVMSG" in text and channel in text and "hello" in text:
irc.send(channel, "Hello!")
@@ -0,0 +1,73 @@
'''
Copyright (C) 2014 Plasmasolutions
software@plasmasolutions.de
Created by Thomas Beck
Donated to CGCookie and the world
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/>.
'''
import bpy
from .blender import show_blender_popup, show_blender_text
from .globals import Globals
class Logger:
_log_filename = 'Logger'
_divider = '\n\n%s\n' % ('='*80)
@staticmethod
def set_log_filename(path):
Logger._log_filename = path
@staticmethod
def get_log_filename():
return Logger._log_filename
@staticmethod
def get_log(create=True):
if Logger._log_filename not in bpy.data.texts:
if not create: return None
old = { t.name for t in bpy.data.texts }
# create a log file for recording
bpy.ops.text.new()
for t in bpy.data.texts:
if t.name in old: continue
t.name = Logger._log_filename
break
else:
assert False
return bpy.data.texts[Logger._log_filename]
@staticmethod
def has_log():
return Logger.get_log(create=False) is not None
@staticmethod
def add(line):
log = Logger.get_log()
log.write('%s%s' % (Logger._divider, str(line)))
@staticmethod
def open_log():
if Logger.has_log():
show_blender_text(Logger._log_filename)
else:
show_blender_popup('Log file (%s) not found' % Logger._log_filename)
logger = Logger()
Globals.set(logger)
@@ -0,0 +1,85 @@
'''
Copyright (C) 2020 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson
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/>.
'''
import re
class Markdown:
# markdown line (first line only, ex: table)
line_tests = {
'h1': re.compile(r'# +(?P<text>.+)'),
'h2': re.compile(r'## +(?P<text>.+)'),
'h3': re.compile(r'### +(?P<text>.+)'),
'ul': re.compile(r'(?P<indent> *)- +(?P<text>.+)'),
'ol': re.compile(r'(?P<indent> *)\d+\. +(?P<text>.+)'),
'img': re.compile(r'!\[(?P<caption>[^\]]*)\]\((?P<filename>[^) ]+)(?P<style>[^)]*)\)'),
'table': re.compile(r'\| +(([^|]*?) +\|)+'),
}
# markdown inline
inline_tests = {
'br': re.compile(r'<br */?> *'),
'img': re.compile(r'!\[(?P<caption>[^\]]*)\]\((?P<filename>[^) ]+)(?P<style>[^)]*)\)'),
'bold': re.compile(r'\*(?P<text>.+?)\*'),
'code': re.compile(r'`(?P<text>[^`]+)`'),
'link': re.compile(r'\[(?P<text>.+?)\]\((?P<link>.+?)\)'),
'italic': re.compile(r'_(?P<text>.+?)_'),
}
# https://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url
re_url = re.compile(r'^((https?)|mailto)://([-a-zA-Z0-9@:%._\+~#=]+\.)*?[-a-zA-Z0-9@:%._+~#=]+\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)$')
@staticmethod
def preprocess(txt):
# process message similarly to Markdown
txt = re.sub(r'<!--.*?-->', r'', txt) # remove comments
txt = re.sub(r'^\n*', r'', txt) # remove leading \n
txt = re.sub(r'\n*$', r'', txt) # remove trailing \n
txt = re.sub(r'\n\n\n*', r'\n\n', txt) # 2+ \n => \n\n
txt = re.sub(r'---', r'', txt) # em dash
txt = re.sub(r'--', r'', txt) # en dash
return txt
@staticmethod
def is_url(txt): return Markdown.re_url.match(txt) is not None
@staticmethod
def match_inline(line):
#line = line.lstrip() # ignore leading spaces
for (t,r) in Markdown.inline_tests.items():
m = r.match(line)
if m: return (t, m)
return (None, None)
@staticmethod
def match_line(line):
line = line.rstrip() # ignore trailing spaces
for (t,r) in Markdown.line_tests.items():
m = r.match(line)
if m: return (t, m)
return (None, None)
@staticmethod
def split_word(line):
if ' ' not in line:
return (line,'')
i = line.index(' ') + 1
return (line[:i],line[i:])
@@ -0,0 +1,76 @@
'''
Copyright (C) 2020 Taylor University, CG Cookie
Created by Dr. Jon Denning and Spring 2015 COS 424 class
Some code copied from CG Cookie Retopoflow project
https://github.com/CGCookie/retopoflow
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 abc import ABCMeta, abstractmethod
'''
RegisterRFClasses handles self registering classes to simplify creating new tools, cursors, etc.
With self registration, the new entities only need to by imported in, and they automatically
show up as an available entity.
'''
class SingletonClass(type):
'''
from https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
''' # noqa
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
supercls = super(SingletonClass, cls)
cls._instances[cls] = supercls.__call__(*args, *kwargs)
return cls._instances[cls]
# def __getattr__(cls, name):
# return cls._instances[cls].__getattr__(name)
class RegisterClass(type):
'''
# from http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Metaprogramming.html#example-self-registration-of-subclasses
''' # noqa
def __init__(cls, name, bases, nmspc):
super(RegisterClass, cls).__init__(name, bases, nmspc)
if not hasattr(cls, 'registry'):
cls.registry = set()
cls.registry.add(cls)
cls.registry -= set(bases) # Remove base classes
# Metamethods, called on class objects:
def __iter__(cls):
return iter(cls.registry)
def __str__(cls):
if cls in cls.registry:
return cls.__name__
return cls.__name__ + ": " + ", ".join([sc.__name__ for sc in cls])
def __len__(cls):
return len(cls.registry)
class SingletonRegisterClass(SingletonClass, RegisterClass):
pass
@@ -0,0 +1,155 @@
'''
Copyright (C) 2020 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson
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/>.
'''
import re
#####################################################################################
# below are helper classes for converting input to character stream,
# and for converting character stream to token stream
class Parse_CharStream:
def __init__(self, charstream):
self.i_char = 0
self.i_line = 0
self.charstream = charstream
def numberoflines(self):
return self.charstream.count('\n')
def endofstream(self):
return self.i_char >= len(self.charstream)
def peek(self, l=1):
if self.endofstream(): return ''
return self.charstream[self.i_char:self.i_char+l]
def peek_restofline(self):
if self.endofstream(): return ''
i = self.charstream.find('\n', self.i_char)
if i == -1: return self.charstream[self.i_char:]
return self.charstream[self.i_char:i]
def peek_remaining(self):
if self.endofstream(): return ''
return self.charstream[self.i_char:]
def consume(self, m=None, l=None):
if l is None: l = 1 if m is None else len(m)
o = self.peek(l=l)
if m is not None: assert o == m
self.i_char += l
self.i_line += o.count('\n')
return o
def consume_while_in(self, s):
w = ''
while self.peek() in s: w += self.consume()
return w
class Parse_Lexer:
'''
Converts character stream input into a stream of tokens
'''
def __init__(self, charstream:Parse_CharStream, token_rules):
token_rules = [(tname, conv, list(map(re.compile, retokens))) for (tname,conv,retokens) in token_rules]
self.tokens = []
self.i = 0
self.max_lines = charstream.numberoflines()
while not charstream.endofstream():
rest = charstream.peek_remaining()
i_line = charstream.i_line+1
# match against all possible tokens
matches = [(tname, conv, retoken.match(rest)) for (tname,conv,retokens) in token_rules for retoken in retokens]
# filter out non-matches
matches = list(filter(lambda nm: nm[2] is not None, matches))
assert matches, 'syntax error on line %d: "%s"' % (i_line, charstream.peek_restofline())
# find longest match
longest = max(len(m.group(0)) for (tname,conv,m) in matches)
# filter out non-longest matches
matches = list(filter(lambda nm: len(nm[2].group(0))==longest, matches))
matches = {k:(c,v) for (k,c,v) in matches}
charstream.consume(l=longest)
# convert token to python/blender types
for k,(conv,v) in list(matches.items()):
v = conv(v)
if v is None: del matches[k]
else: matches[k] = v
if not matches: continue
ks = set(matches.keys())
v = list(matches.values())[0]
self.tokens.append((ks, v, i_line))
def current_line(self):
tts,tv,ti_line = self.tokens[self.i]
return ti_line
def match_t_v(self, t):
assert self.i < len(self.tokens), 'hit end on token stream'
tts,tv,ti_line = self.tokens[self.i]
t = {t} if type(t) is str else set(t)
assert tts & t, 'expected type(s) "%s" but saw "%s" (text: "%s", line: %d)' % ('","'.join(t), '","'.join(tts), tv, ti_line)
self.i += 1
return tv
def match_v_v(self, v):
assert self.i < len(self.tokens), 'hit end on token stream'
tts,tv,ti_line = self.tokens[self.i]
v = {v} if type(v) is str else set(v)
assert tv in v, 'expected value(s) "%s" but saw "%s" (type: "%s", line: %d)' % ('","'.join(v), tv, '","'.join(tts), ti_line)
self.i += 1
return tv
def next_t(self):
assert self.i < len(self.tokens), 'hit end of token stream'
tts,tv,ti_line = self.tokens[self.i]
self.i += 1
return tts
def next_v(self):
assert self.i < len(self.tokens), 'hit end of token stream'
tts,tv,ti_line = self.tokens[self.i]
self.i += 1
return tv
def peek(self):
if self.i == len(self.tokens): return ('eof','eof',self.max_lines)
return self.tokens[self.i]
def peek_t(self):
if self.i == len(self.tokens): return 'eof'
tts,tv,ti_line = self.tokens[self.i]
return tts
def peek_v(self):
if self.i == len(self.tokens): return 'eof'
tts,tv,ti_line = self.tokens[self.i]
return tv
@@ -0,0 +1,314 @@
'''
Copyright (C) 2020 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson, and Patrick Moore
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/>.
'''
import os
import time
import inspect
import contextlib
from .globals import Globals
class ProfilerHelper:
def __init__(self, pr, text):
full_text = (pr.stack[-1].full_text+'^' if pr.stack else '') + text
parent_text = (pr.stack[-1].full_text) if pr.stack else None
if full_text in pr.d_start:
Profiler._broken = True
assert False, '"%s" found in profiler already?' % text
self.pr = pr
self.text = text
self.full_text = full_text
self.parent_text = parent_text
self.all_call = '~~ All Calls ~~^%s' % text
self.parent_all_call = pr.stack[-1].all_call if pr.stack else None
self.direct_call = '~~ Direct Calls ~~^%s --> %s' % (pr.stack[-1].text if pr.stack else 'None', text)
self.parent_direct_call = pr.stack[-1].direct_call if pr.stack else None
self._is_done = False
self.pr.d_start[self.full_text] = time.time()
self.pr.stack.append(self)
def __del__(self):
if Profiler._broken:
return
if self._is_done:
return
Profiler._broken = True
print('Deleting Profiler (%s) before finished' % self.full_text)
#assert False, 'Deleting Profiler before finished'
def update(self, key, delta, key_parent=None):
self.pr.d_count[key] = self.pr.d_count.get(key, 0) + 1
self.pr.d_times[key] = self.pr.d_times.get(key, 0) + delta
if key_parent:
self.pr.d_times_sub[key_parent] = self.pr.d_times_sub.get(key_parent, 0) + delta
self.pr.d_mins[key] = min(
self.pr.d_mins.get(key, float('inf')), delta)
self.pr.d_maxs[key] = max(
self.pr.d_maxs.get(key, float('-inf')), delta)
self.pr.d_last[key] = delta
def done(self):
while self.pr.stack and self.pr.stack[-1] != self:
self.pr.stack.pop()
if not self.pr.stack:
if self.full_text in self.pr.d_start:
del self.pr.d_start[self.full_text]
return
#assert self.pr.stack[-1] == self
assert not self._is_done
self.pr.stack.pop()
self._is_done = True
st = self.pr.d_start[self.full_text]
en = time.time()
delta = en-st
self.update(self.full_text, delta, key_parent=self.parent_text)
self.update('~~ All Calls ~~', delta)
self.update(self.all_call, delta, key_parent=self.parent_all_call)
self.update('~~ Direct Calls ~~', delta)
self.update(self.direct_call, delta, key_parent=self.parent_direct_call)
del self.pr.d_start[self.full_text]
self.pr.clear_handler()
class ProfilerHelper_Ignore:
def __init__(self, *args, **kwargs): pass
def done(self): pass
profilerhelper_ignore = ProfilerHelper_Ignore()
class Profiler:
_enabled = False
_filename = 'Profiler'
_broken = False
_clear = False
@staticmethod
def set_profiler_enabled(v):
Profiler._enabled = v
@staticmethod
def get_profiler_enabled():
return Profiler._enabled
@staticmethod
def set_profiler_filename(path):
Profiler._filename = path
@staticmethod
def get_profiler_filename():
return Profiler._filename
def __init__(self):
self.clear_handler(force=True)
def reset(self):
self._broken = False
self.clear()
@staticmethod
def is_broken():
return Profiler._broken
def clear_handler(self, force=False):
if not force:
if not self._clear: return
if self.stack: return
self.d_start = {}
self.d_times = {}
self.d_times_sub = {}
self.d_mins = {}
self.d_maxs = {}
self.d_last = {}
self.d_count = {}
self.stack = []
self.last_profile_out = 0
self.clear_time = time.time()
self._clear = False
def clear(self):
self._clear = True
self.clear_handler()
def start(self, text=None, addFile=True, enabled=True, n_backs=1):
# assert not Profiler._broken
if Profiler._broken:
print('Profiler broken. Ignoring')
return profilerhelper_ignore
if not Profiler._enabled:
return profilerhelper_ignore
if not enabled:
return profilerhelper_ignore
frame = inspect.currentframe()
for _ in range(n_backs): frame = frame.f_back
filename = os.path.basename(frame.f_code.co_filename)
linenum = frame.f_lineno
fnname = frame.f_code.co_name
if addFile:
text = text or fnname
space = ' '*(30-len(text))
text = '%s%s (%s:%d)' % (text, space, filename, linenum)
else:
text = text or fnname
return ProfilerHelper(self, text)
def __del__(self):
# self.printout()
pass
def add_note(self, *args, **kwargs):
self.start(*args, n_backs=2, **kwargs).done()
@contextlib.contextmanager
def code(self, *args, enabled=True, **kwargs):
if not Profiler._enabled or not enabled:
yield None
return
try:
pr = self.start(*args, n_backs=3, **kwargs) # n_backs=3 for contextlib wrapper
yield pr
pr.done()
except Exception as e:
pr.done()
print('Caught exception while profiling:', args, kwargs)
Globals.debugger.print_exception()
raise e
def function(self, fn):
if not Profiler._enabled:
return fn
frame = inspect.currentframe().f_back
f_locals = frame.f_locals
filename = os.path.basename(frame.f_code.co_filename)
clsname = f_locals['__qualname__'] if '__qualname__' in f_locals else ''
linenum = frame.f_lineno
fnname = fn.__name__ # frame.f_code.co_name
if clsname:
fnname = clsname + '.' + fnname
space = ' '*(30-len(fnname))
text = '%s%s (%s:%d)' % (fnname, space, filename, linenum)
def wrapper(*args, **kwargs):
# assert not Profiler._broken
if Profiler._broken:
return fn(*args, **kwargs)
if not Profiler._enabled:
return fn(*args, **kwargs)
pr = self.start(text=text, addFile=False)
ret = None
try:
ret = fn(*args, **kwargs)
pr.done()
return ret
except Exception as e:
pr.done()
print('CAUGHT EXCEPTION ' + str(e))
print(text)
Globals.debugger.print_exception()
raise e
wrapper.__name__ = fn.__name__
wrapper.__doc__ = fn.__doc__
return wrapper
def strout(self):
if not Profiler._enabled:
return ''
s = [
'Profiler:',
' run: %6.2fsecs' % (time.time() - self.clear_time),
'----------------------------------------------------------------------------------------------',
' total call ------- seconds / call ------- delta ',
' secs / count = last, min, avg, max ( fps) - time - call stack ',
'----------------------------------------------------------------------------------------------',
]
for text in sorted(self.d_times):
tottime = self.d_times[text]
totcount = self.d_count[text]
deltime = self.d_times[text] - self.d_times_sub.get(text, 0)
avgt = tottime / totcount
mint = self.d_mins[text]
maxt = self.d_maxs[text]
last = self.d_last[text]
calls = text.split('^')
t = text if len(calls) == 1 else (
' | '*(len(calls)-2) + ' \\- ' + calls[-1])
fps = totcount / tottime if tottime > 0 else 1000
fps = ' 1k+ ' if fps >= 1000 else '%5.1f' % fps
s += [' %6.2f / %7d = %6.4f, %6.4f, %6.4f, %6.4f, (%s) - %6.2f - %s' % (
tottime, totcount, last, mint, avgt, maxt, fps, deltime, t)]
s += ['run: %6.2fsecs' % (time.time() - self.clear_time)]
return '\n'.join(s)
def printout(self):
if not Profiler._enabled:
return
print('%s\n\n\n' % self.strout())
def printfile(self, interval=0.25):
# $ # to watch the file from terminal (bash) use:
# $ watch --interval 0.1 cat filename
if not Profiler._enabled:
return
if time.time() < self.last_profile_out + interval:
return
self.last_profile_out = time.time()
# .. back to retopoflow root
path = os.path.dirname(os.path.abspath(__file__))
filename = os.path.join(path, '..', Profiler._filename)
open(filename, 'wt').write(self.strout())
profiler = Profiler()
Globals.set(profiler)
# class CodeProfiler:
# def __init__(self, *args, **kwargs):
# self.args = args
# self.kwargs = kwargs
# def __enter__(self):
# self.pr = profiler.start(*self.args, n_backs=2, **self.kwargs)
# def __exit__(self, exc_type, exc_val, exc_tb):
# self.pr.done()
# profiler.code = CodeProfiler
@contextlib.contextmanager
def time_it(*args, **kwargs):
start = time.time()
frame = inspect.currentframe()
n_backs = 2
for _ in range(n_backs): frame = frame.f_back
filename = os.path.basename(frame.f_code.co_filename)
linenum = frame.f_lineno
fnname = frame.f_code.co_name
try:
yield None
finally:
print('time_it %s:%d fn:%s = %f' % (filename, linenum, fnname, time.time() - start))
@@ -0,0 +1,415 @@
'''
Copyright (C) 2020 CG Cookie
Created by Jonathan Denning, Jonathan Williamson
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/>.
'''
import os
import re
import bpy
import bgl
import ctypes
from .debug import dprint
from .globals import Globals
from ..ext.bgl_ext import VoidBufValue
# note: not all supported by user system, but we don't need full functionality
# https://en.wikipedia.org/wiki/OpenGL_Shading_Language#Versions
# OpenGL GLSL OpenGL GLSL
# 2.0 110 4.0 400
# 2.1 120 4.1 410
# 3.0 130 4.2 420
# 3.1 140 4.3 430
# 3.2 150 4.4 440
# 3.3 330 4.5 450
# 4.6 460
print('(shaders) GLSL Version:', bgl.glGetString(bgl.GL_SHADING_LANGUAGE_VERSION))
DEBUG_PRINT = False
vbv_zero = VoidBufValue(0)
buf_zero = vbv_zero.buf #bgl.Buffer(bgl.GL_BYTE, 1, [0])
Globals.buf_zero = buf_zero
class Shader():
@staticmethod
def shader_compile(name, shader, src):
'''
logging and error-checking not quite working :(
'''
bgl.glCompileShader(shader)
# report shader compilation log (if any)
bufLogLen = bgl.Buffer(bgl.GL_INT, 1)
bgl.glGetShaderiv(shader, bgl.GL_INFO_LOG_LENGTH, bufLogLen)
if bufLogLen[0] > 0:
# report log available
bufLog = bgl.Buffer(bgl.GL_BYTE, bufLogLen)
bgl.glGetShaderInfoLog(shader, bufLogLen[0], bufLogLen, bufLog)
log = ''.join(chr(v) for v in bufLog.to_list() if v)
if log:
print('SHADER REPORT %s' % name)
print('\n'.join([' %s'%l for l in log.splitlines()]))
else:
print('Shader %s has no report' % name)
else:
log = ''
# report shader compilation status
bufStatus = bgl.Buffer(bgl.GL_INT, 1)
bgl.glGetShaderiv(shader, bgl.GL_COMPILE_STATUS, bufStatus)
if bufStatus[0] == 0:
print('ERROR WHILE COMPILING SHADER %s' % name)
print('\n'.join([' % 4d %s'%(i+1,l) for (i,l) in enumerate(src.splitlines())]))
assert False
return log
@staticmethod
def parse_string(string, includeVersion=True, constant_overrides=None, define_overrides=None):
# NOTE: GEOMETRY SHADER NOT FULLY SUPPORTED, YET
# need to find a way to handle in/out
constant_overrides = constant_overrides or {}
define_overrides = define_overrides or {}
uniforms, varyings, attributes, consts = [],[],[],[]
vertSource, geoSource, fragSource, commonSource = [],[],[],[]
vertVersion, geoVersion, fragVersion = '','',''
mode = None
lines = string.splitlines()
assert '// vertex shader' in lines, 'could not detect vertex shader'
assert '// fragment shader' in lines, 'could not detect fragment shader'
for line in lines:
if line.startswith('uniform '):
uniforms.append(line)
elif line.startswith('attribute '):
attributes.append(line)
elif line.startswith('varying '):
varyings.append(line)
elif line.startswith('const '):
m = re.match(r'const +(?P<type>bool|int|float) +(?P<var>[a-zA-Z0-9_]+) *= *(?P<val>[^;]+);', line)
if m is None:
print('Shader could not match const line:', line)
elif m.group('var') in constant_overrides:
line = 'const %s %s = %s' % (m.group('type'), m.group('var'), constant_overrides[m.group('var')])
consts.append(line)
elif line.startswith('#define '):
m0 = re.match(r'#define +(?P<var>[a-zA-Z0-9_]+)$', line)
m1 = re.match(r'#define +(?P<var>[a-zA-Z0-9_]+) +(?P<val>.+)$', line)
if m0 and m0.group('var') in define_overrides:
if not define_overrides[m0.group('var')]:
line = ''
if m1 and m1.group('var') in define_overrides:
line = '#define %s %s' % (m1.group('var'), define_overrides[m1.group('var')])
if not m0 and not m1:
print('Shader could not match #define line:', line)
consts.append(line)
elif line.startswith('#version '):
if mode == 'vert':
vertVersion = line
elif mode == 'geo':
geoVersion = line
elif mode == 'frag':
fragVersion = line
elif line == '// vertex shader':
mode = 'vert'
elif line == '// geometry shader':
mode = 'geo'
elif line == '// fragment shader':
mode = 'frag'
else:
if not line.strip(): continue
if mode == 'vert':
vertSource.append(line)
elif mode == 'geo':
geoSource.append(line)
elif mode == 'frag':
fragSource.append(line)
else:
commonSource.append(line)
v_attributes = [a.replace('attribute ', 'in ') for a in attributes]
v_varyings = [v.replace('varying ', 'out ') for v in varyings]
f_varyings = [v.replace('varying ', 'in ') for v in varyings]
srcVertex = '\n'.join(
([vertVersion] if includeVersion else []) +
uniforms + v_attributes + v_varyings + consts + commonSource + vertSource
)
srcFragment = '\n'.join(
([fragVersion] if includeVersion else []) +
uniforms + f_varyings + consts + commonSource + fragSource
)
return (srcVertex, srcFragment)
@staticmethod
def parse_file(filename, includeVersion=True, constant_overrides=None, define_overrides=None):
filename_guess = os.path.join(os.path.dirname(__file__), 'shaders', filename)
if os.path.exists(filename):
pass
elif os.path.exists(filename_guess):
filename = filename_guess
else:
assert False, "Shader file could not be found: %s" % filename
string = open(filename, 'rt').read()
return Shader.parse_string(string, includeVersion=includeVersion, constant_overrides=constant_overrides, define_overrides=define_overrides)
@staticmethod
def load_from_string(name, string, *args, **kwargs):
srcVertex, srcFragment = Shader.parse_string(string)
return Shader(name, srcVertex, srcFragment, *args, **kwargs)
@staticmethod
def load_from_file(name, filename, *args, **kwargs):
# https://www.blender.org/api/blender_python_api_2_77_1/bgl.html
# https://en.wikibooks.org/wiki/GLSL_Programming/Blender/Shading_in_View_Space
# https://www.khronos.org/opengl/wiki/Built-in_Variable_(GLSL)
srcVertex, srcFragment = Shader.parse_file(filename)
return Shader(name, srcVertex, srcFragment, *args, **kwargs)
def __init__(self, name, srcVertex, srcFragment, funcStart=None, funcEnd=None, checkErrors=True, bindTo0=None):
self.drawing = Globals.drawing
self.name = name
self.shaderProg = bgl.glCreateProgram()
self.shaderVert = bgl.glCreateShader(bgl.GL_VERTEX_SHADER)
self.shaderFrag = bgl.glCreateShader(bgl.GL_FRAGMENT_SHADER)
self.checkErrors = checkErrors
srcVertex = '\n'.join(l for l in srcVertex.split('\n'))
srcFragment = '\n'.join(l for l in srcFragment.split('\n'))
bgl.glShaderSource(self.shaderVert, srcVertex)
bgl.glShaderSource(self.shaderFrag, srcFragment)
dprint('RetopoFlow Shader Info: %s (%d)' % (self.name,self.shaderProg))
logv = self.shader_compile(name, self.shaderVert, srcVertex)
logf = self.shader_compile(name, self.shaderFrag, srcFragment)
if len(logv.strip()):
print(' vert log:\n' + '\n'.join((' '+l) for l in logv.splitlines()))
if len(logf.strip()):
print(' frag log:\n' + '\n'.join((' '+l) for l in logf.splitlines()))
bgl.glAttachShader(self.shaderProg, self.shaderVert)
bgl.glAttachShader(self.shaderProg, self.shaderFrag)
if bindTo0:
bgl.glBindAttribLocation(self.shaderProg, 0, bindTo0)
bgl.glLinkProgram(self.shaderProg)
self.shaderVars = {}
lvars = [l for l in srcVertex.splitlines() if l.startswith('in ')]
lvars += [l for l in srcVertex.splitlines() if l.startswith('attribute ')]
lvars += [l for l in srcVertex.splitlines() if l.startswith('uniform ')]
lvars += [l for l in srcFragment.splitlines() if l.startswith('uniform ')]
for l in lvars:
m = re.match('^(?P<qualifier>[^ ]+) +(?P<type>[^ ]+) +(?P<name>[^ ;]+)', l)
assert m
m = m.groupdict()
q,t,n = m['qualifier'],m['type'],m['name']
locate = bgl.glGetAttribLocation if q in {'in','attribute'} else bgl.glGetUniformLocation
if n in self.shaderVars: continue
self.shaderVars[n] = {
'qualifier': q,
'type': t,
'location': locate(self.shaderProg, n),
'reported': False,
}
dprint(' attribs: ' + ', '.join((k + ' (%d)'%self.shaderVars[k]['location']) for k in self.shaderVars if self.shaderVars[k]['qualifier'] in {'in','attribute'}))
dprint(' uniforms: ' + ', '.join((k + ' (%d)'%self.shaderVars[k]['location']) for k in self.shaderVars if self.shaderVars[k]['qualifier'] in {'uniform'}))
self.funcStart = funcStart
self.funcEnd = funcEnd
self.mvpmatrix_buffer = bgl.Buffer(bgl.GL_FLOAT, [4,4])
def __setitem__(self, varName, varValue): self.assign(varName, varValue)
def assign_buffer(self, varName, varValue):
return self.assign(varName, bgl.Buffer(bgl.GL_FLOAT, [4,4], varValue))
# https://www.opengl.org/sdk/docs/man/html/glVertexAttrib.xhtml
# https://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml
def assign(self, varName, varValue):
assert varName in self.shaderVars, 'Variable %s not found' % varName
try:
v = self.shaderVars[varName]
q,l,t = v['qualifier'],v['location'],v['type']
if l == -1:
if not v['reported']:
dprint('ASSIGNING TO UNUSED ATTRIBUTE (%s): %s = %s' % (self.name, varName,str(varValue)))
v['reported'] = True
return
if DEBUG_PRINT:
print('%s (%s,%d,%s) = %s' % (varName, q, l, t, str(varValue)))
if q in {'in','attribute'}:
if t == 'float':
bgl.glVertexAttrib1f(l, varValue)
elif t == 'int':
bgl.glVertexAttrib1i(l, varValue)
elif t == 'vec2':
bgl.glVertexAttrib2f(l, *varValue)
elif t == 'vec3':
bgl.glVertexAttrib3f(l, *varValue)
elif t == 'vec4':
bgl.glVertexAttrib4f(l, *varValue)
else:
assert False, 'Unhandled type %s for attrib %s' % (t, varName)
if self.checkErrors:
self.drawing.glCheckError('assign attrib %s = %s' % (varName, str(varValue)))
elif q in {'uniform'}:
# cannot set bools with BGL! :(
if t == 'float':
bgl.glUniform1f(l, varValue)
elif t == 'vec2':
bgl.glUniform2f(l, *varValue)
elif t == 'vec3':
bgl.glUniform3f(l, *varValue)
elif t == 'vec4':
bgl.glUniform4f(l, *varValue)
elif t == 'mat3':
bgl.glUniformMatrix3fv(l, 1, bgl.GL_TRUE, varValue)
elif t == 'mat4':
bgl.glUniformMatrix4fv(l, 1, bgl.GL_TRUE, varValue)
else:
assert False, 'Unhandled type %s for uniform %s' % (t, varName)
if self.checkErrors:
self.drawing.glCheckError('assign uniform %s (%s %d) = %s' % (varName, t, l, str(varValue)))
else:
assert False, 'Unhandled qualifier %s for variable %s' % (q, varName)
except Exception as e:
print('ERROR Shader.assign(%s, %s)): %s' % (varName, str(varValue), str(e)))
def enableVertexAttribArray(self, varName):
assert varName in self.shaderVars, 'Variable %s not found' % varName
v = self.shaderVars[varName]
q,l,t = v['qualifier'],v['location'],v['type']
if l == -1:
if not v['reported']:
print('COULD NOT FIND %s' % (varName))
v['reported'] = True
return
if DEBUG_PRINT:
print('enable vertattrib array: %s (%s,%d,%s)' % (varName, q, l, t))
bgl.glEnableVertexAttribArray(l)
if self.checkErrors:
self.drawing.glCheckError('enableVertexAttribArray %s' % varName)
gltype_names = {
bgl.GL_BYTE:'byte',
bgl.GL_SHORT:'short',
bgl.GL_UNSIGNED_BYTE:'ubyte',
bgl.GL_UNSIGNED_SHORT:'ushort',
bgl.GL_FLOAT:'float',
}
def vertexAttribPointer(self, vbo, varName, size, gltype, normalized=bgl.GL_FALSE, stride=0, buf=buf_zero, enable=True):
assert varName in self.shaderVars, 'Variable %s not found' % varName
v = self.shaderVars[varName]
q,l,t = v['qualifier'],v['location'],v['type']
if l == -1:
if not v['reported']:
print('COULD NOT FIND %s' % (varName))
v['reported'] = True
return
if DEBUG_PRINT:
print('assign (enable=%s) vertattrib pointer: %s (%s,%d,%s) = %d (%dx%s,normalized=%s,stride=%d)' % (str(enable), varName, q, l, t, vbo, size, self.gltype_names[gltype], str(normalized),stride))
bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, vbo)
bgl.glVertexAttribPointer(l, size, gltype, normalized, stride, buf)
if self.checkErrors: self.drawing.glCheckError('vertexAttribPointer %s' % varName)
if enable: bgl.glEnableVertexAttribArray(l)
if self.checkErrors: self.drawing.glCheckError('vertexAttribPointer %s' % varName)
bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, 0)
def disableVertexAttribArray(self, varName):
assert varName in self.shaderVars, 'Variable %s not found' % varName
v = self.shaderVars[varName]
q,l,t = v['qualifier'],v['location'],v['type']
if l == -1:
if not v['reported']:
print('COULD NOT FIND %s' % (varName))
v['reported'] = True
return
if DEBUG_PRINT:
print('disable vertattrib array: %s (%s,%d,%s)' % (varName, q, l, t))
bgl.glDisableVertexAttribArray(l)
if self.checkErrors:
self.drawing.glCheckError('disableVertexAttribArray %s' % varName)
def useFor(self,funcCallback):
try:
bgl.glUseProgram(self.shaderProg)
if self.funcStart: self.funcStart(self)
funcCallback(self)
except Exception as e:
print('ERROR WITH USING SHADER: ' + str(e))
finally:
bgl.glUseProgram(0)
def enable(self):
try:
if DEBUG_PRINT:
print('enabling shader <==================')
if self.checkErrors:
self.drawing.glCheckError('using program (%s, %d) pre' % (self.name, self.shaderProg))
bgl.glUseProgram(self.shaderProg)
if self.checkErrors:
self.drawing.glCheckError('using program (%s, %d) post' % (self.name, self.shaderProg))
# special uniforms
# - uMVPMatrix works around deprecated gl_ModelViewProjectionMatrix
if 'uMVPMatrix' in self.shaderVars:
mvpmatrix = bpy.context.region_data.perspective_matrix
mvpmatrix_buffer = bgl.Buffer(bgl.GL_FLOAT, [4,4], mvpmatrix)
self.assign('uMVPMatrix', mvpmatrix_buffer)
if self.funcStart: self.funcStart(self)
except Exception as e:
print('Error with using shader: ' + str(e))
bgl.glUseProgram(0)
def disable(self):
if DEBUG_PRINT:
print('disabling shader <=================')
if self.checkErrors:
self.drawing.glCheckError('disable program (%d) pre' % self.shaderProg)
try:
if self.funcEnd: self.funcEnd(self)
except Exception as e:
print('Error with shader: ' + str(e))
bgl.glUseProgram(0)
if self.checkErrors:
self.drawing.glCheckError('disable program (%d) post' % self.shaderProg)
brushStrokeShader = Shader.load_from_file('brushStrokeShader', 'brushstroke.glsl', checkErrors=False, bindTo0='vPos')
edgeShortenShader = Shader.load_from_file('edgeShortenShader', 'edgeshorten.glsl', checkErrors=False, bindTo0='vPos')
arrowShader = Shader.load_from_file('arrowShader', 'arrow.glsl', checkErrors=False)
def circleShaderStart(shader):
bgl.glDisable(bgl.GL_POINT_SMOOTH)
bgl.glEnable(bgl.GL_POINT_SPRITE)
def circleShaderEnd(shader):
bgl.glDisable(bgl.GL_POINT_SPRITE)
circleShader = Shader.load_from_file('circleShader', 'circle.glsl', checkErrors=False, funcStart=circleShaderStart, funcEnd=circleShaderEnd)
@@ -0,0 +1,63 @@
uniform mat4 uMVPMatrix;
uniform float uInOut;
attribute vec4 vPos;
attribute vec4 vFrom;
attribute vec4 vInColor;
attribute vec4 vOutColor;
varying float aRot;
varying vec4 aInColor;
varying vec4 aOutColor;
/////////////////////////////////////////////////////////////////////////
// vertex shader
#version 330
float angle(vec2 d) { return atan(d.y, d.x); }
void main() {
vec4 p0 = uMVPMatrix * vFrom;
vec4 p1 = uMVPMatrix * vPos;
gl_Position = p1;
aRot = angle((p1.xy / p1.w) - (p0.xy / p0.w));
aInColor = vInColor;
aOutColor = vOutColor;
}
/////////////////////////////////////////////////////////////////////////
// fragment shader
#version 330
out vec4 outColor;
float alpha(vec2 dir) {
vec2 d0 = dir - vec2(1,1);
vec2 d1 = dir - vec2(1,-1);
float d0v = -d0.x/2.0 - d0.y;
float d1v = -d1.x/2.0 + d1.y;
float dv0 = length(dir);
float dv1 = distance(dir, vec2(-2,0));
if(d0v < 1.0 || d1v < 1.0) return -1.0;
// if(dv0 > 1.0) return -1.0;
if(dv1 < 1.3) return -1.0;
if(d0v - 1.0 < (1.0 - uInOut) || d1v - 1.0 < (1.0 - uInOut)) return 0.0;
//if(dv0 > uInOut) return 0.0;
if(dv1 - 1.3 < (1.0 - uInOut)) return 0.0;
return 1.0;
}
void main() {
vec2 d = 2.0 * (gl_PointCoord - vec2(0.5, 0.5));
vec2 dr = vec2(cos(aRot)*d.x - sin(aRot)*d.y, sin(aRot)*d.x + cos(aRot)*d.y);
float a = alpha(dr);
if(a < 0.0) discard;
outColor = mix(aOutColor, aInColor, a);
}
@@ -0,0 +1,14 @@
[remap]
importer="glsl"
type="RDShaderFile"
uid="uid://p7jlrrqbbk2d"
path="res://.godot/imported/arrow.glsl-191c8445d031b18168ca21b09cdd1838.res"
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/shaders/arrow.glsl"
dest_files=["res://.godot/imported/arrow.glsl-191c8445d031b18168ca21b09cdd1838.res"]
[params]
@@ -0,0 +1,279 @@
uniform vec4 color; // color of geometry if not selected
uniform vec4 color_selected; // color of geometry if selected
uniform bool use_selection; // false: ignore selected, true: consider selected
uniform bool use_rounding;
uniform mat4 matrix_m; // model xform matrix
uniform mat3 matrix_mn; // model xform matrix for normal (inv transpose of matrix_m)
uniform mat4 matrix_t; // target xform matrix
uniform mat4 matrix_ti; // target xform matrix inverse
uniform mat4 matrix_v; // view xform matrix
uniform mat3 matrix_vn; // view xform matrix for normal
uniform mat4 matrix_p; // projection matrix
uniform int mirror_view; // 0=none; 1=draw edge at plane; 2=color faces on far side of plane
uniform float mirror_effect; // strength of effect: 0=none, 1=full
uniform bvec3 mirroring; // mirror along axis: 0=false, 1=true
uniform vec3 mirror_o; // mirroring origin wrt world
uniform vec3 mirror_x; // mirroring x-axis wrt world
uniform vec3 mirror_y; // mirroring y-axis wrt world
uniform vec3 mirror_z; // mirroring z-axis wrt world
uniform float hidden; // affects alpha for geometry below surface. 0=opaque, 1=transparent
uniform vec3 vert_scale; // used for mirroring
uniform float normal_offset; // how far to push geometry along normal
uniform bool constrain_offset; // should constrain offset by focus
uniform vec3 dir_forward; // forward direction
uniform float unit_scaling_factor;
uniform bool perspective;
uniform float clip_start;
uniform float clip_end;
uniform float view_distance;
uniform vec2 screen_size;
uniform float focus_mult;
uniform float offset;
uniform float dotoffset;
uniform bool cull_backfaces;
uniform float alpha_backface;
uniform float radius;
attribute vec3 vert_pos0; // position wrt model
attribute vec3 vert_pos1; // position wrt model
attribute vec2 vert_offset;
attribute vec3 vert_norm; // normal wrt model
attribute float selected; // is vertex selected? 0=no; 1=yes
varying vec4 vPPosition; // final position (projected)
varying vec4 vCPosition; // position wrt camera
varying vec4 vWPosition; // position wrt world
varying vec4 vMPosition; // position wrt model
varying vec4 vTPosition; // position wrt target
varying vec4 vWTPosition_x; // position wrt target world
varying vec4 vWTPosition_y; // position wrt target world
varying vec4 vWTPosition_z; // position wrt target world
varying vec4 vCTPosition_x; // position wrt target camera
varying vec4 vCTPosition_y; // position wrt target camera
varying vec4 vCTPosition_z; // position wrt target camera
varying vec4 vPTPosition_x; // position wrt target projected
varying vec4 vPTPosition_y; // position wrt target projected
varying vec4 vPTPosition_z; // position wrt target projected
varying vec3 vCNormal; // normal wrt camera
varying vec3 vWNormal; // normal wrt world
varying vec3 vMNormal; // normal wrt model
varying vec3 vTNormal; // normal wrt target
varying vec4 vColor; // color of geometry (considers selection)
varying vec2 vPCPosition;
/////////////////////////////////////////////////////////////////////////
// vertex shader
vec4 get_pos(vec3 p) {
float mult = 1.0;
if(constrain_offset) {
mult = 1.0;
} else {
float clip_dist = clip_end - clip_start;
float focus = (view_distance - clip_start) / clip_dist + 0.04;
mult = focus;
}
return vec4((p + vert_norm * normal_offset * mult * unit_scaling_factor) * vert_scale, 1.0);
}
vec4 xyz(vec4 v) {
return vec4(v.xyz / abs(v.w), sign(v.w));
}
void main() {
vec4 pos0 = get_pos(vert_pos0);
vec4 pos1 = get_pos(vert_pos1);
vec2 ppos0 = xyz(matrix_p * matrix_v * matrix_m * pos0).xy;
vec2 ppos1 = xyz(matrix_p * matrix_v * matrix_m * pos1).xy;
vec2 pdir0 = normalize(ppos1 - ppos0);
vec2 pdir1 = vec2(-pdir0.y, pdir0.x);
vec4 off = vec4((radius + 2.0) * pdir1 * 2.0 * (vert_offset.y-0.5) / screen_size, 0, 0);
vec4 pos = pos0 + vert_offset.x * (pos1 - pos0);
vec3 norm = normalize(vert_norm * vert_scale);
vec4 wpos = matrix_m * pos;
vec3 wnorm = normalize(matrix_mn * norm);
vec4 tpos = matrix_ti * wpos;
vec3 tnorm = vec3(
dot(wnorm, mirror_x),
dot(wnorm, mirror_y),
dot(wnorm, mirror_z));
vMPosition = pos;
vWPosition = wpos;
vCPosition = matrix_v * wpos;
vPPosition = off + xyz(matrix_p * matrix_v * wpos);
vPCPosition = xyz(matrix_p * matrix_v * wpos).xy;
vMNormal = norm;
vWNormal = wnorm;
vCNormal = normalize(matrix_vn * wnorm);
vTPosition = tpos;
vWTPosition_x = matrix_t * vec4(0.0, tpos.y, tpos.z, 1.0);
vWTPosition_y = matrix_t * vec4(tpos.x, 0.0, tpos.z, 1.0);
vWTPosition_z = matrix_t * vec4(tpos.x, tpos.y, 0.0, 1.0);
vCTPosition_x = matrix_v * vWTPosition_x;
vCTPosition_y = matrix_v * vWTPosition_y;
vCTPosition_z = matrix_v * vWTPosition_z;
vPTPosition_x = matrix_p * vCTPosition_x;
vPTPosition_y = matrix_p * vCTPosition_y;
vPTPosition_z = matrix_p * vCTPosition_z;
vTNormal = tnorm;
gl_Position = vPPosition;
vColor = (!use_selection || selected < 0.5) ? color : color_selected;
vColor.a *= (selected > 0.5) ? 1.0 : 1.0 - hidden;
//vColor.a *= 1.0 - hidden;
}
/////////////////////////////////////////////////////////////////////////
// fragment shader
layout(location = 0) out vec4 outColor;
vec3 xyz(vec4 v) { return v.xyz / v.w; }
// adjusts color based on mirroring settings and fragment position
vec4 coloring(vec4 orig) {
vec4 mixer = vec4(0.6, 0.6, 0.6, 0.0);
if(mirror_view == 0) {
// NO SYMMETRY VIEW
} else if(mirror_view == 1) {
// EDGE VIEW
float edge_width = 5.0 / screen_size.y;
vec3 viewdir;
if(perspective) {
viewdir = normalize(xyz(vCPosition));
} else {
viewdir = vec3(0,0,1);
}
vec3 diffc_x = xyz(vCTPosition_x) - xyz(vCPosition);
vec3 diffc_y = xyz(vCTPosition_y) - xyz(vCPosition);
vec3 diffc_z = xyz(vCTPosition_z) - xyz(vCPosition);
vec3 dirc_x = normalize(diffc_x);
vec3 dirc_y = normalize(diffc_y);
vec3 dirc_z = normalize(diffc_z);
vec3 diffp_x = xyz(vPTPosition_x) - xyz(vPPosition);
vec3 diffp_y = xyz(vPTPosition_y) - xyz(vPPosition);
vec3 diffp_z = xyz(vPTPosition_z) - xyz(vPPosition);
vec3 aspect = vec3(1.0, screen_size.y / screen_size.x, 0.0);
if(mirroring.x && length(diffp_x * aspect) < edge_width * (1.0 - pow(abs(dot(viewdir,dirc_x)), 10.0))) {
float s = (vTPosition.x < 0.0) ? 1.0 : 0.1;
mixer.r = 1.0;
mixer.a = mirror_effect * s + mixer.a * (1.0 - s);
}
if(mirroring.y && length(diffp_y * aspect) < edge_width * (1.0 - pow(abs(dot(viewdir,dirc_y)), 10.0))) {
float s = (vTPosition.y > 0.0) ? 1.0 : 0.1;
mixer.g = 1.0;
mixer.a = mirror_effect * s + mixer.a * (1.0 - s);
}
if(mirroring.z && length(diffp_z * aspect) < edge_width * (1.0 - pow(abs(dot(viewdir,dirc_z)), 10.0))) {
float s = (vTPosition.z < 0.0) ? 1.0 : 0.1;
mixer.b = 1.0;
mixer.a = mirror_effect * s + mixer.a * (1.0 - s);
}
} else if(mirror_view == 2) {
// FACE VIEW
if(mirroring.x && vTPosition.x < 0.0) {
mixer.r = 1.0;
mixer.a = mirror_effect;
}
if(mirroring.y && vTPosition.y > 0.0) {
mixer.g = 1.0;
mixer.a = mirror_effect;
}
if(mirroring.z && vTPosition.z < 0.0) {
mixer.b = 1.0;
mixer.a = mirror_effect;
}
}
float m0 = mixer.a, m1 = 1.0 - mixer.a;
return vec4(mixer.rgb * m0 + orig.rgb * m1, m0 + orig.a * m1);
}
void main() {
float clip = clip_end - clip_start;
float focus = (view_distance - clip_start) / clip + 0.04;
vec3 rgb = vColor.rgb;
float alpha = vColor.a;
float dist_from_center = length(screen_size * (vPCPosition - vPPosition.xy));
float alpha_mult = 1.0 - (dist_from_center - radius);
if(alpha_mult <= 0) {
discard;
return;
}
alpha *= alpha_mult;
if(perspective) {
// perspective projection
vec3 v = xyz(vCPosition);
float l = length(v);
float l_clip = (l - clip_start) / clip;
float d = -dot(vCNormal, v) / l;
if(d <= 0.0) {
if(cull_backfaces) {
alpha = 0.0;
discard;
return;
} else {
alpha *= alpha_backface;
}
}
float focus_push = focus_mult * sign(focus - l_clip) * pow(abs(focus - l_clip), 4.0) * 400.0;
float dist_push = pow(view_distance, 3.0) * 0.000001;
// MAGIC!
gl_FragDepth =
gl_FragCoord.z
- offset * l_clip * 200.0
- dotoffset * l_clip * 0.0001 * (1.0 - d)
- focus_push
;
} else {
// orthographic projection
vec3 v = vec3(0, 0, clip * 0.5); // + vCPosition.xyz / vCPosition.w;
float l = length(v);
float l_clip = (l - clip_start) / clip;
float d = dot(vCNormal, v) / l;
if(d <= 0.0) {
if(cull_backfaces) {
alpha = 0.0;
discard;
return;
} else {
alpha *= alpha_backface;
}
}
// MAGIC!
gl_FragDepth =
gl_FragCoord.z
- offset * l_clip * 1.0
+ dotoffset * l_clip * 0.000001 * (1.0 - d)
;
}
alpha *= pow(max(vCNormal.z, 0.01), 0.25);
outColor = coloring(vec4(rgb, alpha));
}
@@ -0,0 +1,14 @@
[remap]
importer="glsl"
type="RDShaderFile"
uid="uid://lfbh1eqrk6d1"
path="res://.godot/imported/bmesh_render_edges.glsl-6f2facf65fc336ac5f396a35bf787d21.res"
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/shaders/bmesh_render_edges.glsl"
dest_files=["res://.godot/imported/bmesh_render_edges.glsl-6f2facf65fc336ac5f396a35bf787d21.res"]
[params]
@@ -0,0 +1,248 @@
uniform vec4 color; // color of geometry if not selected
uniform vec4 color_selected; // color of geometry if selected
uniform bool use_selection; // false: ignore selected, true: consider selected
uniform bool use_rounding;
uniform mat4 matrix_m; // model xform matrix
uniform mat3 matrix_mn; // model xform matrix for normal (inv transpose of matrix_m)
uniform mat4 matrix_t; // target xform matrix
uniform mat4 matrix_ti; // target xform matrix inverse
uniform mat4 matrix_v; // view xform matrix
uniform mat3 matrix_vn; // view xform matrix for normal
uniform mat4 matrix_p; // projection matrix
uniform int mirror_view; // 0=none; 1=draw edge at plane; 2=color faces on far side of plane
uniform float mirror_effect; // strength of effect: 0=none, 1=full
uniform bvec3 mirroring; // mirror along axis: 0=false, 1=true
uniform vec3 mirror_o; // mirroring origin wrt world
uniform vec3 mirror_x; // mirroring x-axis wrt world
uniform vec3 mirror_y; // mirroring y-axis wrt world
uniform vec3 mirror_z; // mirroring z-axis wrt world
uniform float hidden; // affects alpha for geometry below surface. 0=opaque, 1=transparent
uniform vec3 vert_scale; // used for mirroring
uniform float normal_offset; // how far to push geometry along normal
uniform bool constrain_offset; // should constrain offset by focus
uniform vec3 dir_forward; // forward direction
uniform float unit_scaling_factor;
uniform bool perspective;
uniform float clip_start;
uniform float clip_end;
uniform float view_distance;
uniform vec2 screen_size;
uniform float focus_mult;
uniform float offset;
uniform float dotoffset;
uniform bool cull_backfaces;
uniform float alpha_backface;
uniform float radius;
attribute vec3 vert_pos; // position wrt model
attribute vec3 vert_norm; // normal wrt model
attribute float selected; // is vertex selected? 0=no; 1=yes
varying vec4 vPPosition; // final position (projected)
varying vec4 vCPosition; // position wrt camera
varying vec4 vTPosition; // position wrt target
varying vec4 vCTPosition_x; // position wrt target camera
varying vec4 vCTPosition_y; // position wrt target camera
varying vec4 vCTPosition_z; // position wrt target camera
varying vec4 vPTPosition_x; // position wrt target projected
varying vec4 vPTPosition_y; // position wrt target projected
varying vec4 vPTPosition_z; // position wrt target projected
varying vec3 vCNormal; // normal wrt camera
varying vec4 vColor; // color of geometry (considers selection)
/////////////////////////////////////////////////////////////////////////
// vertex shader
vec4 get_pos(vec3 p) {
float mult = 1.0;
if(constrain_offset) {
mult = 1.0;
} else {
float clip_dist = clip_end - clip_start;
float focus = (view_distance - clip_start) / clip_dist + 0.04;
mult = focus;
}
return vec4((p + vert_norm * normal_offset * mult * unit_scaling_factor) * vert_scale, 1.0);
}
vec4 xyz(vec4 v) {
return vec4(v.xyz / abs(v.w), sign(v.w));
}
void main() {
//vec4 off = vec4(radius * (vert_dir0 * vert_offset.x + vert_dir1 * vert_offset.y) / screen_size, 0, 0);
vec4 pos = get_pos(vert_pos);
vec3 norm = normalize(vert_norm * vert_scale);
vec4 wpos = matrix_m * pos;
vec3 wnorm = normalize(matrix_mn * norm);
vec4 tpos = matrix_ti * wpos;
vec3 tnorm = vec3(
dot(wnorm, mirror_x),
dot(wnorm, mirror_y),
dot(wnorm, mirror_z));
vCPosition = matrix_v * wpos;
vPPosition = xyz(matrix_p * matrix_v * wpos);
vCNormal = normalize(matrix_vn * wnorm);
vTPosition = tpos;
vCTPosition_x = matrix_v * matrix_t * vec4(0.0, tpos.y, tpos.z, 1.0);
vCTPosition_y = matrix_v * matrix_t * vec4(tpos.x, 0.0, tpos.z, 1.0);
vCTPosition_z = matrix_v * matrix_t * vec4(tpos.x, tpos.y, 0.0, 1.0);
vPTPosition_x = matrix_p * vCTPosition_x;
vPTPosition_y = matrix_p * vCTPosition_y;
vPTPosition_z = matrix_p * vCTPosition_z;
gl_Position = vPPosition;
vColor = (!use_selection || selected < 0.5) ? color : color_selected;
vColor.a *= (selected > 0.5) ? 1.0 : 1.0 - hidden;
}
/////////////////////////////////////////////////////////////////////////
// fragment shader
layout(location = 0) out vec4 outColor;
vec3 xyz(vec4 v) { return v.xyz / v.w; }
// adjusts color based on mirroring settings and fragment position
vec4 coloring(vec4 orig) {
vec4 mixer = vec4(0.6, 0.6, 0.6, 0.0);
if(mirror_view == 0) {
// NO SYMMETRY VIEW
// do nothing
} else if(mirror_view == 1) {
// EDGE VIEW
float edge_width = 5.0 / screen_size.y;
vec3 viewdir;
if(perspective) {
viewdir = normalize(xyz(vCPosition));
} else {
viewdir = vec3(0,0,1);
}
vec3 diffc_x = xyz(vCTPosition_x) - xyz(vCPosition);
vec3 diffc_y = xyz(vCTPosition_y) - xyz(vCPosition);
vec3 diffc_z = xyz(vCTPosition_z) - xyz(vCPosition);
vec3 dirc_x = normalize(diffc_x);
vec3 dirc_y = normalize(diffc_y);
vec3 dirc_z = normalize(diffc_z);
vec3 diffp_x = xyz(vPTPosition_x) - xyz(vPPosition);
vec3 diffp_y = xyz(vPTPosition_y) - xyz(vPPosition);
vec3 diffp_z = xyz(vPTPosition_z) - xyz(vPPosition);
vec3 aspect = vec3(1.0, screen_size.y / screen_size.x, 0.0);
float s = 0.0;
if(mirroring.x && length(diffp_x * aspect) < edge_width * (1.0 - pow(abs(dot(viewdir,dirc_x)), 10.0))) {
mixer.r = 1.0;
s = max(s, (vTPosition.x < 0.0) ? 1.0 : 0.1);
}
if(mirroring.y && length(diffp_y * aspect) < edge_width * (1.0 - pow(abs(dot(viewdir,dirc_y)), 10.0))) {
mixer.g = 1.0;
s = max(s, (vTPosition.y > 0.0) ? 1.0 : 0.1);
}
if(mirroring.z && length(diffp_z * aspect) < edge_width * (1.0 - pow(abs(dot(viewdir,dirc_z)), 10.0))) {
mixer.b = 1.0;
s = max(s, (vTPosition.z < 0.0) ? 1.0 : 0.1);
}
mixer.a = mirror_effect * s + mixer.a * (1.0 - s);
} else if(mirror_view == 2) {
// FACE VIEW
if(mirroring.x && vTPosition.x < 0.0) {
mixer.r = 1.0;
mixer.a = mirror_effect;
}
if(mirroring.y && vTPosition.y > 0.0) {
mixer.g = 1.0;
mixer.a = mirror_effect;
}
if(mirroring.z && vTPosition.z < 0.0) {
mixer.b = 1.0;
mixer.a = mirror_effect;
}
}
vec3 n = normalize(vCNormal);
if(n.z < 0) discard;
float m = sign(n.z) * pow(abs(n.z), 0.25) / 2.0 + 0.5;
//mixer.a *= clamp(m, 0.0, 1.0);
float m0 = mixer.a, m1 = 1.0 - mixer.a;
return vec4(mixer.rgb * m0 + orig.rgb * orig.a * m1, m0 + orig.a * m1);
}
void main() {
float clip = clip_end - clip_start;
float focus = (view_distance - clip_start) / clip + 0.04;
vec3 rgb = vColor.rgb;
float alpha = vColor.a;
if(perspective) {
// perspective projection
vec3 v = xyz(vCPosition);
float l = length(v);
float l_clip = (l - clip_start) / clip;
float d = -dot(vCNormal, v) / l;
if(d <= 0.0) {
if(cull_backfaces) {
alpha = 0.0;
discard;
return;
} else {
alpha *= alpha_backface;
}
}
float focus_push = focus_mult * sign(focus - l_clip) * pow(abs(focus - l_clip), 4.0) * 400.0;
float dist_push = pow(view_distance, 3.0) * 0.000001;
// MAGIC!
gl_FragDepth =
gl_FragCoord.z
- offset * l_clip * 200.0
- dotoffset * l_clip * 0.0001 * (1.0 - d)
- focus_push
;
} else {
// orthographic projection
vec3 v = vec3(0, 0, clip * 0.5); // + vCPosition.xyz / vCPosition.w;
float l = length(v);
float l_clip = (l - clip_start) / clip;
float d = dot(vCNormal, v) / l;
if(d <= 0.0) {
if(cull_backfaces) {
alpha = 0.0;
discard;
return;
} else {
alpha *= alpha_backface;
}
}
// MAGIC!
gl_FragDepth =
gl_FragCoord.z
- offset * l_clip * 1.0
+ dotoffset * l_clip * 0.000001 * (1.0 - d)
;
}
alpha *= pow(max(vCNormal.z, 0.01), 0.25);
outColor = coloring(vec4(rgb, alpha));
}
@@ -0,0 +1,14 @@
[remap]
importer="glsl"
type="RDShaderFile"
uid="uid://bcod1hg2qqalf"
path="res://.godot/imported/bmesh_render_faces.glsl-e769cdfa9e4f9bfed9ebd89caf95ca2f.res"
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/shaders/bmesh_render_faces.glsl"
dest_files=["res://.godot/imported/bmesh_render_faces.glsl-e769cdfa9e4f9bfed9ebd89caf95ca2f.res"]
[params]
@@ -0,0 +1,265 @@
uniform vec4 color; // color of geometry if not selected
uniform vec4 color_selected; // color of geometry if selected
uniform float use_selection; // 0.0: ignore selected, 1.0: consider selected
uniform float use_rounding; // 0.0: draw normally; 1.0: rounding (for points)
uniform mat4 matrix_m; // model xform matrix
uniform mat3 matrix_mn; // model xform matrix for normal (inv transpose of matrix_m)
uniform mat4 matrix_t; // target xform matrix
uniform mat4 matrix_ti; // target xform matrix inverse
uniform mat4 matrix_v; // view xform matrix
uniform mat3 matrix_vn; // view xform matrix for normal
uniform mat4 matrix_p; // projection matrix
uniform float mirror_view; // 0=none; 1=draw edge at plane; 2=color faces on far side of plane
uniform float mirror_effect; // strength of effect: 0=none, 1=full
uniform vec3 mirroring; // mirror along axis: 0=false, 1=true
uniform vec3 mirror_o; // mirroring origin wrt world
uniform vec3 mirror_x; // mirroring x-axis wrt world
uniform vec3 mirror_y; // mirroring y-axis wrt world
uniform vec3 mirror_z; // mirroring z-axis wrt world
uniform float hidden; // affects alpha for geometry below surface. 0=opaque, 1=transparent
uniform vec3 vert_scale; // used for mirroring
uniform float normal_offset; // how far to push geometry along normal
uniform float constrain_offset; // should constrain offset by focus
uniform vec3 dir_forward; // forward direction
uniform float perspective;
uniform float clip_start;
uniform float clip_end;
uniform float view_distance;
uniform vec2 screen_size;
uniform float focus_mult;
uniform float offset;
uniform float dotoffset;
uniform float cull_backfaces; // 0=no, 1=yes
uniform float alpha_backface;
attribute vec3 vert_pos; // position wrt model
attribute vec3 vert_norm; // normal wrt model
attribute float selected; // is vertex selected?
varying vec4 vPPosition; // final position (projected)
varying vec4 vCPosition; // position wrt camera
varying vec4 vWPosition; // position wrt world
varying vec4 vMPosition; // position wrt model
varying vec4 vTPosition; // position wrt target
varying vec4 vWTPosition_x; // position wrt target world
varying vec4 vWTPosition_y; // position wrt target world
varying vec4 vWTPosition_z; // position wrt target world
varying vec4 vCTPosition_x; // position wrt target camera
varying vec4 vCTPosition_y; // position wrt target camera
varying vec4 vCTPosition_z; // position wrt target camera
varying vec4 vPTPosition_x; // position wrt target projected
varying vec4 vPTPosition_y; // position wrt target projected
varying vec4 vPTPosition_z; // position wrt target projected
varying vec3 vCNormal; // normal wrt camera
varying vec3 vWNormal; // normal wrt world
varying vec3 vMNormal; // normal wrt model
varying vec3 vTNormal; // normal wrt target
varying vec4 vColor; // color of geometry (considers selection)
/////////////////////////////////////////////////////////////////////////
// vertex shader
#version 330
bool floatnear(float v, float n) { return abs(v-n) < 0.5; }
vec4 get_pos(void) {
float mult = 1.0;
if(floatnear(constrain_offset, 0.0)) {
mult = 1.0;
} else {
float clip_dist = clip_end - clip_start;
float focus = (view_distance - clip_start) / clip_dist + 0.04;
mult = focus;
}
return vec4((vert_pos + vert_norm * normal_offset * mult) * vert_scale, 1.0);
}
void main() {
vec4 pos = get_pos();
vec3 norm = normalize(vert_norm * vert_scale);
vec4 wpos = matrix_m * pos;
vec3 wnorm = normalize(matrix_mn * norm);
vec4 tpos = matrix_ti * wpos;
vec3 tnorm = vec3(
dot(wnorm, mirror_x),
dot(wnorm, mirror_y),
dot(wnorm, mirror_z));
vMPosition = pos;
vWPosition = wpos;
vCPosition = matrix_v * wpos;
vPPosition = matrix_p * matrix_v * wpos;
vMNormal = norm;
vWNormal = wnorm;
vCNormal = normalize(matrix_vn * wnorm);
vTPosition = tpos;
vWTPosition_x = matrix_t * vec4(0.0, tpos.y, tpos.z, 1.0);
vWTPosition_y = matrix_t * vec4(tpos.x, 0.0, tpos.z, 1.0);
vWTPosition_z = matrix_t * vec4(tpos.x, tpos.y, 0.0, 1.0);
vCTPosition_x = matrix_v * vWTPosition_x;
vCTPosition_y = matrix_v * vWTPosition_y;
vCTPosition_z = matrix_v * vWTPosition_z;
vPTPosition_x = matrix_p * vCTPosition_x;
vPTPosition_y = matrix_p * vCTPosition_y;
vPTPosition_z = matrix_p * vCTPosition_z;
vTNormal = tnorm;
gl_Position = vPPosition;
vColor = (use_selection < 0.5 || selected < 0.5) ? color : color_selected;
vColor.a *= 1.0 - hidden;
}
/////////////////////////////////////////////////////////////////////////
// fragment shader
#version 330
out vec4 outColor;
vec3 xyz(vec4 v) { return v.xyz / v.w; }
bool floatnear(float v, float n) { return abs(v-n) < 0.5; }
// adjusts color based on mirroring settings and fragment position
vec4 coloring(vec4 orig) {
vec4 mixer = vec4(0.6, 0.6, 0.6, 0.0);
if(floatnear(mirror_view, 0.0)) {
// NO SYMMETRY VIEW
} else if(floatnear(mirror_view, 1.0)) {
// EDGE VIEW
float edge_width = 5.0 / screen_size.y;
vec3 viewdir;
if(floatnear(perspective, 1.0)) {
viewdir = normalize(xyz(vCPosition));
} else {
viewdir = vec3(0,0,1);
}
vec3 diffc_x = xyz(vCTPosition_x) - xyz(vCPosition);
vec3 diffc_y = xyz(vCTPosition_y) - xyz(vCPosition);
vec3 diffc_z = xyz(vCTPosition_z) - xyz(vCPosition);
vec3 dirc_x = normalize(diffc_x);
vec3 dirc_y = normalize(diffc_y);
vec3 dirc_z = normalize(diffc_z);
vec3 diffp_x = xyz(vPTPosition_x) - xyz(vPPosition);
vec3 diffp_y = xyz(vPTPosition_y) - xyz(vPPosition);
vec3 diffp_z = xyz(vPTPosition_z) - xyz(vPPosition);
vec3 aspect = vec3(1.0, screen_size.y / screen_size.x, 0.0);
if(floatnear(mirroring.x, 1.0) && length(diffp_x * aspect) < edge_width * (1.0 - pow(abs(dot(viewdir,dirc_x)), 10.0))) {
float s = (vTPosition.x < 0.0) ? 1.0 : 0.1;
mixer.r = 1.0;
mixer.a = mirror_effect * s + mixer.a * (1.0 - s);
}
if(floatnear(mirroring.y, 1.0) && length(diffp_y * aspect) < edge_width * (1.0 - pow(abs(dot(viewdir,dirc_y)), 10.0))) {
float s = (vTPosition.y > 0.0) ? 1.0 : 0.1;
mixer.g = 1.0;
mixer.a = mirror_effect * s + mixer.a * (1.0 - s);
}
if(floatnear(mirroring.z, 1.0) && length(diffp_z * aspect) < edge_width * (1.0 - pow(abs(dot(viewdir,dirc_z)), 10.0))) {
float s = (vTPosition.z < 0.0) ? 1.0 : 0.1;
mixer.b = 1.0;
mixer.a = mirror_effect * s + mixer.a * (1.0 - s);
}
} else if(floatnear(mirror_view, 2.0)) {
// FACE VIEW
if(floatnear(mirroring.x, 1.0) && vTPosition.x < 0.0) {
mixer.r = 1.0;
mixer.a = mirror_effect;
}
if(floatnear(mirroring.y, 1.0) && vTPosition.y > 0.0) {
mixer.g = 1.0;
mixer.a = mirror_effect;
}
if(floatnear(mirroring.z, 1.0) && vTPosition.z < 0.0) {
mixer.b = 1.0;
mixer.a = mirror_effect;
}
}
float m0 = mixer.a, m1 = 1.0 - mixer.a;
return vec4(mixer.rgb * m0 + orig.rgb * m1, m0 + orig.a * m1);
}
void main() {
float clip = clip_end - clip_start;
float focus = (view_distance - clip_start) / clip + 0.04;
vec3 rgb = vColor.rgb;
float alpha = vColor.a;
//gl_FragColor = coloring(vColor);
//gl_FragDepth = gl_FragCoord.z * 0.9999;
//return;
if(use_rounding > 0.5 && length(gl_PointCoord - vec2(0.5,0.5)) > 0.5) discard;
if(floatnear(perspective, 1.0)) {
// perspective projection
vec3 v = vCPosition.xyz / vCPosition.w;
float l = length(v);
float l_clip = (l - clip_start) / clip;
float d = -dot(vCNormal, v) / l;
if(d <= 0.0) {
if(cull_backfaces > 0.5) {
alpha = 0.0;
discard;
} else {
alpha *= alpha_backface;
}
}
float focus_push = focus_mult * sign(focus - l_clip) * pow(abs(focus - l_clip), 4.0) * 400.0;
float dist_push = pow(view_distance, 3.0) * 0.000001;
// MAGIC!
gl_FragDepth =
gl_FragCoord.z
- offset * l_clip * 200.0
- dotoffset * l_clip * 0.0001 * (1.0 - d)
- focus_push
;
} else {
// orthographic projection
vec3 v = vec3(0, 0, clip * 0.5); // + vCPosition.xyz / vCPosition.w;
float l = length(v);
float l_clip = (l - clip_start) / clip;
float d = dot(vCNormal, v) / l;
if(d <= 0.0) {
if(cull_backfaces > 0.5) {
alpha = 0.0;
discard;
} else {
alpha *= alpha_backface;
}
}
// MAGIC!
gl_FragDepth =
gl_FragCoord.z
- offset * l_clip * 1.0
+ dotoffset * l_clip * 0.000001 * (1.0 - d)
;
}
alpha *= pow(max(vCNormal.z, 0.01), 0.25);
outColor = coloring(vec4(rgb, alpha));
}
@@ -0,0 +1,14 @@
[remap]
importer="glsl"
type="RDShaderFile"
uid="uid://boaqy00a8vtst"
path="res://.godot/imported/bmesh_render_old.glsl-d47999fa51bbeff357ad06b40627c9ea.res"
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/shaders/bmesh_render_old.glsl"
dest_files=["res://.godot/imported/bmesh_render_old.glsl-d47999fa51bbeff357ad06b40627c9ea.res"]
[params]
@@ -0,0 +1,259 @@
uniform vec4 color; // color of geometry if not selected
uniform vec4 color_selected; // color of geometry if selected
uniform bool use_selection; // false: ignore selected, true: consider selected
uniform bool use_rounding;
uniform mat4 matrix_m; // model xform matrix
uniform mat3 matrix_mn; // model xform matrix for normal (inv transpose of matrix_m)
uniform mat4 matrix_t; // target xform matrix
uniform mat4 matrix_ti; // target xform matrix inverse
uniform mat4 matrix_v; // view xform matrix
uniform mat3 matrix_vn; // view xform matrix for normal
uniform mat4 matrix_p; // projection matrix
uniform int mirror_view; // 0=none; 1=draw edge at plane; 2=color faces on far side of plane
uniform float mirror_effect; // strength of effect: 0=none, 1=full
uniform bvec3 mirroring; // mirror along axis: 0=false, 1=true
uniform vec3 mirror_o; // mirroring origin wrt world
uniform vec3 mirror_x; // mirroring x-axis wrt world
uniform vec3 mirror_y; // mirroring y-axis wrt world
uniform vec3 mirror_z; // mirroring z-axis wrt world
uniform float hidden; // affects alpha for geometry below surface. 0=opaque, 1=transparent
uniform vec3 vert_scale; // used for mirroring
uniform float normal_offset; // how far to push geometry along normal
uniform bool constrain_offset; // should constrain offset by focus
uniform vec3 dir_forward; // forward direction
uniform float unit_scaling_factor;
uniform bool perspective;
uniform float clip_start;
uniform float clip_end;
uniform float view_distance;
uniform vec2 screen_size;
uniform float focus_mult;
uniform float offset;
uniform float dotoffset;
uniform bool cull_backfaces;
uniform float alpha_backface;
uniform float radius;
attribute vec3 vert_pos; // position wrt model
attribute vec2 vert_offset;
attribute vec3 vert_norm; // normal wrt model
attribute float selected; // is vertex selected? 0=no; 1=yes
varying vec4 vPPosition; // final position (projected)
varying vec4 vCPosition; // position wrt camera
varying vec4 vTPosition; // position wrt target
varying vec4 vCTPosition_x; // position wrt target camera
varying vec4 vCTPosition_y; // position wrt target camera
varying vec4 vCTPosition_z; // position wrt target camera
varying vec4 vPTPosition_x; // position wrt target projected
varying vec4 vPTPosition_y; // position wrt target projected
varying vec4 vPTPosition_z; // position wrt target projected
varying vec3 vCNormal; // normal wrt camera
varying vec4 vColor; // color of geometry (considers selection)
varying vec2 vPCPosition;
/////////////////////////////////////////////////////////////////////////
// vertex shader
vec4 get_pos(vec3 p) {
float mult = 1.0;
if(constrain_offset) {
mult = 1.0;
} else {
float clip_dist = clip_end - clip_start;
float focus = (view_distance - clip_start) / clip_dist + 0.04;
mult = focus;
}
return vec4((p + vert_norm * normal_offset * mult * unit_scaling_factor) * vert_scale, 1.0);
}
vec4 xyz(vec4 v) {
return vec4(v.xyz / abs(v.w), sign(v.w));
}
void main() {
vec2 vo = vert_offset * 2 - vec2(1, 1);
vec4 off = vec4((radius + 2) * vo / screen_size, 0, 0);
vec4 pos = get_pos(vert_pos);
vec3 norm = normalize(vert_norm * vert_scale);
vec4 wpos = matrix_m * pos;
vec3 wnorm = normalize(matrix_mn * norm);
vec4 tpos = matrix_ti * wpos;
vec3 tnorm = vec3(
dot(wnorm, mirror_x),
dot(wnorm, mirror_y),
dot(wnorm, mirror_z));
vCPosition = matrix_v * wpos;
vPPosition = off + xyz(matrix_p * matrix_v * wpos);
vPCPosition = xyz(matrix_p * matrix_v * wpos).xy;
vCNormal = normalize(matrix_vn * wnorm);
vTPosition = tpos;
vCTPosition_x = matrix_v * matrix_t * vec4(0.0, tpos.y, tpos.z, 1.0);
vCTPosition_y = matrix_v * matrix_t * vec4(tpos.x, 0.0, tpos.z, 1.0);
vCTPosition_z = matrix_v * matrix_t * vec4(tpos.x, tpos.y, 0.0, 1.0);
vPTPosition_x = matrix_p * vCTPosition_x;
vPTPosition_y = matrix_p * vCTPosition_y;
vPTPosition_z = matrix_p * vCTPosition_z;
gl_Position = vPPosition;
vColor = (!use_selection || selected < 0.5) ? color : color_selected;
vColor.a *= (selected > 0.5) ? 1.0 : 1.0 - hidden;
//vColor.a *= 1.0 - hidden;
}
/////////////////////////////////////////////////////////////////////////
// fragment shader
layout(location = 0) out vec4 outColor;
vec3 xyz(vec4 v) { return v.xyz / v.w; }
// adjusts color based on mirroring settings and fragment position
vec4 coloring(vec4 orig) {
vec4 mixer = vec4(0.6, 0.6, 0.6, 0.0);
if(mirror_view == 0) {
// NO SYMMETRY VIEW
} else if(mirror_view == 1) {
// EDGE VIEW
float edge_width = 5.0 / screen_size.y;
vec3 viewdir;
if(perspective) {
viewdir = normalize(xyz(vCPosition));
} else {
viewdir = vec3(0,0,1);
}
vec3 diffc_x = xyz(vCTPosition_x) - xyz(vCPosition);
vec3 diffc_y = xyz(vCTPosition_y) - xyz(vCPosition);
vec3 diffc_z = xyz(vCTPosition_z) - xyz(vCPosition);
vec3 dirc_x = normalize(diffc_x);
vec3 dirc_y = normalize(diffc_y);
vec3 dirc_z = normalize(diffc_z);
vec3 diffp_x = xyz(vPTPosition_x) - xyz(vPPosition);
vec3 diffp_y = xyz(vPTPosition_y) - xyz(vPPosition);
vec3 diffp_z = xyz(vPTPosition_z) - xyz(vPPosition);
vec3 aspect = vec3(1.0, screen_size.y / screen_size.x, 0.0);
if(mirroring.x && length(diffp_x * aspect) < edge_width * (1.0 - pow(abs(dot(viewdir,dirc_x)), 10.0))) {
float s = (vTPosition.x < 0.0) ? 1.0 : 0.1;
mixer.r = 1.0;
mixer.a = mirror_effect * s + mixer.a * (1.0 - s);
}
if(mirroring.y && length(diffp_y * aspect) < edge_width * (1.0 - pow(abs(dot(viewdir,dirc_y)), 10.0))) {
float s = (vTPosition.y > 0.0) ? 1.0 : 0.1;
mixer.g = 1.0;
mixer.a = mirror_effect * s + mixer.a * (1.0 - s);
}
if(mirroring.z && length(diffp_z * aspect) < edge_width * (1.0 - pow(abs(dot(viewdir,dirc_z)), 10.0))) {
float s = (vTPosition.z < 0.0) ? 1.0 : 0.1;
mixer.b = 1.0;
mixer.a = mirror_effect * s + mixer.a * (1.0 - s);
}
} else if(mirror_view == 2) {
// FACE VIEW
if(mirroring.x && vTPosition.x < 0.0) {
mixer.r = 1.0;
mixer.a = mirror_effect;
}
if(mirroring.y && vTPosition.y > 0.0) {
mixer.g = 1.0;
mixer.a = mirror_effect;
}
if(mirroring.z && vTPosition.z < 0.0) {
mixer.b = 1.0;
mixer.a = mirror_effect;
}
}
float m0 = mixer.a, m1 = 1.0 - mixer.a;
return vec4(mixer.rgb * m0 + orig.rgb * m1, m0 + orig.a * m1);
}
void main() {
float clip = clip_end - clip_start;
float focus = (view_distance - clip_start) / clip + 0.04;
vec3 rgb = vColor.rgb;
float alpha = vColor.a;
if(use_rounding) {
float dist_from_center = length(screen_size * (vPCPosition - vPPosition.xy));
float alpha_mult = 1.0 - (dist_from_center - radius);
if(alpha_mult <= 0) {
discard;
return;
}
alpha *= alpha_mult;
}
if(perspective) {
// perspective projection
vec3 v = xyz(vCPosition);
float l = length(v);
float l_clip = (l - clip_start) / clip;
float d = -dot(vCNormal, v) / l;
if(d <= 0.0) {
if(cull_backfaces) {
alpha = 0.0;
discard;
return;
} else {
alpha *= alpha_backface;
}
}
float focus_push = focus_mult * sign(focus - l_clip) * pow(abs(focus - l_clip), 4.0) * 400.0;
float dist_push = pow(view_distance, 3.0) * 0.000001;
// MAGIC!
gl_FragDepth =
gl_FragCoord.z
- offset * l_clip * 200.0
- dotoffset * l_clip * 0.0001 * (1.0 - d)
- focus_push
;
} else {
// orthographic projection
vec3 v = vec3(0, 0, clip * 0.5); // + vCPosition.xyz / vCPosition.w;
float l = length(v);
float l_clip = (l - clip_start) / clip;
float d = dot(vCNormal, v) / l;
if(d <= 0.0) {
if(cull_backfaces) {
alpha = 0.0;
discard;
return;
} else {
alpha *= alpha_backface;
}
}
// MAGIC!
gl_FragDepth =
gl_FragCoord.z
- offset * l_clip * 1.0
+ dotoffset * l_clip * 0.000001 * (1.0 - d)
;
}
alpha *= pow(max(vCNormal.z, 0.01), 0.25);
outColor = coloring(vec4(rgb, alpha));
}
@@ -0,0 +1,14 @@
[remap]
importer="glsl"
type="RDShaderFile"
uid="uid://ctp5dpovwud4n"
path="res://.godot/imported/bmesh_render_verts.glsl-9a029148102a1ca62b9f56406ba73f13.res"
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/shaders/bmesh_render_verts.glsl"
dest_files=["res://.godot/imported/bmesh_render_verts.glsl-9a029148102a1ca62b9f56406ba73f13.res"]
[params]
@@ -0,0 +1,33 @@
uniform mat4 uMVPMatrix;
attribute vec2 vPos;
attribute vec4 vColor;
attribute float vDistAccum;
varying vec4 aColor;
varying float aDistAccum;
/////////////////////////////////////////////////////////////////////////
// vertex shader
#version 330
void main() {
gl_Position = uMVPMatrix * vec4(vPos, 0.0, 1.0);
aColor = vColor;
aDistAccum = vDistAccum;
}
/////////////////////////////////////////////////////////////////////////
// fragment shader
#version 330
out vec4 outColor;
void main() {
if(mod(int(aDistAccum / 2), 4) >= 2) discard;
outColor = aColor;
}
@@ -0,0 +1,14 @@
[remap]
importer="glsl"
type="RDShaderFile"
uid="uid://dvia0yn8w0wp8"
path="res://.godot/imported/brushstroke.glsl-84fe5abf680a06d301fa790284d626fc.res"
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/shaders/brushstroke.glsl"
dest_files=["res://.godot/imported/brushstroke.glsl-84fe5abf680a06d301fa790284d626fc.res"]
[params]
@@ -0,0 +1,35 @@
uniform mat4 uMVPMatrix;
uniform float uInOut;
attribute vec4 vPos;
attribute vec4 vInColor;
attribute vec4 vOutColor;
varying vec4 aInColor;
varying vec4 aOutColor;
/////////////////////////////////////////////////////////////////////////
// vertex shader
#version 330
void main() {
gl_Position = uMVPMatrix * vPos;
aInColor = vInColor;
aOutColor = vOutColor;
}
/////////////////////////////////////////////////////////////////////////
// fragment shader
#version 330
out vec4 outColor;
void main() {
float d = 2.0 * distance(gl_PointCoord, vec2(0.5, 0.5));
if(d > 1.0) discard;
outColor = (d > uInOut) ? aOutColor : aInColor;
}
@@ -0,0 +1,14 @@
[remap]
importer="glsl"
type="RDShaderFile"
uid="uid://dgdfcqyqyawtw"
path="res://.godot/imported/circle.glsl-4da0d16912b8b92fbcdc6f375b12caa9.res"
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/shaders/circle.glsl"
dest_files=["res://.godot/imported/circle.glsl-4da0d16912b8b92fbcdc6f375b12caa9.res"]
[params]
@@ -0,0 +1,78 @@
/*
draws an antialiased, stippled circle
ex: stipple [3,2] color0 '=' color1 '-'
produces '===--===--===--===-' (just wrapped as a circle!)
*/
#define PI 3.14159265359
#define TAU 6.28318530718
uniform vec2 screensize; // width,height of screen (for antialiasing)
uniform mat4 MVPMatrix; // pixel matrix
uniform vec2 center; // center of circle
uniform float radius; // radius of circle
uniform vec2 stipple; // lengths of on/off stipple
uniform float stippleOffset; // length to shift initial stipple of front
uniform vec4 color0; // color of on stipple
uniform vec4 color1; // color of off stipple
uniform float width; // line width, perpendicular to line
/////////////////////////////////////////////////////////////////////////
// vertex shader
in vec2 pos; // x: [0,1], ratio of circumference. y: [0,1], inner/outer radius (width)
noperspective out vec2 vpos; // position scaled by screensize
noperspective out vec2 cpos; // center of line, scaled by screensize
noperspective out float offset; // stipple offset of individual fragment
void main() {
float circumference = TAU * radius;
float ang = TAU * pos.x;
float r = radius + (pos.y - 0.5) * (width + 2.0);
vec2 v = vec2(cos(ang), sin(ang));
vec2 p = center + vec2(0.5,0.5) + r * v;
vec2 cp = center + vec2(0.5,0.5) + radius * v;
vec4 pcp = MVPMatrix * vec4(cp, 0.0, 1.0);
gl_Position = MVPMatrix * vec4(p, 0.0, 1.0);
offset = circumference * pos.x + stippleOffset;
vpos = vec2(gl_Position.x * screensize.x, gl_Position.y * screensize.y);
cpos = vec2(pcp.x * screensize.x, pcp.y * screensize.y);
}
/////////////////////////////////////////////////////////////////////////
// fragment shader
noperspective in vec2 vpos;
noperspective in vec2 cpos;
noperspective in float offset;
out vec4 outColor;
void main() {
// stipple
if(stipple.y <= 0) { // stipple disabled
outColor = color0;
} else {
float t = stipple.x + stipple.y;
float s = mod(offset, t);
float sd = s - stipple.x;
if(s <= 0.5 || s >= t - 0.5) {
outColor = mix(color1, color0, mod(s + 0.5, t));
} else if(s >= stipple.x - 0.5 && s <= stipple.x + 0.5) {
outColor = mix(color0, color1, s - (stipple.x - 0.5));
} else if(s < stipple.x) {
outColor = color0;
} else {
outColor = color1;
}
}
// antialias along edge of line
float cdist = length(cpos - vpos);
if(cdist > width) {
outColor.a *= clamp(1.0 - (cdist - width), 0.0, 1.0);
}
}
@@ -0,0 +1,14 @@
[remap]
importer="glsl"
type="RDShaderFile"
uid="uid://dipfr275tpuoj"
path="res://.godot/imported/circle_2D.glsl-94eb0fd6821260572ee695a12dfb5998.res"
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/shaders/circle_2D.glsl"
dest_files=["res://.godot/imported/circle_2D.glsl-94eb0fd6821260572ee695a12dfb5998.res"]
[params]
@@ -0,0 +1,34 @@
#define PI 3.14159265359
#define TAU 6.28318530718
uniform mat4 MVPMatrix; // pixel matrix
uniform vec3 center; // center of circle
uniform vec4 color; // color of circle
uniform vec3 plane_x; // x direction in plane the circle lies in
uniform vec3 plane_y; // y direction in plane the circle lies in
uniform float radius; // radius of circle
uniform float width; // line width, perpendicular to line (in plane)
/////////////////////////////////////////////////////////////////////////
// vertex shader
in vec2 pos; // x: [0,1], ratio of circumference. y: [0,1], inner/outer radius (width)
void main() {
float ang = TAU * pos.x;
float r = radius + pos.y * width;
vec3 p = center + r * (plane_x * cos(ang) + plane_y * sin(ang));
gl_Position = MVPMatrix * vec4(p, 1.0);
}
/////////////////////////////////////////////////////////////////////////
// fragment shader
out vec4 outColor;
void main() {
outColor = color;
}
@@ -0,0 +1,14 @@
[remap]
importer="glsl"
type="RDShaderFile"
uid="uid://burcc1mtgf38j"
path="res://.godot/imported/circle_3D.glsl-191982998016c51ad47063898682d8b0.res"
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/shaders/circle_3D.glsl"
dest_files=["res://.godot/imported/circle_3D.glsl-191982998016c51ad47063898682d8b0.res"]
[params]
@@ -0,0 +1,40 @@
uniform vec2 uScreenSize;
uniform mat4 uMVPMatrix;
attribute vec4 vPos;
attribute vec4 vFrom;
attribute vec4 vColor;
attribute float vRadius;
varying vec4 aColor;
/////////////////////////////////////////////////////////////////////////
// vertex shader
#version 330
void main() {
vec4 p0 = uMVPMatrix * vPos;
vec4 p1 = uMVPMatrix * vFrom;
vec2 s0 = uScreenSize * p0.xy / p0.w;
vec2 s1 = uScreenSize * p1.xy / p1.w;
vec2 d = normalize(s1 - s0);
vec2 s2 = s0 + d * vRadius;
gl_Position = vec4(s2 / uScreenSize * p0.w, p0.z, p0.w);
aColor = vColor;
}
/////////////////////////////////////////////////////////////////////////
// fragment shader
#version 330
out vec4 outColor;
void main() {
outColor = aColor;
}
@@ -0,0 +1,14 @@
[remap]
importer="glsl"
type="RDShaderFile"
uid="uid://hv4nft6gjfbk"
path="res://.godot/imported/edgeshorten.glsl-ac29532c8cc9f0b87ec9f39745da8533.res"
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/shaders/edgeshorten.glsl"
dest_files=["res://.godot/imported/edgeshorten.glsl-ac29532c8cc9f0b87ec9f39745da8533.res"]
[params]
@@ -0,0 +1,76 @@
/*
draws an antialiased, stippled line
ex: stipple [3,2] color0 '=' color1 '-'
produces '===--===--===--===-'
| |
\_pos0 pos1_/
*/
uniform vec2 screensize; // width,height of screen (for antialiasing)
uniform mat4 MVPMatrix; // pixel matrix
uniform vec2 pos0; // front end of line
uniform vec2 pos1; // back end of line
uniform vec2 stipple; // lengths of on/off stipple
uniform float stippleOffset; // length to shift initial stipple of front
uniform vec4 color0; // color of on stipple
uniform vec4 color1; // color of off stipple
uniform float width; // line width, perpendicular to line
/////////////////////////////////////////////////////////////////////////
// vertex shader
in vec2 pos; // which corner of line ([0,0], [0,1], [1,1], [1,0])
noperspective out vec2 vpos; // position scaled by screensize
noperspective out vec2 cpos; // center of line, scaled by screensize
noperspective out float offset; // stipple offset of individual fragment
void main() {
vec2 v01 = pos1 - pos0;
vec2 d01 = normalize(v01);
vec2 perp = vec2(-d01.y, d01.x);
vec2 cp = pos0 + vec2(0.5,0.5) + (pos.x * v01);
vec2 p = cp + ((width+2.0) * (pos.y - 0.5) * perp);
vec4 pcp = MVPMatrix * vec4(cp, 0.0, 1.0);
gl_Position = MVPMatrix * vec4(p, 0.0, 1.0);
offset = length(v01) * pos.x + stippleOffset;
vpos = vec2(gl_Position.x * screensize.x, gl_Position.y * screensize.y);
cpos = vec2(pcp.x * screensize.x, pcp.y * screensize.y);
}
/////////////////////////////////////////////////////////////////////////
// fragment shader
noperspective in vec2 vpos;
noperspective in vec2 cpos;
noperspective in float offset;
out vec4 outColor;
void main() {
// stipple
if(stipple.y <= 0) { // stipple disabled
outColor = color0;
} else {
float t = stipple.x + stipple.y;
float s = mod(offset, t);
float sd = s - stipple.x;
vec4 colors = color1;
if(colors.a < (1.0/255.0)) colors.rgb = color0.rgb;
if(s <= 0.5 || s >= t - 0.5) {
outColor = mix(colors, color0, mod(s + 0.5, t));
} else if(s >= stipple.x - 0.5 && s <= stipple.x + 0.5) {
outColor = mix(color0, colors, s - (stipple.x - 0.5));
} else if(s < stipple.x) {
outColor = color0;
} else {
outColor = colors;
}
}
// antialias along edge of line
float cdist = length(cpos - vpos);
if(cdist > width) {
outColor.a *= clamp(1.0 - (cdist - width), 0.0, 1.0);
}
}
@@ -0,0 +1,14 @@
[remap]
importer="glsl"
type="RDShaderFile"
uid="uid://6d7xgy7qt0ve"
path="res://.godot/imported/lineseg_2D.glsl-1fe4d78a9561c152623e95fb5cdb480f.res"
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/shaders/lineseg_2D.glsl"
dest_files=["res://.godot/imported/lineseg_2D.glsl-1fe4d78a9561c152623e95fb5cdb480f.res"]
[params]
@@ -0,0 +1,53 @@
uniform vec2 uScreenSize;
uniform mat4 uMVPMatrix;
uniform vec2 uPos0;
uniform vec2 uPos1;
uniform vec4 uColor0;
uniform vec4 uColor1;
uniform float uWidth;
uniform vec2 uStipple;
uniform float uStippleOffset;
attribute vec2 aWeight;
varying vec4 vPos;
varying float vDist;
/////////////////////////////////////////////////////////////////////////
// vertex shader
#version 330
void main() {
vec2 d01 = normalize(uPos1 - uPos0);
vec2 perp = vec2(-d01.y, d01.x);
float dist = distance(uPos0, uPos1);
vec2 p =
(1.0 - aWeight.x) * uPos0 +
aWeight.x * uPos1 +
(aWeight.y - 0.5) * uWidth * perp;
vPos = uMVPMatrix * vec4(p, 0.0, 1.0);
vDist = dist * aWeight.x;
gl_Position = vPos;
}
/////////////////////////////////////////////////////////////////////////
// fragment shader
#version 330
out vec4 outColor;
void main() {
float s = mod(vDist + uStippleOffset, uStipple.x + uStipple.y);
if(s <= uStipple.x) {
outColor = uColor0;
} else {
outColor = uColor1;
if(uColor1.a <= 0) discard;
}
}
@@ -0,0 +1,14 @@
[remap]
importer="glsl"
type="RDShaderFile"
uid="uid://yjee3y6rjuq2"
path="res://.godot/imported/linesegment.glsl-0793b964a97cd1bf02e458f63e069f56.res"
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/shaders/linesegment.glsl"
dest_files=["res://.godot/imported/linesegment.glsl-0793b964a97cd1bf02e458f63e069f56.res"]
[params]
@@ -0,0 +1,44 @@
uniform mat4 MVPMatrix; // pixel matrix
uniform vec2 screensize; // width,height of screen (for antialiasing)
uniform vec2 center; // center of point
uniform float radius; // radius of circle
uniform float border; // width of border
uniform vec4 color; // color point
uniform vec4 colorBorder; // color of border
/////////////////////////////////////////////////////////////////////////
// vertex shader
in vec2 pos; // four corners of point ([0,0], [0,1], [1,1], [1,0])
noperspective out vec2 vpos; // position scaled by screensize
void main() {
vec2 p = center + vec2((pos.x - 0.5) * (radius+border), (pos.y - 0.5) * (radius+border));
gl_Position = MVPMatrix * vec4(p, 0.0, 1.0);
vpos = vec2(gl_Position.x * screensize.x, gl_Position.y * screensize.y); // just p?
}
/////////////////////////////////////////////////////////////////////////
// fragment shader
noperspective in vec2 vpos;
out vec4 outColor;
void main() {
vec4 colorb = colorBorder;
if(colorb.a < (1.0/255.0)) colorb.rgb = color.rgb;
vec2 ctr = (MVPMatrix * vec4(center, 0.0, 1.0)).xy;
float d = distance(vpos, vec2(ctr.x * screensize.x, ctr.y * screensize.y));
if(d > radius + border) discard;
if(d <= radius) {
float d2 = radius - d;
outColor = mix(colorb, color, clamp(d2 - border/2, 0.0, 1.0));
} else {
float d2 = d - radius;
outColor = mix(colorb, vec4(colorb.rgb,0), clamp(d2 - border/2, 0.0, 1.0));
}
}
@@ -0,0 +1,14 @@
[remap]
importer="glsl"
type="RDShaderFile"
uid="uid://ct1c63d67sgtp"
path="res://.godot/imported/point_2D.glsl-38530721d676c5eb02adb50f182d6d49.res"
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/shaders/point_2D.glsl"
dest_files=["res://.godot/imported/point_2D.glsl-38530721d676c5eb02adb50f182d6d49.res"]
[params]
@@ -0,0 +1,41 @@
uniform mat4 MVPMatrix; // pixel matrix
uniform vec2 screensize; // width,height of screen (for antialiasing)
uniform vec2 pos0;
uniform vec4 color0;
uniform vec2 pos1;
uniform vec4 color1;
uniform vec2 pos2;
uniform vec4 color2;
/////////////////////////////////////////////////////////////////////////
// vertex shader
in vec2 pos; // x: [0,1], alpha. y: [0,1], beta
out vec4 color;
void main() {
float a = clamp(pos.x, 0.0, 1.0);
float b = clamp(pos.y, 0.0, 1.0);
float c = 1.0 - a - b;
vec2 p = pos0 * a + pos1 * b + pos2 * c;
gl_Position = MVPMatrix * vec4(p, 0.0, 1.0);
color = color0 * a + color1 * b + color2 * c;
}
/////////////////////////////////////////////////////////////////////////
// fragment shader
in vec4 color;
out vec4 outColor;
void main() {
outColor = color;
}
@@ -0,0 +1,14 @@
[remap]
importer="glsl"
type="RDShaderFile"
uid="uid://nrw1lnh80b6a"
path="res://.godot/imported/triangle_2D.glsl-45ff10e936275be9ae51871b6f0c7410.res"
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/shaders/triangle_2D.glsl"
dest_files=["res://.godot/imported/triangle_2D.glsl-45ff10e936275be9ae51871b6f0c7410.res"]
[params]
@@ -0,0 +1,40 @@
uniform mat4 MVPMatrix; // view matrix
uniform vec3 pos0;
uniform vec4 color0;
uniform vec3 pos1;
uniform vec4 color1;
uniform vec3 pos2;
uniform vec4 color2;
/////////////////////////////////////////////////////////////////////////
// vertex shader
in vec2 pos; // x: [0,1], alpha. y: [0,1], beta
out vec4 color;
void main() {
float a = clamp(pos.x, 0.0, 1.0);
float b = clamp(pos.y, 0.0, 1.0);
float c = 1.0 - a - b;
vec3 p = pos0 * a + pos1 * b + pos2 * c;
gl_Position = MVPMatrix * vec4(p, 1.0);
color = color0 * a + color1 * b + color2 * c;
}
/////////////////////////////////////////////////////////////////////////
// fragment shader
in vec4 color;
out vec4 outColor;
void main() {
outColor = color;
}
@@ -0,0 +1,14 @@
[remap]
importer="glsl"
type="RDShaderFile"
uid="uid://doua25ld1yeew"
path="res://.godot/imported/triangle_3D.glsl-22c67fdcf8e6e9e641b9e70c896857c6.res"
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/shaders/triangle_3D.glsl"
dest_files=["res://.godot/imported/triangle_3D.glsl-22c67fdcf8e6e9e641b9e70c896857c6.res"]
[params]
@@ -0,0 +1,301 @@
uniform mat4 uMVPMatrix;
uniform float left;
uniform float right;
uniform float top;
uniform float bottom;
uniform float width;
uniform float height;
uniform float margin_left;
uniform float margin_right;
uniform float margin_top;
uniform float margin_bottom;
uniform float padding_left;
uniform float padding_right;
uniform float padding_top;
uniform float padding_bottom;
uniform float border_width;
uniform float border_radius;
uniform vec4 border_left_color;
uniform vec4 border_right_color;
uniform vec4 border_top_color;
uniform vec4 border_bottom_color;
uniform vec4 background_color;
uniform int using_image;
uniform int image_fit;
uniform sampler2D image;
attribute vec2 pos;
varying vec2 screen_pos;
const bool DEBUG = false;
const bool DEBUG_CHECKER = true;
const int REGION_OUTSIDE_LEFT = -4;
const int REGION_OUTSIDE_BOTTOM = -3;
const int REGION_OUTSIDE_RIGHT = -2;
const int REGION_OUTSIDE_TOP = -1;
const int REGION_OUTSIDE = 0;
const int REGION_BORDER_TOP = 1;
const int REGION_BORDER_RIGHT = 2;
const int REGION_BORDER_BOTTOM = 3;
const int REGION_BORDER_LEFT = 4;
const int REGION_BACKGROUND = 5;
const int REGION_ERROR = -100;
/////////////////////////////////////////////////////////////////////////
// vertex shader
#version 330
precision highp float;
void main() {
// set vertex to bottom-left, top-left, top-right, or bottom-right location, depending on pos
vec2 p = vec2(
(pos.x < 0.5) ? (left - 1) : (right + 1),
(pos.y < 0.5) ? (bottom - 1) : (top + 1)
);
screen_pos = p;
gl_Position = uMVPMatrix * vec4(p, 0, 1);
}
/////////////////////////////////////////////////////////////////////////
// fragment shader
#version 330
precision highp float;
out vec4 outColor;
float sqr(float s) { return s * s; }
int get_region() {
/* return values:
0 - outside border region
1 - top border
2 - right border
3 - bottom border
4 - left border
5 - inside border region
-1 - ERROR (should never happen)
*/
float dist_left = screen_pos.x - (left + margin_left);
float dist_right = (right - margin_right + 1) - screen_pos.x;
float dist_bottom = screen_pos.y - (bottom + margin_bottom - 1);
float dist_top = (top - margin_top) - screen_pos.y;
float radwid = max(border_radius, border_width);
float rad = max(0, border_radius - border_width);
float radwid2 = sqr(radwid);
float rad2 = sqr(rad);
float r2;
// outside
float dist_min = min(min(min(dist_left, dist_right), dist_top), dist_bottom);
if(dist_min < 0) {
if(dist_min == dist_left) return REGION_OUTSIDE_LEFT;
if(dist_min == dist_right) return REGION_OUTSIDE_RIGHT;
if(dist_min == dist_top) return REGION_OUTSIDE_TOP;
if(dist_min == dist_bottom) return REGION_OUTSIDE_BOTTOM;
return REGION_ERROR;
}
// within top and bottom, might be left or right side
if(dist_bottom > radwid && dist_top > radwid) {
if(dist_left > border_width && dist_right > border_width) return REGION_BACKGROUND;
if(dist_left < dist_right) return REGION_BORDER_LEFT;
return REGION_BORDER_RIGHT;
}
// within left and right, might be bottom or top
if(dist_left > radwid && dist_right > radwid) {
if(dist_bottom > border_width && dist_top > border_width) return REGION_BACKGROUND;
if(dist_bottom < dist_top) return REGION_BORDER_BOTTOM;
return REGION_BORDER_TOP;
}
// top-left
if(dist_top <= radwid && dist_left <= radwid) {
r2 = sqr(dist_left - radwid) + sqr(dist_top - radwid);
if(r2 > radwid2) return REGION_OUTSIDE;
if(r2 < rad2) return REGION_BACKGROUND;
if(dist_left < dist_top) return REGION_BORDER_LEFT;
return REGION_BORDER_TOP;
}
// top-right
if(dist_top <= radwid && dist_right <= radwid) {
r2 = sqr(dist_right - radwid) + sqr(dist_top - radwid);
if(r2 > radwid2) return REGION_OUTSIDE;
if(r2 < rad2) return REGION_BACKGROUND;
if(dist_right < dist_top) return REGION_BORDER_RIGHT;
return REGION_BORDER_TOP;
}
// bottom-left
if(dist_bottom <= radwid && dist_left <= radwid) {
r2 = sqr(dist_left - radwid) + sqr(dist_bottom - radwid);
if(r2 > radwid2) return REGION_OUTSIDE;
if(r2 < rad2) return REGION_BACKGROUND;
if(dist_left < dist_bottom) return REGION_BORDER_LEFT;
return REGION_BORDER_BOTTOM;
}
// bottom-right
if(dist_bottom <= radwid && dist_right <= radwid) {
r2 = sqr(dist_right - radwid) + sqr(dist_bottom - radwid);
if(r2 > radwid2) return REGION_OUTSIDE;
if(r2 < rad2) return REGION_BACKGROUND;
if(dist_right < dist_bottom) return REGION_BORDER_RIGHT;
return REGION_BORDER_BOTTOM;
}
// something bad happened
return REGION_ERROR;
}
vec4 mix_image(vec4 bg) {
vec4 c = bg;
// drawing space
float dw = width - (margin_left + border_width + padding_left + padding_right + border_width + margin_right);
float dh = height - (margin_top + border_width + padding_top + padding_bottom + border_width + margin_bottom);
float dx = screen_pos.x - (left + (margin_left + border_width + padding_left));
float dy = -(screen_pos.y - (top - (margin_top + border_width + padding_top)));
float dsx = dx / dw;
float dsy = dy / dh;
// texture
vec2 tsz = textureSize(image, 0);
float tw = tsz.x, th = tsz.y;
float tx, ty;
vec4 debug_color = vec4(0,0,0,0);
switch(image_fit) {
case 0:
// object-fit: fill = stretch / squash to fill entire drawing space (non-uniform scale)
// do nothing here
tx = tw * dx / dw;
ty = th * dy / dh;
break;
case 1: {
// object-fit: contain = uniformly scale texture to fit entirely in drawing space (will be letterboxed)
// find smaller scaled dimension, and use that
float _tw, _th;
if(dw / dh < tw / th) {
// scaling by height is too big, so scale by width
_tw = tw;
_th = tw * dh / dw;
} else {
_tw = th * dw / dh;
_th = th;
}
tx = dsx * _tw - (_tw - tw) / 2.0;
ty = dsy * _th - (_th - th) / 2.0;
break; }
case 2: {
// object-fit: cover = uniformly scale texture to fill entire drawing space (will be cropped)
// find larger scaled dimension, and use that
float _tw, _th;
if(dw / dh > tw / th) {
// scaling by height is too big, so scale by width
_tw = tw;
_th = tw * dh / dw;
} else {
_tw = th * dw / dh;
_th = th;
}
tx = dsx * _tw - (_tw - tw) / 2.0;
ty = dsy * _th - (_th - th) / 2.0;
break; }
case 3:
// object-fit: scale-down = either none or contain, whichever is smaller
if(dw >= tw && dh >= th) {
// none
tx = dx + (tw - dw) / 2.0;
ty = dy + (th - dh) / 2.0;
} else {
float _tw, _th;
if(dw / dh < tw / th) {
// scaling by height is too big, so scale by width
_tw = tw;
_th = tw * dh / dw;
} else {
_tw = th * dw / dh;
_th = th;
}
tx = dsx * _tw - (_tw - tw) / 2.0;
ty = dsy * _th - (_th - th) / 2.0;
}
break;
case 4:
// object-fit: none (no resizing)
tx = dx + (tw - dw) / 2.0;
ty = dy + (th - dh) / 2.0;
break;
default: // error!
tx = tw / 2.0;
ty = th / 2.0;
break;
}
vec2 texcoord = vec2(tx / tw, ty / th);
if(0 <= texcoord.x && texcoord.x < 1 && 0 <= texcoord.y && texcoord.y < 1) {
vec4 t = texture(image, texcoord) + debug_color;
float a = t.a + c.a * (1.0 - t.a);
c = vec4((t.rgb * t.a + c.rgb * c.a * (1.0 - t.a)) / a, a);
if(DEBUG && DEBUG_CHECKER) {
int i = (int(32 * texcoord.x) + 4 * int(32 * texcoord.y)) % 16;
if(i == 0) c = vec4(0.0, 0.0, 0.0, 1);
else if(i == 1) c = vec4(0.0, 0.0, 0.5, 1);
else if(i == 2) c = vec4(0.0, 0.5, 0.0, 1);
else if(i == 3) c = vec4(0.0, 0.5, 0.5, 1);
else if(i == 4) c = vec4(0.5, 0.0, 0.0, 1);
else if(i == 5) c = vec4(0.5, 0.0, 0.5, 1);
else if(i == 6) c = vec4(0.5, 0.5, 0.0, 1);
else if(i == 7) c = vec4(0.5, 0.5, 0.5, 1);
else if(i == 8) c = vec4(0.3, 0.3, 0.3, 1);
else if(i == 9) c = vec4(0.0, 0.0, 1.0, 1);
else if(i == 10) c = vec4(0.0, 1.0, 0.0, 1);
else if(i == 11) c = vec4(0.0, 1.0, 1.0, 1);
else if(i == 12) c = vec4(1.0, 0.0, 0.0, 1);
else if(i == 13) c = vec4(1.0, 0.0, 1.0, 1);
else if(i == 14) c = vec4(1.0, 1.0, 0.0, 1);
else if(i == 15) c = vec4(1.0, 1.0, 1.0, 1);
}
} else if(DEBUG) {
// vec4 t = vec4(0,1,1,0.50);
// float a = t.a + c.a * (1.0 - t.a);
// c = vec4((t.rgb * t.a + c.rgb * c.a * (1.0 - t.a)) / a, a);
c = vec4(
1.0 - (1.0 - c.r) * 0.5,
1.0 - (1.0 - c.g) * 0.5,
1.0 - (1.0 - c.b) * 0.5,
c.a
);
}
return c;
}
void main() {
vec4 c = vec4(0,0,0,0);
int region = get_region();
if(region == REGION_OUTSIDE_TOP) { c = vec4(1,0,0,0.25); if(!DEBUG) discard; }
else if(region == REGION_OUTSIDE_RIGHT) { c = vec4(0,1,0,0.25); if(!DEBUG) discard; }
else if(region == REGION_OUTSIDE_BOTTOM) { c = vec4(0,0,1,0.25); if(!DEBUG) discard; }
else if(region == REGION_OUTSIDE_LEFT) { c = vec4(0,1,1,0.25); if(!DEBUG) discard; }
else if(region == REGION_OUTSIDE) { c = vec4(1,1,0,0.25); if(!DEBUG) discard; }
else if(region == REGION_BORDER_TOP) c = border_top_color;
else if(region == REGION_BORDER_RIGHT) c = border_right_color;
else if(region == REGION_BORDER_BOTTOM) c = border_bottom_color;
else if(region == REGION_BORDER_LEFT) c = border_left_color;
else if(region == REGION_BACKGROUND) c = background_color;
else if(region == REGION_ERROR) c = vec4(1,0,0,1); // should never hit here
else c = vec4(1,0,1,1); // should really never hit here
if(using_image > 0) c = mix_image(c);
outColor = c;
}
@@ -0,0 +1,14 @@
[remap]
importer="glsl"
type="RDShaderFile"
uid="uid://cmdmfaxl41bcy"
path="res://.godot/imported/ui_element.glsl-802dcdc4bfed05facdc94815a98c6af0.res"
[deps]
source_file="res://reference/blender-wow-studio-3.4-1.1.0_Experimental/io_scene_wmo/addon_common/common/shaders/ui_element.glsl"
dest_files=["res://.godot/imported/ui_element.glsl-802dcdc4bfed05facdc94815a98c6af0.res"]
[params]
@@ -0,0 +1,835 @@
'''
Copyright (C) 2020 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson
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/>.
'''
import os
import re
import math
import time
import types
import struct
import random
import traceback
import functools
import urllib.request
from itertools import chain
from concurrent.futures import ThreadPoolExecutor
import bpy
import bgl
from .ui_core import UI_Element, UI_Proxy
from .ui_utilities import (
UIRender_Block, UIRender_Inline,
helper_argtranslate, helper_argsplitter,
)
from .utils import kwargopts, iter_head
from .ui_styling import UI_Styling
from .boundvar import BoundVar
from .decorators import blender_version_wrapper
from .drawing import Drawing, ScissorStack
from .fontmanager import FontManager
from .globals import Globals
from .maths import Point2D, Vec2D, clamp, mid, Color, Box2D, Size2D
from .markdown import Markdown
from ..ext import png
'''
Notes about addon_common's UI system
- The system is designed similarly to how the Browser will render HTML+CSS
- All UI elements are containers
- All classes herein are simply "starter" UI elements
- You can freely change all properties to make any element turn into another
- Styling
- Styling specified here is base styling for UI elements of same type
- Base styling specified here are overridden by stylesheet, which is overridden by custom styling
- Note: changing tagname will not reset the base styling. in other words, if the element starts off
as a UI_Button, changing tagname to "flexbox" will not change base styling from what is
specified in UI_Button.
Implementation details
- root element will be sized to entire 3D view region
- each element
- is responsible for communicating with children
- will estimate its size (min, max, preferred), but these are only suggestions for the parent
- dictates size and position of its children
- must submit to the sizing and position given by the parent
See top comment in `ui_utilities.py` for links to useful resources.
'''
# all html tags: https://www.w3schools.com/tags/
def button(**kwargs):
helper_argtranslate('label', 'innerText', kwargs)
return UI_Element(tagName='button', **kwargs)
def p(**kwargs):
return UI_Element(tagName='p', **kwargs)
def a(**kwargs):
elem = UI_Element(tagName='a', **kwargs)
# def mouseclick(e):
# nonlocal elem
# if not elem.href: return
# if Markdown.is_url(elem.href):
# bpy.ops.wm.url_open(url=elem.href)
# elem.add_eventListener('on_mouseclick', mouseclick)
return elem
def b(**kwargs):
return UI_Element(tagName='b', **kwargs)
def i(**kwargs):
return UI_Element(tagName='i', **kwargs)
def div(**kwargs):
return UI_Element(tagName='div', **kwargs)
def span(**kwargs):
return UI_Element(tagName='span', **kwargs)
def h1(**kwargs):
return UI_Element(tagName='h1', **kwargs)
def h2(**kwargs):
return UI_Element(tagName='h2', **kwargs)
def h3(**kwargs):
return UI_Element(tagName='h3', **kwargs)
def pre(**kwargs):
return UI_Element(tagName='pre', **kwargs)
def code(**kwargs):
return UI_Element(tagName='code', **kwargs)
def br(**kwargs):
return UI_Element(tagName='br', **kwargs)
def img(**kwargs):
return UI_Element(tagName='img', **kwargs)
def table(**kwargs):
return UI_Element(tagName='table', **kwargs)
def tr(**kwargs):
return UI_Element(tagName='tr', **kwargs)
def th(**kwargs):
return UI_Element(tagName='th', **kwargs)
def td(**kwargs):
return UI_Element(tagName='td', **kwargs)
def textarea(**kwargs):
return UI_Element(tagName='textarea', **kwargs)
def dialog(**kwargs):
return UI_Element(tagName='dialog', **kwargs)
def label(**kwargs):
return UI_Element(tagName='label', **kwargs)
def input_radio(**kwargs):
helper_argtranslate('label', 'innerText', kwargs)
kw_label = helper_argsplitter({'innerText'}, kwargs)
kw_all = helper_argsplitter({'title'}, kwargs)
# https://www.w3schools.com/howto/howto_css_custom_checkbox.asp
ui_input = UI_Element(tagName='input', type='radio', can_focus=True, **kwargs, **kw_all)
ui_radio = UI_Element(tagName='img', classes='radio', parent=ui_input, **kw_all)
ui_label = UI_Element(tagName='label', parent=ui_input, **kw_label, **kw_all)
def mouseclick(e):
ui_input.checked = True
def on_input(e):
# if ui_input is checked, uncheck all others with same name
if not ui_input.checked: return
if ui_input.name is None: return
ui_elements = ui_input.get_root().getElementsByName(ui_input.name)
for ui_element in ui_elements:
if ui_element != ui_input: ui_element.checked = False
ui_input.add_eventListener('on_mouseclick', mouseclick)
ui_input.add_eventListener('on_input', on_input)
ui_proxy = UI_Proxy(ui_input)
ui_proxy.translate('label', 'innerText')
ui_proxy.map({'innerText','children','append_child','delete_child','clear_children','builder'}, ui_label)
ui_proxy.map_to_all({'title'})
return ui_proxy
def input_checkbox(**kwargs):
helper_argtranslate('label', 'innerText', kwargs)
kw_label = helper_argsplitter({'innerText'}, kwargs)
kw_all = helper_argsplitter({'title'}, kwargs)
# https://www.w3schools.com/howto/howto_css_custom_checkbox.asp
ui_input = UI_Element(tagName='input', type='checkbox', can_focus=False, **kwargs, **kw_all)
ui_checkmark = UI_Element(tagName='img', classes='checkbox', parent=ui_input, **kw_all)
ui_label = UI_Element(tagName='label', parent=ui_input, **kw_label, **kw_all)
def mouseclick(e):
ui_input.checked = not bool(ui_input.checked)
ui_input.add_eventListener('on_mouseclick', mouseclick)
ui_proxy = UI_Proxy(ui_input)
ui_proxy.translate('label', 'innerText')
ui_proxy.translate('value', 'checked')
ui_proxy.map({'innerText','children','append_child','delete_child','clear_children', 'builder'}, ui_label)
ui_proxy.map_to_all({'title'})
return ui_proxy
def labeled_input_text(label, **kwargs):
kw_container = helper_argsplitter({'parent', 'id'}, kwargs)
kw_all = helper_argsplitter({'title'}, kwargs)
ui_container = UI_Element(tagName='div', classes='labeledinputtext-container', **kw_container, **kw_all)
ui_left = UI_Element(tagName='div', classes='labeledinputtext-label-container', parent=ui_container, **kw_all)
ui_label = UI_Element(tagName='label', classes='labeledinputtext-label', innerText=label, parent=ui_left, **kw_all)
ui_right = UI_Element(tagName='div', classes='labeledinputtext-input-container', parent=ui_container, **kw_all)
ui_input = input_text(parent=ui_right, **kwargs, **kw_all)
ui_proxy = UI_Proxy(ui_container)
ui_proxy.translate_map('label', 'innerText', ui_label)
ui_proxy.map('value', ui_input)
ui_proxy.map_to_all({'title'})
return ui_proxy
def input_text(**kwargs):
# TODO: find a better structure for input text boxes!
# can we get by with just input and inner span (cursor)?
kwargs.setdefault('value', '')
kw_container = helper_argsplitter({'parent'}, kwargs)
ui_container = UI_Element(tagName='span', classes='inputtext-container', **kw_container)
ui_input = UI_Element(tagName='input', classes='inputtext-input', type='text', can_focus=True, parent=ui_container, **kwargs)
ui_cursor = UI_Element(tagName='span', classes='inputtext-cursor', parent=ui_input, innerText='|')
data = {'orig': None, 'text': None, 'idx': 0, 'pos': None}
def preclean():
if data['text'] is None:
if type(ui_input.value) is float:
ui_input.innerText = '%0.4f' % ui_input.value
else:
ui_input.innerText = str(ui_input.value)
else:
ui_input.innerText = data['text']
#print(ui_input, type(ui_input.innerText), ui_input.innerText, type(ui_input.value), ui_input.value)
def postflow():
if data['text'] is None: return
data['pos'] = ui_input.get_text_pos(data['idx'])
ui_cursor.left = data['pos'].x - ui_input._mbp_left - ui_cursor._absolute_size.width / 2
ui_cursor.top = data['pos'].y + ui_input._mbp_top
def cursor_postflow():
if data['text'] is None: return
ui_input._setup_ltwh()
ui_cursor._setup_ltwh()
# if ui_cursor._l < ui_input._l:
# ui_input._scroll_offset.x = min(0, ui_input._l - ui_cursor._l)
vl = ui_input._l + ui_input._mbp_left
vr = ui_input._r - ui_input._mbp_right
vw = ui_input._w - ui_input._mbp_width
if ui_cursor._r > vr:
dx = ui_cursor._r - vr + 2
ui_input.scrollLeft = ui_input.scrollLeft + dx
ui_input._setup_ltwh()
if ui_cursor._l < vl:
dx = ui_cursor._l - vl - 2
ui_input.scrollLeft = ui_input.scrollLeft + dx
ui_input._setup_ltwh()
def set_cursor(e):
data['idx'] = ui_input.get_text_index(e.mouse)
data['pos'] = None
ui_input.dirty_flow()
def focus(e):
if type(ui_input.value) is float:
s = '%0.4f' % ui_input.value
else:
s = str(ui_input.value)
data['orig'] = data['text'] = s
set_cursor(e)
def mousemove(e):
if data['text'] is None: return
if not e.button[0]: return
set_cursor(e)
def mousedown(e):
if data['text'] is None: return
if not e.button[0]: return
set_cursor(e)
def blur(e):
ui_input.value = data['text']
data['text'] = None
#print('container:', ui_container._dynamic_full_size, ' input:', ui_input._dynamic_full_size, type(ui_input.value), ui_input.value)
def keypress(e):
if data['text'] == None: return
if type(e.key) is int:
# https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_event_key_keycode2
# TODO: use enum rather than magic numbers!
if e.key == 8:
if data['idx'] == 0: return
data['text'] = data['text'][0:data['idx']-1] + data['text'][data['idx']:]
data['idx'] -= 1
elif e.key == 13:
ui_input.blur()
elif e.key == 27:
data['text'] = data['orig']
ui_input.blur()
elif e.key == 35:
data['idx'] = len(data['text'])
ui_input.dirty_flow()
elif e.key == 36:
data['idx'] = 0
ui_input.dirty_flow()
elif e.key == 37:
data['idx'] = max(data['idx'] - 1, 0)
ui_input.dirty_flow()
elif e.key == 39:
data['idx'] = min(data['idx'] + 1, len(data['text']))
ui_input.dirty_flow()
elif e.key == 46:
if data['idx'] == len(data['text']): return
data['text'] = data['text'][0:data['idx']] + data['text'][data['idx']+1:]
else:
changed = False
else:
data['text'] = data['text'][0:data['idx']] + e.key + data['text'][data['idx']:]
data['idx'] += 1
preclean()
ui_input.preclean = preclean
ui_input.postflow = postflow
ui_cursor.postflow = cursor_postflow
ui_input.add_eventListener('on_focus', focus)
ui_input.add_eventListener('on_blur', blur)
ui_input.add_eventListener('on_keypress', keypress)
ui_input.add_eventListener('on_mousemove', mousemove)
ui_input.add_eventListener('on_mousedown', mousedown)
ui_proxy = UI_Proxy(ui_container)
ui_proxy.map('value', ui_input)
ui_proxy.map('innerText', ui_input)
preclean()
return ui_proxy
def collection(label, **kwargs):
kw_inside = helper_argsplitter({'children'}, kwargs)
ui_container = UI_Element(tagName='div', classes='collection', **kwargs)
ui_label = div(innerText=label, classes='header', parent=ui_container)
ui_inside = UI_Element(tagName='div', classes='inside', parent=ui_container, **kw_inside)
ui_proxy = UI_Proxy(ui_container)
ui_proxy.map(['children','append_child','delete_child','clear_children', 'builder'], ui_inside)
return ui_proxy
def collapsible(label, **kwargs):
helper_argtranslate('collapsed', 'checked', kwargs)
kwargs.setdefault('checked', True)
kw_input = helper_argsplitter({'checked'}, kwargs)
kw_inside = helper_argsplitter({'children'}, kwargs)
kw_all = helper_argsplitter({'title'}, kwargs)
kwargs['classes'] = 'collapsible %s' % kwargs.get('classes', '')
ui_container = UI_Element(tagName='div', **kwargs, **kw_all)
ui_label = input_checkbox(label=label, id='%s_check'%(kwargs.get('id',str(random.random()))), classes='header', parent=ui_container, **kw_input, **kw_all)
# ui_label = UI_Element(tagName='input', classes='header', innerText=label, type="checkbox", parent=ui_container, **kw_input)
ui_inside = UI_Element(tagName='div', classes='inside', parent=ui_container, **kw_inside, **kw_all)
def toggle():
if ui_label.checked: ui_inside.add_class('collapsed')
else: ui_inside.del_class('collapsed')
ui_inside.dirty(parent=False, children=True)
ui_label.add_eventListener('on_input', toggle)
toggle()
ui_proxy = UI_Proxy(ui_container)
ui_proxy.translate_map('collapsed', 'checked', ui_label)
ui_proxy.map({'label', 'innerText'}, ui_label)
ui_proxy.map(['children','append_child','delete_child','clear_children', 'builder'], ui_inside)
ui_proxy.map_to_all({'title'})
return ui_proxy
def get_mdown_path(fn, ext=None, subfolders=None):
# if no subfolders are given, assuming image path is <root>/icons
# or <root>/images where <root> is the 2 levels above this file
if subfolders is None:
subfolders = ['help']
if ext:
fn = '%s.%s' % (fn,ext)
path_here = os.path.dirname(__file__)
path_root = os.path.join(path_here, '..', '..')
paths = [os.path.join(path_root, p, fn) for p in subfolders]
paths += [os.path.join(path_here, 'images', fn)]
paths = [p for p in paths if os.path.exists(p)]
return iter_head(paths, None)
def set_markdown(ui_mdown, mdown=None, mdown_path=None):
if mdown_path: mdown = open(get_mdown_path(mdown_path), 'rt').read()
mdown = Markdown.preprocess(mdown or '') # preprocess mdown
if getattr(ui_mdown, '__mdown', None) == mdown: return # ignore updating if it's exactly the same as previous
ui_mdown.__mdown = mdown # record the mdown to prevent reprocessing same
def process_words(text, word_fn):
while text:
word,text = Markdown.split_word(text)
word_fn(word)
def process_para(container, para, **kwargs):
container.defer_dirty_propagation = True
opts = kwargopts(kwargs, classes='')
# break each ui_item onto it's own line
para = re.sub(r'\n', ' ', para) # join sentences of paragraph
para = re.sub(r' *', ' ', para) # 1+ spaces => 1 space
# TODO: revisit this, and create an actual parser
para = para.lstrip()
while para:
t,m = Markdown.match_inline(para)
if t is None:
word,para = Markdown.split_word(para)
container.append_child(span(innerText=word))
else:
if t == 'br':
container.append_child(br())
elif t == 'img':
style = m.group('style').strip() or None
UI_Element(tagName='img', classes='inline', style=style, src=m.group('filename'), title=m.group('caption'), parent=container)
elif t == 'code':
container.append_child(code(innerText=m.group('text')))
elif t == 'link':
text,link = m.group('text'),m.group('link')
title = 'Click to open URL in default web browser' if Markdown.is_url(link) else 'Click to open help'
def mouseclick():
if Markdown.is_url(link):
bpy.ops.wm.url_open(url=link)
else:
set_markdown(ui_mdown, mdown_path=link)
process_words(text, lambda word: a(innerText=word, href=link, title=title, on_mouseclick=mouseclick, parent=container))
elif t == 'bold':
process_words(m.group('text'), lambda word: b(innerText=word, parent=container))
elif t == 'italic':
process_words(m.group('text'), lambda word: i(innerText=word, parent=container))
else:
assert False, 'Unhandled inline markdown type "%s" ("%s") with "%s"' % (str(t), str(m), line)
para = para[m.end():]
container.defer_dirty_propagation = False
ui_mdown.defer_dirty_propagation = True
ui_mdown.clear_children()
paras = mdown.split('\n\n') # split into paragraphs
for para in paras:
t,m = Markdown.match_line(para)
if t is None:
p_element = ui_mdown.append_child(p())
process_para(p_element, para)
elif t in ['h1','h2','h3']:
hn = {'h1':h1, 'h2':h2, 'h3':h3}[t]
#hn(innerText=m.group('text'), parent=ui_mdown)
ui_hn = hn(parent=ui_mdown)
process_para(ui_hn, m.group('text'))
elif t == 'ul':
ui_ul = UI_Element(tagName='ul', parent=ui_mdown)
ui_ul.defer_dirty_propagation = True
para = para[2:]
for litext in re.split(r'\n- ', para):
ui_li = UI_Element(tagName='li', parent=ui_ul)
UI_Element(tagName='img', classes='dot', src='radio.png', parent=ui_li)
span_element = UI_Element(tagName='span', classes='text', parent=ui_li)
process_para(span_element, litext)
ui_ul.defer_dirty_propagation = False
elif t == 'ol':
ui_ol = UI_Element(tagName='ol', parent=ui_mdown)
ui_ol.defer_dirty_propagation = True
para = para[2:]
for ili,litext in enumerate(re.split(r'\n\d+\. ', para)):
ui_li = UI_Element(tagName='li', parent=ui_ol)
UI_Element(tagName='span', classes='number', innerText='%d.'%(ili+1), parent=ui_li)
span_element = UI_Element(tagName='span', classes='text', parent=ui_li)
process_para(span_element, litext)
ui_ol.defer_dirty_propagation = False
elif t == 'img':
style = m.group('style').strip() or None
UI_Element(tagName='img', style=style, src=m.group('filename'), title=m.group('caption'), parent=ui_mdown)
elif t == 'table':
# table!
def split_row(row):
row = re.sub(r'^\| ', r'', row)
row = re.sub(r' \|$', r'', row)
return [col.strip() for col in row.split(' | ')]
data = [l for l in para.split('\n')]
header = split_row(data[0])
add_header = any(header)
align = data[1]
data = [split_row(row) for row in data[2:]]
rows,cols = len(data),len(data[0])
table_element = table(parent=ui_mdown)
if add_header:
tr_element = tr(parent=table_element)
for c in range(cols):
th(innerText=header[c], parent=tr_element)
for r in range(rows):
tr_element = tr(parent=table_element)
for c in range(cols):
td_element = td(parent=tr_element)
process_para(td_element, data[r][c])
pass
else:
assert False, 'Unhandled markdown line type "%s" ("%s") with "%s"' % (str(t), str(m), para)
ui_mdown.scrollToTop()
ui_mdown.defer_dirty_propagation = False
def set_markdown_old(ui_mdown, mdown):
ui_mdown.defer_dirty_propagation = True
ui_mdown.clear_children()
# process message similarly to Markdown
mdown = re.sub(r'^\n*', r'', mdown) # remove leading \n
mdown = re.sub(r'\n*$', r'', mdown) # remove trailing \n
mdown = re.sub(r'\n\n\n*', r'\n\n', mdown) # 2+ \n => \n\n
paras = mdown.split('\n\n') # split into paragraphs
for p in paras:
if p.startswith('# '):
# h1 heading!
h1text = re.sub(r'# +', r'', p)
UI_Element(tagName='h1', innerText=h1text, parent=ui_mdown)
elif p.startswith('## '):
# h2 heading!
h2text = re.sub(r'## +', r'', p)
UI_Element(tagName='h2', innerText=h2text, parent=ui_mdown)
elif p.startswith('### '):
# h3 heading!
h3text = re.sub(r'### +', r'', p)
UI_Element(tagName='h3', innerText=h3text, parent=ui_mdown)
elif p.startswith('- '):
# unordered list!
ui_ul = UI_Element(tagName='ul', parent=ui_mdown)
p = p[2:]
for litext in re.split(r'\n- ', p):
# litext = re.sub(r'- ', r'', litext)
ui_li = UI_Element(tagName='li', parent=ui_ul)
UI_Element(tagName='img', src='radio.png', parent=ui_li)
UI_Element(tagName='span', innerText=litext, parent=ui_li)
elif p.startswith('!['):
# image!
m = re.match(r'^!\[(?P<caption>.*)\]\((?P<filename>.*)\)$', p)
fn = m.group('filename')
UI_Element(tagName='img', src=fn, parent=ui_mdown)
elif p.startswith('| '):
# table
data = [l for l in p.split('\n')]
data = [re.sub(r'^\| ', r'', l) for l in data]
data = [re.sub(r' \|$', r'', l) for l in data]
data = [l.split(' | ') for l in data]
rows,cols = len(data),len(data[0])
# t = container.add(UI_TableContainer(rows, cols))
for r in range(rows):
for c in range(cols):
if c == 0:
pass
# t.set(r, c, UI_Label(data[r][c]))
else:
pass
# t.set(r, c, UI_WrappedLabel(data[r][c], min_size=(0, 12), max_size=(400, 12000)))
else:
p = re.sub(r'\n', ' ', p) # join sentences of paragraph
UI_Element(tagName='p', innerText=p, parent=ui_mdown)
ui_mdown.defer_dirty_propagation = False
def markdown(mdown=None, mdown_path=None, **kwargs):
ui_container = UI_Element(tagName='div', classes='mdown', **kwargs)
set_markdown(ui_container, mdown=mdown, mdown_path=mdown_path)
return ui_container
def framed_dialog(label=None, resizable=None, resizable_x=True, resizable_y=False, closeable=True, moveable=True, hide_on_close=False, close_callback=None, **kwargs):
# TODO: always add header, and use UI_Proxy translate+map "label" to change header
kw_inside = helper_argsplitter({'children'}, kwargs)
ui_document = Globals.ui_document
kwargs['classes'] = 'framed %s %s' % (kwargs.get('classes', ''), 'moveable' if moveable else '')
ui_dialog = UI_Element(tagName='dialog', **kwargs)
ui_header = UI_Element(tagName='div', classes='dialog-header', parent=ui_dialog)
if closeable:
def close():
if close_callback: close_callback()
if hide_on_close:
ui_dialog.is_visible = False
return
if ui_dialog._parent is None: return
if ui_dialog._parent == ui_dialog: return
ui_dialog._parent.delete_child(ui_dialog)
title = 'Close dialog' # 'Hide' if hide_on_close??
ui_close = UI_Element(tagName='button', classes='dialog-close', title=title, on_mouseclick=close, parent=ui_header)
ui_label = UI_Element(tagName='span', classes='dialog-title', innerText=label or '', parent=ui_header)
if moveable:
is_dragging = False
mousedown_pos = None
original_pos = None
def mousedown(e):
nonlocal is_dragging, mousedown_pos, original_pos, ui_dialog
if e.target != ui_header and e.target != ui_label: return
ui_document.ignore_hover_change = True
is_dragging = True
mousedown_pos = e.mouse
l = ui_dialog.left_pixels
if l is None or l == 'auto': l = 0
t = ui_dialog.top_pixels
if t is None or t == 'auto': t = 0
original_pos = Point2D((float(l), float(t)))
def mouseup(e):
nonlocal is_dragging
is_dragging = False
ui_document.ignore_hover_change = False
def mousemove(e):
nonlocal is_dragging, mousedown_pos, original_pos, ui_dialog
if not is_dragging: return
delta = e.mouse - mousedown_pos
new_pos = original_pos + delta
ui_dialog.reposition(left=new_pos.x, top=new_pos.y)
ui_header.add_eventListener('on_mousedown', mousedown)
ui_header.add_eventListener('on_mouseup', mouseup)
ui_header.add_eventListener('on_mousemove', mousemove)
if resizable is not None: resizable_x = resizable_y = resizable
if resizable_x or resizable_y:
is_resizing = False
mousedown_pos = None
original_size = None
def resizing(e):
nonlocal ui_dialog
dpi_mult = Globals.drawing.get_dpi_mult()
l,t,w,h = ui_dialog.left_pixels, ui_dialog.top_pixels, ui_dialog.width_pixels, ui_dialog.height_pixels
mt,mr,mb,ml = ui_dialog._get_style_trbl('margin', scale=dpi_mult)
bw = ui_dialog._get_style_num('border-width', 0, scale=dpi_mult)
ro = ui_dialog._relative_offset
gl = l + ro.x + w - mr - bw
gb = t - ro.y - h + mb + bw
rx = resizable_x and gl <= e.mouse.x < gl + bw
ry = resizable_y and gb >= e.mouse.y > gl - bw
if rx and ry: return 'both'
if rx: return 'width'
if ry: return 'height'
return False
def mousedown(e):
nonlocal is_resizing, mousedown_pos, original_size, ui_dialog
if e.target != ui_dialog: return
ui_document.ignore_hover_change = True
l,t,w,h = ui_dialog.left_pixels, ui_dialog.top_pixels, ui_dialog.width_pixels, ui_dialog.height_pixels
is_resizing = resizing(e)
mousedown_pos = e.mouse
original_size = (w,h)
def mouseup(e):
nonlocal is_resizing
ui_document.ignore_hover_change = False
is_resizing = False
def mousemove(e):
nonlocal is_resizing, mousedown_pos, original_size, ui_dialog
if not is_resizing:
r = resizing(e)
if r == 'width': ui_dialog._computed_styles['cursor'] = 'ew-resize'
elif r == 'height': ui_dialog._computed_styles['cursor'] = 'ns-resize'
elif r == 'both': ui_dialog._computed_styles['cursor'] = 'grab'
else: ui_dialog._computed_styles['cursor'] = 'default'
else:
delta = e.mouse - mousedown_pos
minw,maxw = ui_dialog._computed_min_width, ui_dialog._computed_max_width
minh,maxh = ui_dialog._computed_min_height, ui_dialog._computed_max_height
if minw == 'auto': minw = 0
if maxw == 'auto': maxw = float('inf')
if minh == 'auto': minh = 0
if maxh == 'auto': maxh = float('inf')
if is_resizing in {'width', 'both'}:
ui_dialog.width = clamp(original_size[0] + delta.x, minw, maxw)
if is_resizing in {'height', 'both'}:
ui_dialog.height = clamp(original_size[1] - delta.y, minh, maxh)
ui_dialog.dirty_flow()
ui_dialog.add_eventListener('on_mousedown', mousedown)
ui_dialog.add_eventListener('on_mouseup', mouseup)
ui_dialog.add_eventListener('on_mousemove', mousemove)
ui_inside = UI_Element(tagName='div', classes='inside', style='overflow-y:scroll', parent=ui_dialog, **kw_inside)
# ui_footer = UI_Element(tagName='div', classes='dialog-footer', parent=ui_dialog)
# ui_footer_label = UI_Element(tagName='span', innerText='footer', parent=ui_footer)
ui_proxy = UI_Proxy(ui_dialog)
ui_proxy.translate_map('label', 'innerText', ui_label)
ui_proxy.map(['children','append_child','delete_child','clear_children','builder', 'getElementById'], ui_inside)
return ui_proxy
# class UI_Flexbox(UI_Core):
# '''
# This container will resize the width/height of all children to fill the available space.
# This element is useful for lists of children elements, growing along one dimension and filling along other dimension.
# Children of row flexboxes will take up entire height; children of column flexboxes will take up entire width.
# TODO: model off flexbox more closely? https://css-tricks.com/snippets/css/a-guide-to-flexbox/
# '''
# style_default = '''
# display: flexbox;
# flex-direction: row;
# flex-wrap: nowrap;
# overflow: scroll;
# '''
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
# def compute_content_size(self):
# for child in self._children:
# pass
# def layout_children(self):
# for child in self._children: child.recalculate()
# # assuming all children are drawn on top on one another
# w,h = self._min_width,self._min_height
# W,H = self._max_width,self._max_height
# for child in self.get_visible_children():
# w = max(w, child._min_width)
# h = max(h, child._min_height)
# W = min(W, child._max_width)
# H = min(H, child._max_height)
# self._min_width,self.min_height = w,h
# self._max_width,self.max_height = W,H
# # do not clean self if any children are still dirty (ex: they are deferring recalculation)
# self._is_dirty = any(child._is_dirty for child in self._children)
# def position_children(self, left, top, width, height):
# for child in self.get_visible_children():
# child.position(left, top, width, height)
# def draw_children(self):
# for child in self.get_visible_children():
# child.draw()
# class UI_Label(UI_Core):
# def __init__(self, label=None, *args, **kwargs):
# super().__init__(*args, **kwargs)
# self._label = label or ''
# class UI_Button(UI_Core):
# def __init__(self, label=None, click=None, *args, **kwargs):
# super().__init__(*args, **kwargs)
# self._label = label or ''
# self._click = click
# class UI_Dialog(UI_Core):
# '''
# a dialog window, can be shown modal
# '''
# def __init__(self, *args, **kwargs):
# super().__init__()
# class UI_Body(UI_Core):
# def __init__(self, actions, *args, **kwargs):
# super().__init__(*args, **kwargs)
# self._actions = actions
# self._active = None # element that is currently active
# self._active_last = None
# self._focus = None # either active element or element under the cursor
# self._focus_last = None
# def modal(self, actions):
# if self.actions.mousemove:
# # update the tooltip's position
# # close windows that have focus
# pass
# if event.type == 'MOUSEMOVE':
# mouse = Point2D((float(event.mouse_region_x), float(event.mouse_region_y)))
# self.tooltip_window.fn_sticky.set(mouse + self.tooltip_offset)
# self.tooltip_window.update_pos()
# if self.focus and self.focus_close_on_leave:
# d = self.focus.distance(mouse)
# if d > self.focus_close_distance:
# self.delete_window(self.focus)
# ret = {}
# if self.active and self.active.state != 'main':
# ret = self.active.modal(context, event)
# if not ret: self.active = None
# elif self.focus:
# ret = self.focus.modal(context, event)
# else:
# self.active = None
# for win in reversed(self.windows):
# ret = win.modal(context, event)
# if ret:
# self.active = win
# break
# if self.active != self.active_last:
# if self.active_last and self.active_last.fn_event_handler:
# self.active_last.fn_event_handler(context, UI_Event('HOVER', 'LEAVE'))
# if self.active and self.active.fn_event_handler:
# self.active.fn_event_handler(context, UI_Event('HOVER', 'ENTER'))
# self.active_last = self.active
# if self.active:
# if self.active.fn_event_handler:
# self.active.fn_event_handler(context, event)
# if self.active:
# tooltip = self.active.get_tooltip()
# self.set_tooltip_label(tooltip)
# else:
# self.set_tooltip_label(None)
# return ret

Some files were not shown because too many files have changed in this diff Show More