├── .editorconfig
├── .github
├── FUNDING.yml
└── ISSUE_TEMPLATE
│ └── bug_report.md
├── .gitignore
├── .pylintrc
├── .vscode
├── FUNDING.yml
└── settings.json
├── LICENSE
├── README.md
├── __init__.py
├── baker.py
├── blender_manifest.toml
├── build.bat
├── constants.py
├── operators
├── __init__.py
├── core.py
├── marmoset.py
└── material.py
├── preferences.py
├── ui.py
└── utils
├── __init__.py
├── baker.py
├── generic.py
├── io.py
├── marmoset.py
├── node.py
├── pack.py
├── render.py
└── scene.py
/.editorconfig:
--------------------------------------------------------------------------------
1 | # EditorConfig is awesome: https://EditorConfig.org
2 |
3 | # top-most EditorConfig file
4 | root = true
5 |
6 | # Unix-style newlines with a newline ending every file
7 | [*]
8 | end_of_line = lf
9 | insert_final_newline = true
10 |
11 | # Python
12 | [*.py]
13 | indent_style = space
14 | indent_size = 4
15 | max_line_length = 100
16 |
17 | # YAML
18 | [*.yaml]
19 | indent_style = space
20 | indent_size = 2
21 |
22 | # JSON
23 | [*.json]
24 | indent_style = space
25 | indent_size = 4
26 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
4 | patreon: # Replace with a single Patreon username
5 | open_collective: # Replace with a single Open Collective username
6 | ko_fi: razed # Replace with a single Ko-fi username
7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9 | liberapay: # Replace with a single Liberapay username
10 | issuehunt: # Replace with a single IssueHunt username
11 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
12 | polar: # Replace with a single Polar username
13 | buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
14 | thanks_dev: # Replace with a single thanks.dev username
15 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
16 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve GrabDoc
4 | title: ''
5 | labels: ''
6 | assignees: oRazeD
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Required steps to reproduce the behavior.
15 |
16 | **Expected behavior**
17 | A clear and concise description of what you expected to happen.
18 |
19 | **Screenshots**
20 | If applicable, add visual examples to help explain your problem.
21 |
22 | **Extra Information:**
23 | - OS: [e.g. Windows 11, Mac]
24 | - Blender Version [e.g. 4.2.1]
25 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | *.pyc
3 |
4 | grabdoc_updater/
5 |
6 | LICENSE
7 |
8 | README.md
9 |
10 | _temp/
11 |
12 | grabdocgit_updater/
13 |
14 | utils/temp/
15 |
16 | temp/
17 |
18 | *.log
19 |
20 | *.zip
21 |
--------------------------------------------------------------------------------
/.pylintrc:
--------------------------------------------------------------------------------
1 | [MASTER]
2 |
3 | ignore=__pycache__, .vscode, _source
4 | disable=
5 | no-member,
6 | too-many-arguments,
7 | too-few-public-methods,
8 | logging-format-interpolation,
9 | missing-module-docstring,
10 | missing-function-docstring,
11 | missing-class-docstring,
12 | no-name-in-module,
13 | c-extension-no-member,
14 | fixme,
15 | invalid-name,
16 | consider-using-with,
17 | wrong-import-position,
18 | consider-using-f-string,
19 | wrong-import-order,
20 | ungrouped-imports,
21 | unnecessary-lambda,
22 | unused-wildcard-import,
23 | attribute-defined-outside-init,
24 | assignment-from-no-return
25 |
26 |
27 | [FORMAT]
28 |
29 | max-line-length=88
30 |
--------------------------------------------------------------------------------
/.vscode/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
3 | patreon: # Replace with a single Patreon username
4 | open_collective: # Replace with a single Open Collective username
5 | ko_fi: razed # Replace with a single Ko-fi username
6 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
7 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
8 | liberapay: # Replace with a single Liberapay username
9 | issuehunt: # Replace with a single IssueHunt username
10 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
11 | polar: # Replace with a single Polar username
12 | buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
13 | thanks_dev: # Replace with a single thanks.dev username
14 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
15 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "python.analysis.typeCheckingMode": "off",
3 | "python.analysis.diagnosticSeverityOverrides": {
4 | "reportGeneralTypeIssues": "none",
5 | "reportInvalidTypeForm": "none"
6 | },
7 | "python.analysis.autoImportCompletions": true,
8 | "cSpell.words": [
9 | "backface",
10 | "BLACKMAN",
11 | "BSDF",
12 | "colorspace",
13 | "depsgraph",
14 | "eevee",
15 | "frustrum",
16 | "gtao",
17 | "matcap",
18 | "mathutils",
19 | "Metalness",
20 | "overscan",
21 | "ssao",
22 | "Toolbag",
23 | "viewlayer"
24 | ]
25 | }
26 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | # Introduction
4 |
5 | GrabDoc is a Blender 4+ add-on for quickly baking trim sheets and tileable texture maps.
6 |
7 | After installation, run the one-click scene setup and then start modeling! GrabDoc provides a camera object with the ability to preview your rendered texture maps in real-time via custom shaders in Workbench, EEVEE, and Cycles. Once satisfied you can bake all maps using in-house options or even utilizing Marmoset Toolbag 4's baker for the best results!
8 |
9 | # Features
10 |
11 | Head to the [Gumroad](https://gumroad.com/l/grabdoc) page for a full feature list!
12 |
13 | # Support
14 |
15 | GrabDoc is a FOSS (Free and Open Source Software) project, which means I see very little return on my time spent developing and maintaining it.
16 |
17 | If you would like to support me, consider buying this add-on on [Gumroad](https://gumroad.com/l/grabdoc), or if you've already done that, send me a tip on [Ko-fi](https://ko-fi.com/razed)!
18 |
--------------------------------------------------------------------------------
/__init__.py:
--------------------------------------------------------------------------------
1 | import importlib
2 |
3 | import bpy
4 | from bpy.app.handlers import persistent
5 |
6 | from .ui import register_baker_panels
7 |
8 |
9 | #########################
10 | # HANDLERS
11 | #########################
12 |
13 |
14 | @persistent
15 | def load_post_handler(_dummy):
16 | register_baker_panels()
17 |
18 |
19 | #########################
20 | # REGISTRATION
21 | #########################
22 |
23 |
24 | module_names = (
25 | "operators.core",
26 | "operators.material",
27 | "preferences",
28 | "ui"
29 | )
30 |
31 | modules = []
32 | for module_name in module_names:
33 | if module_name in locals():
34 | modules.append(importlib.reload(locals()[module_name]))
35 | else:
36 | modules.append(importlib.import_module(f".{module_name}", __package__))
37 |
38 | def register():
39 | for mod in modules:
40 | mod.register()
41 |
42 | bpy.app.handlers.load_post.append(load_post_handler)
43 |
44 | def unregister():
45 | for mod in modules:
46 | mod.unregister()
47 |
--------------------------------------------------------------------------------
/baker.py:
--------------------------------------------------------------------------------
1 | import bpy
2 | from bpy.types import PropertyGroup, UILayout, Context, NodeTree
3 | from bpy.props import (
4 | BoolProperty, StringProperty, EnumProperty,
5 | IntProperty, FloatProperty, PointerProperty,
6 | CollectionProperty
7 | )
8 |
9 | from .constants import Global
10 | from .utils.scene import scene_setup
11 | from .utils.node import (
12 | generate_shader_interface, get_group_inputs, get_material_output_sockets
13 | )
14 | from .utils.render import (
15 | set_guide_height, get_rendered_objects, set_color_management
16 | )
17 |
18 |
19 | class Baker(PropertyGroup):
20 | """A Blender shader and render settings automation system with
21 | efficient setup and clean up of desired render targets non-destructively.
22 |
23 | This system is designed for rapid development of new
24 | bake map types with minimal unique implementation.
25 |
26 | The most minimal examples of subclasses require the following:
27 | - Core shader properties (e.g. ID, Name, etc.)
28 | - BPY code for re-creating the desired shader / node group"""
29 | ID: str = ''
30 | NAME: str = ID.capitalize()
31 | VIEW_TRANSFORM: str = 'Standard'
32 | MARMOSET_COMPATIBLE: bool = True
33 | REQUIRED_SOCKETS: tuple[str] = ()
34 | OPTIONAL_SOCKETS: tuple[str] = ('Alpha',)
35 | SUPPORTED_ENGINES = (('blender_eevee_next', "EEVEE", ""),
36 | ('cycles', "Cycles", ""),
37 | ('blender_workbench', "Workbench", ""))
38 |
39 | def __init__(self):
40 | """Called when `bpy.ops.grab_doc.scene_setup` operator is ran.
41 |
42 | This method is NOT called when created via `CollectionProperty`."""
43 | self.node_input = None
44 | self.node_output = None
45 |
46 | # NOTE: For properties using constants as defaults
47 | self.__class__.suffix = StringProperty(
48 | description="The suffix of the exported bake map",
49 | name="Suffix", default=self.ID
50 | )
51 | self.__class__.engine = EnumProperty(
52 | name='Render Engine',
53 | items=self.SUPPORTED_ENGINES,
54 | update=self.__class__.apply_render_settings
55 | )
56 | self.__class__.suffix = StringProperty(
57 | description="The suffix of the exported bake map",
58 | name="Suffix", default=self.ID
59 | )
60 | self.__class__.enabled = BoolProperty(
61 | name="Export Enabled", default=self.MARMOSET_COMPATIBLE
62 | )
63 |
64 | if self.index == -1:
65 | gd = bpy.context.scene.gd
66 | self.index = self.get_unique_index(getattr(gd, self.ID))
67 | if self.index > 0:
68 | self.node_name = self.get_node_name(self.NAME, self.index+1)
69 | if not self.suffix[-1].isdigit():
70 | self.suffix = f"{self.suffix}_{self.index+1}"
71 |
72 | @staticmethod
73 | def get_unique_index(collection: CollectionProperty) -> int:
74 | """Get a unique index value based on a given `CollectionProperty`."""
75 | indices = [baker.index for baker in collection]
76 | index = 0
77 | while True:
78 | if index not in indices:
79 | break
80 | index += 1
81 | return index
82 |
83 | @staticmethod
84 | def get_node_name(name: str, idx: int=0):
85 | """Set node name based on given base `name` and optional `idx`."""
86 | node_name = Global.FLAG_PREFIX + name.replace(" ", "")
87 | if idx:
88 | node_name += f"_{idx}"
89 | return node_name
90 |
91 | def setup(self):
92 | """General operations to run before bake export."""
93 | self.apply_render_settings(requires_preview=False)
94 |
95 | def node_setup(self):
96 | """Shader logic to generate a node group.
97 |
98 | Base method logic gets/creates a new group with
99 | valid sockets and adds I/O nodes to the tree."""
100 | if not self.node_name:
101 | self.node_name = self.get_node_name(self.NAME)
102 | self.node_tree = bpy.data.node_groups.get(self.node_name)
103 | if self.node_tree is None:
104 | self.node_tree = \
105 | bpy.data.node_groups.new(self.node_name, 'ShaderNodeTree')
106 | # NOTE: Default alpha socket for pre-built bakers
107 | self.node_tree.interface.new_socket(
108 | name='Alpha', socket_type='NodeSocketFloat'
109 | ).default_value = 1
110 |
111 | self.node_tree.use_fake_user = True
112 | self.node_input = self.node_tree.nodes.new('NodeGroupInput')
113 | self.node_input.location = (-1500, 0)
114 | self.node_output = self.node_tree.nodes.new('NodeGroupOutput')
115 | generate_shader_interface(self.node_tree, get_material_output_sockets())
116 |
117 | def reimport_setup(self, material, image):
118 | """Shader logic to link an imported image texture a generic BSDF."""
119 | links = material.node_tree.links
120 | bsdf = material.node_tree.nodes['Principled BSDF']
121 | try:
122 | links.new(bsdf.inputs[self.ID.capitalize()], image.outputs["Color"])
123 | except KeyError:
124 | pass
125 |
126 | def cleanup(self):
127 | """Operations to revert unique scene modifications after bake export."""
128 |
129 | def apply_render_settings(self, requires_preview: bool=True) -> None:
130 | """Apply global baker render and color management settings."""
131 | if requires_preview and not bpy.context.scene.gd.preview_state:
132 | return
133 |
134 | scene = bpy.context.scene
135 | render = scene.render
136 | cycles = scene.cycles
137 | if scene.gd.use_filtering and not self.disable_filtering:
138 | render.filter_size = cycles.filter_width = scene.gd.filter_width
139 | else:
140 | render.filter_size = cycles.filter_width = .01
141 |
142 | eevee = scene.eevee
143 | display = scene.display
144 | render.engine = str(self.engine).upper()
145 | if render.engine == "blender_eevee_next".upper():
146 | eevee.taa_render_samples = eevee.taa_samples = self.samples
147 | elif render.engine == 'CYCLES':
148 | cycles.samples = cycles.preview_samples = self.samples_cycles
149 | elif render.engine == 'BLENDER_WORKBENCH':
150 | display.render_aa = display.viewport_aa = self.samples_workbench
151 |
152 | set_color_management(self.VIEW_TRANSFORM,
153 | self.contrast.replace('_', ' '))
154 |
155 | def filter_required_sockets(self, sockets: list[str]) -> str:
156 | """Filter out optional sockets from a list of socket names."""
157 | required_sockets = []
158 | for socket in sockets:
159 | if socket in self.REQUIRED_SOCKETS:
160 | required_sockets.append(socket)
161 | return ", ".join(required_sockets)
162 |
163 | def draw_properties(self, context: Context, layout: UILayout):
164 | """Dedicated layout for specific bake map properties."""
165 |
166 | def draw(self, context: Context, layout: UILayout):
167 | """Dropdown layout for bake map properties and operators."""
168 | layout.use_property_split = True
169 | layout.use_property_decorate = False
170 | col = layout.column()
171 |
172 | box = col.box()
173 | box.label(text="Properties", icon="PROPERTIES")
174 | row = box.row(align=True)
175 | if len(self.SUPPORTED_ENGINES) < 2:
176 | row.enabled = False
177 | row.prop(self, 'engine')
178 |
179 | self.draw_properties(context, box)
180 |
181 | box = col.box()
182 | box.label(text="Settings", icon="SETTINGS")
183 | col_set = box.column()
184 | gd = context.scene.gd
185 | if gd.engine == 'grabdoc':
186 | col_set.prop(self, 'reimport')
187 | col_set.prop(self, 'disable_filtering')
188 | prop = 'samples'
189 | if self.engine == 'blender_workbench':
190 | prop = 'samples_workbench'
191 | elif self.engine == 'cycles':
192 | prop = 'samples_cycles'
193 | col_set.prop(self, prop, text='Samples')
194 | col_set.prop(self, 'contrast')
195 | col_set.prop(self, 'suffix')
196 |
197 | col_info = col.column(align=True)
198 | col_info.scale_y = .9
199 | if not self.MARMOSET_COMPATIBLE:
200 | box = col_info.box()
201 | col2 = box.column(align=True)
202 | col2.label(text="Marmoset not supported", icon='INFO')
203 | if self.node_tree and self.REQUIRED_SOCKETS:
204 | box = col_info.box()
205 | col2 = box.column(align=True)
206 | col2.label(text="Requires socket(s):", icon='WARNING_LARGE')
207 | row = col2.row(align=True)
208 | inputs_fmt = ", ".join(self.REQUIRED_SOCKETS)
209 | row.label(text=f" {inputs_fmt}", icon='BLANK1')
210 | if self.node_tree and self.OPTIONAL_SOCKETS:
211 | box = col_info.box()
212 | col2 = box.column(align=True)
213 | col2.label(text="Supports socket(s):", icon='INFO')
214 | row = col2.row(align=True)
215 | inputs_fmt = ", ".join(self.OPTIONAL_SOCKETS)
216 | row.label(text=f" {inputs_fmt}", icon='BLANK1')
217 |
218 | # NOTE: Internal properties
219 | index: IntProperty(default=-1)
220 | node_name: StringProperty()
221 | node_tree: PointerProperty(type=NodeTree)
222 |
223 | # NOTE: Default properties
224 | reimport: BoolProperty(
225 | description="Reimport bake map texture into a Blender material",
226 | name="Re-import"
227 | )
228 | visibility: BoolProperty(
229 | description="Toggle UI visibility of this bake map", default=True
230 | )
231 | disable_filtering: BoolProperty(
232 | description="Override global filtering setting and set filter to .01px",
233 | name="Override Filtering", default=False, update=apply_render_settings
234 | )
235 | samples: IntProperty(name="EEVEE Samples", update=apply_render_settings,
236 | default=32, min=1, soft_max=256)
237 | samples_cycles: IntProperty(name="Cycles Samples",
238 | update=apply_render_settings,
239 | default=16, min=1, soft_max=256)
240 | samples_workbench: EnumProperty(
241 | items=(('OFF', "No Anti-Aliasing", ""),
242 | ('FXAA', "1 Sample", ""),
243 | ('5', "5 Samples", ""),
244 | ('8', "8 Samples", ""),
245 | ('11', "11 Samples", ""),
246 | ('16', "16 Samples", ""),
247 | ('32', "32 Samples", "")),
248 | name="Workbench Samples", default="8", update=apply_render_settings
249 | )
250 | contrast: EnumProperty(
251 | items=(('None', "Default", ""),
252 | ('Very_High_Contrast', "Very High", ""),
253 | ('High_Contrast', "High", ""),
254 | ('Medium_High_Contrast', "Medium High", ""),
255 | ('Medium_Low_Contrast', "Medium Low", ""),
256 | ('Low_Contrast', "Low", ""),
257 | ('Very_Low_Contrast', "Very Low", "")),
258 | name="Contrast", update=apply_render_settings
259 | )
260 |
261 |
262 | class Normals(Baker):
263 | ID = 'normals'
264 | NAME = ID.capitalize()
265 | VIEW_TRANSFORM = "Raw"
266 | MARMOSET_COMPATIBLE = True
267 | REQUIRED_SOCKETS = ()
268 | OPTIONAL_SOCKETS = ('Alpha', 'Normal')
269 | SUPPORTED_ENGINES = Baker.SUPPORTED_ENGINES[:-1]
270 |
271 | def node_setup(self):
272 | super().node_setup()
273 | self.node_tree.interface.new_socket(
274 | name='Normal', socket_type='NodeSocketVector'
275 | )
276 |
277 | bevel = self.node_tree.nodes.new('ShaderNodeBevel')
278 | bevel.inputs[0].default_value = 0
279 | bevel.location = (-1000, 0)
280 |
281 | vec_transform = self.node_tree.nodes.new('ShaderNodeVectorTransform')
282 | vec_transform.vector_type = 'NORMAL'
283 | vec_transform.convert_to = 'CAMERA'
284 | vec_transform.location = (-800, 0)
285 |
286 | vec_mult = self.node_tree.nodes.new('ShaderNodeVectorMath')
287 | vec_mult.operation = 'MULTIPLY'
288 | vec_mult.inputs[1].default_value[0] = .5
289 | vec_mult.inputs[1].default_value[1] = -.5 if self.flip_y else .5
290 | vec_mult.inputs[1].default_value[2] = -.5
291 | vec_mult.location = (-600, 0)
292 |
293 | vec_add = self.node_tree.nodes.new('ShaderNodeVectorMath')
294 | vec_add.inputs[1].default_value[0] = \
295 | vec_add.inputs[1].default_value[1] = \
296 | vec_add.inputs[1].default_value[2] = 0.5
297 | vec_add.location = (-400, 0)
298 |
299 | invert = self.node_tree.nodes.new('ShaderNodeInvert')
300 | invert.location = (-1000, -300)
301 |
302 | subtract = self.node_tree.nodes.new('ShaderNodeMixRGB')
303 | subtract.blend_type = 'SUBTRACT'
304 | subtract.inputs[0].default_value = 1
305 | subtract.inputs[1].default_value = (1, 1, 1, 1)
306 | subtract.location = (-800, -300)
307 |
308 | transp_shader = self.node_tree.nodes.new('ShaderNodeBsdfTransparent')
309 | transp_shader.location = (-400, -400)
310 |
311 | mix_shader = self.node_tree.nodes.new('ShaderNodeMixShader')
312 | mix_shader.location = (-200, -300)
313 |
314 | links = self.node_tree.links
315 | links.new(bevel.inputs["Normal"], self.node_input.outputs["Normal"])
316 | links.new(vec_transform.inputs["Vector"], bevel.outputs["Normal"])
317 | links.new(vec_mult.inputs["Vector"], vec_transform.outputs["Vector"])
318 | links.new(vec_add.inputs["Vector"], vec_mult.outputs["Vector"])
319 |
320 | links.new(invert.inputs['Color'], self.node_input.outputs['Alpha'])
321 | links.new(subtract.inputs['Color2'], invert.outputs['Color'])
322 | links.new(mix_shader.inputs['Fac'], subtract.outputs['Color'])
323 | links.new(mix_shader.inputs[1], transp_shader.outputs['BSDF'])
324 | links.new(mix_shader.inputs[2], vec_add.outputs['Vector'])
325 |
326 | # NOTE: Update if use_texture default changes
327 | links.new(self.node_output.inputs["Shader"],
328 | mix_shader.outputs["Shader"])
329 |
330 | def reimport_setup(self, material, image):
331 | bsdf = material.node_tree.nodes['Principled BSDF']
332 | normal = material.node_tree.nodes['Normal Map']
333 | if normal is None:
334 | normal = material.node_tree.nodes.new('ShaderNodeNormalMap')
335 | normal.hide = True
336 | normal.location = (image.location[0] + 100, image.location[1])
337 | image.location = (image.location[0] - 200, image.location[1])
338 | links = material.node_tree.links
339 | links.new(normal.inputs["Color"], image.outputs["Color"])
340 | links.new(bsdf.inputs["Normal"], normal.outputs["Normal"])
341 |
342 | def draw_properties(self, context: Context, layout: UILayout):
343 | col = layout.column()
344 | col.prop(self, 'flip_y')
345 | if context.scene.gd.engine == 'grabdoc':
346 | col.prop(self, 'use_texture')
347 | if self.engine == 'cycles':
348 | col.prop(self, 'bevel_weight')
349 |
350 | def update_flip_y(self, _context: Context):
351 | vec_multiply = self.node_tree.nodes['Vector Math']
352 | vec_multiply.inputs[1].default_value[1] = -.5 if self.flip_y else .5
353 |
354 | def update_use_texture(self, context: Context) -> None:
355 | if not context.scene.gd.preview_state:
356 | return
357 | group_output = self.node_tree.nodes['Group Output']
358 | links = self.node_tree.links
359 | if self.use_texture:
360 | links.new(group_output.inputs["Shader"],
361 | self.node_tree.nodes['Mix Shader'].outputs["Shader"])
362 | return
363 | links.new(group_output.inputs["Shader"],
364 | self.node_tree.nodes['Vector Math.001'].outputs["Vector"])
365 |
366 | def update_bevel_weight(self, _context: Context):
367 | bevel = self.node_tree.nodes['Bevel']
368 | bevel.inputs[0].default_value = self.bevel_weight
369 |
370 | flip_y: BoolProperty(
371 | description="Flip the normal map Y direction (DirectX format)",
372 | name="Invert (-Y)", options={'SKIP_SAVE'}, update=update_flip_y
373 | )
374 | use_texture: BoolProperty(
375 | description="Use texture normals linked to the Principled BSDF",
376 | name="Mix Textures", options={'SKIP_SAVE'},
377 | default=True, update=update_use_texture
378 | )
379 | bevel_weight: FloatProperty(
380 | description="Bevel shader weight (May need to increase samples)",
381 | name="Bevel", options={'SKIP_SAVE'}, update=update_bevel_weight,
382 | default=0, step=1, min=0, max=10, soft_max=1
383 | )
384 |
385 |
386 | class Curvature(Baker):
387 | ID = 'curvature'
388 | NAME = ID.capitalize()
389 | VIEW_TRANSFORM = "Standard"
390 | MARMOSET_COMPATIBLE = True
391 | REQUIRED_SOCKETS = ()
392 | OPTIONAL_SOCKETS = ()
393 | SUPPORTED_ENGINES = Baker.SUPPORTED_ENGINES[1:]
394 |
395 | def __init__(self):
396 | super().__init__()
397 | self.engine = self.SUPPORTED_ENGINES[-1][0]
398 |
399 | def setup(self) -> None:
400 | super().setup()
401 | scene = bpy.context.scene
402 | scene_shading = scene.display.shading
403 | scene_shading.light = 'FLAT'
404 | scene_shading.color_type = 'SINGLE'
405 | scene_shading.show_cavity = True
406 | scene_shading.cavity_type = 'BOTH'
407 | scene_shading.cavity_ridge_factor = \
408 | scene_shading.curvature_ridge_factor = self.ridge
409 | scene_shading.curvature_valley_factor = self.valley
410 | scene_shading.cavity_valley_factor = 0
411 | scene_shading.single_color = (.214041, .214041, .214041)
412 | scene.display.matcap_ssao_distance = .075
413 | self.update_range(bpy.context)
414 |
415 | def node_setup(self):
416 | super().node_setup()
417 |
418 | geometry = self.node_tree.nodes.new('ShaderNodeNewGeometry')
419 | geometry.location = (-800, 0)
420 |
421 | color_ramp = self.node_tree.nodes.new('ShaderNodeValToRGB')
422 | color_ramp.color_ramp.elements.new(.5)
423 | color_ramp.color_ramp.elements[0].position = 0.49
424 | color_ramp.color_ramp.elements[2].position = 0.51
425 | color_ramp.location = (-600, 0)
426 |
427 | emission = self.node_tree.nodes.new('ShaderNodeEmission')
428 | emission.location = (-200, 0)
429 |
430 | links = self.node_tree.links
431 | links.new(color_ramp.inputs["Fac"], geometry.outputs["Pointiness"])
432 | links.new(emission.inputs["Color"], color_ramp.outputs["Color"])
433 | links.new(self.node_output.inputs["Shader"],
434 | emission.outputs["Emission"])
435 |
436 | def apply_render_settings(self, requires_preview: bool=True):
437 | super().apply_render_settings(requires_preview)
438 | scene = bpy.context.scene
439 | view_transform = self.VIEW_TRANSFORM
440 | if scene.render.engine != 'BLENDER_WORKBENCH':
441 | view_transform = "Raw"
442 | set_color_management(view_transform)
443 |
444 | def draw_properties(self, context: Context, layout: UILayout):
445 | if context.scene.gd.engine != 'grabdoc':
446 | return
447 | col = layout.column()
448 | if context.scene.render.engine == 'BLENDER_WORKBENCH':
449 | col.prop(self, 'ridge', text="Ridge")
450 | col.prop(self, 'valley', text="Valley")
451 | elif context.scene.render.engine == 'CYCLES':
452 | col.prop(self, 'range', text="Range")
453 |
454 | def cleanup(self) -> None:
455 | bpy.data.objects[Global.BG_PLANE_NAME].color[3] = 1
456 |
457 | def update_curvature(self, context: Context):
458 | if not context.scene.gd.preview_state:
459 | return
460 | scene_shading = context.scene.display.shading
461 | scene_shading.cavity_ridge_factor = \
462 | scene_shading.curvature_ridge_factor = self.ridge
463 | scene_shading.curvature_valley_factor = self.valley
464 |
465 | def update_range(self, _context: Context):
466 | color_ramp = self.node_tree.nodes['Color Ramp']
467 | color_ramp.color_ramp.elements[0].position = 0.49 - (self.range/2+.01)
468 | color_ramp.color_ramp.elements[2].position = 0.51 + (self.range/2-.01)
469 |
470 | ridge: FloatProperty(name="", update=update_curvature,
471 | default=2, min=0, max=2, precision=3,
472 | step=.1, subtype='FACTOR')
473 | valley: FloatProperty(name="", update=update_curvature,
474 | default=1.5, min=0, max=2, precision=3,
475 | step=.1, subtype='FACTOR')
476 | range: FloatProperty(name="", update=update_range,
477 | default=.05, min=0, max=1, step=.1, subtype='FACTOR')
478 |
479 |
480 | class Occlusion(Baker):
481 | ID = 'occlusion'
482 | NAME = ID.capitalize()
483 | VIEW_TRANSFORM = "Raw"
484 | MARMOSET_COMPATIBLE = True
485 | REQUIRED_SOCKETS = ()
486 | OPTIONAL_SOCKETS = ('Alpha', 'Normal')
487 | SUPPORTED_ENGINES = Baker.SUPPORTED_ENGINES[:-1]
488 |
489 | def setup(self) -> None:
490 | super().setup()
491 | scene = bpy.context.scene
492 | eevee = scene.eevee
493 | if scene.render.engine == "blender_eevee_next".upper():
494 | eevee.use_gtao = True
495 | eevee.use_overscan = True
496 | eevee.overscan_size = 25
497 |
498 | def node_setup(self):
499 | super().node_setup()
500 | normal = self.node_tree.interface.new_socket(
501 | name='Normal', socket_type='NodeSocketVector'
502 | )
503 | normal.default_value = (0.5, 0.5, 1)
504 |
505 | ao = self.node_tree.nodes.new('ShaderNodeAmbientOcclusion')
506 | ao.samples = 32
507 | ao.location = (-800, 0)
508 |
509 | gamma = self.node_tree.nodes.new('ShaderNodeGamma')
510 | gamma.inputs[1].default_value = 1
511 | gamma.location = (-600, 0)
512 |
513 | invert = self.node_tree.nodes.new('ShaderNodeInvert')
514 | invert.inputs[0].default_value = 0
515 | invert.location = (-400, 0)
516 |
517 | emission = self.node_tree.nodes.new('ShaderNodeEmission')
518 | emission.location = (-200, 0)
519 |
520 | links = self.node_tree.links
521 | links.new(ao.inputs["Normal"], self.node_input.outputs["Normal"])
522 | links.new(invert.inputs["Color"], ao.outputs["Color"])
523 | links.new(gamma.inputs["Color"], invert.outputs["Color"])
524 | links.new(emission.inputs["Color"], gamma.outputs["Color"])
525 | links.new(self.node_output.inputs["Shader"],
526 | emission.outputs["Emission"])
527 |
528 | def draw_properties(self, context: Context, layout: UILayout):
529 | gd = context.scene.gd
530 | col = layout.column()
531 | if gd.engine == 'marmoset':
532 | col.prop(gd, "mt_occlusion_samples", text="Ray Count")
533 | return
534 | col.prop(self, 'invert')
535 | col.prop(self, 'gamma')
536 | col.prop(self, 'distance')
537 |
538 | def update_gamma(self, _context: Context):
539 | gamma = self.node_tree.nodes['Gamma']
540 | gamma.inputs[1].default_value = self.gamma
541 |
542 | def update_distance(self, _context: Context):
543 | ao = self.node_tree.nodes['Ambient Occlusion']
544 | ao.inputs[1].default_value = self.distance
545 |
546 | def update_invert(self, _context: Context):
547 | invert = self.node_tree.nodes['Invert Color']
548 | invert.inputs[0].default_value = 1 if self.invert else 0
549 |
550 | gamma: FloatProperty(
551 | description="Intensity of AO (calculated with gamma)",
552 | default=1, min=.001, soft_max=10, step=.17,
553 | name="Intensity", update=update_gamma
554 | )
555 | distance: FloatProperty(
556 | description="The distance AO rays travel",
557 | default=1, min=0, soft_max=100, step=.03, subtype='DISTANCE',
558 | name="Distance", update=update_distance
559 | )
560 | invert: BoolProperty(
561 | name="Invert", description="Invert the mask", update=update_invert
562 | )
563 |
564 |
565 | class Height(Baker):
566 | ID = 'height'
567 | NAME = ID.capitalize()
568 | VIEW_TRANSFORM = "Raw"
569 | MARMOSET_COMPATIBLE = True
570 | REQUIRED_SOCKETS = ()
571 | OPTIONAL_SOCKETS = ()
572 | SUPPORTED_ENGINES = Baker.SUPPORTED_ENGINES[:-1]
573 |
574 | def setup(self) -> None:
575 | super().setup()
576 | if self.method == 'AUTO':
577 | rendered_obs = get_rendered_objects()
578 | set_guide_height(rendered_obs)
579 |
580 | def node_setup(self):
581 | super().node_setup()
582 |
583 | camera = self.node_tree.nodes.new('ShaderNodeCameraData')
584 | camera.location = (-800, 0)
585 |
586 | # NOTE: Map Range updates handled on map preview
587 | map_range = self.node_tree.nodes.new('ShaderNodeMapRange')
588 | map_range.location = (-600, 0)
589 |
590 | ramp = self.node_tree.nodes.new('ShaderNodeValToRGB')
591 | ramp.color_ramp.elements[0].color = (1, 1, 1, 1)
592 | ramp.color_ramp.elements[1].color = (0, 0, 0, 1)
593 | ramp.location = (-400, 0)
594 |
595 | links = self.node_tree.links
596 | links.new(map_range.inputs["Value"], camera.outputs["View Z Depth"])
597 | links.new(ramp.inputs["Fac"], map_range.outputs["Result"])
598 | links.new(self.node_output.inputs["Shader"], ramp.outputs["Color"])
599 |
600 | def draw_properties(self, context: Context, layout: UILayout):
601 | col = layout.column()
602 | if context.scene.gd.engine == 'grabdoc':
603 | col.prop(self, 'invert', text="Invert")
604 | row = col.row()
605 | row.prop(self, 'method', text="Method", expand=True)
606 | if self.method == 'MANUAL':
607 | col.prop(self, 'distance', text="0-1 Range")
608 |
609 | def update_method(self, context: Context):
610 | scene_setup(self, context)
611 | if not context.scene.gd.preview_state:
612 | return
613 | if self.method == 'AUTO':
614 | rendered_obs = get_rendered_objects()
615 | set_guide_height(rendered_obs)
616 |
617 | def update_guide(self, context: Context):
618 | map_range = self.node_tree.nodes['Map Range']
619 | camera_object_z = Global.CAMERA_DISTANCE * bpy.context.scene.gd.scale
620 | map_range.inputs[1].default_value = camera_object_z - self.distance
621 | map_range.inputs[2].default_value = camera_object_z
622 |
623 | ramp = self.node_tree.nodes['Color Ramp']
624 | ramp.color_ramp.elements[0].color = \
625 | (0, 0, 0, 1) if self.invert else (1, 1, 1, 1)
626 | ramp.color_ramp.elements[1].color = \
627 | (1, 1, 1, 1) if self.invert else (0, 0, 0, 1)
628 | ramp.location = (-400, 0)
629 |
630 | if self.method == 'MANUAL':
631 | scene_setup(self, context)
632 |
633 | invert: BoolProperty(
634 | description="Invert height mask, useful for sculpting negatively",
635 | update=update_guide
636 | )
637 | distance: FloatProperty(
638 | name="", update=update_guide,
639 | default=1, min=.01, soft_max=100, step=.03, subtype='DISTANCE'
640 | )
641 | method: EnumProperty(
642 | description="Height method, use manual if auto produces range errors",
643 | name="Method", update=update_method,
644 | items=(('AUTO', "Auto", ""),
645 | ('MANUAL', "Manual", ""))
646 | )
647 |
648 |
649 | class Id(Baker):
650 | ID = 'id'
651 | NAME = "Material ID"
652 | VIEW_TRANSFORM = "Standard"
653 | MARMOSET_COMPATIBLE = True
654 | REQUIRED_SOCKETS = ()
655 | OPTIONAL_SOCKETS = ()
656 | SUPPORTED_ENGINES = (Baker.SUPPORTED_ENGINES[-1],)
657 |
658 | def __init__(self):
659 | super().__init__()
660 | self.disable_filtering = True
661 |
662 | def setup(self) -> None:
663 | super().setup()
664 | if bpy.context.scene.render.engine == 'BLENDER_WORKBENCH':
665 | self.update_method(bpy.context)
666 |
667 | def node_setup(self):
668 | pass
669 |
670 | def draw_properties(self, context: Context, layout: UILayout):
671 | gd = context.scene.gd
672 | row = layout.row()
673 | if gd.engine != 'marmoset':
674 | row.prop(self, 'method')
675 | if self.method != 'MATERIAL':
676 | return
677 |
678 | col = layout.column(align=True)
679 | col.separator(factor=.5)
680 | col.scale_y = 1.1
681 | col.operator("grab_doc.quick_id_setup")
682 |
683 | row = col.row(align=True)
684 | row.scale_y = .9
685 | row.label(text=" Remove:")
686 | row.operator(
687 | "grab_doc.remove_mats_by_name",
688 | text='All'
689 | ).name = Global.RANDOM_ID_PREFIX
690 |
691 | col = layout.column(align=True)
692 | col.separator(factor=.5)
693 | col.scale_y = 1.1
694 | col.operator("grab_doc.quick_id_selected")
695 |
696 | row = col.row(align=True)
697 | row.scale_y = .9
698 | row.label(text=" Remove:")
699 | row.operator("grab_doc.remove_mats_by_name",
700 | text='All').name = Global.ID_PREFIX
701 | row.operator("grab_doc.quick_remove_selected_mats",
702 | text='Selected')
703 |
704 | def update_method(self, context: Context):
705 | shading = context.scene.display.shading
706 | shading.show_cavity = False
707 | shading.light = 'FLAT'
708 | shading.color_type = self.method
709 |
710 | method: EnumProperty(
711 | items=(('MATERIAL', 'Material', ''),
712 | ('SINGLE', 'Single', ''),
713 | ('OBJECT', 'Object', ''),
714 | ('RANDOM', 'Random', ''),
715 | ('VERTEX', 'Vertex', ''),
716 | ('TEXTURE', 'Texture', '')),
717 | name="Method", update=update_method, default='RANDOM'
718 | )
719 |
720 | class Alpha(Baker):
721 | ID = 'alpha'
722 | NAME = ID.capitalize()
723 | VIEW_TRANSFORM = "Raw"
724 | MARMOSET_COMPATIBLE = True
725 | REQUIRED_SOCKETS = ()
726 | OPTIONAL_SOCKETS = Baker.OPTIONAL_SOCKETS
727 | SUPPORTED_ENGINES = Baker.SUPPORTED_ENGINES[:-1]
728 |
729 | def node_setup(self):
730 | super().node_setup()
731 |
732 | camera = self.node_tree.nodes.new('ShaderNodeCameraData')
733 | camera.location = (-1000, 0)
734 |
735 | map_range = self.node_tree.nodes.new('ShaderNodeMapRange')
736 | map_range.location = (-800, 0)
737 | camera_object_z = Global.CAMERA_DISTANCE * bpy.context.scene.gd.scale
738 | map_range.inputs[1].default_value = camera_object_z - .00001
739 | map_range.inputs[2].default_value = camera_object_z
740 |
741 | invert_mask = self.node_tree.nodes.new('ShaderNodeInvert')
742 | invert_mask.name = "Invert Mask"
743 | invert_mask.location = (-600, 200)
744 |
745 | invert_depth = self.node_tree.nodes.new('ShaderNodeInvert')
746 | invert_depth.name = "Invert Depth"
747 | invert_depth.location = (-600, 0)
748 |
749 | mix = self.node_tree.nodes.new('ShaderNodeMix')
750 | mix.name = "Invert Mask"
751 | mix.data_type = "RGBA"
752 | mix.inputs["B"].default_value = (0, 0, 0, 1)
753 | mix.location = (-400, 0)
754 |
755 | emission = self.node_tree.nodes.new('ShaderNodeEmission')
756 | emission.location = (-200, 0)
757 |
758 | links = self.node_tree.links
759 | links.new(invert_mask.inputs["Color"], self.node_input.outputs["Alpha"])
760 | links.new(mix.inputs["Factor"], invert_mask.outputs["Color"])
761 |
762 | links.new(map_range.inputs["Value"], camera.outputs["View Z Depth"])
763 | links.new(invert_depth.inputs["Color"], map_range.outputs["Result"])
764 | links.new(mix.inputs["A"], invert_depth.outputs["Color"])
765 |
766 | links.new(emission.inputs["Color"], mix.outputs["Result"])
767 | links.new(self.node_output.inputs["Shader"],
768 | emission.outputs["Emission"])
769 |
770 | def draw_properties(self, context: Context, layout: UILayout):
771 | if context.scene.gd.engine != 'grabdoc':
772 | return
773 | col = layout.column()
774 | col.prop(self, 'invert_depth', text="Invert Depth")
775 | col.prop(self, 'invert_mask', text="Invert Mask")
776 |
777 | def update_map_range(self, _context: Context):
778 | map_range = self.node_tree.nodes['Map Range']
779 | camera_object_z = Global.CAMERA_DISTANCE * bpy.context.scene.gd.scale
780 | map_range.inputs[1].default_value = camera_object_z - .00001
781 | map_range.inputs[2].default_value = camera_object_z
782 | invert_depth = self.node_tree.nodes['Invert Depth']
783 | invert_depth.inputs[0].default_value = 0 if self.invert_depth else 1
784 | invert_mask = self.node_tree.nodes['Invert Mask']
785 | invert_mask.inputs[0].default_value = 0 if self.invert_mask else 1
786 |
787 | invert_depth: BoolProperty(
788 | description="Invert the global depth mask", update=update_map_range
789 | )
790 | invert_mask: BoolProperty(
791 | description="Invert the alpha mask", update=update_map_range
792 | )
793 |
794 |
795 | class Roughness(Baker):
796 | ID = 'roughness'
797 | NAME = ID.capitalize()
798 | VIEW_TRANSFORM = "Raw"
799 | MARMOSET_COMPATIBLE = False
800 | REQUIRED_SOCKETS = (NAME,)
801 | OPTIONAL_SOCKETS = ()
802 | SUPPORTED_ENGINES = Baker.SUPPORTED_ENGINES[:-1]
803 |
804 | def node_setup(self):
805 | super().node_setup()
806 | self.node_tree.interface.new_socket(
807 | name=self.NAME, socket_type='NodeSocketFloat'
808 | )
809 |
810 | invert = self.node_tree.nodes.new('ShaderNodeInvert')
811 | invert.location = (-400, 0)
812 | invert.inputs[0].default_value = 0
813 |
814 | emission = self.node_tree.nodes.new('ShaderNodeEmission')
815 | emission.location = (-200, 0)
816 |
817 | links = self.node_tree.links
818 | links.new(invert.inputs["Color"], self.node_input.outputs["Roughness"])
819 | links.new(emission.inputs["Color"], invert.outputs["Color"])
820 | links.new(self.node_output.inputs["Shader"],
821 | emission.outputs["Emission"])
822 |
823 | def draw_properties(self, _context: Context, layout: UILayout):
824 | col = layout.column()
825 | col.prop(self, 'invert', text="Invert")
826 |
827 | def update_invert(self, _context: Context):
828 | invert = self.node_tree.nodes['Invert Color']
829 | invert.inputs[0].default_value = 1 if self.invert else 0
830 |
831 | invert: BoolProperty(description="Invert the Roughness (AKA Glossiness)",
832 | update=update_invert)
833 |
834 |
835 | class Color(Baker):
836 | ID = 'color'
837 | NAME = "Base Color"
838 | VIEW_TRANSFORM = "Standard"
839 | MARMOSET_COMPATIBLE = False
840 | REQUIRED_SOCKETS = (NAME,)
841 | OPTIONAL_SOCKETS = ()
842 | SUPPORTED_ENGINES = Baker.SUPPORTED_ENGINES[:-1]
843 |
844 | def node_setup(self):
845 | super().node_setup()
846 | self.node_tree.interface.new_socket(
847 | name=self.NAME, socket_type='NodeSocketColor'
848 | )
849 |
850 | emission = self.node_tree.nodes.new('ShaderNodeEmission')
851 | emission.location = (-200, 0)
852 |
853 | links = self.node_tree.links
854 | links.new(emission.inputs["Color"],
855 | self.node_input.outputs["Base Color"])
856 | links.new(self.node_output.inputs["Shader"],
857 | emission.outputs["Emission"])
858 |
859 | def reimport_setup(self, material, image):
860 | image.image.colorspace_settings.name = 'Non-Color'
861 | bsdf = material.node_tree.nodes['Principled BSDF']
862 | links = material.node_tree.links
863 | links.new(bsdf.inputs["Base Color"], image.outputs["Color"])
864 |
865 |
866 | class Emissive(Baker):
867 | ID = 'emissive'
868 | NAME = ID.capitalize()
869 | VIEW_TRANSFORM = "Standard"
870 | MARMOSET_COMPATIBLE = False
871 | REQUIRED_SOCKETS = ("Emission Color", "Emission Strength")
872 | OPTIONAL_SOCKETS = ()
873 | SUPPORTED_ENGINES = Baker.SUPPORTED_ENGINES[:-1]
874 |
875 | def node_setup(self):
876 | super().node_setup()
877 | emit_color = self.node_tree.interface.new_socket(
878 | name="Emission Color", socket_type='NodeSocketColor'
879 | )
880 | emit_color.default_value = (0, 0, 0, 1)
881 | emit_strength = self.node_tree.interface.new_socket(
882 | name="Emission Strength", socket_type='NodeSocketFloat'
883 | )
884 | emit_strength.default_value = 1
885 |
886 | emission = self.node_tree.nodes.new('ShaderNodeEmission')
887 | emission.location = (-200, 0)
888 |
889 | links = self.node_tree.links
890 | links.new(emission.inputs["Color"],
891 | self.node_input.outputs["Emission Color"])
892 | links.new(emission.inputs["Strength"],
893 | self.node_input.outputs["Emission Strength"])
894 | links.new(self.node_output.inputs["Shader"],
895 | emission.outputs["Emission"])
896 |
897 | def reimport_setup(self, material, image):
898 | image.image.colorspace_settings.name = 'Non-Color'
899 | bsdf = material.node_tree.nodes['Principled BSDF']
900 | links = material.node_tree.links
901 | links.new(bsdf.inputs["Emission Color"], image.outputs["Color"])
902 |
903 |
904 | class Metallic(Baker):
905 | ID = 'metallic'
906 | NAME = ID.capitalize()
907 | VIEW_TRANSFORM = "Raw"
908 | MARMOSET_COMPATIBLE = False
909 | REQUIRED_SOCKETS = (NAME,)
910 | OPTIONAL_SOCKETS = ()
911 | SUPPORTED_ENGINES = Baker.SUPPORTED_ENGINES[:-1]
912 |
913 | def node_setup(self):
914 | super().node_setup()
915 | self.node_tree.interface.new_socket(
916 | name=self.NAME, socket_type='NodeSocketFloat'
917 | )
918 |
919 | invert = self.node_tree.nodes.new('ShaderNodeInvert')
920 | invert.location = (-400, 0)
921 | invert.inputs[0].default_value = 0
922 |
923 | emission = self.node_tree.nodes.new('ShaderNodeEmission')
924 | emission.location = (-200, 0)
925 |
926 | links = self.node_tree.links
927 | links.new(emission.inputs["Color"], self.node_input.outputs["Metallic"])
928 | links.new(self.node_output.inputs["Shader"],
929 | emission.outputs["Emission"])
930 |
931 | def reimport_setup(self, material, image):
932 | bsdf = material.node_tree.nodes['Principled BSDF']
933 | links = material.node_tree.links
934 | links.new(bsdf.inputs["Metallic"], image.outputs["Color"])
935 |
936 | def draw_properties(self, _context: Context, layout: UILayout):
937 | col = layout.column()
938 | col.prop(self, 'invert', text="Invert")
939 |
940 | def update_invert(self, _context: Context):
941 | invert = self.node_tree.nodes['Invert Color']
942 | invert.inputs[0].default_value = 1 if self.invert else 0
943 |
944 | invert: BoolProperty(description="Invert the mask", update=update_invert)
945 |
946 |
947 | class Custom(Baker):
948 | ID = 'custom'
949 | NAME = ID.capitalize()
950 | VIEW_TRANSFORM = "Raw"
951 | MARMOSET_COMPATIBLE = False
952 | REQUIRED_SOCKETS = ()
953 | OPTIONAL_SOCKETS = ()
954 | SUPPORTED_ENGINES = Baker.SUPPORTED_ENGINES[:-1]
955 |
956 | def update_view_transform(self, _context: Context):
957 | self.VIEW_TRANSFORM = self.view_transform.capitalize()
958 | self.apply_render_settings()
959 |
960 | def draw_properties(self, context: Context, layout: UILayout):
961 | col = layout.column()
962 | row = col.row()
963 | if context.scene.gd.preview_state:
964 | row.enabled = False
965 | if not isinstance(self.node_tree, NodeTree):
966 | row.alert = True
967 | row.prop(self, 'node_tree')
968 | col.prop(self, 'view_transform')
969 |
970 | def node_setup(self, _context: Context=bpy.context):
971 | if not isinstance(self.node_tree, NodeTree):
972 | self.node_name = ""
973 | return
974 | self.node_name = self.node_tree.name
975 | self.__class__.REQUIRED_SOCKETS = \
976 | tuple(socket.name for socket in get_group_inputs(self.node_tree))
977 | generate_shader_interface(self.node_tree, get_material_output_sockets())
978 |
979 | # NOTE: Subclassed property - implement as user-facing
980 | node_tree: PointerProperty(
981 | description="Your baking shader, MUST have shader output",
982 | name='Shader', type=NodeTree, update=node_setup
983 | )
984 | view_transform: EnumProperty(items=(('raw', "Raw", ""),
985 | ('standard', "Standard", "")),
986 | name="View", default=VIEW_TRANSFORM.lower(),
987 | update=update_view_transform)
988 |
--------------------------------------------------------------------------------
/blender_manifest.toml:
--------------------------------------------------------------------------------
1 | schema_version = "1.0.0"
2 |
3 | id = "GrabDoc"
4 | version = "2.0.0"
5 | name = "GrabDoc"
6 | tagline = "A trim & tileable baker for Blender"
7 | maintainer = "Ethan Simon-Law "
8 | type = "add-on"
9 |
10 | website = "https://github.com/oRazeD/GrabDoc"
11 |
12 | tags = ["3D View", "Material", "Bake", "Compositing", "Render", "Import-Export"]
13 |
14 | blender_version_min = "4.2.0"
15 | blender_version_max = "4.7.0"
16 |
17 | license = [
18 | "SPDX:GPL-3.0-or-later",
19 | ]
20 |
21 | # [permissions]
22 | files = "Read/Write Images"
23 |
--------------------------------------------------------------------------------
/build.bat:
--------------------------------------------------------------------------------
1 | blender --command extension build
2 | explorer %~dp0
3 |
--------------------------------------------------------------------------------
/constants.py:
--------------------------------------------------------------------------------
1 |
2 | class Global:
3 | """A collection of constants used for global variable standardization"""
4 | FLAG_PREFIX = "[GrabDoc] "
5 | LOW_SUFFIX = "_low_gd"
6 | HIGH_SUFFIX = "_high_gd"
7 | NODE_GROUP_WARN_NAME = "_grabdoc_ng_warning"
8 |
9 | REFERENCE_NAME = FLAG_PREFIX + "Reference"
10 | TRIM_CAMERA_NAME = FLAG_PREFIX + "Trim Camera"
11 | BG_PLANE_NAME = FLAG_PREFIX + "Background Plane"
12 | HEIGHT_GUIDE_NAME = FLAG_PREFIX + "Height Guide"
13 | ORIENT_GUIDE_NAME = FLAG_PREFIX + "Orient Guide"
14 | GD_MATERIAL_NAME = FLAG_PREFIX + "Material"
15 | ID_PREFIX = FLAG_PREFIX + "ID"
16 | RANDOM_ID_PREFIX = FLAG_PREFIX + "RANDOM_ID"
17 | REIMPORT_MAT_NAME = FLAG_PREFIX + "Bake Result"
18 | COLL_CORE_NAME = FLAG_PREFIX + "Core"
19 | COLL_GROUP_NAME = FLAG_PREFIX + "Bake Group"
20 |
21 | CAMERA_DISTANCE = 15
22 |
23 | INVALID_BAKE_TYPES = ('EMPTY',
24 | 'VOLUME',
25 | 'ARMATURE',
26 | 'LATTICE',
27 | 'LIGHT',
28 | 'LIGHT_PROBE',
29 | 'CAMERA')
30 |
31 | IMAGE_FORMATS = {'TIFF': 'tif',
32 | 'TARGA': 'tga',
33 | 'OPEN_EXR': 'exr',
34 | 'PNG': 'png'}
35 |
36 | NODE_GROUP_WARN = """
37 | This node is generated by GrabDoc! Once exiting Map Preview,
38 | every node link will be returned to their original sockets.
39 |
40 | Avoid editing the contents of this node group. If you do make
41 | changes, using the Remove Setup operator will overwrite any changes!"""
42 |
43 |
44 | class Error:
45 | """A collection of constants used for error code/message standardization"""
46 | NO_OBJECTS_SELECTED = "There are no objects selected"
47 | BAKE_GROUPS_EMPTY = "No objects found in bake collections"
48 | NO_VALID_PATH_SET = "There is no export path set"
49 | ALL_MAPS_DISABLED = "No bake maps are enabled"
50 | MARMOSET_EXPORT_COMPLETE = "Export completed! Opening Marmoset Toolbag..."
51 | MARMOSET_REFRESH_COMPLETE = "Models re-exported! Switch to Marmoset Toolbag"
52 | EXPORT_COMPLETE = "Export completed!"
53 | CAMERA_NOT_FOUND = \
54 | "GrabDoc camera not found, please run the Refresh Scene operator"
55 | MISSING_SLOT_LINKS = \
56 | "socket(s) found without links, bake results may appear incorrect"
57 |
--------------------------------------------------------------------------------
/operators/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/oRazeD/GrabDoc/4486964418f7605965771cbc6d3d684d53b75ac3/operators/__init__.py
--------------------------------------------------------------------------------
/operators/core.py:
--------------------------------------------------------------------------------
1 | import os
2 | import time
3 |
4 | import bpy
5 | import blf
6 | from bpy.types import SpaceView3D, Event, Context, Operator, UILayout
7 | from bpy.props import StringProperty, IntProperty
8 |
9 | from ..constants import Global, Error
10 | from ..ui import register_baker_panels
11 | from ..utils.io import get_format, get_temp_path
12 | from ..utils.render import get_rendered_objects
13 | from ..utils.generic import get_user_preferences
14 | from ..utils.node import link_group_to_object, node_cleanup
15 | from ..utils.scene import (
16 | camera_in_3d_view, is_scene_valid,
17 | scene_setup, scene_cleanup, validate_scene
18 | )
19 | from ..utils.baker import (
20 | get_baker_collections, import_baker_textures, baker_setup,
21 | baker_cleanup, get_bakers, get_baker_by_index
22 | )
23 | from ..utils.pack import (
24 | get_channel_path, pack_image_channels, is_pack_maps_enabled
25 | )
26 |
27 |
28 | class GRABDOC_OT_load_reference(Operator):
29 | """Import a reference onto the background plane"""
30 | bl_idname = "grab_doc.load_reference"
31 | bl_label = "Load Reference"
32 | bl_options = {'REGISTER', 'UNDO'}
33 |
34 | filepath: StringProperty(subtype="FILE_PATH")
35 |
36 | def execute(self, context: Context):
37 | bpy.data.images.load(self.filepath, check_existing=True)
38 | path = os.path.basename(os.path.normpath(self.filepath))
39 | context.scene.gd.reference = bpy.data.images[path]
40 | return {'FINISHED'}
41 |
42 | def invoke(self, context: Context, _event: Event):
43 | context.window_manager.fileselect_add(self)
44 | return {'RUNNING_MODAL'}
45 |
46 |
47 | class GRABDOC_OT_open_folder(Operator):
48 | """Opens up the File Explorer to the designated folder location"""
49 | bl_idname = "grab_doc.open_folder"
50 | bl_label = "Open Export Folder"
51 | bl_options = {'REGISTER', 'UNDO'}
52 |
53 | def execute(self, context: Context):
54 | try:
55 | bpy.ops.wm.path_open(filepath=context.scene.gd.filepath)
56 | except RuntimeError:
57 | self.report({'ERROR'}, Error.NO_VALID_PATH_SET)
58 | return {'CANCELLED'}
59 | return {'FINISHED'}
60 |
61 |
62 | class GRABDOC_OT_toggle_camera_view(Operator):
63 | """View or leave the GrabDoc camera view"""
64 | bl_idname = "grab_doc.toggle_camera_view"
65 | bl_label = "Toggle Camera View"
66 |
67 | def execute(self, context: Context):
68 | context.scene.camera = bpy.data.objects[Global.TRIM_CAMERA_NAME]
69 | bpy.ops.view3d.view_camera()
70 | return {'FINISHED'}
71 |
72 |
73 | class GRABDOC_OT_scene_setup(Operator):
74 | """Setup or rebuild GrabDoc in your current scene.
75 |
76 | Useful for rare cases where GrabDoc isn't compatible with an existing setup.
77 |
78 | Can also potentially fix console spam from UI elements"""
79 | bl_idname = "grab_doc.scene_setup"
80 | bl_label = "Setup GrabDoc Scene"
81 | bl_options = {'REGISTER', 'INTERNAL'}
82 |
83 | @classmethod
84 | def poll(cls, context: Context) -> bool:
85 | return GRABDOC_OT_baker_export_single.poll(context)
86 |
87 | def execute(self, context: Context):
88 | for baker_prop in get_baker_collections():
89 | baker_prop.clear()
90 | baker = baker_prop.add()
91 |
92 | register_baker_panels()
93 | scene_setup(self, context)
94 |
95 | for baker in get_bakers():
96 | baker.node_setup()
97 | return {'FINISHED'}
98 |
99 |
100 | class GRABDOC_OT_scene_cleanup(Operator):
101 | """Remove all GrabDoc objects from the scene; keeps reimported textures"""
102 | bl_idname = "grab_doc.scene_cleanup"
103 | bl_label = "Remove GrabDoc Scene"
104 | bl_options = {'REGISTER', 'INTERNAL'}
105 |
106 | @classmethod
107 | def poll(cls, context: Context) -> bool:
108 | return GRABDOC_OT_baker_export_single.poll(context)
109 |
110 | def execute(self, context: Context):
111 | scene_cleanup(context)
112 | return {'FINISHED'}
113 |
114 |
115 | class GRABDOC_OT_baker_add(Operator):
116 | """Add a new baker of this type to the current scene"""
117 | bl_idname = "grab_doc.baker_add"
118 | bl_label = "Add Bake Map"
119 | bl_options = {'REGISTER', 'UNDO', 'INTERNAL'}
120 |
121 | map_type: StringProperty()
122 |
123 | def execute(self, context: Context):
124 | baker_prop = getattr(context.scene.gd, self.map_type)
125 | baker = baker_prop.add()
126 | register_baker_panels()
127 | baker.node_setup()
128 | return {'FINISHED'}
129 |
130 |
131 | class GRABDOC_OT_baker_remove(Operator):
132 | """Remove the current baker from the current scene"""
133 | bl_idname = "grab_doc.baker_remove"
134 | bl_label = "Remove Baker"
135 | bl_options = {'REGISTER', 'UNDO', 'INTERNAL'}
136 |
137 | map_type: StringProperty()
138 | baker_index: IntProperty()
139 |
140 | def execute(self, context: Context):
141 | baker_prop = getattr(context.scene.gd, self.map_type)
142 | baker = get_baker_by_index(baker_prop, self.baker_index)
143 | if baker.node_tree:
144 | bpy.data.node_groups.remove(baker.node_tree)
145 | for idx, bake_map in enumerate(baker_prop):
146 | if bake_map.index == baker.index:
147 | baker_prop.remove(idx)
148 | break
149 | register_baker_panels()
150 | return {'FINISHED'}
151 |
152 |
153 | class GRABDOC_OT_baker_export(Operator, UILayout):
154 | """Bake and export all enabled bake maps"""
155 | bl_idname = "grab_doc.baker_export"
156 | bl_label = "Export Maps"
157 | bl_options = {'REGISTER', 'INTERNAL'}
158 |
159 | progress_factor = 0.0
160 |
161 | @classmethod
162 | def poll(cls, context: Context) -> bool:
163 | gd = context.scene.gd
164 | if gd.filepath == "//" and not bpy.data.filepath:
165 | cls.poll_message_set("Relative export path but file not saved")
166 | return False
167 | if gd.preview_state:
168 | cls.poll_message_set("Cannot run while in Map Preview")
169 | return False
170 | return True
171 |
172 | @staticmethod
173 | def export(context: Context, suffix: str, path: str = None) -> str:
174 | gd = context.scene.gd
175 | render = context.scene.render
176 | saved_path = render.filepath
177 |
178 | name = f"{gd.filename}_{suffix}"
179 | if path is None:
180 | path = gd.filepath
181 | path = os.path.join(path, name + get_format())
182 | render.filepath = path
183 |
184 | context.scene.camera = bpy.data.objects[Global.TRIM_CAMERA_NAME]
185 |
186 | bpy.ops.render.render(write_still=True)
187 | render.filepath = saved_path
188 | return path
189 |
190 | def execute(self, context: Context):
191 | gd = context.scene.gd
192 | report_value, report_string = validate_scene(context)
193 | if report_value:
194 | self.report({'ERROR'}, report_string)
195 | return {'CANCELLED'}
196 | bakers = get_bakers(filter_enabled=True)
197 | if not bakers:
198 | self.report({'ERROR'}, Error.ALL_MAPS_DISABLED)
199 | return {'CANCELLED'}
200 | if gd.use_pack_maps is True and not is_pack_maps_enabled():
201 | self.report(
202 | {'ERROR'},
203 | "Map packing enabled but incorrect export maps enabled"
204 | )
205 | return {'CANCELLED'}
206 |
207 | self.map_type = 'export'
208 |
209 | start = time.time()
210 | context.window_manager.progress_begin(0, 9999)
211 | completion_step = 100 / (1 + len(bakers))
212 | completion_percent = 0
213 |
214 | saved_properties = baker_setup(context)
215 |
216 | active_selected = False
217 | if context.object:
218 | activeCallback = context.object.name
219 | modeCallback = context.object.mode
220 | if bpy.ops.object.mode_set.poll():
221 | bpy.ops.object.mode_set(mode='OBJECT')
222 | active_selected = True
223 |
224 | # Scale up BG Plane (helps overscan & border pixels)
225 | plane_ob = bpy.data.objects[Global.BG_PLANE_NAME]
226 | plane_ob.scale[0] = plane_ob.scale[1] = 3
227 |
228 | rendered_objects = get_rendered_objects()
229 | for baker in bakers:
230 | baker.setup()
231 | if not baker.node_tree:
232 | continue
233 | for ob in rendered_objects:
234 | sockets = link_group_to_object(ob, baker.node_tree)
235 | sockets = baker.filter_required_sockets(sockets)
236 | if not sockets:
237 | continue
238 | self.report(
239 | {'WARNING'},
240 | f"{ob.name}: {sockets} {Error.MISSING_SLOT_LINKS}"
241 | )
242 |
243 | self.export(context, baker.suffix)
244 | baker.cleanup()
245 | if baker.node_tree:
246 | node_cleanup(baker.node_tree)
247 |
248 | completion_percent += completion_step
249 | context.window_manager.progress_update(completion_percent)
250 |
251 | # Reimport textures to render result material
252 | bakers_to_reimport = [baker for baker in bakers if baker.reimport]
253 | if bakers_to_reimport:
254 | import_baker_textures(bakers_to_reimport)
255 |
256 | # Refresh all original settings
257 | baker_cleanup(context, saved_properties)
258 |
259 | plane_ob = bpy.data.objects[Global.BG_PLANE_NAME]
260 | plane_ob.scale[0] = plane_ob.scale[1] = 1
261 |
262 | if active_selected:
263 | context.view_layer.objects.active = bpy.data.objects[activeCallback]
264 | if bpy.ops.object.mode_set.poll():
265 | bpy.ops.object.mode_set(mode=modeCallback)
266 |
267 | elapsed = round(time.time() - start, 2)
268 | self.report(
269 | {'INFO'}, f"{Error.EXPORT_COMPLETE} (execution time: {elapsed}s)"
270 | )
271 | context.window_manager.progress_end()
272 |
273 | if gd.use_pack_maps is True:
274 | bpy.ops.grab_doc.baker_pack()
275 | return {'FINISHED'}
276 |
277 |
278 | class GRABDOC_OT_baker_export_single(Operator):
279 | """Render the selected bake map and preview it within Blender.
280 |
281 | Rendering a second time will overwrite the internal image"""
282 | bl_idname = "grab_doc.baker_export_single"
283 | bl_label = ""
284 | bl_options = {'REGISTER', 'INTERNAL'}
285 |
286 | map_type: StringProperty()
287 | baker_index: IntProperty()
288 |
289 | @classmethod
290 | def poll(cls, context: Context) -> bool:
291 | if context.scene.gd.preview_state:
292 | cls.poll_message_set("Cannot do this while in Map Preview")
293 | return False
294 | return True
295 |
296 | def open_render_image(self, filepath: str):
297 | bpy.ops.screen.userpref_show("INVOKE_DEFAULT")
298 | area = bpy.context.window_manager.windows[-1].screen.areas[0]
299 | area.type = "IMAGE_EDITOR"
300 | area.spaces.active.image = bpy.data.images.load(
301 | filepath, check_existing=True
302 | )
303 |
304 | def execute(self, context: Context):
305 | report_value, report_string = validate_scene(context, False)
306 | if report_value:
307 | self.report({'ERROR'}, report_string)
308 | return {'CANCELLED'}
309 |
310 | start = time.time()
311 |
312 | activeCallback = None
313 | if context.object:
314 | activeCallback = context.object.name
315 | modeCallback = context.object.mode
316 | if bpy.ops.object.mode_set.poll():
317 | bpy.ops.object.mode_set(mode='OBJECT')
318 |
319 | plane_ob = bpy.data.objects[Global.BG_PLANE_NAME]
320 | plane_ob.scale[0] = plane_ob.scale[1] = 3
321 |
322 | saved_properties = baker_setup(context)
323 |
324 | gd = context.scene.gd
325 | self.baker = getattr(gd, self.map_type)[self.baker_index]
326 | self.baker.setup()
327 | if self.baker.node_tree:
328 | for ob in get_rendered_objects():
329 | sockets = link_group_to_object(ob, self.baker.node_tree)
330 | sockets = self.baker.filter_required_sockets(sockets)
331 | if not sockets:
332 | continue
333 | self.report(
334 | {'WARNING'},
335 | f"{ob.name}: {sockets} {Error.MISSING_SLOT_LINKS}"
336 | )
337 | path = GRABDOC_OT_baker_export.export(
338 | context, self.baker.suffix, path=get_temp_path()
339 | )
340 | self.open_render_image(path)
341 | self.baker.cleanup()
342 | if self.baker.node_tree:
343 | node_cleanup(self.baker.node_tree)
344 |
345 | # Reimport textures to render result material
346 | if self.baker.reimport:
347 | import_baker_textures([self.baker])
348 |
349 | baker_cleanup(context, saved_properties)
350 |
351 | plane_ob = bpy.data.objects[Global.BG_PLANE_NAME]
352 | plane_ob.scale[0] = plane_ob.scale[1] = 1
353 |
354 | if activeCallback:
355 | context.view_layer.objects.active = bpy.data.objects[activeCallback]
356 | # NOTE: Also helps refresh viewport
357 | if bpy.ops.object.mode_set.poll():
358 | bpy.ops.object.mode_set(mode=modeCallback)
359 |
360 | elapsed = round(time.time() - start, 2)
361 | self.report(
362 | {'INFO'}, f"{Error.EXPORT_COMPLETE} (execute time: {elapsed}s)"
363 | )
364 | return {'FINISHED'}
365 |
366 |
367 | class GRABDOC_OT_baker_preview_exit(Operator):
368 | """Exit the current Map Preview"""
369 | bl_idname = "grab_doc.baker_preview_exit"
370 | bl_label = "Exit Map Preview"
371 | bl_options = {'REGISTER', 'INTERNAL'}
372 |
373 | def execute(self, context: Context):
374 | context.scene.gd.preview_state = False
375 | return {'FINISHED'}
376 |
377 |
378 | # NOTE: This needs to be outside of the class due
379 | # to how `draw_handler_add` handles args
380 | def draw_callback_px(self, context: Context) -> None:
381 | font_id = 0
382 | font_size = 25
383 | font_opacity = .8
384 | font_x_pos = 15
385 | font_y_pos = 80
386 | font_pos_offset = 50
387 |
388 | # NOTE: Handle small viewports
389 | for area in context.screen.areas:
390 | if area.type != 'VIEW_3D':
391 | continue
392 | for region in area.regions:
393 | if region.type != 'WINDOW':
394 | continue
395 | if region.width <= 700 or region.height <= 400:
396 | font_size *= .5
397 | font_pos_offset *= .5
398 | break
399 |
400 | blf.enable(font_id, 4)
401 | blf.shadow(font_id, 0, *(0, 0, 0, font_opacity))
402 | blf.position(font_id, font_x_pos, (font_y_pos + font_pos_offset), 0)
403 | blf.size(font_id, font_size)
404 | blf.color(font_id, *(1, 1, 1, font_opacity))
405 | render_text = f"{self.preview_name.capitalize()} Preview"
406 | if self.disable_binds:
407 | render_text += " | [ESC] to exit"
408 | blf.draw(font_id, render_text)
409 | blf.position(font_id, font_x_pos, font_y_pos, 0)
410 | blf.size(font_id, font_size+1)
411 | blf.color(font_id, *(1, 1, 0, font_opacity))
412 | blf.draw(font_id, "You are in Map Preview mode!")
413 |
414 |
415 | class GRABDOC_OT_baker_preview(Operator):
416 | """Preview the selected bake map type"""
417 | bl_idname = "grab_doc.baker_preview"
418 | bl_label = ""
419 | bl_options = {'REGISTER', 'UNDO', 'INTERNAL'}
420 |
421 | baker_index: IntProperty()
422 | map_type: StringProperty()
423 | last_ob_amount: int = 0
424 | disable_binds: bool = False
425 |
426 | def modal(self, context: Context, event: Event):
427 | scene = context.scene
428 | gd = scene.gd
429 |
430 | # Format
431 | # NOTE: Set alpha channel if background plane not visible in render
432 | image_settings = scene.render.image_settings
433 | if not gd.coll_rendered:
434 | scene.render.film_transparent = True
435 | image_settings.color_mode = 'RGBA'
436 | else:
437 | scene.render.film_transparent = False
438 | image_settings.color_mode = 'RGB'
439 |
440 | image_settings.file_format = gd.format
441 | if gd.format == 'OPEN_EXR':
442 | image_settings.color_depth = gd.exr_depth
443 | elif gd.format != 'TARGA':
444 | image_settings.color_depth = gd.depth
445 |
446 | # Handle newly added object materials
447 | ob_amount = len(bpy.data.objects)
448 | if ob_amount > self.last_ob_amount and self.baker.node_tree:
449 | link_group_to_object(context.object, self.baker.node_tree)
450 | self.last_ob_amount = ob_amount
451 |
452 | # Exit check
453 | if not gd.preview_state \
454 | or (event.type in {'ESC'} and self.disable_binds) \
455 | or not is_scene_valid():
456 | self.cleanup(context)
457 | return {'CANCELLED'}
458 | return {'PASS_THROUGH'}
459 |
460 | def cleanup(self, context: Context) -> None:
461 | context.scene.gd.preview_state = False
462 |
463 | SpaceView3D.draw_handler_remove(self._handle, 'WINDOW')
464 |
465 | self.baker.cleanup()
466 | if self.baker.node_tree:
467 | node_cleanup(self.baker.node_tree)
468 | baker_cleanup(context, self.saved_properties)
469 |
470 | for screens in self.original_workspace.screens:
471 | for area in screens.areas:
472 | if area.type != 'VIEW_3D':
473 | continue
474 | for space in area.spaces:
475 | space.shading.type = self.saved_render_view
476 | break
477 |
478 | if self.user_preferences.exit_camera_preview and is_scene_valid():
479 | context.scene.camera = bpy.data.objects[Global.TRIM_CAMERA_NAME]
480 | bpy.ops.view3d.view_camera()
481 |
482 | def execute(self, context: Context):
483 | report_value, report_string = validate_scene(context, False)
484 | if report_value:
485 | self.report({'ERROR'}, report_string)
486 | return {'CANCELLED'}
487 |
488 | self.user_preferences = get_user_preferences()
489 |
490 | gd = context.scene.gd
491 | self.saved_properties = baker_setup(context)
492 | # TODO: Necessary to save?
493 | self.saved_properties['bpy.context.scene.gd.engine'] = gd.engine
494 |
495 | gd.preview_state = True
496 | gd.preview_map_type = self.map_type
497 | gd.engine = 'grabdoc'
498 |
499 | self.last_ob_amount = len(bpy.data.objects)
500 | self.disable_binds = not self.user_preferences.disable_preview_binds
501 |
502 | if bpy.ops.object.mode_set.poll():
503 | bpy.ops.object.mode_set(mode='OBJECT')
504 |
505 | self.original_workspace = context.workspace
506 | for area in context.screen.areas:
507 | if area.type == 'VIEW_3D':
508 | for space in area.spaces:
509 | self.saved_render_view = space.shading.type
510 | space.shading.type = 'RENDERED'
511 | break
512 |
513 | context.scene.camera = bpy.data.objects[Global.TRIM_CAMERA_NAME]
514 | if not camera_in_3d_view():
515 | bpy.ops.view3d.view_camera()
516 |
517 | gd.preview_index = self.baker_index
518 | baker_prop = getattr(gd, self.map_type)
519 | self.baker = get_baker_by_index(baker_prop, self.baker_index)
520 | self.baker.setup()
521 |
522 | self.preview_name = self.map_type
523 | if self.baker.ID == 'custom':
524 | self.preview_name = self.baker.suffix.capitalize()
525 | self._handle = SpaceView3D.draw_handler_add( # pylint: disable=E1120
526 | draw_callback_px, (self, context), 'WINDOW', 'POST_PIXEL'
527 | )
528 | context.window_manager.modal_handler_add(self)
529 |
530 | if self.baker.node_tree:
531 | for ob in get_rendered_objects():
532 | sockets = link_group_to_object(ob, self.baker.node_tree)
533 | sockets = self.baker.filter_required_sockets(sockets)
534 | if not sockets:
535 | continue
536 | self.report(
537 | {'WARNING'},
538 | f"{ob.name}: {sockets} {Error.MISSING_SLOT_LINKS}"
539 | )
540 | return {'RUNNING_MODAL'}
541 |
542 |
543 | class GRABDOC_OT_baker_preview_export(Operator):
544 | """Export the currently previewed material"""
545 | bl_idname = "grab_doc.baker_export_preview"
546 | bl_label = "Export Preview"
547 | bl_options = {'REGISTER'}
548 |
549 | baker_index: IntProperty()
550 |
551 | @classmethod
552 | def poll(cls, context: Context) -> bool:
553 | gd = context.scene.gd
554 | if gd.filepath == "//" and not bpy.data.filepath:
555 | cls.poll_message_set("Relative export path but file not saved")
556 | return False
557 | return not GRABDOC_OT_baker_export_single.poll(context)
558 |
559 | def execute(self, context: Context):
560 | report_value, report_string = validate_scene(context)
561 | if report_value:
562 | self.report({'ERROR'}, report_string)
563 | return {'CANCELLED'}
564 |
565 | start = time.time()
566 |
567 | # NOTE: Manual plane scale to account for overscan
568 | plane_ob = bpy.data.objects[Global.BG_PLANE_NAME]
569 | scale_plane = False
570 | if plane_ob.scale[0] == 1:
571 | scale_plane = True
572 | plane_ob.scale[0] = plane_ob.scale[1] = 3
573 |
574 | gd = context.scene.gd
575 | baker = getattr(gd, gd.preview_map_type)[self.baker_index]
576 |
577 | GRABDOC_OT_baker_export.export(context, baker.suffix)
578 | if baker.reimport:
579 | import_baker_textures([baker])
580 |
581 | if scale_plane:
582 | plane_ob.scale[0] = plane_ob.scale[1] = 1
583 |
584 | elapsed = round(time.time() - start, 2)
585 | self.report(
586 | {'INFO'}, f"{Error.EXPORT_COMPLETE} (execution time: {elapsed}s)"
587 | )
588 | return {'FINISHED'}
589 |
590 |
591 | class GRABDOC_OT_baker_visibility(Operator):
592 | """Configure bake map UI visibility, will also disable baking"""
593 | bl_idname = "grab_doc.baker_visibility"
594 | bl_label = "Configure Baker Visibility"
595 | bl_options = {'REGISTER'}
596 |
597 | @classmethod
598 | def poll(cls, context: Context) -> bool:
599 | return GRABDOC_OT_baker_export_single.poll(context)
600 |
601 | def execute(self, _context: Context):
602 | return {'FINISHED'}
603 |
604 | def invoke(self, context: Context, _event: Event):
605 | return context.window_manager.invoke_props_dialog(self, width=200)
606 |
607 | def draw(self, _context: Context):
608 | col = self.layout.column(align=True)
609 | for baker in get_bakers():
610 | icon = "BLENDER" if not baker.MARMOSET_COMPATIBLE else "WORLD"
611 | col.prop(baker, 'visibility', icon=icon,
612 | text=f"{baker.NAME} {baker.index+1}")
613 |
614 |
615 | class GRABDOC_OT_baker_pack(Operator):
616 | """Merge previously exported bake maps into single packed texture"""
617 | bl_idname = "grab_doc.baker_pack"
618 | bl_label = "Run Pack"
619 | bl_options = {'REGISTER'}
620 |
621 | @classmethod
622 | def poll(cls, context: Context) -> bool:
623 | gd = context.scene.gd
624 | r = get_channel_path(gd.channel_r)
625 | g = get_channel_path(gd.channel_g)
626 | b = get_channel_path(gd.channel_b)
627 | a = get_channel_path(gd.channel_a)
628 | if not all((r, g, b)):
629 | cls.poll_message_set("No bake maps exported yet")
630 | return False
631 | if gd.channel_a != 'none' and a is None:
632 | cls.poll_message_set("The A channel set but texture not exported")
633 | return False
634 | return True
635 |
636 | def execute(self, context: Context):
637 | gd = context.scene.gd
638 | pack_name = gd.filename + "_" + gd.pack_name
639 | path = gd.filepath
640 |
641 | # Loads all images into blender to avoid using a
642 | # separate python module to convert to np array
643 | image_r = bpy.data.images.load(get_channel_path(gd.channel_r))
644 | image_g = bpy.data.images.load(get_channel_path(gd.channel_g))
645 | image_b = bpy.data.images.load(get_channel_path(gd.channel_b))
646 | pack_order = [(image_r, (0, 0)),
647 | (image_g, (0, 1)),
648 | (image_b, (0, 2))]
649 | if gd.channel_a != 'none':
650 | image_a = bpy.data.images.load(get_channel_path(gd.channel_a))
651 | pack_order.append((image_a, (0, 3)))
652 |
653 | dst_image = pack_image_channels(pack_order, pack_name)
654 | dst_image.filepath_raw = path+"//"+pack_name+get_format()
655 | dst_image.file_format = gd.format
656 | dst_image.save()
657 |
658 | # Remove images from blend file to keep it clean
659 | bpy.data.images.remove(image_r)
660 | bpy.data.images.remove(image_g)
661 | bpy.data.images.remove(image_b)
662 | if gd.channel_a != 'none':
663 | bpy.data.images.remove(image_a)
664 | bpy.data.images.remove(dst_image)
665 |
666 | # Option to delete the extra maps through the operator panel
667 | if gd.remove_original_maps is True:
668 | if os.path.exists(get_channel_path(gd.channel_r)):
669 | os.remove(get_channel_path(gd.channel_r))
670 | if os.path.exists(get_channel_path(gd.channel_g)):
671 | os.remove(get_channel_path(gd.channel_g))
672 | if os.path.exists(get_channel_path(gd.channel_b)):
673 | os.remove(get_channel_path(gd.channel_b))
674 | if gd.channel_a != 'none' and \
675 | os.path.exists(get_channel_path(gd.channel_a)):
676 | os.remove(get_channel_path(gd.channel_a))
677 | return {'FINISHED'}
678 |
679 |
680 | ################################################
681 | # REGISTRATION
682 | ################################################
683 |
684 |
685 | classes = (
686 | GRABDOC_OT_load_reference,
687 | GRABDOC_OT_open_folder,
688 | GRABDOC_OT_toggle_camera_view,
689 | GRABDOC_OT_scene_setup,
690 | GRABDOC_OT_scene_cleanup,
691 | GRABDOC_OT_baker_add,
692 | GRABDOC_OT_baker_remove,
693 | GRABDOC_OT_baker_export,
694 | GRABDOC_OT_baker_export_single,
695 | GRABDOC_OT_baker_preview,
696 | GRABDOC_OT_baker_preview_exit,
697 | GRABDOC_OT_baker_preview_export,
698 | GRABDOC_OT_baker_visibility,
699 | GRABDOC_OT_baker_pack
700 | )
701 |
702 | def register():
703 | for cls in classes:
704 | bpy.utils.register_class(cls)
705 |
706 | def unregister():
707 | for cls in classes:
708 | bpy.utils.unregister_class(cls)
709 |
--------------------------------------------------------------------------------
/operators/marmoset.py:
--------------------------------------------------------------------------------
1 |
2 | import os
3 | import subprocess
4 | import json
5 | from pathlib import Path
6 |
7 | import bpy
8 | from bpy.types import Context, Operator, Object
9 | from ..utils.io import get_temp_path
10 |
11 | from ..constants import Global, Error
12 | from ..utils.generic import get_user_preferences
13 | from ..utils.baker import get_bakers
14 | from ..utils.scene import validate_scene
15 | from ..utils.render import set_guide_height, get_rendered_objects
16 |
17 |
18 | class GrabDoc_OT_send_to_marmo(Operator):
19 | """Export your models, open and bake the enabled maps in Marmoset Toolbag"""
20 | bl_idname = "grab_doc.bake_marmoset"
21 | bl_label = "Open / Refresh in Marmoset"
22 | bl_options = {'REGISTER', 'INTERNAL'}
23 |
24 | send_type: bpy.props.EnumProperty(items=(('open', "Open", ""),
25 | ('refresh', "Refresh", "")),
26 | options={'HIDDEN'})
27 |
28 | @classmethod
29 | def poll(cls, _context: Context) -> bool:
30 | return os.path.exists(get_user_preferences().mt_executable)
31 |
32 | def open_marmoset(self, context: Context, temp_path, addon_path):
33 | executable = get_user_preferences().mt_executable
34 |
35 | # Create a dictionary of variables to transfer into Marmoset
36 | gd = context.scene.gd
37 | properties = {
38 | 'file_path': \
39 | f'{gd.filepath}{gd.filename}.{gd.mt_format.lower()}',
40 | 'format': gd.mt_format.lower(),
41 | 'filepath': bpy.path.abspath(gd.filepath),
42 | 'hdri_path': \
43 | f'{os.path.dirname(executable)}\\data\\sky\\Evening Clouds.tbsky',
44 |
45 | 'resolution_x': gd.resolution_x,
46 | 'resolution_y': gd.resolution_y,
47 | 'bits_per_channel': int(gd.depth),
48 | 'samples': int(gd.mt_samples),
49 |
50 | 'auto_bake': gd.mt_auto_bake,
51 | 'close_after_bake': gd.mt_auto_close,
52 |
53 | 'export_normal': gd.normals[0].enabled and gd.normals[0].visibility,
54 | 'flipy_normal': gd.normals[0].flip_y,
55 | 'suffix_normal': gd.normals[0].suffix,
56 |
57 | 'export_curvature': gd.curvature[0].enabled and gd.curvature[0].visibility,
58 | 'suffix_curvature': gd.curvature[0].suffix,
59 |
60 | 'export_occlusion': gd.occlusion[0].enabled and gd.occlusion[0].visibility,
61 | 'ray_count_occlusion': gd.mt_occlusion_samples,
62 | 'suffix_occlusion': gd.occlusion[0].suffix,
63 |
64 | 'export_height': gd.height[0].enabled and gd.height[0].visibility,
65 | 'cage_height': gd.height[0].distance * 100 * 2,
66 | 'suffix_height': gd.height[0].suffix,
67 |
68 | 'export_alpha': gd.alpha[0].enabled and gd.alpha[0].visibility,
69 | 'suffix_alpha': gd.alpha[0].suffix,
70 |
71 | 'export_matid': gd.id[0].enabled and gd.id[0].visibility,
72 | 'suffix_id': gd.id[0].suffix
73 | }
74 |
75 | # Flip the slashes of the first dict value
76 | # NOTE: This is gross but I don't
77 | # know another way to do it
78 | for key, value in properties.items():
79 | properties[key] = value.replace("\\", "/")
80 | break
81 |
82 | json_properties = json.dumps(properties, indent=4)
83 | json_path = os.path.join(temp_path, "mt_vars.json")
84 | with open(json_path, "w", encoding='utf-8') as file:
85 | file.write(json_properties)
86 |
87 | args = [
88 | executable,
89 | os.path.join(addon_path, "utils", "marmoset.py")
90 | ]
91 |
92 | if self.send_type == 'refresh':
93 | # TODO: don't use shell=True arg
94 | output = subprocess.check_output('tasklist', shell=True)
95 | path_ext_only = \
96 | os.path.basename(os.path.normpath(executable)).encode()
97 | if not path_ext_only in output:
98 | subprocess.Popen(args)
99 | self.report({'INFO'}, Error.MARMOSET_EXPORT_COMPLETE)
100 | else:
101 | self.report({'INFO'}, Error.MARMOSET_REFRESH_COMPLETE)
102 | return {'FINISHED'}
103 | subprocess.Popen(args)
104 | self.report({'INFO'}, Error.MARMOSET_EXPORT_COMPLETE)
105 | return {'FINISHED'}
106 |
107 | def execute(self, context: Context):
108 | report_value, report_string = validate_scene(context)
109 | if report_value:
110 | self.report({'ERROR'}, report_string)
111 | return {'CANCELLED'}
112 | if not get_bakers(filter_enabled=True):
113 | self.report({'ERROR'}, Error.ALL_MAPS_DISABLED)
114 | return {'CANCELLED'}
115 |
116 | saved_selected = context.view_layer.objects.selected.keys()
117 |
118 | if bpy.ops.object.mode_set.poll():
119 | bpy.ops.object.mode_set(mode='OBJECT')
120 |
121 | rendered_obs = get_rendered_objects()
122 | gd = context.scene.gd
123 | if gd.height[0].enabled and gd.height[0].method == 'AUTO':
124 | set_guide_height(rendered_obs)
125 |
126 | # Attach _high suffix to all user assets
127 | # NOTE: Only supports single bake group for now
128 | for ob in context.view_layer.objects[:]:
129 | ob.select_set(False)
130 | if ob in rendered_obs \
131 | and Global.FLAG_PREFIX not in ob.name:
132 | ob.select_set(True)
133 | # NOTE: Add name to end of name for reuse later
134 | ob.name = \
135 | Global.BG_PLANE_NAME + Global.HIGH_SUFFIX + ob.name
136 |
137 | # Get background plane low and high poly
138 | plane_low: Object = bpy.data.objects.get(Global.BG_PLANE_NAME)
139 | plane_low.name = Global.BG_PLANE_NAME + Global.LOW_SUFFIX
140 | bpy.data.collections[Global.COLL_CORE_NAME].hide_select = \
141 | plane_low.hide_select = False
142 | plane_low.select_set(True)
143 | plane_high: Object = plane_low.copy()
144 | context.collection.objects.link(plane_high)
145 | plane_high.name = Global.BG_PLANE_NAME + Global.HIGH_SUFFIX
146 | plane_high.select_set(True)
147 |
148 | # Remove reference material
149 | # TODO: Does this need to be re-added back?
150 | if Global.REFERENCE_NAME in bpy.data.materials:
151 | bpy.data.materials.remove(
152 | bpy.data.materials.get(Global.REFERENCE_NAME)
153 | )
154 |
155 | temp_path = get_temp_path()
156 | bpy.ops.export_scene.fbx(
157 | filepath=os.path.join(temp_path, "mesh_export.fbx"),
158 | use_selection=True, path_mode='ABSOLUTE'
159 | )
160 |
161 | # Cleanup
162 | for ob in context.view_layer.objects:
163 | ob.select_set(False)
164 | if ob.name.endswith(Global.LOW_SUFFIX):
165 | ob.name = ob.name.replace(Global.LOW_SUFFIX, "")
166 | elif plane_high.name in ob.name:
167 | ob.name = ob.name.replace(plane_high.name, "")
168 |
169 | bpy.data.objects.remove(plane_high)
170 |
171 | if not gd.coll_selectable:
172 | bpy.data.collections[Global.COLL_CORE_NAME].hide_select = True
173 |
174 | for ob_name in saved_selected:
175 | ob = context.scene.objects.get(ob_name)
176 | ob.select_set(True)
177 |
178 | addon_path = os.path.dirname(Path(__file__).parent)
179 | addon_path = Path(__file__).parents[1]
180 | self.open_marmoset(context, temp_path, addon_path)
181 | return {'FINISHED'}
182 |
183 |
184 | ################################################
185 | # REGISTRATION
186 | ################################################
187 |
188 |
189 | def register():
190 | bpy.utils.register_class(GrabDoc_OT_send_to_marmo)
191 |
192 | def unregister():
193 | bpy.utils.unregister_class(GrabDoc_OT_send_to_marmo)
194 |
--------------------------------------------------------------------------------
/operators/material.py:
--------------------------------------------------------------------------------
1 | from random import random, randint
2 |
3 | import bpy
4 | from bpy.types import Context, Operator
5 |
6 | from ..constants import Global
7 | from ..utils.generic import UseSelectedOnly
8 | from ..utils.render import get_rendered_objects
9 |
10 |
11 | class GRABDOC_OT_quick_id_setup(Operator):
12 | """Sets up materials on all objects within the cameras view frustrum"""
13 | bl_idname = "grab_doc.quick_id_setup"
14 | bl_label = "Auto ID Full Scene"
15 | bl_options = {'REGISTER', 'UNDO'}
16 |
17 | @staticmethod
18 | def generate_random_name(prefix: str,
19 | minimum: int=1000,
20 | maximum: int=100000) -> str:
21 | """Generates a random id map name based on a given prefix"""
22 | while True:
23 | name = prefix+str(randint(minimum, maximum))
24 | if name not in bpy.data.materials:
25 | break
26 | return name
27 |
28 | @staticmethod
29 | def quick_material_cleanup() -> None:
30 | for mat in bpy.data.materials:
31 | if mat.name.startswith(Global.ID_PREFIX) \
32 | and not mat.users \
33 | or mat.name.startswith(Global.RANDOM_ID_PREFIX) \
34 | and not mat.users:
35 | bpy.data.materials.remove(mat)
36 |
37 | def execute(self, _context: Context):
38 | for mat in bpy.data.materials:
39 | if mat.name.startswith(Global.RANDOM_ID_PREFIX):
40 | bpy.data.materials.remove(mat)
41 |
42 | rendered_obs = get_rendered_objects()
43 | for ob in rendered_obs:
44 | add_mat = True
45 | if ob.name.startswith(Global.FLAG_PREFIX):
46 | continue
47 | for slot in ob.material_slots:
48 | if slot.name.startswith(Global.ID_PREFIX):
49 | add_mat = False
50 | break
51 | if not add_mat:
52 | continue
53 |
54 | mat = bpy.data.materials.new(
55 | self.generate_random_name(Global.RANDOM_ID_PREFIX)
56 | )
57 | mat.use_nodes = True
58 | # NOTE: Viewport color
59 | mat.diffuse_color = (random(), random(), random(), 1)
60 |
61 | bsdf = mat.node_tree.nodes.get('Principled BSDF')
62 | bsdf.inputs[0].default_value = mat.diffuse_color
63 |
64 | ob.active_material_index = 0
65 | ob.active_material = mat
66 | self.quick_material_cleanup()
67 | return {'FINISHED'}
68 |
69 |
70 | class GRABDOC_OT_quick_id_selected(UseSelectedOnly, Operator):
71 | """Adds a new single material with a random color to the selected objects"""
72 | bl_idname = "grab_doc.quick_id_selected"
73 | bl_label = "Add ID to Selected"
74 | bl_options = {'REGISTER', 'UNDO'}
75 |
76 | def execute(self, context: Context):
77 | mat = bpy.data.materials.new(
78 | GRABDOC_OT_quick_id_setup.generate_random_name(Global.ID_PREFIX)
79 | )
80 | mat.use_nodes = True
81 | mat.diffuse_color = (random(), random(), random(), 1)
82 |
83 | bsdf = mat.node_tree.nodes.get('Principled BSDF')
84 | bsdf.inputs[0].default_value = mat.diffuse_color
85 |
86 | for ob in context.selected_objects:
87 | if ob.type not in ('MESH', 'CURVE'):
88 | continue
89 | ob.active_material_index = 0
90 | ob.active_material = mat
91 | GRABDOC_OT_quick_id_setup.quick_material_cleanup()
92 | return {'FINISHED'}
93 |
94 |
95 | class GRABDOC_OT_remove_mats_by_name(Operator):
96 | """Remove materials based on an internal prefixed name"""
97 | bl_idname = "grab_doc.remove_mats_by_name"
98 | bl_label = "Remove Mats by Name"
99 | bl_options = {'REGISTER', 'UNDO'}
100 |
101 | name: bpy.props.StringProperty(options={'HIDDEN'})
102 |
103 | def execute(self, _context: Context):
104 | for mat in bpy.data.materials:
105 | if mat.name.startswith(self.name):
106 | bpy.data.materials.remove(mat)
107 | return {'FINISHED'}
108 |
109 |
110 | class GRABDOC_OT_quick_remove_selected_mats(UseSelectedOnly, Operator):
111 | """Remove all GrabDoc ID materials based on the selected objects from the scene"""
112 | bl_idname = "grab_doc.quick_remove_selected_mats"
113 | bl_label = "Remove Selected Materials"
114 | bl_options = {'REGISTER', 'UNDO'}
115 |
116 | def execute(self, context: Context):
117 | for ob in context.selected_objects:
118 | if ob.type not in ('MESH', 'CURVE'):
119 | continue
120 | for slot in ob.material_slots:
121 | if not slot.name.startswith(Global.ID_PREFIX):
122 | continue
123 | bpy.data.materials.remove(bpy.data.materials[slot.name])
124 | break
125 | return {'FINISHED'}
126 |
127 |
128 | ################################################
129 | # REGISTRATION
130 | ################################################
131 |
132 |
133 | classes = (
134 | GRABDOC_OT_quick_id_setup,
135 | GRABDOC_OT_quick_id_selected,
136 | GRABDOC_OT_remove_mats_by_name,
137 | GRABDOC_OT_quick_remove_selected_mats
138 | )
139 |
140 | def register():
141 | for cls in classes:
142 | bpy.utils.register_class(cls)
143 |
144 | def unregister():
145 | for cls in classes:
146 | bpy.utils.unregister_class(cls)
147 |
--------------------------------------------------------------------------------
/preferences.py:
--------------------------------------------------------------------------------
1 |
2 | import os
3 |
4 | import bpy
5 | from bl_operators.presets import AddPresetBase
6 | from bl_ui.utils import PresetPanel
7 | from bpy.types import (
8 | Menu, Panel, Operator, AddonPreferences,
9 | Context, PropertyGroup, Image, Scene,
10 | Collection, Object, Node
11 | )
12 | from bpy.props import (
13 | BoolProperty, PointerProperty, CollectionProperty,
14 | StringProperty, EnumProperty, IntProperty, FloatProperty
15 | )
16 |
17 | from .baker import Baker
18 | from .utils.scene import scene_setup
19 |
20 |
21 | class GRABDOC_AP_preferences(AddonPreferences):
22 | bl_idname = __package__
23 |
24 | mt_executable: StringProperty(
25 | description="Path to Marmoset Toolbag 3 / 4 executable",
26 | name="Marmoset EXE Path", default="", subtype="FILE_PATH"
27 | )
28 | render_within_frustrum: BoolProperty(
29 | description=\
30 | """Only render objects within the camera's viewing frustrum.
31 |
32 | Improves render speed but it may apply materials incorrectly (void objects)""",
33 | name="Render Within Frustrum", default=False
34 | )
35 | exit_camera_preview: BoolProperty(
36 | description="Exit the camera when leaving Map Preview",
37 | name="Auto-exit Preview Camera", default=False
38 | )
39 | disable_preview_binds: BoolProperty(
40 | description=\
41 | """By default, pressing escape while in Map Preview automatically exits preview.
42 |
43 | This can get in the way of other modal operators, causing some friction""",
44 | name="Disable Keybinds in Preview", default=False
45 | )
46 |
47 | def draw(self, _context: Context):
48 | for prop in self.__annotations__.keys():
49 | self.layout.prop(self, prop)
50 |
51 |
52 | class GRABDOC_PG_properties(PropertyGroup):
53 | def update_filename(self, _context: Context):
54 | if not self.filename:
55 | self.filename = "untitled"
56 |
57 | def update_filepath(self, _context: Context):
58 | if self.filepath == '//':
59 | return
60 | if not os.path.exists(self.filepath):
61 | self.filepath = '//'
62 |
63 | def update_res_x(self, context: Context):
64 | if self.resolution_lock and self.resolution_x != self.resolution_y:
65 | self.resolution_y = self.resolution_x
66 | scene_setup(self, context)
67 |
68 | def update_res_y(self, context: Context):
69 | if self.resolution_lock and self.resolution_y != self.resolution_x:
70 | self.resolution_x = self.resolution_y
71 | scene_setup(self, context)
72 |
73 | def update_scale(self, context: Context):
74 | scene_setup(self, context)
75 |
76 | # Scene
77 | coll_selectable: BoolProperty(
78 | description="Sets the background plane selection capability",
79 | update=scene_setup
80 | )
81 | coll_visible: BoolProperty(default=True, update=scene_setup,
82 | description="Sets the visibility in the viewport")
83 | coll_rendered: BoolProperty(
84 | description=\
85 | """Sets visibility of background plane in exports.
86 |
87 | Enables transparency and alpha channel if disabled""",
88 | default=True, update=scene_setup
89 | )
90 |
91 | scale: FloatProperty(
92 | description="Background plane and camera; applied to exported plane",
93 | name="Scale", update=scene_setup,
94 | default=2, min=.1, soft_max=100, precision=3, subtype='DISTANCE'
95 | )
96 | use_filtering: BoolProperty(
97 | description=\
98 | """Blurs sharp edge shapes to reduce harsh, aliased edges.
99 |
100 | When disabled, pixel filtering is reduced to .01px""",
101 | name='', default=True, update=scene_setup
102 | )
103 | filter_width: FloatProperty(
104 | description="The width in pixels used for filtering",
105 | name="Filter Amount", update=scene_setup,
106 | default=1.2, min=0, soft_max=10, subtype='PIXEL'
107 | )
108 | use_grid: BoolProperty(
109 | description="Wireframe grid on plane for better snapping usability",
110 | name='Use Grid', default=False, update=scene_setup
111 | )
112 | grid_subdivs: IntProperty(
113 | description="Subdivision count for the background plane's grid",
114 | name="Grid Subdivisions", update=scene_setup,
115 | default=2, min=0, soft_max=64
116 | )
117 | reference: PointerProperty(
118 | description="Select an image reference to use on the background plane",
119 | name='Reference Selection', type=Image, update=scene_setup
120 | )
121 |
122 | # Output
123 | engine: EnumProperty(
124 | description="The baking engine you would like to use",
125 | name="Engine",
126 | items=(('grabdoc', "GrabDoc", "Set Baker: GrabDoc (Blender)"),
127 | ('marmoset', "Toolbag", "Set Baker: Marmoset Toolbag"))
128 | )
129 | filepath: StringProperty(
130 | description="The path all textures will be exported to",
131 | name="Export Filepath", default="//", subtype='DIR_PATH',
132 | update=update_filepath
133 | )
134 | filename: StringProperty(
135 | description="Prefix name used for exported maps",
136 | name="", default="untitled", update=update_filename
137 | )
138 | resolution_x: IntProperty(name="X Resolution", update=update_res_x,
139 | default=2048, min=4, soft_max=8192)
140 | resolution_y: IntProperty(name="Y Resolution", update=update_res_y,
141 | default=2048, min=4, soft_max=8192)
142 | resolution_lock: BoolProperty(name='Lock Resolution',
143 | default=True, update=update_res_x)
144 | format: EnumProperty(name="Format",
145 | items=(('PNG', "PNG", ""),
146 | ('TIFF', "TIFF", ""),
147 | ('TARGA', "TGA", ""),
148 | ('OPEN_EXR', "EXR", "")))
149 | depth: EnumProperty(items=(('16', "16", ""),
150 | ('8', "8", "")))
151 | exr_depth: EnumProperty(items=(('16', "16", ""),
152 | ('32', "32", "")))
153 | tga_depth: EnumProperty(items=(('8', "8", ""),
154 | ('16', "16", "")))
155 | png_compression: IntProperty(
156 | description="Lossless compression; lower file size, longer bake times",
157 | name="", default=50, min=0, max=100, subtype='PERCENTAGE'
158 | )
159 | use_bake_collection: BoolProperty(
160 | description="Add a collection to the scene for use as bake groups",
161 | update=scene_setup
162 | )
163 |
164 | # Bake maps
165 | MAP_TYPES = [('none', "None", "")]
166 | baker_props = {}
167 | for baker in Baker.__subclasses__():
168 | baker_props[baker.ID] = CollectionProperty(type=baker, name=baker.NAME)
169 | MAP_TYPES.append((baker.ID, baker.NAME, ""))
170 | __annotations__.update(baker_props) # pylint: disable=E0602
171 |
172 | # Map preview
173 | preview_map_type: EnumProperty(items=MAP_TYPES)
174 | preview_index: IntProperty()
175 | preview_state: BoolProperty(
176 | description="Flags if the user is currently in Map Preview"
177 | )
178 |
179 | # Marmoset
180 | mt_auto_bake: BoolProperty(name="Auto bake", default=True)
181 | mt_auto_close: BoolProperty(name="Close after baking")
182 | mt_samples: EnumProperty(
183 | description=\
184 | "Samples rendered per pixel. 64x not supported in MT3 (defaults to 16)",
185 | items=(('1', "1x", ""),
186 | ('4', "4x", ""),
187 | ('16', "16x", ""),
188 | ('64', "64x", "")),
189 | default="16", name="Marmoset Samples"
190 | )
191 | mt_occlusion_samples: IntProperty(default=512, min=32, soft_max=4096)
192 | mt_format: EnumProperty(
193 | items=(('PNG', "PNG", ""),
194 | ('PSD', "PSD", "")),
195 | name="Format"
196 | )
197 |
198 | # Pack maps
199 | use_pack_maps: BoolProperty(
200 | description="Pack textures using the selected channels after exporting",
201 | name="Pack on Export", default=False
202 | )
203 | remove_original_maps: BoolProperty(
204 | description="Remove the original unpacked maps after exporting",
205 | name="Remove Original", default=False
206 | )
207 | pack_name: StringProperty(name="Packed Map Name", default="ORM")
208 | channel_r: EnumProperty(items=MAP_TYPES[1:], default="occlusion", name='R')
209 | channel_g: EnumProperty(items=MAP_TYPES[1:], default="roughness", name='G')
210 | channel_b: EnumProperty(items=MAP_TYPES[1:], default="metallic", name='B')
211 | channel_a: EnumProperty(items=MAP_TYPES, default="none", name='A')
212 |
213 |
214 | ################################################
215 | # PRESETS
216 | ################################################
217 |
218 |
219 | class GRABDOC_MT_presets(Menu):
220 | bl_label = ""
221 | preset_subdir = "gd"
222 | preset_operator = "script.execute_preset"
223 | draw = Menu.draw_preset
224 |
225 |
226 | class GRABDOC_PT_presets(PresetPanel, Panel):
227 | bl_label = 'Bake Presets'
228 | preset_subdir = 'grab_doc'
229 | preset_operator = 'script.execute_preset'
230 | preset_add_operator = 'grab_doc.preset_add'
231 |
232 |
233 | class GRABDOC_OT_add_preset(AddPresetBase, Operator):
234 | bl_idname = "grab_doc.preset_add"
235 | bl_label = "Add a new preset"
236 | preset_menu = "GRABDOC_MT_presets"
237 |
238 | preset_subdir = "grab_doc"
239 | preset_defines = ["gd=bpy.context.scene.gd"]
240 | preset_values = []
241 | bakers = [baker.ID for baker in Baker.__subclasses__()]
242 | for name in GRABDOC_PG_properties.__annotations__.keys():
243 | if name.startswith("preview_"):
244 | continue
245 | if name in bakers:
246 | preset_values.append(f"gd.{name}[0]")
247 | continue
248 | preset_values.append(f"gd.{name}")
249 |
250 | # TODO: Figure out a way to run register_baker_panels
251 | # in order to support multi-baker presets
252 | #def execute(self, context: Context):
253 | # super().execute(context)
254 |
255 |
256 | ##################################
257 | # REGISTRATION
258 | ##################################
259 |
260 |
261 | classes = [
262 | GRABDOC_AP_preferences,
263 | GRABDOC_MT_presets,
264 | GRABDOC_PT_presets,
265 | GRABDOC_OT_add_preset
266 | ]
267 | # NOTE: Register properties last for collection generation
268 | classes.extend([*Baker.__subclasses__(), GRABDOC_PG_properties])
269 |
270 | def register():
271 | for cls in classes:
272 | bpy.utils.register_class(cls)
273 |
274 | Scene.gd = PointerProperty(type=GRABDOC_PG_properties)
275 | Node.gd_spawn = BoolProperty()
276 | Object.gd_object = BoolProperty()
277 | Collection.gd_collection = BoolProperty()
278 |
279 | def unregister():
280 | for cls in classes:
281 | bpy.utils.unregister_class(cls)
282 |
--------------------------------------------------------------------------------
/ui.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | import bpy
4 | from bpy.types import Context, Panel, UILayout, NodeTree
5 |
6 | from .preferences import GRABDOC_PT_presets
7 | from .utils.baker import get_baker_collections
8 | from .utils.generic import get_version, get_user_preferences
9 | from .utils.scene import camera_in_3d_view, is_scene_valid
10 |
11 |
12 | class GDPanel(Panel):
13 | bl_category = 'GrabDoc'
14 | bl_space_type = 'VIEW_3D'
15 | bl_region_type = 'UI'
16 | bl_label = ""
17 |
18 |
19 | class GRABDOC_PT_grabdoc(GDPanel):
20 | bl_label = "GrabDoc " + get_version()
21 | documentation = "https://github.com/oRazeD/GrabDoc/wiki"
22 |
23 | def draw_header_preset(self, _context: Context):
24 | row = self.layout.row()
25 | if is_scene_valid():
26 | GRABDOC_PT_presets.draw_menu(row, text="Presets")
27 | row.operator(
28 | "wm.url_open", text="", icon='HELP'
29 | ).url = self.documentation
30 | row.separator(factor=.2)
31 |
32 | def draw(self, _context: Context):
33 | if is_scene_valid():
34 | return
35 | row = self.layout.row(align=True)
36 | row.scale_y = 1.5
37 | row.operator("grab_doc.scene_setup",
38 | text="Setup Scene", icon='TOOL_SETTINGS')
39 |
40 |
41 | class GRABDOC_PT_scene(GDPanel):
42 | bl_label = 'Scene'
43 | bl_parent_id = "GRABDOC_PT_grabdoc"
44 |
45 | @classmethod
46 | def poll(cls, _context: Context) -> bool:
47 | return is_scene_valid()
48 |
49 | def draw_header(self, _context: Context):
50 | self.layout.label(icon='SCENE_DATA')
51 |
52 | def draw_header_preset(self, _context: Context):
53 | row2 = self.layout.row(align=True)
54 | row2.operator("grab_doc.toggle_camera_view",
55 | text="Leave" if camera_in_3d_view() else "View",
56 | icon="OUTLINER_OB_CAMERA")
57 |
58 | def draw(self, context: Context):
59 | gd = context.scene.gd
60 | layout = self.layout
61 |
62 | row = self.layout.row(align=True)
63 | row.scale_x = row.scale_y = 1.25
64 | row.operator("grab_doc.scene_setup",
65 | text="Rebuild Scene", icon='FILE_REFRESH')
66 | row.operator("grab_doc.scene_cleanup", text="", icon="CANCEL")
67 |
68 | box = layout.box()
69 | row = box.row(align=True)
70 | row.scale_y = .9
71 | row.label(text="Camera Restrictions")
72 | row.prop(gd, "coll_selectable", text="", emboss=False,
73 | icon='RESTRICT_SELECT_OFF' if gd.coll_selectable else 'RESTRICT_SELECT_ON')
74 | row.prop(gd, "coll_visible", text="", emboss=False,
75 | icon='RESTRICT_VIEW_OFF' if gd.coll_visible else 'RESTRICT_VIEW_ON')
76 | row.prop(gd, "coll_rendered", text="", emboss=False,
77 | icon='RESTRICT_RENDER_OFF' if gd.coll_rendered else 'RESTRICT_RENDER_ON')
78 |
79 | col = layout.column(align=True)
80 | col.use_property_split = True
81 | col.use_property_decorate = False
82 | col.prop(gd, "scale", text='Scaling', expand=True)
83 | row = col.row()
84 | row.prop(gd, "grid_subdivs", text="Grid")
85 | row.separator()
86 | row.prop(gd, "use_grid", text="")
87 | row = col.row()
88 | row.enabled = not gd.preview_state
89 | row.prop(gd, "reference", text='Reference')
90 | row.operator("grab_doc.load_reference", text="", icon='FILE_FOLDER')
91 |
92 |
93 | class GRABDOC_PT_output(GDPanel):
94 | bl_label = 'Output'
95 | bl_parent_id = "GRABDOC_PT_grabdoc"
96 |
97 | @classmethod
98 | def poll(cls, _context: Context) -> bool:
99 | return is_scene_valid()
100 |
101 | def draw_header(self, _context: Context):
102 | self.layout.label(icon='OUTPUT')
103 |
104 | def draw_header_preset(self, context: Context):
105 | mt_executable = get_user_preferences().mt_executable
106 | if context.scene.gd.engine == 'marmoset' \
107 | and not os.path.exists(mt_executable):
108 | self.layout.enabled = False
109 | self.layout.scale_x = 1
110 | self.layout.operator("grab_doc.baker_export",
111 | text="Export", icon="EXPORT")
112 |
113 | def mt_header_layout(self, layout: UILayout):
114 | preferences = get_user_preferences()
115 | mt_executable = preferences.mt_executable
116 |
117 | col = layout.column(align=True)
118 | row = col.row()
119 | if not os.path.exists(mt_executable):
120 | row.alignment = 'CENTER'
121 | row.label(text="Marmoset Toolbag Executable Required", icon='INFO')
122 | row = col.row()
123 | row.prop(preferences, 'mt_executable', text="Executable Path")
124 | return
125 | row.prop(preferences, 'mt_executable', text="Executable Path")
126 | row = col.row(align=True)
127 | row.scale_y = 1.25
128 | row.operator("grab_doc.bake_marmoset", text="Bake in Marmoset",
129 | icon="EXPORT").send_type = 'open'
130 | row.operator("grab_doc.bake_marmoset",
131 | text="", icon='FILE_REFRESH').send_type = 'refresh'
132 |
133 | def draw(self, context: Context):
134 | gd = context.scene.gd
135 |
136 | layout = self.layout
137 | layout.activate_init = True
138 | layout.use_property_split = True
139 | layout.use_property_decorate = False
140 |
141 | if gd.engine == 'marmoset':
142 | self.mt_header_layout(layout)
143 |
144 | col2 = layout.column()
145 | row = col2.row()
146 | row.prop(gd, 'engine')
147 | row = col2.row()
148 | row.prop(gd, 'filepath', text="Path")
149 | row.operator("grab_doc.open_folder",
150 | text="", icon="FOLDER_REDIRECT")
151 | col2.prop(gd, "filename", text="Name")
152 | row = col2.row()
153 | row.prop(gd, "resolution_x", text='Resolution')
154 | row.prop(gd, "resolution_y", text='')
155 | row.prop(gd, 'resolution_lock', icon_only=True,
156 | icon="LOCKED" if gd.resolution_lock else "UNLOCKED")
157 |
158 | row = col2.row()
159 | if gd.engine == "marmoset":
160 | image_format = "mt_format"
161 | else:
162 | image_format = "format"
163 | row.prop(gd, image_format)
164 |
165 | row2 = row.row()
166 | if gd.format == "OPEN_EXR":
167 | row2.prop(gd, "exr_depth", expand=True)
168 | elif gd.format != "TARGA" or gd.engine == 'marmoset':
169 | row2.prop(gd, "depth", expand=True)
170 | else:
171 | row2.enabled = False
172 | row2.prop(gd, "tga_depth", expand=True)
173 | if gd.format != "TARGA":
174 | image_settings = bpy.context.scene.render.image_settings
175 | row = col2.row(align=True)
176 | if gd.format == "PNG":
177 | row.prop(gd, "png_compression", text="Compression")
178 | elif gd.format == "OPEN_EXR":
179 | row.prop(image_settings, "exr_codec", text="Codec")
180 | else: # TIFF
181 | row.prop(image_settings, "tiff_codec", text="Codec")
182 |
183 | row = col2.row()
184 | row.prop(gd, "filter_width", text="Filtering")
185 | row.separator() # NOTE: Odd spacing without these
186 | row.prop(gd, "use_filtering", text="")
187 |
188 | if gd.engine == "marmoset":
189 | row = col2.row(align=True)
190 | row.prop(gd, "mt_samples", text="Samples", expand=True)
191 |
192 | col = layout.column(align=True)
193 | col.prop(gd, "use_bake_collection", text="Bake Groups")
194 | col.prop(gd, 'use_pack_maps')
195 | if gd.use_pack_maps:
196 | col.prop(gd, 'remove_original_maps')
197 | if gd.engine == "marmoset":
198 | col.prop(gd, 'mt_auto_bake', text='Bake on Import')
199 | row = col.row()
200 | row.enabled = gd.mt_auto_bake
201 | row.prop(gd, 'mt_auto_close', text='Close after Baking')
202 |
203 |
204 | class GRABDOC_PT_bake_maps(GDPanel):
205 | bl_label = 'Bake Maps'
206 | bl_parent_id = "GRABDOC_PT_grabdoc"
207 |
208 | @classmethod
209 | def poll(cls, _context: Context) -> bool:
210 | return is_scene_valid()
211 |
212 | def draw_header(self, _context: Context):
213 | self.layout.label(icon='SHADING_RENDERED')
214 |
215 | def draw_header_preset(self, _context: Context):
216 | self.layout.operator("grab_doc.baker_visibility",
217 | emboss=False, text="", icon="SETTINGS")
218 |
219 | def draw(self, context: Context):
220 | if not context.scene.gd.preview_state:
221 | return
222 |
223 | layout = self.layout
224 | col = layout.column(align=True)
225 |
226 | row = col.row(align=True)
227 | row.alert = True
228 | row.scale_y = 1.5
229 | row.operator("grab_doc.baker_preview_exit", icon="CANCEL")
230 |
231 | row = col.row(align=True)
232 | row.scale_y = 1.1
233 |
234 | gd = context.scene.gd
235 | baker = getattr(gd, gd.preview_map_type)[gd.preview_index]
236 | row.operator("grab_doc.baker_export_preview",
237 | text=f"Export {baker.NAME}", icon="EXPORT")
238 | baker.draw(context, layout)
239 |
240 |
241 | class GRABDOC_PT_pack_maps(GDPanel):
242 | bl_label = 'Pack Maps'
243 | bl_parent_id = "GRABDOC_PT_grabdoc"
244 | bl_options = {'DEFAULT_CLOSED'}
245 |
246 | @classmethod
247 | def poll(cls, context: Context) -> bool:
248 | if context.scene.gd.preview_state:
249 | return False
250 | return is_scene_valid()
251 |
252 | def draw_header(self, _context: Context):
253 | self.layout.label(icon='RENDERLAYERS')
254 |
255 | def draw_header_preset(self, _context: Context):
256 | self.layout.scale_x = .9
257 | self.layout.operator("grab_doc.baker_pack")
258 |
259 | def draw(self, context: Context):
260 | layout = self.layout
261 | layout.use_property_split = True
262 | layout.use_property_decorate = False
263 |
264 | gd = context.scene.gd
265 | col = layout.column(align=True)
266 | col.prop(gd, 'channel_r')
267 | col.prop(gd, 'channel_g')
268 | col.prop(gd, 'channel_b')
269 | col.prop(gd, 'channel_a')
270 | col.prop(gd, 'pack_name', text="Suffix")
271 |
272 |
273 | class BakerPanel(GDPanel):
274 | bl_parent_id = "GRABDOC_PT_bake_maps"
275 | bl_options = {'DEFAULT_CLOSED', 'HEADER_LAYOUT_EXPAND'}
276 |
277 | baker = None
278 |
279 | @classmethod
280 | def poll(cls, context: Context) -> bool:
281 | if cls.baker is None:
282 | return False
283 | return not context.scene.gd.preview_state and cls.baker.visibility
284 |
285 | def draw_header(self, context: Context):
286 | row = self.layout.row(align=True)
287 |
288 | baker_name = self.baker.NAME
289 | if self.baker.ID == 'custom':
290 | baker_name = self.baker.suffix.capitalize()
291 |
292 | index = self.baker.index
293 | if index > 0 and not self.baker.ID == 'custom':
294 | baker_name = f"{self.baker.NAME} {index+1}"
295 | text = f"{baker_name} Preview".replace("_", " ")
296 |
297 | row2 = row.row(align=True)
298 | if self.baker.ID == 'custom' \
299 | and not isinstance(self.baker.node_tree, NodeTree):
300 | row2.enabled = False
301 | row2.separator(factor=.5)
302 | row2.prop(self.baker, 'enabled', text="")
303 | preview = row2.operator("grab_doc.baker_preview", text=text)
304 | preview.map_type = self.baker.ID
305 | preview.baker_index = self.baker.index
306 | row2.operator("grab_doc.baker_export_single",
307 | text="", icon='RENDER_STILL').map_type = self.baker.ID
308 |
309 | if self.baker == getattr(context.scene.gd, self.baker.ID)[0]:
310 | row.operator("grab_doc.baker_add",
311 | text="", icon='ADD').map_type = self.baker.ID
312 | return
313 | remove = row.operator("grab_doc.baker_remove", text="", icon='TRASH')
314 | remove.map_type = self.baker.ID
315 | remove.baker_index = self.baker.index
316 |
317 | def draw(self, context: Context):
318 | self.baker.draw(context, self.layout)
319 |
320 |
321 | ################################################
322 | # REGISTRATION
323 | ################################################
324 |
325 |
326 | def create_baker_panels():
327 | """Creates panels for every item in the baker
328 | `CollectionProperty`s utilizing dynamic subclassing."""
329 | baker_classes = []
330 | for baker_prop in get_baker_collections():
331 | for baker in baker_prop:
332 | if baker.index == -1:
333 | baker.__init__() # pylint: disable=C2801
334 | class_name = f"GRABDOC_PT_{baker.ID}_{baker.index}"
335 | panel_cls = type(class_name, (BakerPanel,), {})
336 | panel_cls.baker = baker
337 | baker_classes.append(panel_cls)
338 | return baker_classes
339 |
340 |
341 | def register_baker_panels():
342 | for cls in BakerPanel.__subclasses__():
343 | try:
344 | bpy.utils.unregister_class(cls)
345 | except RuntimeError:
346 | continue
347 | for cls in create_baker_panels():
348 | bpy.utils.register_class(cls)
349 |
350 |
351 | classes = [
352 | GRABDOC_PT_grabdoc,
353 | GRABDOC_PT_scene,
354 | GRABDOC_PT_output,
355 | GRABDOC_PT_bake_maps,
356 | GRABDOC_PT_pack_maps
357 | ]
358 |
359 | def register():
360 | for cls in classes:
361 | bpy.utils.register_class(cls)
362 |
363 | def unregister():
364 | for cls in classes:
365 | bpy.utils.unregister_class(cls)
366 |
--------------------------------------------------------------------------------
/utils/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/oRazeD/GrabDoc/4486964418f7605965771cbc6d3d684d53b75ac3/utils/__init__.py
--------------------------------------------------------------------------------
/utils/baker.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | import bpy
4 | from bpy.types import Context
5 | from bpy.props import CollectionProperty
6 |
7 | from ..baker import Baker
8 | from ..constants import Global
9 | from .io import get_format
10 | from .generic import load_properties, save_properties
11 |
12 |
13 | def baker_setup(context: Context) -> dict:
14 | """Baker scene bootstrapper."""
15 | scene = context.scene
16 | gd = scene.gd
17 | render = scene.render
18 | eevee = scene.eevee
19 | cycles = scene.cycles
20 | view_layer = context.view_layer
21 | display = scene.display
22 | shading = scene.display.shading
23 | view_settings = scene.view_settings
24 | display_settings = scene.display_settings
25 | image_settings = render.image_settings
26 |
27 | properties = (view_layer, render, eevee, cycles,
28 | shading, display, view_settings,
29 | display_settings, image_settings)
30 | saved_properties = save_properties(properties)
31 | saved_properties['bpy.context.scene.camera'] = scene.camera
32 | saved_properties['bpy.context.scene.gd.reference'] = gd.reference
33 |
34 | # Active Camera
35 | for area in context.screen.areas:
36 | if area.type != 'VIEW_3D':
37 | continue
38 | for space in area.spaces:
39 | space.use_local_camera = False
40 | break
41 | scene.camera = bpy.data.objects.get(Global.TRIM_CAMERA_NAME)
42 | if scene.world:
43 | scene.world.use_nodes = False
44 |
45 | view_layer.use = render.use_single_layer = True
46 |
47 | eevee.use_gtao = False
48 | eevee.use_taa_reprojection = False
49 | eevee.gtao_distance = .2
50 | eevee.gtao_quality = .5
51 |
52 | cycles.pixel_filter_type = 'BLACKMAN_HARRIS'
53 |
54 | render.resolution_x = gd.resolution_x
55 | render.resolution_y = gd.resolution_y
56 | render.resolution_percentage = 100
57 | render.use_sequencer = render.use_compositing = False
58 | render.dither_intensity = 0
59 |
60 | # Output
61 | # NOTE: If background plane not visible in render, create alpha channel
62 | image_settings.color_mode = 'RGB'
63 | if not gd.coll_rendered:
64 | image_settings.color_mode = 'RGBA'
65 | render.film_transparent = True
66 |
67 | # Format
68 | image_settings.file_format = gd.format
69 | if gd.format == 'OPEN_EXR':
70 | image_settings.color_depth = gd.exr_depth
71 | elif gd.format != 'TARGA':
72 | image_settings.color_depth = gd.depth
73 | if gd.format == "PNG":
74 | image_settings.compression = gd.png_compression
75 |
76 | # Viewport shading
77 | shading.show_backface_culling = \
78 | shading.show_xray = \
79 | shading.show_shadows = \
80 | shading.show_cavity = \
81 | shading.use_dof = \
82 | shading.show_object_outline = \
83 | shading.show_specular_highlight = False
84 |
85 | # Background plane visibility
86 | bg_plane = bpy.data.objects.get(Global.BG_PLANE_NAME)
87 | bg_plane.hide_viewport = not gd.coll_visible
88 | bg_plane.hide_render = not gd.coll_rendered
89 | bg_plane.hide_set(False)
90 |
91 | return saved_properties
92 |
93 |
94 | def baker_cleanup(context: Context, properties: dict) -> None:
95 | """Baker core cleanup, reverses any values changed by `baker_setup`."""
96 | if context.scene.world:
97 | context.scene.world.use_nodes = True
98 | load_properties(properties)
99 |
100 |
101 | def get_baker_by_index(
102 | collection: CollectionProperty, index: int
103 | ) -> Baker | None:
104 | """Get a specific baker based on a given collection
105 | property and custom index property value."""
106 | for baker in collection:
107 | if baker.index == index:
108 | return baker
109 | return None
110 |
111 |
112 | def get_bakers(filter_enabled: bool = False) -> list[Baker]:
113 | """Get all bakers in the current scene."""
114 | all_bakers = []
115 | for baker_id in [baker.ID for baker in Baker.__subclasses__()]:
116 | baker = getattr(bpy.context.scene.gd, baker_id)
117 | # NOTE: Flatten collections into single list
118 | for bake_map in baker:
119 | if filter_enabled \
120 | and (not bake_map.enabled or not bake_map.visibility):
121 | continue
122 | all_bakers.append(bake_map)
123 | return all_bakers
124 |
125 |
126 | def get_baker_collections() -> list[CollectionProperty]:
127 | """Get all baker collection properties in the current scene."""
128 | bakers = []
129 | for baker_id in [baker.ID for baker in Baker.__subclasses__()]:
130 | baker = getattr(bpy.context.scene.gd, baker_id)
131 | bakers.append(baker)
132 | return bakers
133 |
134 |
135 | def import_baker_textures(bakers: list[Baker]) -> None:
136 | """Import last exported textures as a material for use inside of Blender."""
137 | mat = bpy.data.materials.get(Global.REIMPORT_MAT_NAME)
138 | if mat is None:
139 | mat = bpy.data.materials.new(Global.REIMPORT_MAT_NAME)
140 | mat.use_nodes = True
141 |
142 | bsdf = mat.node_tree.nodes['Principled BSDF']
143 | bsdf.inputs["Emission Color"].default_value = (0,0,0,1)
144 | bsdf.inputs["Emission Strength"].default_value = 1
145 |
146 | y_offset = 256
147 | gd = bpy.context.scene.gd
148 | for baker in bakers:
149 | image = mat.node_tree.nodes.get(baker.ID)
150 | if image is None:
151 | image = mat.node_tree.nodes.new('ShaderNodeTexImage')
152 | image.hide = True
153 | image.name = image.label = baker.ID
154 | image.location = (-300, y_offset)
155 | y_offset -= 32
156 |
157 | filename = f'{gd.filename}_{baker.ID}'
158 | filepath = os.path.join(gd.filepath, filename + get_format())
159 | if not os.path.exists(filepath):
160 | continue
161 | image.image = bpy.data.images.load(filepath, check_existing=True)
162 |
163 | baker.reimport_setup(mat, image)
164 |
--------------------------------------------------------------------------------
/utils/generic.py:
--------------------------------------------------------------------------------
1 | import os
2 | import re
3 | import tomllib
4 | from pathlib import Path
5 |
6 | import bpy
7 | from bpy.types import Context
8 |
9 | from ..constants import Error
10 |
11 |
12 | class UseSelectedOnly():
13 | @classmethod
14 | def poll(cls, context: Context) -> bool:
15 | return True if len(context.selected_objects) \
16 | else cls.poll_message_set(Error.NO_OBJECTS_SELECTED)
17 |
18 |
19 | def get_version(version: tuple[int, int, int] | None = None) -> str | None:
20 | if version is None:
21 | addon_path = Path(os.path.abspath(__file__)).parents[1]
22 | toml_path = addon_path / "blender_manifest.toml"
23 | with open(toml_path, "rb") as f:
24 | data = tomllib.load(f)
25 | return data.get("version", None)
26 | # NOTE: Since 4.2 this pattern is deprecated
27 | version_pattern = r'\((\d+), (\d+), (\d+)\)'
28 | match = re.match(version_pattern, str(version))
29 | return '.'.join(match.groups()) if match else None
30 |
31 |
32 | def get_user_preferences():
33 | package = __package__.rsplit(".", maxsplit=1)[0]
34 | return bpy.context.preferences.addons[package].preferences
35 |
36 |
37 | def save_properties(properties: list) -> dict:
38 | """Store all given iterable properties."""
39 | saved_properties = {}
40 | for data in properties:
41 | for attr in dir(data):
42 | if data not in saved_properties:
43 | saved_properties[data] = {}
44 | saved_properties[data][attr] = getattr(data, attr)
45 | return saved_properties
46 |
47 |
48 | def load_properties(properties: dict) -> None:
49 | """Set all given properties to their assigned value."""
50 | custom_properties = {}
51 | for key, values in properties.items():
52 | if not isinstance(values, dict):
53 | custom_properties[key] = values
54 | continue
55 | for name, value in values.items():
56 | try:
57 | setattr(key, name, value)
58 | except (AttributeError, TypeError): # Read only attribute
59 | pass
60 | # NOTE: Extra entries added after running `save_properties`
61 | for key, value in custom_properties.items():
62 | name = key.rsplit('.', maxsplit=1)[-1]
63 | components = key.split('.')[:-1]
64 | root = globals()[components[0]]
65 | components = components[1:]
66 | # Reconstruct attribute chain
67 | obj = root
68 | for part in components:
69 | next_attr = getattr(obj, part)
70 | if next_attr is None:
71 | break
72 | obj = next_attr
73 | if obj == root:
74 | continue
75 | try:
76 | setattr(obj, name, value)
77 | except ReferenceError:
78 | pass
79 |
80 |
81 | def enum_members_from_type(rna_type, prop_str):
82 | prop = rna_type.bl_rna.properties[prop_str]
83 | return [e.identifier for e in prop.enum_items]
84 |
85 |
86 | def enum_members_from_instance(rna_item, prop_str):
87 | return enum_members_from_type(type(rna_item), prop_str)
88 |
--------------------------------------------------------------------------------
/utils/io.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | import bpy
4 | from bpy.types import Context
5 |
6 | from ..constants import Global
7 |
8 |
9 | def get_temp_path() -> str:
10 | """Gets or creates a temporary directory based on the extensions system."""
11 | return bpy.utils.extension_path_user(
12 | __package__.rsplit(".", maxsplit=1)[0], path="temp", create=True
13 | )
14 |
15 |
16 | def get_format() -> str:
17 | """Get the correct file extension based on `format` attribute"""
18 | return f".{Global.IMAGE_FORMATS[bpy.context.scene.gd.format]}"
19 |
--------------------------------------------------------------------------------
/utils/marmoset.py:
--------------------------------------------------------------------------------
1 | """Startup script to run alongside Marmoset Toolbag.
2 | """
3 |
4 |
5 | import os
6 | import json
7 | from pathlib import Path
8 |
9 | import mset
10 |
11 |
12 | def run_auto_baker(baker, properties: dict) -> None:
13 | baker.bake()
14 | os.startfile(properties['filepath'])
15 |
16 | # TODO: Implement alpha mask
17 | # NOTE: There is no alpha support in Marmoset so we use
18 | # height with a modified range and run another bake pass
19 | #if properties['export_alpha'] and properties['auto_bake']:
20 | # enabled_maps = \
21 | # [bake_map for bake_map in baker.getAllMaps() is bake_map.enabled]
22 | # for bake_map in baker.getAllMaps():
23 | # bake_map.enabled = False
24 | # alpha = baker.getMap("Height")
25 | # alpha.enabled = True
26 | # alpha.suffix = properties['suffix_alpha']
27 | # alpha.innerDistance = 0
28 | # alpha.outerDistance = .01
29 | # baker.bake()
30 | #
31 | # # NOTE: Refresh original bake
32 | # baker_setup()
33 | # alpha.enabled = False
34 |
35 | # Close marmo if the option is selected
36 | if properties['close_after_bake']:
37 | mset.quit()
38 | return
39 |
40 | mset.findObject('High').visible = False
41 |
42 |
43 | def create_baker(properties: dict):
44 | mset.newScene()
45 | baker = mset.BakerObject()
46 | baker.outputPath = properties['file_path']
47 | baker.outputBits = properties['bits_per_channel']
48 | baker.edgePadding = "None"
49 | baker.outputSoften = 0.5
50 | baker.useHiddenMeshes = True
51 | baker.ignoreTransforms = False
52 | baker.smoothCage = True
53 | baker.ignoreBackfaces = True
54 | baker.multipleTextureSets = False
55 | baker.outputWidth = properties['resolution_x']
56 | baker.outputHeight = properties['resolution_y']
57 | # NOTE: Output samples is broken in older APIs
58 | if mset.getToolbagVersion() < 4000 and properties['samples'] == 64:
59 | baker.outputSamples = 16
60 | else:
61 | baker.outputSamples = properties['samples']
62 | return baker
63 |
64 |
65 | def baker_setup(baker, properties: dict) -> None:
66 | for bake_map in baker.getAllMaps():
67 | bake_map.enabled = False
68 |
69 | normals = baker.getMap("Normals")
70 | normals.enabled = properties['export_normal']
71 | normals.suffix = properties['suffix_normal']
72 | normals.flipY = properties['flipy_normal']
73 | normals.flipX = False
74 | normals.dither = False
75 |
76 | curvature = baker.getMap("Curvature")
77 | curvature.enabled = properties['export_curvature']
78 | curvature.suffix = properties['suffix_curvature']
79 |
80 | occlusion = baker.getMap("Ambient Occlusion")
81 | occlusion.enabled = properties['export_occlusion']
82 | occlusion.suffix = properties['suffix_occlusion']
83 | occlusion.rayCount = properties['ray_count_occlusion']
84 |
85 | height = baker.getMap("Height")
86 | height.enabled = properties['export_height']
87 | height.suffix = properties['suffix_height']
88 | height.innerDistance = 0
89 | height.outerDistance = properties['cage_height'] / 2 - .02
90 |
91 | material = baker.getMap("Material ID")
92 | material.enabled = properties['export_matid']
93 | material.suffix = properties['suffix_id']
94 |
95 | def shader_setup(properties: dict) -> None:
96 | findDefault = mset.findMaterial("Default")
97 | findDefault.name = "GrabDoc Bake Result"
98 | if properties["export_normal"]:
99 | findDefault.getSubroutine('surface').setField(
100 | 'Normal Map',
101 | properties['file_path'][:-4] + '_' +
102 | properties['suffix_normal'] + '.' + properties['format']
103 | )
104 | if properties["export_occlusion"]:
105 | findDefault.setSubroutine('occlusion', 'Occlusion')
106 | findDefault.getSubroutine('occlusion').setField(
107 | 'Occlusion Map',
108 | properties['file_path'][:-4] + '_' +
109 | properties['suffix_occlusion'] + '.' + properties['format']
110 | )
111 |
112 |
113 | def main():
114 | plugin_path = Path(mset.getPluginPath()).parents[1]
115 | temp_path = os.path.join(plugin_path, "temp")
116 | properties_path = os.path.join(temp_path, "mt_vars.json")
117 |
118 | # Check if file location has been repopulated
119 | if not os.path.exists(properties_path):
120 | return
121 |
122 | with open(properties_path, 'r', encoding='utf-8') as file:
123 | properties = json.load(file)
124 | # NOTE: Remove the file so when the file is
125 | # recreated we know to update scene properties
126 | os.remove(properties_path)
127 |
128 | # Baker setup
129 | baker = create_baker(properties)
130 | model_path = os.path.join(temp_path, "mesh_export.fbx")
131 | baker.importModel(model_path)
132 |
133 | # Set cage distance
134 | mset.findObject('Low').maxOffset = properties['cage_height'] + .001
135 |
136 | # Scale up the high poly plane
137 | mset.findObject(
138 | "[GrabDoc] Background Plane_high_gd"
139 | ).scale = [300, 300, 300]
140 |
141 | # Rotate imported group to align with camera
142 | bake_group = mset.findObject("[GrabDoc] Background Plane")
143 | bake_group.rotation = [90, 0, 0]
144 | # Create groups for material id
145 | for mat in mset.getAllMaterials():
146 | if mat.name.startswith("GD_"):
147 | mat.setGroup('[GrabDoc] Materials')
148 |
149 | baker_setup(baker, properties)
150 | if properties['auto_bake']:
151 | run_auto_baker(baker, properties)
152 | # NOTE: Delete FBX file to avoid temp folder bloat
153 | #os.remove(model_path)
154 | shader_setup(properties)
155 |
156 |
157 | if __name__ == "__main__":
158 | mset.callbacks.onRegainFocus = main
159 | main()
160 |
--------------------------------------------------------------------------------
/utils/node.py:
--------------------------------------------------------------------------------
1 | import bpy
2 | from bpy.types import Object, NodeTree, NodeTreeInterfaceItem
3 |
4 | from ..constants import Global
5 |
6 |
7 | def node_cleanup(node_tree: NodeTree) -> None:
8 | """Remove node group and return original links if they exist"""
9 | inputs = get_material_output_sockets()
10 | for mat in bpy.data.materials:
11 | mat.use_nodes = True
12 | if mat.name == Global.GD_MATERIAL_NAME:
13 | bpy.data.materials.remove(mat)
14 | continue
15 | nodes = mat.node_tree.nodes
16 | if node_tree.name not in nodes:
17 | continue
18 |
19 | # Get node group in material
20 | gd_nodes = [node for node in nodes if node.gd_spawn is True]
21 | for gd_node in gd_nodes:
22 | if gd_node.type != 'FRAME':
23 | node = gd_node
24 | break
25 | output_node = None
26 | for output in node.outputs:
27 | for link in output.links:
28 | if link.to_node.type != 'OUTPUT_MATERIAL':
29 | continue
30 | output_node = link.to_node
31 | break
32 | if output_node is None:
33 | for gd_node in gd_nodes:
34 | nodes.remove(gd_node)
35 | continue
36 |
37 | # Return original connections
38 | for node_input in node.inputs:
39 | for link in node_input.links:
40 | if node_input.name.split(' ')[-1] not in inputs:
41 | continue
42 | original_node_connection = nodes.get(link.from_node.name)
43 | original_node_socket = link.from_socket.name
44 | for connection_name in inputs:
45 | if node_input.name != connection_name:
46 | continue
47 | mat.node_tree.links.new(
48 | output_node.inputs[connection_name],
49 | original_node_connection.outputs[original_node_socket]
50 | )
51 |
52 | warning_text = bpy.data.texts.get(Global.NODE_GROUP_WARN_NAME)
53 | if warning_text is not None:
54 | bpy.data.texts.remove(warning_text)
55 | for gd_node in gd_nodes:
56 | nodes.remove(gd_node)
57 |
58 |
59 | def get_material_output_sockets() -> dict:
60 | """Create a dummy node group if none is supplied and
61 | capture the default material output sockets/`inputs`."""
62 | tree = bpy.data.node_groups.new('Material Output', 'ShaderNodeTree')
63 | output = tree.nodes.new('ShaderNodeOutputMaterial')
64 | material_output_sockets = {}
65 | for node_input in output.inputs:
66 | node_type = node_input.type.capitalize()
67 | if node_input.type == "VALUE":
68 | node_type = "Float"
69 | bpy_node_type = f'NodeSocket{node_type}'
70 | material_output_sockets[node_input.name] = bpy_node_type
71 | bpy.data.node_groups.remove(tree)
72 | return material_output_sockets
73 |
74 |
75 | def get_group_inputs(
76 | node_tree: NodeTree, remove_cache: bool=True
77 | ) -> list[NodeTreeInterfaceItem]:
78 | """Get the interface inputs of a given `NodeTree`."""
79 | inputs = []
80 | for item in node_tree.interface.items_tree:
81 | if not hasattr(item, 'in_out') \
82 | or item.in_out != 'INPUT':
83 | continue
84 | inputs.append(item)
85 | if remove_cache:
86 | inputs = inputs[:-4]
87 | return inputs
88 |
89 |
90 | def link_group_to_object(ob: Object, node_tree: NodeTree) -> list[str]:
91 | """Add given `NodeTree` to the objects' material slots.
92 |
93 | Handles cases with empty or no material slots.
94 |
95 | Returns list of socket names without links."""
96 | if not ob.material_slots or "" in ob.material_slots:
97 | if Global.GD_MATERIAL_NAME in bpy.data.materials:
98 | mat = bpy.data.materials[Global.GD_MATERIAL_NAME]
99 | else:
100 | mat = bpy.data.materials.new(name=Global.GD_MATERIAL_NAME)
101 | mat.use_nodes = True
102 | bsdf = mat.node_tree.nodes['Principled BSDF']
103 | bsdf.inputs["Emission Color"].default_value = (0,0,0,1)
104 |
105 | # NOTE: Do not remove empty slots as they are used in geometry masking
106 | for slot in ob.material_slots:
107 | if slot.name == '':
108 | ob.material_slots[slot.name].material = mat
109 | if not ob.active_material or ob.active_material.name == '':
110 | ob.active_material = mat
111 |
112 | inputs = get_group_inputs(node_tree)
113 | input_names: list[str] = [node_input.name for node_input in inputs]
114 | unlinked: dict[str, list[str]] = {}
115 |
116 | for slot in ob.material_slots:
117 | material = bpy.data.materials.get(slot.name)
118 | material.use_nodes = True
119 | nodes = material.node_tree.nodes
120 | if node_tree.name in nodes:
121 | continue
122 | if material.name.startswith(Global.FLAG_PREFIX):
123 | unlinked[material.name] = []
124 | else:
125 | unlinked[material.name] = input_names
126 |
127 | output = None
128 | output_nodes = [mat for mat in nodes if mat.type == 'OUTPUT_MATERIAL']
129 | for output_node in output_nodes:
130 | if output_node.is_active_output:
131 | output = output_node
132 | break
133 | if output is None:
134 | output = nodes.new('ShaderNodeOutputMaterial')
135 |
136 | node_group = nodes.new('ShaderNodeGroup')
137 | node_group.hide = True
138 | node_group.gd_spawn = True
139 | node_group.node_tree = node_tree
140 | node_group.name = node_tree.name
141 | node_group.location = (output.location[0], output.location[1] - 160)
142 |
143 | warning_text = bpy.data.texts.get(Global.NODE_GROUP_WARN_NAME)
144 | if warning_text is None:
145 | warning_text = bpy.data.texts.new(Global.NODE_GROUP_WARN_NAME)
146 | warning_text.write(Global.NODE_GROUP_WARN)
147 | frame = nodes.new('NodeFrame')
148 | frame.name = node_tree.name
149 | frame.width = 750
150 | frame.height = 200
151 | frame.gd_spawn = True
152 | frame.location = (output.location[0], output.location[1] - 200)
153 | frame.text = warning_text
154 |
155 | # Link identical outputs from BSDF to output node
156 | from_output_node = output.inputs[0].links[0].from_node
157 | for node_input in from_output_node.inputs:
158 | if node_input.name not in input_names or not node_input.links:
159 | continue
160 | link = node_input.links[0]
161 | material.node_tree.links.new(
162 | node_group.inputs[node_input.name],
163 | link.from_node.outputs[link.from_socket.name]
164 | )
165 | if node_input.name in unlinked[material.name]:
166 | unlinked[material.name].remove(node_input.name)
167 |
168 | # Link matching input names from BSDF to baker
169 | for node_input in output.inputs:
170 | for link in node_input.links:
171 | material.node_tree.links.new(
172 | node_group.inputs[node_input.name],
173 | link.from_node.outputs[link.from_socket.name]
174 | )
175 | material.node_tree.links.remove(link)
176 | material.node_tree.links.new(output.inputs["Surface"],
177 | node_group.outputs["Shader"])
178 |
179 | # NOTE: Collapse found unlinked sockets into flat list
180 | unlinked_names = set()
181 | for input_names in unlinked.values():
182 | for name in input_names:
183 | unlinked_names.add(name)
184 | return list(unlinked_names)
185 |
186 |
187 | def generate_shader_interface(
188 | tree: NodeTree, inputs: dict[str, str],
189 | name: str = "Output Cache", hidden: bool=True
190 | ) -> None:
191 | """Add sockets to a new panel in a given `NodeTree`
192 | and expected input of sockets. Defaults to `Shader` output.
193 |
194 | Generally used alongside other automation
195 | for creating reusable node input schemes.
196 |
197 | Dict formatting examples:
198 | - {'Displacement': 'NodeSocketVector'}
199 | - {SocketName: SocketType}"""
200 | if name in tree.interface.items_tree:
201 | return
202 | saved_links = tree.interface.new_panel(name, default_closed=hidden)
203 | for socket_name, socket_type in inputs.items():
204 | tree.interface.new_socket(name=socket_name, parent=saved_links,
205 | socket_type=socket_type)
206 | if "Shader" in tree.interface.items_tree:
207 | return
208 | tree.interface.new_socket(name="Shader", socket_type="NodeSocketShader",
209 | in_out='OUTPUT')
210 |
--------------------------------------------------------------------------------
/utils/pack.py:
--------------------------------------------------------------------------------
1 | import os
2 | import numpy # pylint: disable=E0401
3 |
4 | import bpy
5 |
6 | from .io import get_format
7 | from .baker import get_bakers
8 |
9 |
10 | def pack_image_channels(pack_order, PackName):
11 | """NOTE: Original code sourced from:
12 | https://blender.stackexchange.com/questions/274712/how-to-channel-pack-texture-in-python
13 | """
14 | dst_array = None
15 | has_alpha = False
16 |
17 | # Build the packed pixel array
18 | for pack_item in pack_order:
19 | image = pack_item[0]
20 | # Initialize arrays on the first iteration
21 | if dst_array is None:
22 | w, h = image.size
23 | src_array = numpy.empty(w * h * 4, dtype=numpy.float32)
24 | dst_array = numpy.ones(w * h * 4, dtype=numpy.float32)
25 | assert image.size[:] == (w, h), "Images must be same size"
26 |
27 | # Fetch pixels from the source image and copy channels
28 | image.pixels.foreach_get(src_array)
29 | for src_chan, dst_chan in pack_item[1:]:
30 | if dst_chan == 3:
31 | has_alpha = True
32 | dst_array[dst_chan::4] = src_array[src_chan::4]
33 |
34 | # Create image from the packed pixels
35 | dst_image = bpy.data.images.new(PackName, w, h, alpha=has_alpha)
36 | dst_image.pixels.foreach_set(dst_array)
37 | return dst_image
38 |
39 |
40 | def get_channel_path(channel: str) -> str | None:
41 | """Get the channel path of the given channel name.
42 |
43 | If the channel path is not found returns `None`."""
44 | if channel == "none":
45 | return None
46 | gd = bpy.context.scene.gd
47 | # TODO: Multi-baker support
48 | suffix = getattr(gd, channel)[0].suffix
49 | if suffix is None:
50 | return None
51 | filename = gd.filename + '_' + suffix + get_format()
52 | filepath = os.path.join(gd.filepath, filename)
53 | if not os.path.exists(filepath):
54 | return None
55 | return filepath
56 |
57 |
58 | def is_pack_maps_enabled() -> bool:
59 | """Checks if the chosen pack channels
60 | match the enabled maps to export.
61 |
62 | This function also returns True if a required
63 | bake map is not enabled but the texture exists."""
64 | baker_ids = ['none']
65 | baker_ids += [baker.ID for baker in get_bakers(filter_enabled=True)]
66 |
67 | gd = bpy.context.scene.gd
68 | if gd.channel_r not in baker_ids \
69 | and get_channel_path(gd.channel_r) is None:
70 | return False
71 | if gd.channel_g not in baker_ids \
72 | and get_channel_path(gd.channel_g) is None:
73 | return False
74 | if gd.channel_b not in baker_ids \
75 | and get_channel_path(gd.channel_b) is None:
76 | return False
77 | if gd.channel_a not in baker_ids \
78 | and get_channel_path(gd.channel_a) is None:
79 | return False
80 | return True
81 |
--------------------------------------------------------------------------------
/utils/render.py:
--------------------------------------------------------------------------------
1 | import bpy
2 | from mathutils import Vector
3 | from bpy.types import Object
4 |
5 | from ..constants import Global
6 | from .generic import get_user_preferences
7 |
8 |
9 | def is_object_gd_valid(
10 | ob: Object,
11 | has_prefix: bool=False,
12 | render_visible: bool=True,
13 | invalid_type: bool=True,
14 | is_gd_ob: bool=False
15 | ) -> bool:
16 | """Basic validation checks to detect if an object
17 | will work well within the GrabDoc environment"""
18 | # Default off
19 | if has_prefix and not ob.name.startswith(Global.FLAG_PREFIX):
20 | return False
21 | if is_gd_ob and not ob.gd_object:
22 | return False
23 | if not is_gd_ob and ob.gd_object:
24 | return False
25 |
26 | # Default on
27 | if render_visible and ob.hide_render:
28 | return False
29 | if invalid_type and ob.type in Global.INVALID_BAKE_TYPES:
30 | return False
31 | return True
32 |
33 |
34 | def in_viewing_frustrum(vector: Vector) -> bool:
35 | """Decide whether a given object is within the cameras viewing frustrum."""
36 | bg_plane = bpy.data.objects[Global.BG_PLANE_NAME]
37 | viewing_frustrum = (
38 | Vector((bg_plane.dimensions.x * -1.25 + bg_plane.location[0],
39 | bg_plane.dimensions.y * -1.25 + bg_plane.location[1],
40 | -100)),
41 | Vector((bg_plane.dimensions.x * 1.25 + bg_plane.location[0],
42 | bg_plane.dimensions.y * 1.25 + bg_plane.location[1],
43 | 100))
44 | )
45 | for i in range(0, 3):
46 | if (vector[i] < viewing_frustrum[0][i] \
47 | and vector[i] < viewing_frustrum[1][i] \
48 | or vector[i] > viewing_frustrum[0][i] \
49 | and vector[i] > viewing_frustrum[1][i]):
50 | return False
51 | return True
52 |
53 |
54 | def get_rendered_objects() -> set | None:
55 | """Generate a list of all objects that will be rendered
56 | based on its origin position in world space"""
57 | objects = set()
58 | if bpy.context.scene.gd.use_bake_collection:
59 | for coll in bpy.data.collections:
60 | if coll.gd_collection is False:
61 | continue
62 | objects.update(
63 | [ob for ob in coll.all_objects if is_object_gd_valid(ob)]
64 | )
65 | # TODO: Old method; profile it
66 | #for ob in coll.all_objects:
67 | # if is_valid_grabdoc_object(ob):
68 | # rendered_obs.add(ob.name)
69 | return objects
70 |
71 | objects = bpy.context.view_layer.objects
72 | objects = [ob for ob in objects if is_object_gd_valid(ob)]
73 |
74 | if not get_user_preferences().render_within_frustrum:
75 | return objects
76 |
77 | # Distance based filter
78 | filtered_objects = set()
79 | for ob in objects:
80 | local_bbox_center = .125 * sum(
81 | (Vector(ob) for ob in ob.bound_box), Vector()
82 | )
83 | global_bbox_center = ob.matrix_world @ local_bbox_center
84 | if in_viewing_frustrum(global_bbox_center):
85 | filtered_objects.add(ob)
86 | return filtered_objects
87 |
88 |
89 | def set_guide_height(objects: list[Object]=None) -> None:
90 | """Set guide height maximum property value
91 | based on a given list of objects"""
92 | tallest_vert = find_tallest_object(objects)
93 | bg_plane = bpy.data.objects.get(Global.BG_PLANE_NAME)
94 | bpy.context.scene.gd.height[0].distance = tallest_vert-bg_plane.location[2]
95 |
96 |
97 | def find_tallest_object(objects: list[Object]=None) -> float:
98 | """Find the tallest points in the viewlayer by looping
99 | through objects to find the highest vertex on the Z axis"""
100 | if objects is None:
101 | objects = bpy.context.selectable_objects
102 |
103 | depsgraph = bpy.context.evaluated_depsgraph_get()
104 | tallest_verts = []
105 | objects = [
106 | ob for ob in objects if not ob.name.startswith(Global.FLAG_PREFIX)
107 | ]
108 | for ob in objects:
109 | ob_eval = ob.evaluated_get(depsgraph)
110 | try:
111 | mesh_eval = ob_eval.to_mesh()
112 | except RuntimeError:
113 | # NOTE: Object can't be evaluates as mesh; maybe particle system
114 | continue
115 |
116 | global_vert_co = [
117 | ob_eval.matrix_world @ v.co for v in mesh_eval.vertices
118 | ]
119 |
120 | # NOTE: Find highest Z-value amongst
121 | # object's vertices and append to list
122 | if len(global_vert_co):
123 | max_z_co = max(co.z for co in global_vert_co)
124 | tallest_verts.append(max_z_co)
125 | ob_eval.to_mesh_clear()
126 | if not tallest_verts:
127 | bpy.context.scene.gd.height[0].method = 'MANUAL'
128 | # NOTE: Fallback to manual height value
129 | return bpy.context.scene.gd.height[0].distance
130 | return max(tallest_verts)
131 |
132 |
133 | def set_color_management(
134 | view_transform: str = 'Standard',
135 | look: str = 'None',
136 | display_device: str = 'sRGB'
137 | ) -> None:
138 | """Helper function for supporting custom color management
139 | profiles. Ignores anything that isn't compatible"""
140 | display_settings = bpy.context.scene.display_settings
141 | display_settings.display_device = display_device
142 | view_settings = bpy.context.scene.view_settings
143 | view_settings.view_transform = view_transform
144 | view_settings.look = look
145 | view_settings.exposure = 0
146 | view_settings.gamma = 1
147 | view_settings.use_curve_mapping = False
148 | view_settings.use_hdr_view = False
149 |
--------------------------------------------------------------------------------
/utils/scene.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | import bpy
4 | import bmesh
5 | from bpy.types import Context, Object
6 |
7 | from ..constants import Global, Error
8 |
9 |
10 | # NOTE: Needs self for property update functions to register
11 | def scene_setup(_self, context: Context) -> None:
12 | """Setup all relevant objects, collections, node groups, and properties."""
13 | gd = context.scene.gd
14 | context.scene.render.resolution_x = gd.resolution_x
15 | context.scene.render.resolution_y = gd.resolution_y
16 |
17 | view_layer = context.view_layer
18 | saved_active_collection = view_layer.active_layer_collection
19 | saved_selected_obs = view_layer.objects.selected.keys()
20 |
21 | activeCallback = None
22 | gd_coll = bpy.data.collections.get(Global.COLL_CORE_NAME)
23 | if context.object:
24 | active_ob = context.object
25 | activeCallback = active_ob.name
26 | modeCallback = active_ob.mode
27 |
28 | if active_ob.hide_viewport:
29 | active_ob.hide_viewport = False
30 | elif gd_coll is not None and gd_coll.hide_viewport:
31 | gd_coll.hide_viewport = False
32 |
33 | if bpy.ops.object.mode_set.poll():
34 | bpy.ops.object.mode_set(mode='OBJECT')
35 |
36 | for ob in context.selected_objects:
37 | ob.select_set(False)
38 |
39 | saved_plane_loc, saved_plane_rot, \
40 | saved_mat, was_viewing_camera, saved_bake_group_obs = \
41 | scene_cleanup(context, hard_reset=False)
42 |
43 | # Collections
44 | if gd.use_bake_collection:
45 | bake_group_coll = bpy.data.collections.new(Global.COLL_GROUP_NAME)
46 | bake_group_coll.gd_collection = True
47 |
48 | context.scene.collection.children.link(bake_group_coll)
49 | view_layer.active_layer_collection = \
50 | view_layer.layer_collection.children[-1]
51 |
52 | if len(saved_bake_group_obs):
53 | for ob in saved_bake_group_obs:
54 | bake_group_coll.objects.link(ob)
55 |
56 | gd_coll = bpy.data.collections.new(name=Global.COLL_CORE_NAME)
57 | gd_coll.gd_collection = True
58 | context.scene.collection.children.link(gd_coll)
59 | view_layer.active_layer_collection = \
60 | view_layer.layer_collection.children[-1]
61 | view_layer.active_layer_collection = \
62 | view_layer.layer_collection.children[gd_coll.name]
63 |
64 | # Background plane
65 | bpy.ops.mesh.primitive_plane_add(size=gd.scale,
66 | calc_uvs=True,
67 | align='WORLD',
68 | location=saved_plane_loc,
69 | rotation=saved_plane_rot)
70 | context.object.name = context.object.data.name = Global.BG_PLANE_NAME
71 | plane_ob = bpy.data.objects[Global.BG_PLANE_NAME]
72 | plane_ob.select_set(False)
73 | plane_ob.show_wire = True
74 | plane_ob.lock_scale[0] = \
75 | plane_ob.lock_scale[1] = \
76 | plane_ob.lock_scale[2] = True
77 |
78 | if gd.resolution_x != gd.resolution_y:
79 | if gd.resolution_x > gd.resolution_y:
80 | div_factor = gd.resolution_x / gd.resolution_y
81 | plane_ob.scale[1] /= div_factor
82 | else:
83 | div_factor = gd.resolution_y / gd.resolution_x
84 | plane_ob.scale[0] /= div_factor
85 | bpy.ops.object.transform_apply(location=False, rotation=False)
86 |
87 | # Reference
88 | if gd.reference and not gd.preview_state:
89 | for mat in bpy.data.materials:
90 | if mat.name == Global.REFERENCE_NAME:
91 | mat.node_tree.nodes.get('Image Texture').image = gd.reference
92 | break
93 | else:
94 | # Create a new material & turn on node use
95 | mat = bpy.data.materials.new(Global.REFERENCE_NAME)
96 | mat.use_nodes = True
97 |
98 | # Get / load nodes
99 | output = mat.node_tree.nodes['Material Output']
100 | output.location = (0,0)
101 | mat.node_tree.nodes.remove(
102 | mat.node_tree.nodes['Principled BSDF']
103 | )
104 |
105 | image = mat.node_tree.nodes.new('ShaderNodeTexImage')
106 | image.image = gd.reference
107 | image.location = (-300,0)
108 |
109 | mat.node_tree.links.new(output.inputs["Surface"],
110 | image.outputs["Color"])
111 |
112 | plane_ob.active_material = bpy.data.materials[Global.REFERENCE_NAME]
113 |
114 | for area in context.screen.areas:
115 | if area.type != 'VIEW_3D':
116 | continue
117 | for space in area.spaces:
118 | space.shading.color_type = 'TEXTURE'
119 | else:
120 | # Refresh original material and delete the reference material
121 | if saved_mat is not None:
122 | plane_ob.active_material = saved_mat
123 | # TODO: Removal operation inside of a setup function
124 | if Global.REFERENCE_NAME in bpy.data.materials:
125 | bpy.data.materials.remove(bpy.data.materials[Global.REFERENCE_NAME])
126 |
127 | # Grid
128 | if gd.use_grid and gd.grid_subdivs:
129 | bm = bmesh.new()
130 | bm.from_mesh(plane_ob.data)
131 | bmesh.ops.subdivide_edges(bm, edges=bm.edges,
132 | cuts=gd.grid_subdivs,
133 | use_grid_fill=True)
134 | bm.to_mesh(plane_ob.data)
135 |
136 | # Camera
137 | camera_data = bpy.data.cameras.new(Global.TRIM_CAMERA_NAME)
138 | camera_data.type = 'ORTHO'
139 | camera_data.display_size = .01
140 | camera_data.ortho_scale = gd.scale
141 | camera_data.clip_start = 0.1
142 | camera_data.clip_end = 1000 * (gd.scale / 25)
143 | camera_data.passepartout_alpha = 1
144 |
145 | camera_ob = bpy.data.objects.new(Global.TRIM_CAMERA_NAME, camera_data)
146 | camera_ob.parent = plane_ob
147 | camera_object_z = Global.CAMERA_DISTANCE * gd.scale
148 | camera_ob.location = (0, 0, camera_object_z)
149 | camera_ob.hide_select = camera_ob.gd_object = True
150 |
151 | gd_coll.objects.link(camera_ob)
152 | context.scene.camera = camera_ob
153 | if was_viewing_camera:
154 | bpy.ops.view3d.view_camera()
155 |
156 | # Point cloud
157 | if gd.height[0].enabled and gd.height[0].method == 'MANUAL':
158 | generate_height_guide(Global.HEIGHT_GUIDE_NAME, plane_ob)
159 | generate_orientation_guide(Global.ORIENT_GUIDE_NAME, plane_ob)
160 |
161 | # Cleanup
162 | for ob_name in saved_selected_obs:
163 | ob = context.scene.objects.get(ob_name)
164 | ob.select_set(True)
165 |
166 | view_layer.active_layer_collection = saved_active_collection
167 | if activeCallback:
168 | view_layer.objects.active = bpy.data.objects[activeCallback]
169 | if bpy.ops.object.mode_set.poll():
170 | bpy.ops.object.mode_set(mode=modeCallback)
171 |
172 | gd_coll.hide_select = not gd.coll_selectable
173 | gd_coll.hide_viewport = not gd.coll_visible
174 | gd_coll.hide_render = not gd.coll_rendered
175 |
176 |
177 | def scene_cleanup(context: Context, hard_reset: bool=True) -> None | list:
178 | """Completely removes every element of GrabDoc from
179 | the scene, not including images reimported after bakes
180 |
181 | hard_reset: When refreshing a scene we may want to keep
182 | certain data-blocks that the user can manipulates"""
183 | # NOTE: Move objects contained inside the bake group collection
184 | # to the root collection level and delete the collection
185 | saved_bake_group_obs = []
186 | bake_group_coll = bpy.data.collections.get(Global.COLL_GROUP_NAME)
187 | if bake_group_coll is not None:
188 | for ob in bake_group_coll.all_objects:
189 | if hard_reset or not context.scene.gd.use_bake_collection:
190 | context.scene.collection.objects.link(ob)
191 | else:
192 | saved_bake_group_obs.append(ob)
193 | ob.users_collection[0].objects.unlink(ob)
194 | bpy.data.collections.remove(bake_group_coll)
195 |
196 | # NOTE: Compensate for objects accidentally placed in the core collection
197 | gd_coll = bpy.data.collections.get(Global.COLL_CORE_NAME)
198 | if gd_coll is not None:
199 | for ob in gd_coll.all_objects:
200 | if ob.name not in (Global.BG_PLANE_NAME,
201 | Global.ORIENT_GUIDE_NAME,
202 | Global.HEIGHT_GUIDE_NAME,
203 | Global.TRIM_CAMERA_NAME):
204 | context.scene.collection.objects.link(ob)
205 | ob.gd_coll.objects.unlink(ob)
206 | bpy.data.collections.remove(gd_coll)
207 |
208 | if hard_reset:
209 | for ob_name in (Global.BG_PLANE_NAME,
210 | Global.ORIENT_GUIDE_NAME,
211 | Global.HEIGHT_GUIDE_NAME):
212 | if ob_name in bpy.data.objects:
213 | bpy.data.meshes.remove(bpy.data.meshes[ob_name])
214 | if Global.TRIM_CAMERA_NAME in bpy.data.objects:
215 | bpy.data.cameras.remove(bpy.data.cameras[Global.TRIM_CAMERA_NAME])
216 | if Global.REFERENCE_NAME in bpy.data.materials:
217 | bpy.data.materials.remove(bpy.data.materials[Global.REFERENCE_NAME])
218 | for group in bpy.data.node_groups:
219 | if group.name.startswith(Global.FLAG_PREFIX):
220 | bpy.data.node_groups.remove(group)
221 | return None
222 |
223 | saved_mat = None
224 | saved_plane_loc = saved_plane_rot = (0, 0, 0)
225 | if Global.BG_PLANE_NAME in bpy.data.objects:
226 | plane_ob = bpy.data.objects[Global.BG_PLANE_NAME]
227 | saved_mat = plane_ob.active_material
228 | saved_plane_loc = plane_ob.location.copy()
229 | saved_plane_rot = plane_ob.rotation_euler.copy()
230 | bpy.data.meshes.remove(plane_ob.data)
231 |
232 | # NOTE: Forcibly exit the camera before deleting it
233 | # so the original users camera position is retained
234 | was_viewing_camera = False
235 | if camera_in_3d_view():
236 | was_viewing_camera = True
237 | bpy.ops.view3d.view_camera()
238 |
239 | if Global.TRIM_CAMERA_NAME in bpy.data.cameras:
240 | bpy.data.cameras.remove(bpy.data.cameras[Global.TRIM_CAMERA_NAME])
241 | if Global.HEIGHT_GUIDE_NAME in bpy.data.meshes:
242 | bpy.data.meshes.remove(bpy.data.meshes[Global.HEIGHT_GUIDE_NAME])
243 | if Global.ORIENT_GUIDE_NAME in bpy.data.meshes:
244 | bpy.data.meshes.remove(bpy.data.meshes[Global.ORIENT_GUIDE_NAME])
245 |
246 | return saved_plane_loc, saved_plane_rot, saved_mat, \
247 | was_viewing_camera, saved_bake_group_obs
248 |
249 |
250 | def validate_scene(
251 | context: Context,
252 | is_exporting: bool=True,
253 | report_value=False,
254 | report_string=""
255 | ) -> tuple[bool, str]:
256 | """Determine if specific parts of the scene
257 | are set up incorrectly and return a detailed
258 | explanation of things for the user to fix."""
259 | gd = context.scene.gd
260 |
261 | if not Global.TRIM_CAMERA_NAME in context.view_layer.objects \
262 | and not report_value:
263 | report_value = True
264 | report_string = Error.CAMERA_NOT_FOUND
265 |
266 | if gd.use_bake_collection and not report_value:
267 | if not len(bpy.data.collections[Global.COLL_GROUP_NAME].objects):
268 | report_value = True
269 | report_string = Error.BAKE_GROUPS_EMPTY
270 |
271 | if is_exporting is False:
272 | return report_value, report_string
273 |
274 | if not report_value \
275 | and not gd.filepath == "//" \
276 | and not os.path.exists(gd.filepath):
277 | report_value = True
278 | report_string = Error.NO_VALID_PATH_SET
279 | return report_value, report_string
280 |
281 |
282 | def is_scene_valid() -> bool:
283 | """Validate all required objects to determine correct scene setup."""
284 | object_checks = (Global.COLL_CORE_NAME in bpy.data.collections,
285 | Global.BG_PLANE_NAME in bpy.context.scene.objects,
286 | Global.TRIM_CAMERA_NAME in bpy.context.scene.objects)
287 | return True in object_checks
288 |
289 |
290 | def camera_in_3d_view() -> bool:
291 | """Check if the first found 3D View is currently viewing the camera."""
292 | for area in bpy.context.screen.areas:
293 | if area.type != 'VIEW_3D':
294 | continue
295 | return area.spaces.active.region_3d.view_perspective == 'CAMERA'
296 |
297 |
298 | def generate_height_guide(name: str, plane_ob: Object) -> None:
299 | """Generate a mesh that represents the height map range.
300 |
301 | Generally used for `Manual` Height method to visualize the 0-1 range."""
302 | scene = bpy.context.scene
303 | trim_camera = bpy.data.objects.get(Global.TRIM_CAMERA_NAME)
304 | camera_view_frame = trim_camera.data.view_frame(scene=scene)
305 |
306 | stems_vecs = [
307 | (v[0], v[1], scene.gd.height[0].distance) for v in camera_view_frame
308 | ]
309 | ring_vecs = [(v[0], v[1], v[2]+1) for v in camera_view_frame]
310 | ring_vecs += stems_vecs
311 |
312 | mesh = bpy.data.meshes.new(name)
313 | mesh.from_pydata(vertices=ring_vecs,
314 | edges=[(0,4), (1,5), (2,6),
315 | (3,7), (4,5), (5,6),
316 | (6,7), (7,4)],
317 | faces=[])
318 | mesh.update()
319 |
320 | ob = bpy.data.objects.new(name, mesh)
321 | bpy.context.collection.objects.link(ob)
322 | ob.gd_object = True
323 | ob.parent = plane_ob
324 | ob.hide_select = True
325 |
326 |
327 | def generate_orientation_guide(name: str, plane_ob: Object) -> None:
328 | """Generate a mesh object that sits beside the background plane
329 | to guide the user to the correct "up" orientation"""
330 | mesh = bpy.data.meshes.new(name)
331 | plane_y = plane_ob.dimensions.y / 2
332 | mesh.from_pydata(vertices=[(-.3, plane_y+.1, 0),
333 | (.3, plane_y+.1, 0),
334 | (0, plane_y+.35, 0)],
335 | edges=[(0,2), (0,1), (1,2)],
336 | faces=[])
337 | mesh.update()
338 |
339 | ob = bpy.data.objects.new(name, mesh)
340 | bpy.context.collection.objects.link(ob)
341 | ob.parent = plane_ob
342 | ob.hide_select = True
343 | ob.gd_object = True
344 |
--------------------------------------------------------------------------------