├── .gitignore
├── CHANGELOG.md
├── LICENSE
├── README.md
├── __init__.py
├── data_types.py
├── docs
├── blender.jpg
└── unreal.jpg
├── export_datasmith.py
└── testing
├── README.md
├── datasmith.prof
├── export_all.ps1
└── test_datasmith_export.py
/.gitignore:
--------------------------------------------------------------------------------
1 | testing/**
2 | !testing/*
3 | *.pyc
4 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 | All notable changes to this project will be documented in this file.
3 | Features marked with `*` require the UE4 plugin to work.
4 |
5 | ## [Unreleased]
6 | ### Fixed
7 | * Export metadata is now a flag, off by default, to help in case other addons store info there.
8 | * Libraries with long file paths are now referenced by the blend file name only.
9 |
10 | ## [1.0.3] 2020-08-19
11 | ### Added
12 | + Texture node now supports box projection.
13 | + Smoothing groups are now written in geometry data.
14 | + TGA texture support. _Thanks KeyToon9_
15 |
16 | ### Fixed
17 | * Vertex normals now export correctly (you may need to use the Triangulate modifier). _Thanks KeyToon9_
18 | * Fixed image files names when first char is unvalid. _Thanks KeyToon9_
19 | * Improved light attenuation radius calculation.
20 | * Animation is now correctly exported for non-root objects.
21 |
22 | ## [1.0.2] 2020-07-24
23 | ### Fixed
24 | * Fixed an issue when writing some custom props, that would break the XML structure.
25 |
26 | ## [1.0.0] 2020-07-01
27 | ### Added
28 | + Added support for object and meshes metadata (custom properties in Blender).
29 | + Added an option to prefer custom nodes to generate simpler graphs if you have the UE4 plugin.*
30 | + Added new material nodes:
31 | - Texture Coordinates (partial support)*
32 | - Noise Texture (simulated, not entirely accurate)*
33 | - UV Map*
34 | - Geometry (partial support)*
35 | - Attribute
36 | - Combine/Separate RGB/XYZ
37 | - Combine/Separate HSV*
38 | - Math (some new nodes like SINH, COSH, etc...)*
39 | - Vector Math
40 | - Vector Math (Round, Wrap, Project, Reflect)*
41 | - Mapping (can now do 3d rotations, uses simpler variants when there is no XY rotation)*
42 | - Checker Texture*
43 |
44 | + **This is a big one:** Object animations are now exported in a Level Sequence.
45 |
46 |
47 | ### Fixed
48 | * Fixed nodegroups with output node named different than "Group Output".
49 | * Names are now sanitized to be only alphanumeric.
50 | * Increased size for datasmith_curves image to allow for more baked curves (up to 1024)
51 | * All UV nodes are upcasted to Vector3 to better reflect Blender operations, and masked down to Vector2 when reading from them.
52 | * Improved images recollection flow. Unpacked files are directly copied and packed files are written from packed data instead of resaving them (this fixes some strange formats like RG8, which Blender can read and pack, but cannot save).
53 | * Improved behavior of **ColorRamp** and **RGBCurveLookup** nodes*
54 | * Improved behavior of RGB sockets connected to VALUE sockets
55 | * Math nodes with `Clamp` option are now wrapped with a `Saturate` operation.
56 | * Normal maps with strength different than 1 are now wrapped with a `FlattenNormal` operation.
57 | * Principled BSDF nodes now write the Specular values.
58 | * UV maps set as `Render Active` are now set at UV0 to be read as default UVs in UE4. \
59 | * Improved handling of some meshes with empty materials or no material slots.
60 | * Tested on **Blender 2.83.1**
61 |
62 |
63 | ## [0.4.0] 2020-03-26
64 | ### Added
65 | + Added support for exporting curves as geometry
66 | + Added minimal export option, which skips textures for faster export
67 | + Added new material nodes:
68 | - Blackbody
69 | - Bright/Contrast*
70 | - Object Info
71 | - Gamma (Power)
72 |
73 | ### Fixed
74 | * Improved materials rgb_curves node support
75 | * Improved logging output
76 | * We now support **Blender 2.82**
77 |
78 | ## [0.3.0] 2020-03-09
79 |
80 | ### Added
81 | + Added support for multiple uv maps (datasmith supports up to 8)
82 | + Added support for sphere reflection probes
83 | + Added support for box reflection probes
84 | + Added support for planar reflection probes
85 |
86 | ### Fixed
87 | * Fixed export of material nodetrees inside nodetrees
88 | * Improved export speed of material curves
89 | * Fixed normal map flags for ue4.25
90 | * Fixed profiling flag as export option
91 | * Fixed export for multiple scenes, these scenes export, although some are not
92 | tested in UE4 yet, tested scenes include:
93 | + archiviz
94 | + blender_splash_fishy_cat
95 | + classroom
96 | + forest
97 | + mr_elephant
98 | + pabellon_barcelona
99 | + pokedstudio
100 | + race_spaceship
101 | + temple
102 | + the_junk_shop
103 | + tree_creature
104 | + wanderer
105 | + wasp_bot
106 |
107 | ## [0.2.0]
108 |
109 | This was the first release, changelog wasn't used before this.
110 |
--------------------------------------------------------------------------------
/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 | # Blender Datasmith Export
2 |
3 | Export your Blender scene to UE4 using the Datasmith format.
4 |
5 | It aims to export all the Datasmith format supports. For now it exports:
6 |
7 | * __Meshes__ with normals, vertex colors and up to 8 UV channels.
8 | * __Hierarchy__ is exported keeping meshes references, transforms, parents and
9 | per-instance material overrides from blender.
10 | * __Textures and materials__ are exported using data from the shader graphs.
11 | Materials are closely approximated and a good amount of nodes are supported
12 | (math, mix, fresnel, vertex color and others)
13 | * __Cameras__ are exported trying to match Blender data, keeping focus
14 | distance, focal length, and aperture
15 | * __Lights__ are exported, keeping their type, power, color and size data.
16 | * __Reflection probes__ including Planar, Sphere and Box captures.
17 |
18 | Check out an overview of a previous version here:
19 | https://youtu.be/bUUDqerdqAc
20 |
21 | ## Sample:
22 | You can click the images to open a large preview.
23 |
24 | __Blender Eevee:__
25 |
26 |
27 |
28 | __UE4 using Datasmith:__
29 |
30 |
31 |
32 | This result relies on the **DatasmithBlenderContent**, which is a UE4 Plugin
33 | that improves material import compatibility. Consider supporting the project by
34 | purchasing it from [here][gumroad] (Epic Games store support will be added later)
35 |
36 | [gumroad]: https://gum.co/DQvTL
37 |
38 | This result is in a custom UE4 build, which fixes some issues of the UE4
39 | importer. If you are technical to compile the engine, you can check the fork
40 | [here][ue4 fork]. Hopefully we can get to integrate our fixes into the main
41 | branch.
42 |
43 | [ue4 fork]: https://github.com/0xafbf/UnrealEngine/tree/master
44 |
45 | ## Installation:
46 |
47 | Now [__Download the latest development version__][download_link] and install
48 | from the Blender addons preferences pane.
49 |
50 | [download_link]: https://github.com/0xafbf/blender-datasmith-export/archive/master.zip
51 |
52 | ## Frequently Asked Questions:
53 |
54 | __Q: Does this support weighted normals/smoothing groups?__
55 |
56 | A: Yes, but the plugin is unable to triangulate correctly. For the time
57 | being, you can add a `Triangulate` modifier with the `Keep Normals` option to
58 | work around this.
59 |
60 | __Q: Why are some material nodes not exported?__
61 |
62 | A: Most of the nodes are exported, but not all of them are imported from the
63 | UE4 side. The Datasmith Blender Additions (mentioned above) improves this by
64 | adding implementations for some of these nodes. There is a
65 | [list of nodes in the wiki] with more information on which nodes are
66 | supported, and which require the UE4 plugin to work.
67 |
68 | [list of nodes in the wiki]: https://github.com/0xafbf/blender-datasmith-export/wiki/Supported-Material-Nodes
69 |
70 | __Q: What is this "custom build" you talked about earlier?__
71 |
72 | A: I modified some of the UE4 build to fix a couple of errors when importing
73 | the scenes generated from Blender. These are related to normal maps import
74 | and very specific import issues with lights. If you're interested you can
75 | check this [custom build discussion].
76 |
77 | [custom build discussion]: https://github.com/0xafbf/blender-datasmith-export/issues/25
78 |
79 | If you want to support the project, consider supporting via [Patreon].
80 |
81 | [patreon]: https://www.patreon.com/0xafbf
82 |
83 | Please please, [join the project Discord][join_discord] and share your results!
84 | I want to see what you make and I am open to any feedback you have.
85 |
86 | [join_discord]: https://discord.gg/NJt5ADJ
87 |
88 |
--------------------------------------------------------------------------------
/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright Andrés Botero 2019
2 |
3 | bl_info = {
4 | "name": "Unreal Datasmith format",
5 | "author": "Andrés Botero",
6 | "version": (1, 0, 3),
7 | "blender": (2, 82, 0),
8 | "location": "File > Export > Datasmith (.udatasmith)",
9 | "description": "Export scene as Datasmith asset",
10 | "warning": "",
11 | "category": "Import-Export",
12 | "support": 'COMMUNITY',
13 | "wiki_url": "https://github.com/0xafbf/blender-datasmith-export",
14 | }
15 |
16 |
17 | if "bpy" in locals():
18 | import importlib
19 | if "export_datasmith" in locals():
20 | importlib.reload(export_datasmith)
21 |
22 | import bpy
23 | from bpy.props import (
24 | StringProperty,
25 | BoolProperty,
26 | FloatProperty,
27 | EnumProperty,
28 | )
29 | from bpy_extras.io_utils import (
30 | ImportHelper,
31 | ExportHelper,
32 | path_reference_mode,
33 | axis_conversion,
34 | )
35 |
36 | class ExportDatasmith(bpy.types.Operator, ExportHelper):
37 | """Write a Datasmith file"""
38 | bl_idname = "export_scene.datasmith"
39 | bl_label = "Export Datasmith"
40 | bl_options = {'PRESET'}
41 |
42 | filename_ext = ".udatasmith"
43 | filter_glob: StringProperty(default="*.udatasmith", options={'HIDDEN'})
44 |
45 |
46 | export_selected: BoolProperty(
47 | name="Selected objects only",
48 | description="Exports only the selected objects",
49 | default=False,
50 | )
51 | export_animations: BoolProperty(
52 | name="Export animations",
53 | description="Export object animations (transforms only)",
54 | default=True,
55 | )
56 | apply_modifiers: BoolProperty(
57 | name="Apply modifiers",
58 | description="Applies geometry modifiers when exporting. "
59 | "(This may break mesh instancing)",
60 | default=True,
61 | )
62 | minimal_export: BoolProperty(
63 | name="Skip meshes and textures",
64 | description="Allows for faster exporting, useful if you only changed "
65 | "transforms or shaders",
66 | default=False,
67 | )
68 | use_gamma_hack: BoolProperty(
69 | name="Use sRGB gamma hack (UE 4.24 and below)",
70 | description="Flags sRGB texture to use gamma as sRGB is not supported in old versions",
71 | default=False,
72 | )
73 | compatibility_mode: BoolProperty(
74 | name="Compatibility mode",
75 | description="Enable this if you don't have the UE4 plugin, "
76 | "Improves material nodes support, but at a reduced quality",
77 | default=False,
78 | )
79 | write_metadata: BoolProperty(
80 | name="Write metadata",
81 | description="Writes custom properties of objects and meshes as metadata."
82 | "It may be useful to disable this when using certain addons",
83 | default=True,
84 | )
85 | use_logging: BoolProperty(
86 | name="Enable logging",
87 | description="Enable logging to Window > System console",
88 | default=False,
89 | )
90 | use_profiling: BoolProperty(
91 | name="Enable profiling",
92 | description="For development only, writes a python profile 'datasmith.prof'",
93 | default=False,
94 | )
95 |
96 | def execute(self, context):
97 | keywords = self.as_keywords(ignore=("filter_glob",))
98 | from . import export_datasmith
99 | profile = keywords["use_profiling"]
100 | if not profile:
101 | return export_datasmith.save(context, **keywords)
102 | else:
103 | import cProfile
104 | pr = cProfile.Profile()
105 | pr.enable()
106 | result = export_datasmith.save(context, **keywords)
107 | pr.disable()
108 | path = "datasmith.prof"
109 | pr.dump_stats(path)
110 | return result
111 |
112 | def menu_func_export(self, context):
113 | self.layout.operator(ExportDatasmith.bl_idname, text="Datasmith (.udatasmith)")
114 |
115 | def register():
116 | bpy.utils.register_class(ExportDatasmith)
117 | bpy.types.TOPBAR_MT_file_export.append(menu_func_export)
118 |
119 | def unregister():
120 | bpy.types.TOPBAR_MT_file_export.remove(menu_func_export)
121 | bpy.utils.unregister_class(ExportDatasmith)
122 |
123 |
124 | if __name__ == "__main__":
125 | register()
126 |
--------------------------------------------------------------------------------
/data_types.py:
--------------------------------------------------------------------------------
1 | # Copyright Andrés Botero 2019
2 |
3 | import struct
4 | import os
5 | from os import path
6 | import itertools
7 | import bpy
8 | import numpy as np
9 | import logging
10 | import hashlib
11 | log = logging.getLogger("bl_datasmith")
12 |
13 | def read_array_data(io, data_struct):
14 | struct_size = struct.calcsize(data_struct)
15 | data_struct = "<" + data_struct # force little endianness
16 |
17 | count = struct.unpack(" 47 and char_num < 58:
67 | return True
68 | elif char_num > 64 and char_num < 99:
69 | return True
70 | elif char_num > 96 and char_num < 123:
71 | return True
72 | return False
73 |
74 | def sanitize_name(name):
75 | first_char = ""
76 | if not is_char_valid(name[0]):
77 | first_char = "DS"
78 | sanitized = "".join(letter if is_char_valid(letter) else '_' for letter in name)
79 | return first_char + sanitized
80 |
81 | def f(x):
82 | return '{:6f}'.format(x)
83 |
84 | class Node:
85 | prefix = ""
86 | def __init__(self, name, attrs=None, children=None):
87 | self.name = name
88 | self.children = children or []
89 | if attrs:
90 | assert type(attrs) is dict
91 | self.attrs = attrs or {}
92 |
93 | def __getitem__(self, key):
94 | return self.attrs[key]
95 |
96 | def __setitem__(self, key, value):
97 | self.attrs[key] = value
98 |
99 | def string_rep(self, first=False):
100 | previous_prefix = Node.prefix
101 | if first:
102 | Node.prefix = ""
103 | else:
104 | Node.prefix += "\t"
105 | output = Node.prefix + '<{}'.format(self.name)
106 | if first:
107 | Node.prefix = "\n"
108 | for attr in self.attrs:
109 | output += ' {key}="{value}"'.format(key=attr, value=self.attrs[attr])
110 |
111 | if self.children:
112 | output += '>'
113 | for child in self.children:
114 | output += str(child)
115 | if len(self.children) == 1 and type(self.children[0]) == str:
116 | output += '{}>'.format(self.name)
117 | else:
118 | output += Node.prefix + '{}>'.format(self.name)
119 | else:
120 | output += '/>'
121 | Node.prefix = previous_prefix
122 | return output
123 |
124 | def __str__(self):
125 | return self.string_rep()
126 | def push(self, value):
127 | size = len(self.children)
128 | self.children.append(value)
129 | return size
130 |
131 | def node_value(name, value):
132 | return Node(name, {'value': f(value)})
133 |
134 | class UDMesh():
135 |
136 | def __init__(self, name):
137 | self.name = name
138 |
139 | self.source_models = 'SourceModels'
140 | self.struct_property = 'StructProperty'
141 | self.datasmith_mesh_source_model = 'DatasmithMeshSourceModel'
142 |
143 | self.materials = {}
144 |
145 | self.tris_material_slot = []
146 | self.tris_smoothing_group = []
147 | self.vertices = []
148 | self.triangles = []
149 | self.vertex_normals = []
150 | self.uvs = []
151 | self.vertex_colors = [] # In 0-255 range
152 |
153 | self.test = []
154 |
155 | self.relative_path = None
156 | self.hash = ''
157 |
158 | # this may need some work, found some documentation:
159 | # Engine/Source/Developer/Rawmesh
160 | def write_to_path(self, path):
161 | with open(path, 'wb') as file:
162 | log.debug("writing mesh:"+self.name)
163 | #write_null(file, 8)
164 | file.write(b'\x01\x00\x00\x00\xfd\x04\x00\x00')
165 |
166 | file_start = file.tell()
167 | write_string(file, self.name)
168 | #write_null(file, 5)
169 | file.write(b'\x00\x01\x00\x00\x00')
170 | write_string(file, self.source_models)
171 | write_string(file, self.struct_property)
172 | write_null(file, 8)
173 |
174 | write_string(file, self.datasmith_mesh_source_model)
175 |
176 | write_null(file, 25)
177 |
178 | size_loc = file.tell() # here we have to write the rawmesh size two times
179 | write_data(file, 'II', 0, 0) # just some placeholder data, to rewrite at the end
180 |
181 | file.write(b'\x7d\x00\x00\x00\x00\x00\x00\x00') #125 and zero
182 |
183 | #here starts rawmesh
184 | mesh_start = file.tell()
185 | file.write(b'\x01\x00\x00\x00') # raw mesh version
186 | file.write(b'\x00\x00\x00\x00') # raw mesh lic version
187 |
188 | # further analysis revealed:
189 | # this loops are per triangle
190 | write_array_data(file, 'I', self.tris_material_slot)
191 | write_array_data(file, 'I', self.tris_smoothing_group)
192 |
193 |
194 | # per vertex
195 | write_array_data(file, 'fff', self.vertices) # VertexPositions
196 |
197 | # b2 = write_array_data(file, 'fff', self.test)
198 | # print(self.vertices)
199 | # print(self.test)
200 | # print(b1[0:10])
201 | # print(b2[0:10])
202 |
203 |
204 | # per vertexloop
205 | write_array_data(file, 'I', self.triangles) # WedgeIndices
206 |
207 |
208 | write_null(file, 4) # WedgeTangentX
209 | write_null(file, 4) # WedgeTangentY
210 | write_array_data(file, 'fff', self.vertex_normals) # WedgeTangentZ
211 |
212 | num_uvs = len(self.uvs)
213 | for idx in range(num_uvs):
214 | write_array_data(file, 'ff', self.uvs[idx]) # WedgeTexCoords[0]
215 |
216 | num_empty_uvs = 8 - num_uvs
217 | write_null(file, 4 * num_empty_uvs) # WedgeTexCoords[n..7]
218 | write_array_data(file, 'BBBB', self.vertex_colors) # WedgeColors
219 | # b2 = write_array_data(file, 'BBBB', self.test) # WedgeTexCoords[0]
220 |
221 | # print("old and new are same? {}".format(b1 == b2))
222 | # print(b2[4:24])
223 | # print(self.vertex_colors.tobytes()[:20])
224 | # print(self.vertex_colors[:20])
225 | # print(self.test[:20])
226 |
227 | write_null(file, 4) # MaterialIndexToImportIndex
228 |
229 | #here ends rawmesh
230 | mesh_end = file.tell()
231 |
232 | write_null(file, 16)
233 | write_null(file, 4)
234 | file_end = file.tell()
235 |
236 | mesh_size = mesh_end-mesh_start
237 | file.seek(size_loc)
238 | write_data(file, 'II', mesh_size, mesh_size)
239 |
240 | file.seek(0)
241 | write_data(file, 'II', 1, file_end - file_start)
242 |
243 | def node(self):
244 | n = Node('StaticMesh')
245 | n['label'] = self.name
246 | n['name'] = self.name
247 |
248 | for idx, m in self.materials.items():
249 | n.push(Node('Material', {'id':idx, 'name':m}))
250 | if self.relative_path:
251 | path = self.relative_path.replace('\\', '/')
252 | n.push(Node('file', {'path':path }))
253 | n.push(Node('LightmapUV', {'value': '-1'}))
254 | n.push(Node('Hash', {'value': self.hash}))
255 | return n
256 |
257 | def save(self, basedir, folder_name):
258 | log.debug("writing mesh:"+self.name)
259 | self.relative_path = path.join(folder_name, self.name + '.udsmesh')
260 | abs_path = path.join(basedir, self.relative_path)
261 | self.write_to_path(abs_path)
262 | self.hash = calc_hash(abs_path)
263 |
264 |
265 | def calc_hash(image_path):
266 | hash_md5 = hashlib.md5()
267 | with open(image_path, "rb") as f:
268 | for chunk in iter(lambda: f.read(4096), b""):
269 | hash_md5.update(chunk)
270 | return hash_md5.hexdigest()
271 |
272 |
--------------------------------------------------------------------------------
/docs/blender.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Meisoftcoltd/blender-datasmith-export/ea4e5146b8e34e5f828c556781f40710919852bf/docs/blender.jpg
--------------------------------------------------------------------------------
/docs/unreal.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Meisoftcoltd/blender-datasmith-export/ea4e5146b8e34e5f828c556781f40710919852bf/docs/unreal.jpg
--------------------------------------------------------------------------------
/export_datasmith.py:
--------------------------------------------------------------------------------
1 | # Copyright Andrés Botero 2019
2 |
3 | import bpy
4 | import idprop
5 | import bmesh
6 | import math
7 | import os
8 | import time
9 | import hashlib
10 | import shutil
11 | from os import path
12 | from .data_types import UDMesh, Node, sanitize_name
13 | from mathutils import Matrix, Vector, Euler
14 |
15 | import logging
16 | log = logging.getLogger("bl_datasmith")
17 |
18 | matrix_datasmith = Matrix.Scale(100, 4)
19 | matrix_datasmith[1][1] *= -1.0
20 |
21 | matrix_normals = [
22 | [1, 0, 0],
23 | [0, -1, 0],
24 | [0, 0, 1],
25 | ]
26 |
27 | # used for lights and cameras, whose forward is (0, 0, -1) and its right is (1, 0, 0)
28 | matrix_forward = Matrix((
29 | (0, 1, 0, 0),
30 | (0, 0, -1, 0),
31 | (-1, 0, 0, 0),
32 | (0, 0, 0, 1)
33 | ))
34 |
35 | def exp_vector(value, exp_list):
36 | # n = Node("Color", {
37 | # nocheckin: may not work
38 | n = Node("Color", {
39 | # "Name": name,
40 | "constant": "(R=%.6f,G=%.6f,B=%.6f,A=1.0)"%tuple(value)
41 | })
42 | return exp_list.push(n)
43 |
44 | def exp_color(value, exp_list, name=None):
45 | n = Node("Color", {
46 | "constant": "(R=%.6f,G=%.6f,B=%.6f,A=%.6f)"%tuple(value)
47 | })
48 | if name:
49 | n["Name"] = name
50 | return exp_list.push(n)
51 |
52 | def exp_scalar(value, exp_list):
53 | n = Node("Scalar", {
54 | # "Name": "",
55 | "constant": "%f"%value
56 | })
57 | return exp_list.push(n)
58 |
59 | def exp_texcoord(exp_list, index=0, u_tiling=1.0, v_tiling=1.0):
60 | n = Node("TextureCoordinate")
61 | n["Index"] = index
62 | n["UTiling"] = u_tiling
63 | n["VTiling"] = v_tiling
64 |
65 | pad = Node("AppendVector")
66 | pad.push(Node("0", {"expression": exp_list.push(n) }))
67 | zero = exp_scalar(0, exp_list)
68 | pad.push(Node("1", {"expression": zero }))
69 | return {"expression": exp_list.push(pad) }
70 |
71 | def exp_texcoord_node(socket, exp_list):
72 | socket_name = socket.name
73 | if socket_name == "Generated":
74 | n = Node("FunctionCall", { "Function": "/Engine/Functions/Engine_MaterialFunctions02/UVs/BoundingBoxBased_0-1_UVW"})
75 | return { "expression": exp_list.push(n) }
76 | # if socket_name == "Normal":
77 | if socket_name == "UV":
78 | return exp_texcoord(exp_list)
79 | if socket_name == "Object":
80 | n = Node("FunctionCall", { "Function": op_custom_functions["LOCAL_POSITION"]})
81 | return { "expression": exp_list.push(n) }
82 | # if socket_name == "Camera":
83 | # `position from camera in camera space (blue is camera forward, green is camera up`
84 | # if socket_name == "Window":
85 | # seems to be viewport coordinates
86 | # if socket_name == "Reflection":
87 | # direction of reflection in world coordinates
88 | log.warn("Texcoord node doesn't implement %s yet" % socket_name)
89 |
90 | def exp_tex_noise(socket, exp_list):
91 |
92 | # default if socket.name == "Fac"
93 | function_path = "/DatasmithBlenderContent/MaterialFunctions/TexNoise"
94 | out_socket = 0
95 | if socket.name == "Color":
96 | out_socket = 1
97 | n = Node("FunctionCall", { "Function": function_path})
98 | exp_1 = get_expression(socket.node.inputs['Vector'], exp_list)
99 | exp_2 = get_expression(socket.node.inputs['Scale'], exp_list)
100 | if exp_1:
101 | n.push(Node("0", exp_1))
102 | n.push(Node("1", exp_2))
103 | return { "expression": exp_list.push(n), "OutputIndex":out_socket }
104 |
105 |
106 | def exp_tex_checker(socket, exp_list):
107 | if socket.node in cached_nodes:
108 | exp = { "expression": cached_nodes[socket.node] }
109 | else:
110 | exp = exp_function_call(
111 | "/DatasmithBlenderContent/MaterialFunctions/TexChecker",
112 | exp_list=exp_list,
113 | inputs=socket.node.inputs,
114 | force_default=True,
115 | )
116 | cached_nodes[socket.node] = exp["expression"]
117 |
118 | # could be faster by comparing to constants instead?
119 | exp["OutputIndex"] = socket.node.outputs.find(socket.name)
120 |
121 | return exp
122 |
123 |
124 | def exp_uvmap(node, exp_list):
125 | channel_name = node.uv_map
126 | owner = datasmith_context["material_owner"]
127 | uv_index = 0
128 | m = owner.data
129 | if type(m) is bpy.types.Mesh:
130 | for idx, uv in enumerate(m.uv_layers):
131 | if uv.name == id:
132 | uv_index = idx
133 | return exp_texcoord(exp_list, uv_index)
134 |
135 | # instead of setting coordinates here, use coordinates when creating
136 | # the texture expression instead
137 | def exp_texture(path, name=None): # , tex_coord_exp):
138 | n = Node("Texture")
139 | if name:
140 | n["Name"] = name
141 | n["PathName"] = path
142 | #n.push(Node("Coordinates", tex_coord_exp))
143 | return n
144 |
145 | def exp_rgb_to_bw(socket, exp_list):
146 | input_exp = get_expression(socket.node.inputs[0], exp_list)
147 | n = Node("DotProduct")
148 | n.push(Node("0", input_exp))
149 | exp_1 = exp_vector( (0.2126, 0.7152, 0.0722), exp_list )
150 | n.push( Node( "1", { "expression": exp_1 } ) )
151 | dot_exp = exp_list.push(n)
152 | return { "expression": dot_exp }
153 |
154 | def exp_make_vec3(socket, exp_list):
155 | node = socket.node
156 | output = Node("FunctionCall", { "Function": "/Engine/Functions/Engine_MaterialFunctions02/Utility/MakeFloat3" })
157 | output.push(Node("0", get_expression(node.inputs[0], exp_list)))
158 | output.push(Node("1", get_expression(node.inputs[1], exp_list)))
159 | output.push(Node("2", get_expression(node.inputs[2], exp_list)))
160 | return { "expression": exp_list.push(output) }
161 |
162 | def exp_make_hsv(socket, exp_list):
163 | vec3_input = exp_make_vec3(socket, exp_list)
164 | output = Node("FunctionCall", { "Function": "/DatasmithBlenderContent/MaterialFunctions/HSV_To_RGB" })
165 | output.push(Node("0", vec3_input))
166 | return { "expression": exp_list.push(output) }
167 |
168 | def exp_break_vec3(socket, exp_list):
169 | expression_idx = -1
170 | if socket.node in cached_nodes:
171 | expression_idx = cached_nodes[socket.node]
172 | else:
173 | output = Node("FunctionCall", { "Function": "/Engine/Functions/Engine_MaterialFunctions02/Utility/BreakOutFloat3Components" })
174 | output.push(Node("0", get_expression(socket.node.inputs[0], exp_list)))
175 | expression_idx = exp_list.push(output)
176 | cached_nodes[socket.node] = expression_idx
177 |
178 | output_index = socket.node.outputs.find(socket.name) # could be faster by comparing to constants instead?
179 | return { "expression": expression_idx, "OutputIndex": output_index }
180 |
181 | def exp_break_hsv(socket, exp_list):
182 |
183 | expression_idx = -1
184 | if socket.node in cached_nodes:
185 | expression_idx = cached_nodes[socket.node]
186 | else:
187 | input = Node("FunctionCall", { "Function": "/DatasmithBlenderContent/MaterialFunctions/RGB_To_HSV" })
188 | hsv_expression_idx = input.push(Node("0", get_expression(socket.node.inputs[0], exp_list)))
189 |
190 | output = Node("FunctionCall", { "Function": "/Engine/Functions/Engine_MaterialFunctions02/Utility/BreakOutFloat3Components" })
191 | output.push(Node("0", { "expression": hsv_expression_idx }))
192 | expression_idx = exp_list.push(output)
193 | cached_nodes[socket.node] = expression_idx
194 |
195 | output_index = socket.node.outputs.find(socket.name) # could be faster by comparing to constants instead?
196 | return { "expression": expression_idx, "OutputIndex": output_index }
197 |
198 |
199 | MATH_CUSTOM_FUNCTIONS = {
200 | 'INVERSE_SQRT': (1, "/DatasmithBlenderContent/MaterialFunctions/MathInvSqrt"),
201 | 'EXPONENT': (1, "/DatasmithBlenderContent/MaterialFunctions/MathExp"),
202 | 'SINH': (1, "/DatasmithBlenderContent/MaterialFunctions/MathSinH"),
203 | 'COSH': (1, "/DatasmithBlenderContent/MaterialFunctions/MathCosH"),
204 | 'TANH': (1, "/DatasmithBlenderContent/MaterialFunctions/MathTanH"),
205 | 'MULTIPLY_ADD': (3, "/DatasmithBlenderContent/MaterialFunctions/MathMultiplyAdd"),
206 | 'COMPARE': (3, "/DatasmithBlenderContent/MaterialFunctions/MathCompare"),
207 | 'SMOOTH_MIN': (3, "/DatasmithBlenderContent/MaterialFunctions/MathSmoothMin"),
208 | 'SMOOTH_MAX': (3, "/DatasmithBlenderContent/MaterialFunctions/MathSmoothMax"),
209 | 'WRAP': (3, "/DatasmithBlenderContent/MaterialFunctions/MathWrap"),
210 | 'SNAP': (2, "/DatasmithBlenderContent/MaterialFunctions/MathSnap"),
211 | 'PINGPONG': (2, "/DatasmithBlenderContent/MaterialFunctions/MathPingPong"),
212 | }
213 |
214 | # these map 1:1 with UE4 nodes:
215 | MATH_TWO_INPUTS = {
216 | 'ADD': "Add",
217 | 'SUBTRACT': "Subtract",
218 | 'MULTIPLY': "Multiply",
219 | 'DIVIDE': "Divide",
220 | 'POWER': "Power",
221 | 'MINIMUM': "Min",
222 | 'MAXIMUM': "Max",
223 | 'MODULO': "Fmod",
224 | 'ARCTAN2': "Arctangent2",
225 | }
226 |
227 | # these use only one input in UE4
228 | MATH_ONE_INPUT = {
229 | 'SQRT': "SquareRoot",
230 | 'ABSOLUTE': "Abs",
231 | 'ROUND': "Round",
232 | 'FLOOR': "Floor",
233 | 'CEIL': "Ceil",
234 | 'FRACT': "Frac",
235 | 'SINE': "Sine",
236 | 'COSINE': "Cosine",
237 | 'TANGENT': "Tangent",
238 | 'ARCSINE': "Arcsine",
239 | 'ARCCOSINE': "Arccosine",
240 | 'ARCTANGENT': "Arctangent",
241 | 'SIGN': "Sign",
242 | 'TRUNC': "Truncate",
243 | }
244 |
245 | # these require specific implementations:
246 | MATH_CUSTOM_IMPL = {
247 | 'LOGARITHM', # ue4 only has log2 and log10
248 | 'LESS_THAN', # use UE4 If node
249 | 'GREATER_THAN', # use UE4 If node
250 | 'RADIANS',
251 | 'DEGREES',
252 | }
253 |
254 | def exp_generic(name, inputs, exp_list, force_default=False):
255 | n = Node(name)
256 | for idx, input in enumerate(inputs):
257 | input_exp = get_expression(input, exp_list, force_default)
258 | n.push(Node(str(idx), input_exp))
259 | return { "expression": exp_list.push(n) }
260 |
261 | def exp_function_call(path, inputs, exp_list, force_default=False):
262 | n = Node("FunctionCall", {"Function": path})
263 | for idx, input in enumerate(inputs):
264 | input_exp = get_expression(input, exp_list, force_default)
265 | n.push(Node(str(idx), input_exp))
266 | return { "expression": exp_list.push(n) }
267 |
268 | def exp_math(node, exp_list):
269 | op = node.operation
270 | exp = None
271 | if op in MATH_TWO_INPUTS:
272 | exp = exp_generic(
273 | name= MATH_TWO_INPUTS[op],
274 | inputs= node.inputs[:2],
275 | exp_list=exp_list,
276 | force_default=True,
277 | )
278 | elif op in MATH_ONE_INPUT:
279 | exp = exp_generic(
280 | name= MATH_ONE_INPUT[op],
281 | inputs= node.inputs[:1],
282 | exp_list=exp_list,
283 | force_default=True,
284 | )
285 | elif op in MATH_CUSTOM_FUNCTIONS:
286 | size, path = MATH_CUSTOM_FUNCTIONS[op]
287 | exp = exp_function_call(
288 | path,
289 | inputs= node.inputs[:size],
290 | exp_list=exp_list,
291 | )
292 | elif op in MATH_CUSTOM_IMPL:
293 | in_0 = get_expression(node.inputs[0], exp_list)
294 | n = None
295 | if op == 'RADIANS':
296 | n = Node("Multiply")
297 | n.push(Node("0", in_0))
298 | n.push(Node("1", { "expression": exp_scalar(math.tau / 360, exp_list)}))
299 | elif op == 'DEGREES':
300 | n = Node("Multiply")
301 | n.push(Node("0", in_0))
302 | n.push(Node("1", { "expression": exp_scalar(360 / math.tau, exp_list)}))
303 | else:
304 | # these use two inputs
305 | in_1 = get_expression(node.inputs[1], exp_list)
306 | if op == 'LOGARITHM': # take two logarithms and divide
307 | log0 = Node("Logarithm2")
308 | log0.push(Node("0", in_0))
309 | exp_0 = exp_list.push(log0)
310 | log1 = Node("Logarithm2")
311 | log1.push(Node("0", in_1))
312 | exp_1 = exp_list.push(log1)
313 | n = Node("Divide")
314 | n.push(Node("0", {"expression": exp_0}))
315 | n.push(Node("1", {"expression": exp_1}))
316 | elif op == 'LESS_THAN':
317 | n = Node("If")
318 | one = {"expression": exp_scalar(1.0, exp_list)}
319 | zero = {"expression": exp_scalar(0.0, exp_list)}
320 | n.push(Node("0", in_0)) # A
321 | n.push(Node("1", in_1)) # B
322 | n.push(Node("2", zero)) # A > B
323 | n.push(Node("3", one)) # A == B
324 | n.push(Node("4", one)) # A < B
325 | elif op == 'GREATER_THAN':
326 | n = Node("If")
327 | one = {"expression": exp_scalar(1.0, exp_list)}
328 | zero = {"expression": exp_scalar(0.0, exp_list)}
329 | n.push(Node("0", in_0)) # A
330 | n.push(Node("1", in_1)) # B
331 | n.push(Node("2", one)) # A > B
332 | n.push(Node("3", zero)) # A == B
333 | n.push(Node("4", zero)) # A < B
334 | assert n
335 | exp = { "expression": exp_list.push(n) }
336 |
337 |
338 | assert exp, "unrecognized math operation: %s" % op
339 |
340 | if getattr(node, "use_clamp", False):
341 | clamp = Node("Saturate")
342 | clamp.push(Node("0", exp))
343 | exp = { "expression": exp_list.push(clamp) }
344 | return exp
345 |
346 | # these nodes should only be built-ins (green nodes)
347 | VECT_MATH_SAME_AS_SCALAR = {
348 | 'ADD',
349 | 'SUBTRACT',
350 | 'MULTIPLY',
351 | 'DIVIDE',
352 |
353 | 'ABSOLUTE',
354 | 'MINIMUM',
355 | 'MAXIMUM',
356 | 'FLOOR',
357 | 'CEIL',
358 | 'MODULO',
359 | 'SINE',
360 | 'COSINE',
361 | 'TANGENT',
362 | }
363 |
364 |
365 | VECT_MATH_NODES = {
366 | 'CROSS_PRODUCT': (2, "CrossProduct"),
367 | 'DOT_PRODUCT': (2, "DotProduct"),
368 | 'DISTANCE': (2, "Distance"),
369 | 'NORMALIZE': (1, "Normalize"),
370 | 'FRACTION': (1, "Frac"),
371 | }
372 | VECT_MATH_FUNCTIONS = { # tuples are (input_count, path)
373 |
374 | 'WRAP': (3, "/DatasmithBlenderContent/MaterialFunctions/VectWrap"),
375 | 'SNAP': (2, "/DatasmithBlenderContent/MaterialFunctions/VectSnap"),
376 | 'PROJECT': (2, "/DatasmithBlenderContent/MaterialFunctions/VectProject"),
377 | 'REFLECT': (2, "/DatasmithBlenderContent/MaterialFunctions/VectReflect"),
378 | }
379 |
380 | def exp_vect_math(node, exp_list):
381 | node_op = node.operation
382 | if node_op in VECT_MATH_SAME_AS_SCALAR:
383 | return exp_math(node, exp_list)
384 | elif node_op in VECT_MATH_NODES:
385 | size, name = VECT_MATH_NODES[node_op]
386 | return exp_generic(
387 | name=name,
388 | inputs=node.inputs[:size],
389 | exp_list=exp_list,
390 | force_default=True,
391 | )
392 | elif node_op in VECT_MATH_FUNCTIONS:
393 | size, path = VECT_MATH_FUNCTIONS[node_op]
394 | return exp_function_call(
395 | path,
396 | inputs= node.inputs[:size],
397 | exp_list=exp_list,
398 | force_default=True,
399 | )
400 | elif node_op == 'SCALE':
401 | return exp_generic(
402 | name= "Multiply",
403 | inputs= (node.inputs[0], node.inputs[3]),
404 | exp_list=exp_list,
405 | force_default=True,
406 | )
407 | elif node_op == 'LENGTH':
408 | n = Node("Distance")
409 | n.push(Node("0", get_expression(node.inputs[0], exp_list) ))
410 | n.push(Node("1", { "expression": exp_vector((0,0,0), exp_list) } ))
411 | return { "expression": exp_list.push(n) }
412 |
413 | log.error("VECT_MATH node operation:%s not found" % node_op)
414 |
415 | # TODO: make test cases for all math nodes
416 |
417 | def exp_gamma(node, exp_list):
418 | n = Node(MATH_TWO_INPUTS['POWER'])
419 | exp_0 = get_expression(node.inputs["Color"], exp_list)
420 | n.push(Node("0", exp_0))
421 | exp_1 = get_expression(node.inputs["Gamma"], exp_list)
422 | n.push(Node("1", exp_1))
423 | return {"expression": exp_list.push(n)}
424 |
425 | op_map_color = {
426 | # MIX is handled manually
427 | 'DARKEN': "/Engine/Functions/Engine_MaterialFunctions03/Blends/Blend_Darken",
428 | # MULTIPLY is handled in MATH_TWO_INPUTS
429 | 'BURN': "/Engine/Functions/Engine_MaterialFunctions03/Blends/Blend_ColorBurn",
430 | # TODO: check for blender implementation of burn, it could mean this:
431 | #'BURN': "/Engine/Functions/Engine_MaterialFunctions03/Blends/Blend_LinearBurn",
432 | 'LIGHTEN': "/Engine/Functions/Engine_MaterialFunctions03/Blends/Blend_Lighten",
433 | 'SCREEN': "/Engine/Functions/Engine_MaterialFunctions03/Blends/Blend_Screen",
434 | 'DODGE': "/Engine/Functions/Engine_MaterialFunctions03/Blends/Blend_ColorDodge",
435 | 'OVERLAY': "/Engine/Functions/Engine_MaterialFunctions03/Blends/Blend_Overlay",
436 | # ADD is handled in MATH_TWO_INPUTS
437 | 'SOFT_LIGHT': "/Engine/Functions/Engine_MaterialFunctions03/Blends/Blend_SoftLight",
438 | 'LINEAR_LIGHT': "/Engine/Functions/Engine_MaterialFunctions03/Blends/Blend_LinearLight",
439 | 'DIFFERENCE': "/Engine/Functions/Engine_MaterialFunctions03/Blends/Blend_Difference",
440 | # SUBTRACT is handled in MATH_TWO_INPUTS
441 | # DIVIDE is handled in MATH_TWO_INPUTS
442 | 'HUE': "/DatasmithBlenderContent/MaterialFunctions/Blend_Hue",
443 | 'SATURATION': "/DatasmithBlenderContent/MaterialFunctions/Blend_Saturation",
444 | 'COLOR': "/DatasmithBlenderContent/MaterialFunctions/Blend_Color",
445 | 'VALUE': "/DatasmithBlenderContent/MaterialFunctions/Blend_Value",
446 | }
447 |
448 | def exp_blend(exp_0, exp_1, blend_type, exp_list):
449 | if blend_type == 'MIX':
450 | return exp_1
451 | n = None
452 | if blend_type in {'ADD', 'SUBTRACT', 'MULTIPLY', 'DIVIDE'}:
453 | n = Node(MATH_TWO_INPUTS[blend_type])
454 | else:
455 | n = Node("FunctionCall", { "Function": op_map_color[blend_type]})
456 | assert n
457 | n.push(Node("0", exp_0))
458 | n.push(Node("1", exp_1))
459 | return {"expression": exp_list.push(n)}
460 |
461 | def exp_mixrgb(node, exp_list):
462 | exp_1 = get_expression(node.inputs['Color1'], exp_list)
463 | exp_2 = get_expression(node.inputs['Color2'], exp_list)
464 | # TODO: optimize case fac is disconnected and equals one (or zero)
465 | # TODO: add logic for clamp
466 |
467 | exp_result = exp_blend(exp_1, exp_2, node.blend_type, exp_list)
468 |
469 | lerp = Node("LinearInterpolate")
470 | lerp.push(Node("0", exp_1))
471 | lerp.push(Node("1", exp_result))
472 | exp_fac = get_expression(node.inputs['Fac'], exp_list)
473 | lerp.push(Node("2", exp_fac))
474 |
475 | return exp_list.push(lerp)
476 |
477 | op_custom_functions = {
478 | "BRIGHTCONTRAST": "/DatasmithBlenderContent/MaterialFunctions/BrightContrast",
479 | "COLOR_RAMP": "/DatasmithBlenderContent/MaterialFunctions/ColorRamp",
480 | "CURVE_RGB": "/DatasmithBlenderContent/MaterialFunctions/RGBCurveLookup2",
481 | "FRESNEL": "/DatasmithBlenderContent/MaterialFunctions/BlenderFresnel",
482 | "HUE_SAT": "/DatasmithBlenderContent/MaterialFunctions/AdjustHSV",
483 | "LAYER_WEIGHT": "/DatasmithBlenderContent/MaterialFunctions/LayerWeight",
484 | "LOCAL_POSITION": "/DatasmithBlenderContent/MaterialFunctions/BlenderLocalPosition",
485 | "MAPPING_POINT2D": "/DatasmithBlenderContent/MaterialFunctions/MappingPoint2D_2",
486 | "MAPPING_POINT3D": "/DatasmithBlenderContent/MaterialFunctions/MappingPoint3D",
487 | "MAPPING_TEX2D": "/DatasmithBlenderContent/MaterialFunctions/MappingTexture2D_2",
488 | "MAPPING_TEX3D": "/DatasmithBlenderContent/MaterialFunctions/MappingTexture3D",
489 | "MAPPING_NORMAL": "/DatasmithBlenderContent/MaterialFunctions/MappingNormal",
490 | "NORMAL_FROM_HEIGHT": "/Engine/Functions/Engine_MaterialFunctions03/Procedurals/NormalFromHeightmap",
491 | "WORLD_POSITION": "/DatasmithBlenderContent/MaterialFunctions/BlenderWorldPosition",
492 | }
493 |
494 |
495 |
496 | def exp_generic_function(node, exp_list, node_type, socket_names):
497 | n = Node("FunctionCall", { "Function": op_custom_functions[node_type]})
498 | for idx, socket_name in enumerate(socket_names):
499 | input_expression = get_expression(node.inputs[socket_name], exp_list)
500 | n.push(Node(str(idx), input_expression))
501 | return {"expression": exp_list.push(n) }
502 |
503 | def exp_bright_contrast(node, exp_list):
504 | return exp_generic_function(node, exp_list, 'BRIGHTCONTRAST', ('Color', 'Bright', 'Contrast'))
505 |
506 | def exp_hsv(node, exp_list):
507 | n = Node("FunctionCall", { "Function": op_custom_functions["HUE_SAT"]})
508 | exp_hue = get_expression(node.inputs['Hue'], exp_list)
509 | n.push(Node("0", exp_hue))
510 | exp_sat = get_expression(node.inputs['Saturation'], exp_list)
511 | n.push(Node("1", exp_sat))
512 | exp_value = get_expression(node.inputs['Value'], exp_list)
513 | n.push(Node("2", exp_value))
514 | exp_fac = get_expression(node.inputs['Fac'], exp_list)
515 | n.push(Node("3", exp_fac))
516 | exp_color = get_expression(node.inputs['Color'], exp_list)
517 | n.push(Node("4", exp_color))
518 | return exp_list.push(n)
519 |
520 | def exp_invert(node, exp_list):
521 | n = Node("OneMinus")
522 | exp_color = get_expression(node.inputs['Color'], exp_list)
523 | n.push(Node("0", exp_color))
524 | invert_exp = exp_list.push(n)
525 |
526 | blend = Node("LinearInterpolate")
527 | exp_fac = get_expression(node.inputs['Fac'], exp_list)
528 | blend.push(Node("0", exp_color))
529 | blend.push(Node("1", {"expression": invert_exp}))
530 | blend.push(Node("2", exp_fac))
531 |
532 | return exp_list.push(blend)
533 |
534 | def exp_mapping(node, exp_list):
535 | if node.vector_type == 'NORMAL':
536 | mapping_type = 'MAPPING_NORMAL'
537 | else:
538 | node_input_rot = node.inputs["Rotation"]
539 | default_rot = node_input_rot.default_value
540 | uses_3d_rot = default_rot.x != 0 or default_rot.y != 0
541 | use_2d_node = not node_input_rot.links and not uses_3d_rot
542 | if node.vector_type == 'POINT' or node.vector_type == 'VECTOR':
543 | if use_2d_node:
544 | mapping_type = 'MAPPING_POINT2D'
545 | else:
546 | mapping_type = 'MAPPING_POINT3D'
547 | elif node.vector_type == 'TEXTURE':
548 | if use_2d_node:
549 | mapping_type = 'MAPPING_TEX2D'
550 | else:
551 | mapping_type = 'MAPPING_TEX3D'
552 |
553 | n = Node("FunctionCall", { "Function": op_custom_functions[mapping_type]})
554 |
555 | input_vector = get_expression(node.inputs['Vector'], exp_list)
556 | input_location = get_expression(node.inputs['Location'], exp_list)
557 | input_rotation = get_expression(node.inputs['Rotation'], exp_list)
558 | input_scale = get_expression(node.inputs['Scale'], exp_list)
559 | n.push(Node("0", input_vector))
560 | n.push(Node("1", input_location))
561 | n.push(Node("2", input_rotation))
562 | n.push(Node("3", input_scale))
563 |
564 | return {"expression": exp_list.push(n)}
565 | def exp_normal_map(socket, exp_list):
566 | node_input = socket.node.inputs['Color']
567 | # hack: is it safe to assume that everything under here is normal?
568 | # maybe not, because it could be masks to mix normals
569 | # most certainly, these wouldn't be colors (so should be non-srgb)
570 | push_context("NORMAL")
571 | return_exp = get_expression(node_input, exp_list)
572 | pop_context()
573 |
574 | strength_input = socket.node.inputs["Strength"]
575 | if strength_input.links or strength_input.default_value != 1.0:
576 | node_strength = Node("FunctionCall", {"Function": "/DatasmithBlenderContent/MaterialFunctions/NormalStrength"})
577 | node_strength.push(Node("0", return_exp))
578 | node_strength.push(Node("1", get_expression(strength_input, exp_list)))
579 | return_exp = { "expression": exp_list.push(node_strength) }
580 | return return_exp
581 |
582 |
583 | def exp_new_geometry(socket, exp_list):
584 | socket_name = socket.name
585 | if socket_name == "Position":
586 | blend = Node("FunctionCall", { "Function": op_custom_functions["WORLD_POSITION"]})
587 | n = exp_list.push(blend)
588 | return { "expression": n }
589 | if socket_name == "Normal":
590 | blend = Node("PixelNormalWS")
591 | n = exp_list.push(blend)
592 | return { "expression": n }
593 | if socket_name == "Tangent":
594 | blend = Node("VertexTangentWS")
595 | n = exp_list.push(blend)
596 | return { "expression": n }
597 | if socket_name == "True Normal":
598 | blend = Node("VertexNormalWS")
599 | n = exp_list.push(blend)
600 | return { "expression": n }
601 | # if socket_name == "Incoming":
602 | # this would be cameraposition - worldposition
603 | # if socket_name == "Parametric":
604 | # this appears to be per-triangle barycentric coordinates
605 | # if socket_name == "Backfacing":
606 | # exactly what it says, I thought UE4 had this
607 | if socket_name == "Pointiness":
608 | exp = exp_scalar(0, exp_list)
609 | return {"expression": exp}
610 | # if socket_name == "Random Per Island":
611 | log.error("Node NEW_GEOMETRY has unhanded socket:%s" % socket_name)
612 |
613 |
614 | def exp_texture_coordinates(socket, exp_list):
615 | socket_name = socket.name
616 | if socket_name == "Position":
617 | blend = Node("FunctionCall", { "Function": op_custom_functions["WORLD_POSITION"]})
618 | n = exp_list.push(blend)
619 | return { "expression": n }
620 | if socket_name == "Normal":
621 | blend = Node("PixelNormalWS")
622 | n = exp_list.push(blend)
623 | return { "expression": n }
624 | if socket_name == "Tangent":
625 | blend = Node("VertexTangentWS")
626 | n = exp_list.push(blend)
627 | return { "expression": n }
628 | if socket_name == "True Normal":
629 | blend = Node("VertexNormalWS")
630 | n = exp_list.push(blend)
631 | return { "expression": n }
632 | # if socket_name == "Incoming":
633 | # this would be cameraposition - worldposition
634 | # if socket_name == "Parametric":
635 | # this appears to be per-triangle barycentric coordinates
636 | # if socket_name == "Backfacing":
637 | # exactly what it says, I thought UE4 had this
638 | if socket_name == "Pointiness":
639 | exp = exp_scalar(0, exp_list)
640 | return {"expression": exp}
641 | # if socket_name == "Random Per Island":
642 | log.error("Node NEW_GEOMETRY has unhanded socket:%s" % socket_name)
643 |
644 |
645 | def exp_layer_weight(socket, exp_list):
646 | expr = None
647 | if socket.node in reverse_expressions:
648 | expr = reverse_expressions[socket.node]
649 | else:
650 | exp_blend = get_expression(socket.node.inputs['Blend'], exp_list)
651 | n = Node("FunctionCall", { "Function": op_custom_functions['LAYER_WEIGHT']})
652 | n.push(Node("0", exp_blend))
653 | expr = exp_list.push(n)
654 | reverse_expressions[socket.node] = expr
655 |
656 | log.warn("layer weight missing normal input")
657 |
658 | if socket.name == "Fresnel":
659 | return {"expression": expr, "OutputIndex": 0}
660 | elif socket.name == "Facing":
661 | return {"expression": expr, "OutputIndex": 1}
662 | log.error("LAYER_WEIGHT node from unknown socket")
663 | return {"expression": expr, "OutputIndex": 0}
664 |
665 | def exp_light_path(socket, exp_list):
666 | log.warn("incomplete node implementation: LIGHT_PATH")
667 | n = exp_scalar(1, exp_list)
668 | return {"expression": n}
669 |
670 |
671 | def exp_object_info(socket, exp_list):
672 | field = socket.name
673 | if field == "Location":
674 | # TODO: check if we need to transform these to blender space
675 | exp = exp_list.push(Node("ObjectPositionWS"))
676 | elif field == "Random":
677 | exp = exp_list.push(Node("PerInstanceRandom"))
678 | elif field == "Object Index":
679 | log.warning("Node Object Info>Object Index translated to random as it is used to randomize too")
680 | exp = exp_list.push(Node("PerInstanceRandom"))
681 | else:
682 | log.error("Can't write Material node 'Object Info' field:%s" % field)
683 | exp = exp_scalar(0, exp_list)
684 |
685 | return {"expression": exp, "OutputIndex": 0}
686 |
687 |
688 | DATASMITH_TEXTURE_SIZE = 1024
689 |
690 | def add_material_curve2(curve):
691 |
692 | # do some material curves initialization
693 | material_curves = datasmith_context["material_curves"]
694 | if material_curves is None:
695 | material_curves = np.zeros((DATASMITH_TEXTURE_SIZE, DATASMITH_TEXTURE_SIZE, 4))
696 | datasmith_context["material_curves"] = material_curves
697 | datasmith_context["material_curves_count"] = 0
698 |
699 | mat_curve_idx = datasmith_context["material_curves_count"]
700 | datasmith_context["material_curves_count"] = mat_curve_idx + 1
701 | log.info("writing curve:%s" % mat_curve_idx)
702 |
703 | # write texture from top
704 | row_idx = DATASMITH_TEXTURE_SIZE - mat_curve_idx - 1
705 | values = material_curves[row_idx]
706 | factor = DATASMITH_TEXTURE_SIZE - 1
707 |
708 | # check for curve type, do sampling
709 | curve_type = type(curve)
710 | if curve_type == bpy.types.ColorRamp:
711 | for idx in range(DATASMITH_TEXTURE_SIZE):
712 | values[idx] = curve.evaluate(idx/factor)
713 |
714 | elif curve_type == bpy.types.CurveMapping:
715 | curves = curve.curves
716 |
717 | position = 0
718 | for idx in range(DATASMITH_TEXTURE_SIZE):
719 | position = idx/factor
720 | values[idx, 0] = curve.evaluate(curves[0], position)
721 | values[idx, 1] = curve.evaluate(curves[1], position)
722 | values[idx, 2] = curve.evaluate(curves[2], position)
723 | values[idx, 3] = curve.evaluate(curves[3], position)
724 |
725 | return mat_curve_idx
726 |
727 | def exp_blackbody(from_node, exp_list):
728 | n = Node("BlackBody")
729 | exp_0 = get_expression(from_node.inputs[0], exp_list)
730 | n.push(Node("0", exp_0))
731 | exp = exp_list.push(n)
732 | return {"expression": exp}
733 |
734 | def exp_color_ramp(from_node, exp_list):
735 | ramp = from_node.color_ramp
736 |
737 | idx = add_material_curve2(ramp)
738 |
739 | level = get_expression(from_node.inputs['Fac'], exp_list)
740 |
741 | curve_idx = exp_scalar(idx, exp_list)
742 | compatibility_mode = datasmith_context["compatibility_mode"]
743 | if compatibility_mode:
744 | pixel_offset = exp_scalar(0.5, exp_list)
745 | vertical_res = exp_scalar(1/DATASMITH_TEXTURE_SIZE, exp_list) # curves texture size
746 | n = Node("Add")
747 | n.push(Node("0", {"expression": curve_idx}))
748 | n.push(Node("1", {"expression": pixel_offset}))
749 | curve_y = exp_list.push(n)
750 | n2 = Node("Multiply")
751 | n2.push(Node("0", {"expression": curve_y}))
752 | n2.push(Node("1", {"expression": vertical_res}))
753 | curve_v = exp_list.push(n2)
754 |
755 | n3 = Node("AppendVector")
756 | n3.push(Node("0", level))
757 | n3.push(Node("1", {"expression": curve_v}))
758 | tex_coord = exp_list.push(n3)
759 |
760 | texture_exp = exp_texture("datasmith_curves", "datasmith_curves")
761 | texture_exp.push(Node("Coordinates", {"expression":tex_coord}))
762 |
763 | return exp_list.push(texture_exp)
764 |
765 | else:
766 | vertical_res = exp_scalar(DATASMITH_TEXTURE_SIZE, exp_list) # curves texture size
767 | texture = exp_texture_object("datasmith_curves", exp_list)
768 |
769 | lookup = Node("FunctionCall", { "Function": op_custom_functions["COLOR_RAMP"]})
770 | lookup.push(Node("0", level))
771 | lookup.push(Node("1", {"expression": curve_idx } ))
772 | lookup.push(Node("2", {"expression": vertical_res } ))
773 | lookup.push(Node("3", {"expression": texture } ))
774 | result = exp_list.push(lookup)
775 |
776 | return result
777 |
778 | def exp_curvergb(from_node, exp_list):
779 | mapping = from_node.mapping
780 | mapping.initialize()
781 |
782 | idx = add_material_curve2(mapping)
783 |
784 | factor = get_expression(from_node.inputs['Fac'], exp_list)
785 | color = get_expression(from_node.inputs['Color'], exp_list)
786 |
787 | curve_idx = exp_scalar(idx, exp_list)
788 | vertical_res = exp_scalar(DATASMITH_TEXTURE_SIZE, exp_list) # curves texture size
789 |
790 | texture = exp_texture_object("datasmith_curves", exp_list)
791 |
792 | lookup = Node("FunctionCall", { "Function": op_custom_functions["CURVE_RGB"]})
793 | lookup.push(Node("0", color))
794 | lookup.push(Node("1", {"expression": curve_idx}))
795 | lookup.push(Node("2", {"expression": vertical_res}))
796 | lookup.push(Node("3", {"expression": texture}))
797 | blend_exp = exp_list.push(lookup)
798 |
799 |
800 | blend = Node("LinearInterpolate")
801 | blend.push(Node("0", color))
802 | blend.push(Node("1", {"expression": blend_exp}))
803 | blend.push(Node("2", factor))
804 | result = exp_list.push(blend)
805 |
806 | return result
807 |
808 | def exp_texture_object(name, exp_list):
809 | n = Node("TextureObject")
810 | n.push(Node("0", {
811 | "name": "Texture",
812 | "type": "Texture",
813 | "val": name,
814 | }))
815 | return exp_list.push(n)
816 |
817 |
818 | def exp_bump(node, exp_list):
819 | height_input = node.inputs['Height']
820 | if height_input.links:
821 | from_node = height_input.links[0].from_node
822 | if from_node.type == 'TEX_IMAGE':
823 | image = from_node.image
824 | name = sanitize_name(image.name)
825 |
826 | # ensure that texture is exported
827 | get_or_create_texture(name, image)
828 |
829 | image_object = exp_texture_object(name, exp_list)
830 | bump_node = Node("FunctionCall", { "Function": op_custom_functions["NORMAL_FROM_HEIGHT"]})
831 | bump_node.push(Node("0", {"expression": image_object}))
832 | bump_node.push(Node("1", get_expression(node.inputs['Strength'], exp_list)))
833 | bump_node.push(Node("2", get_expression(node.inputs['Distance'], exp_list)))
834 | bump_node.push(Node("3", get_expression(from_node.inputs['Vector'], exp_list)))
835 | exp = exp_list.push(bump_node)
836 | return {"expression": exp}
837 |
838 | else:
839 | log.warn("trying to export bump node, but input is not an image")
840 | else:
841 | log.warn("trying to export bump node without connections")
842 |
843 |
844 | group_context = {}
845 | def exp_group(socket, exp_list):
846 | node = socket.node
847 | global group_context
848 | global reverse_expressions
849 | global cached_nodes
850 | new_context = {}
851 | new_cached_nodes = {}
852 | for input in node.inputs:
853 | new_context[input.name] = get_expression(input, exp_list)
854 |
855 | previous_reverse = reverse_expressions
856 | reverse_expressions = {}
857 | previous_context = group_context
858 | previous_cached_nodes = cached_nodes
859 | group_context = new_context
860 | cached_nodes = new_cached_nodes
861 |
862 | # now traverse the inner graph
863 | output_name = socket.name
864 |
865 | node_tree = node.node_tree
866 |
867 | # search for active output node:
868 | output_node = None
869 | for node in node_tree.nodes:
870 | if type(node) == bpy.types.NodeGroupOutput:
871 | if node.is_active_output or output_node is None:
872 | output_node = node
873 |
874 | # TODO: handle case when output_node is None
875 |
876 | inner_socket = output_node.inputs[output_name]
877 | inner_exp = get_expression(inner_socket, exp_list)
878 |
879 | group_context = previous_context
880 | cached_nodes = previous_cached_nodes
881 | reverse_expressions = previous_reverse
882 | return inner_exp
883 |
884 | def exp_group_input(socket, exp_list):
885 | outer_expression = group_context[socket.name]
886 | return outer_expression
887 | def exp_attribute(socket, exp_list):
888 | exp = exp_list.push(Node("VertexColor"))
889 | ret = {"expression": exp, "OutputIndex": 0}
890 | # average channels if socket is Fac
891 | if socket.name == "Fac":
892 | #TODO: check if we should do some colorimetric aware convertion to grayscale
893 | n = Node("DotProduct")
894 | n.push(Node("0", ret))
895 | exp_1 = exp_vector((0.333333, 0.333333, 0.333333), exp_list)
896 | n.push(Node("1", {"expression": exp_1}))
897 | dot_exp = exp_list.push(n)
898 | ret = {"expression": dot_exp}
899 | return ret
900 |
901 | def exp_vertex_color(socket, exp_list):
902 | exp = exp_list.push(Node("VertexColor"))
903 | if socket.name == "Color":
904 | return {"expression": exp, "OutputIndex": 0}
905 | elif socket.name == "Alpha":
906 | return {"expression": exp, "OutputIndex": 4}
907 |
908 | def exp_fresnel(node, exp_list):
909 | n = Node("FunctionCall", { "Function": op_custom_functions["FRESNEL"]})
910 | exp_ior = get_expression(node.inputs['IOR'], exp_list)
911 | n.push(Node("0", exp_ior))
912 | return exp_list.push(n)
913 |
914 |
915 | context_stack = []
916 | def push_context(context):
917 | context_stack.append(context)
918 |
919 | def pop_context():
920 | context_stack.pop()
921 |
922 | def get_context():
923 | if context_stack:
924 | return context_stack[-1]
925 |
926 |
927 | expression_log_prefix = ""
928 | def get_expression(field, exp_list, force_default=False):
929 | # this may return none for fields without default value
930 | # most of the time blender doesn't have default value for vector
931 | # node inputs, but it does for scalars and colors
932 | # TODO: check which cases we should be careful
933 | global expression_log_prefix
934 | field_path = f"{field.node.name}/{field.name}:{field.type}"
935 | log.debug(expression_log_prefix + field_path)
936 |
937 | if not field.links:
938 | if field.type == 'VALUE':
939 | exp = exp_scalar(field.default_value, exp_list)
940 | return {"expression": exp, "OutputIndex": 0}
941 | elif field.type == 'RGBA':
942 | exp = exp_color(field.default_value, exp_list)
943 | return {"expression": exp, "OutputIndex": 0}
944 | elif field.type == 'VECTOR':
945 | use_vector_default = force_default or type(field.default_value) in {Vector, Euler}
946 | if use_vector_default:
947 | exp = exp_vector(field.default_value, exp_list)
948 | return {"expression": exp, "OutputIndex": 0}
949 | elif field.type == 'SHADER':
950 | # same as holdout shader
951 | bsdf = {
952 | "BaseColor": {"expression": exp_scalar(0.0, exp_list)},
953 | "Roughness": {"expression": exp_scalar(1.0, exp_list)},
954 | }
955 | return bsdf
956 | log.debug("field has no links, and no default value " + str(field))
957 | return None
958 |
959 | prev_prefix = expression_log_prefix
960 | expression_log_prefix += "| "
961 | return_exp = get_expression_inner(field, exp_list)
962 | expression_log_prefix = prev_prefix
963 |
964 | # if a color output is connected to a scalar input, average by using dot product
965 | if field.type == 'VALUE':
966 | other_output = field.links[0].from_socket
967 | if other_output.type == 'RGBA' or other_output.type == 'VECTOR':
968 | #TODO: check if we should do some colorimetric aware convertion to grayscale
969 | n = Node("DotProduct")
970 | exp_0 = return_exp
971 | n.push(Node("0", exp_0))
972 | exp_1 = exp_vector((0.333333, 0.333333, 0.333333), exp_list)
973 | n.push(Node("1", {"expression": exp_1}))
974 | dot_exp = exp_list.push(n)
975 | return_exp = {"expression": dot_exp}
976 |
977 | socket = field.links[0].from_socket
978 | reverse_expressions[socket] = return_exp
979 |
980 | log.debug("%send field:%s = %s" % (expression_log_prefix, field_path, return_exp))
981 |
982 | return return_exp
983 |
984 | def get_expression_inner(field, exp_list):
985 |
986 | node = field.links[0].from_node
987 | socket = field.links[0].from_socket
988 | log.debug(f"{expression_log_prefix} get_expression_inner {node.name} {socket.name}")
989 | # if this node is already exported, connect to that instead
990 | # I am considering in
991 | if socket in reverse_expressions:
992 | return reverse_expressions[socket]
993 |
994 | # The cases are ordered like in blender Add menu, others first, shaders second, then the rest
995 |
996 | # these are handled first as these can refer bsdfs
997 | if node.type == 'GROUP':
998 | # exp = exp_group(node, exp_list)
999 | # as exp_group can output shaders (dicts with basecolor/roughness)
1000 | # or other types of values (dicts with expression:)
1001 | # it may be better to return as is and handle internally
1002 | return exp_group(socket, exp_list)# TODO node trees can have multiple outputs
1003 |
1004 | if node.type == 'GROUP_INPUT':
1005 | return exp_group_input(socket, exp_list)
1006 |
1007 | if node.type == 'REROUTE':
1008 | return get_expression(node.inputs['Input'], exp_list)
1009 |
1010 | # Shader nodes return a dictionary
1011 | bsdf = None
1012 | if node.type == 'BSDF_PRINCIPLED':
1013 | bsdf = {
1014 | "BaseColor": get_expression(node.inputs['Base Color'], exp_list),
1015 | "Metallic": get_expression(node.inputs['Metallic'], exp_list),
1016 | "Roughness": get_expression(node.inputs['Roughness'], exp_list),
1017 | "Specular": get_expression(node.inputs['Specular'], exp_list),
1018 | }
1019 |
1020 | # only add opacity if transmission != 0
1021 | transmission_field = node.inputs['Transmission']
1022 | add_transmission = False
1023 | if len(transmission_field.links) != 0:
1024 | add_transmission = True
1025 | elif transmission_field.default_value != 0:
1026 | add_transmission = True
1027 | if add_transmission:
1028 | n = Node("OneMinus")
1029 | exp_transmission = get_expression(node.inputs['Transmission'], exp_list)
1030 | n.push(Node("0", exp_transmission))
1031 | exp_opacity = {"expression": exp_list.push(n)}
1032 | bsdf['Opacity'] = exp_opacity
1033 | if node.type == 'EEVEE_SPECULAR':
1034 | log.warn("EEVEE_SPECULAR incomplete implementation")
1035 | bsdf = {
1036 | "BaseColor": get_expression(node.inputs['Base Color'], exp_list),
1037 | "Roughness": get_expression(node.inputs['Roughness'], exp_list),
1038 | }
1039 |
1040 | elif node.type == 'BSDF_DIFFUSE':
1041 | bsdf = {
1042 | "BaseColor": get_expression(node.inputs['Color'], exp_list),
1043 | "Roughness": {"expression": exp_scalar(1.0, exp_list)},
1044 | "Metallic": {"expression": exp_scalar(0.0, exp_list)},
1045 | }
1046 | elif node.type == 'BSDF_TOON':
1047 | log.warn("BSDF_TOON incomplete implementation")
1048 | bsdf = {
1049 | "BaseColor": get_expression(node.inputs['Color'], exp_list),
1050 | "Roughness": {"expression": exp_scalar(1.0, exp_list)},
1051 | "Metallic": {"expression": exp_scalar(0.0, exp_list)},
1052 | }
1053 | elif node.type == 'BSDF_GLOSSY':
1054 | bsdf = {
1055 | "BaseColor": get_expression(node.inputs['Color'], exp_list),
1056 | "Roughness": get_expression(node.inputs['Roughness'], exp_list),
1057 | "Metallic": {"expression": exp_scalar(1.0, exp_list)},
1058 | }
1059 | elif node.type == 'BSDF_VELVET':
1060 | log.warn("BSDF_VELVET incomplete implementation")
1061 | bsdf = {
1062 | "BaseColor": get_expression(node.inputs['Color'], exp_list),
1063 | "Roughness": {"expression": exp_scalar(1.0, exp_list)},
1064 | }
1065 | elif node.type == 'BSDF_TRANSPARENT':
1066 | log.warn("BSDF_TRANSPARENT incomplete implementation")
1067 | bsdf = {
1068 | "BaseColor": get_expression(node.inputs['Color'], exp_list),
1069 | "Refraction": {"expression": exp_scalar(1.0, exp_list)},
1070 | "Opacity": {"expression": exp_scalar(0.0, exp_list)},
1071 | }
1072 | elif node.type == 'BSDF_TRANSLUCENT':
1073 | log.warn("BSDF_TRANSLUCENT incomplete implementation")
1074 | bsdf = {
1075 | "BaseColor": get_expression(node.inputs['Color'], exp_list),
1076 | }
1077 | elif node.type == 'BSDF_GLASS':
1078 | log.warn("BSDF_GLASS incomplete implementation")
1079 | bsdf = {
1080 | "BaseColor": get_expression(node.inputs['Color'], exp_list),
1081 | "Metallic": { "expression": exp_scalar(1, exp_list) },
1082 | "Roughness": get_expression(node.inputs['Roughness'], exp_list),
1083 | "Refraction": get_expression(node.inputs['IOR'], exp_list),
1084 | "Opacity": {"expression": exp_scalar(0.5, exp_list)},
1085 | }
1086 | elif node.type == 'BSDF_HAIR':
1087 | log.warn("BSDF_HAIR incomplete implementation")
1088 | bsdf = {
1089 | "BaseColor": get_expression(node.inputs['Color'], exp_list),
1090 | "Roughness": {"expression": exp_scalar(0.5, exp_list)},
1091 | }
1092 | elif node.type == 'SUBSURFACE_SCATTERING':
1093 | log.warn("node SUBSURFACE_SCATTERING incomplete implementation")
1094 | bsdf = {
1095 | "BaseColor": get_expression(node.inputs['Color'], exp_list)
1096 | }
1097 | elif node.type == 'BSDF_REFRACTION':
1098 | log.warn("BSDF_REFRACTION incomplete implementation")
1099 | bsdf = {
1100 | "BaseColor": get_expression(node.inputs['Color'], exp_list),
1101 | "Roughness": get_expression(node.inputs['Roughness'], exp_list),
1102 | "Refraction": get_expression(node.inputs['IOR'], exp_list),
1103 | "Opacity": {"expression": exp_scalar(0.5, exp_list)},
1104 | }
1105 | elif node.type == 'BSDF_ANISOTROPIC':
1106 | log.warn("BSDF_ANISOTROPIC incomplete implementation")
1107 | bsdf = {
1108 | "BaseColor": get_expression(node.inputs['Color'], exp_list),
1109 | "Roughness": get_expression(node.inputs['Roughness'], exp_list),
1110 | # TODO: read inputs 'Anisotropy' and 'Rotation' and 'Tangent'
1111 | }
1112 |
1113 |
1114 |
1115 | if node.type == 'EMISSION':
1116 | mult = Node("Multiply")
1117 | mult.push(Node("0", get_expression(node.inputs['Color'], exp_list)))
1118 | mult.push(Node("1", get_expression(node.inputs['Strength'], exp_list)))
1119 | mult_exp = exp_list.push(mult)
1120 | return {
1121 | "EmissiveColor": {"expression": mult_exp}
1122 | }
1123 |
1124 | if node.type == 'HOLDOUT':
1125 | return {
1126 | "BaseColor": {"expression": exp_scalar(0.0, exp_list)},
1127 | "Roughness": {"expression": exp_scalar(1.0, exp_list)},
1128 | }
1129 |
1130 | if node.type == 'ADD_SHADER':
1131 | expressions = get_expression(node.inputs[0], exp_list)
1132 | assert expressions
1133 |
1134 | expressions1 = get_expression(node.inputs[1], exp_list)
1135 | assert expressions1
1136 | for name, exp in expressions1.items():
1137 |
1138 | if name in expressions:
1139 | n = Node("Add")
1140 | n.push(Node("0", expressions[name]))
1141 | n.push(Node("1", exp))
1142 | expressions[name] = {"expression":exp_list.push(n)}
1143 | else:
1144 | expressions[name] = exp
1145 | return expressions
1146 | if node.type == 'MIX_SHADER':
1147 | expressions = get_expression(node.inputs[1], exp_list)
1148 | assert expressions
1149 |
1150 | expressions1 = get_expression(node.inputs[2], exp_list)
1151 | assert expressions1
1152 |
1153 | if ("Opacity" in expressions) or ("Opacity" in expressions1):
1154 | # if there is opacity in any, both should have opacity
1155 | if "Opacity" not in expressions:
1156 | expressions["Opacity"] = {"expression": exp_scalar(1, exp_list)}
1157 | if "Opacity" not in expressions1:
1158 | expressions1["Opacity"] = {"expression": exp_scalar(1, exp_list)}
1159 | fac_expression = get_expression(node.inputs['Fac'], exp_list)
1160 | for name, exp in expressions1.items():
1161 | if name in expressions:
1162 | n = Node("LinearInterpolate")
1163 | n.push(Node("0", expressions[name]))
1164 | n.push(Node("1", exp))
1165 | n.push(Node("2", fac_expression))
1166 | expressions[name] = {"expression":exp_list.push(n)}
1167 | else:
1168 | expressions[name] = exp
1169 | return expressions
1170 |
1171 |
1172 | if field.type == 'SHADER':
1173 |
1174 | if bsdf:
1175 | if "Normal" in node.inputs:
1176 | normal_expression = get_expression(node.inputs['Normal'], exp_list)
1177 | if normal_expression:
1178 | bsdf["Normal"] = normal_expression
1179 | else:
1180 | log.error(f"couldn't find bsdf for field {field.name}")
1181 | return bsdf
1182 | # from here the return type should be {expression:node_idx, OutputIndex: socket_idx}
1183 | # Add > Input
1184 |
1185 | # if node.type == 'AMBIENT_OCCLUSION':
1186 | if node.type == 'ATTRIBUTE':
1187 | return exp_attribute(socket, exp_list)
1188 | if node.type == 'VERTEX_COLOR':
1189 | return exp_vertex_color(socket, exp_list)
1190 |
1191 | # if node.type == 'BEVEL':
1192 | # if node.type == 'CAMERA':
1193 | if node.type == 'FRESNEL':
1194 | exp = exp_fresnel(node, exp_list)
1195 | return {"expression": exp}
1196 | if node.type == 'NEW_GEOMETRY':
1197 | result = exp_new_geometry(socket, exp_list)
1198 | if result:
1199 | return result
1200 | # if node.type == 'HAIR_INFO':
1201 | if node.type == 'LAYER_WEIGHT': # fresnel and facing, with "blend" (power?) and normal param
1202 | return exp_layer_weight(socket, exp_list)
1203 | if node.type == 'LIGHT_PATH':
1204 | return exp_light_path(socket, exp_list)
1205 | if node.type == 'OBJECT_INFO':
1206 | return exp_object_info(socket, exp_list)
1207 | # if node.type == 'PARTICLE_INFO':
1208 |
1209 | if node.type == 'RGB':
1210 | exp = exp_color(node.outputs[0].default_value, exp_list)
1211 | return {"expression": exp, "OutputIndex": 0}
1212 |
1213 | # if node.type == 'TANGENT':
1214 | if node.type == 'TEX_COORD':
1215 | exp = exp_texcoord_node(socket, exp_list)
1216 | if exp:
1217 | return exp
1218 |
1219 | if node.type == 'UVMAP':
1220 | return exp_uvmap(node, exp_list)
1221 | if node.type == 'VALUE':
1222 | exp = exp_scalar(node.outputs[0].default_value, exp_list)
1223 | return {"expression": exp}
1224 | # if node.type == 'WIREFRAME':
1225 |
1226 |
1227 | # Add > Texture
1228 | # if node.type == 'TEX_BRICK':
1229 | if node.type == 'TEX_CHECKER':
1230 | return exp_tex_checker(socket, exp_list)
1231 | # if node.type == 'TEX_ENVIRONMENT':
1232 | # if node.type == 'TEX_GRADIENT':
1233 | # if node.type == 'TEX_IES':
1234 | if node.type == 'TEX_NOISE':
1235 | return exp_tex_noise(socket, exp_list)
1236 | if node.type == 'TEX_IMAGE':
1237 | cached_node = None
1238 | if node in reverse_expressions:
1239 | cached_node = reverse_expressions[node]
1240 |
1241 | if not cached_node:
1242 | image = node.image
1243 | if not image:
1244 | return { "expression": exp_scalar(0, exp_list) }
1245 |
1246 |
1247 | tex_coord = get_expression(node.inputs['Vector'], exp_list)
1248 |
1249 |
1250 | name = ""
1251 | if image:
1252 | name = sanitize_name(image.name) # name_full?
1253 |
1254 | # ensure that texture is exported
1255 | texture_type = get_context() or 'SRGB'
1256 | get_or_create_texture(name, image, texture_type)
1257 |
1258 | texture_exp = exp_texture(name)
1259 | if tex_coord:
1260 | if node.projection == 'BOX':
1261 | proj = Node("FunctionCall", { "Function": "/DatasmithBlenderContent/MaterialFunctions/TexCoord_Box"})
1262 | proj.push(Node("0", tex_coord))
1263 | mask_expression = { "expression": exp_list.push(proj) }
1264 | texture_exp.push(Node("Coordinates", mask_expression))
1265 | else:
1266 | if node.projection != 'FLAT':
1267 | log.error("node TEXTURE_COORDINATE has unhandled projection: %s" % node.projection)
1268 | mask = Node("ComponentMask")
1269 | mask.push(Node("0", tex_coord))
1270 | mask_expression = { "expression": exp_list.push(mask) }
1271 | texture_exp.push(Node("Coordinates", mask_expression))
1272 |
1273 | cached_node = exp_list.push(texture_exp)
1274 | reverse_expressions[node] = cached_node
1275 |
1276 | output_index = 0 # RGB
1277 | # indices 1, 2, 3 are separate RGB channels
1278 | if socket.name == 'Alpha':
1279 | output_index = 4 #
1280 |
1281 | return { "expression": cached_node, "OutputIndex": output_index }
1282 |
1283 | # Add > Color
1284 | if node.type == 'BRIGHTCONTRAST':
1285 | return exp_bright_contrast(node, exp_list)
1286 | if node.type == 'GAMMA':
1287 | return exp_gamma(node, exp_list)
1288 | if node.type == 'HUE_SAT':
1289 | exp = exp_hsv(node, exp_list)
1290 | return {"expression": exp, "OutputIndex": 0}
1291 |
1292 | if node.type == 'INVERT':
1293 | exp = exp_invert(node, exp_list)
1294 | return {"expression": exp}
1295 | # if node.type == 'LIGHT_FALLOFF':
1296 | # if node.type == 'TEX_CHECKER':
1297 | # if node.type == 'TEX_CHECKER':
1298 |
1299 | if node.type == 'MIX_RGB':
1300 | exp = exp_mixrgb(node, exp_list)
1301 | return {"expression": exp, "OutputIndex": 0}
1302 |
1303 | if node.type == 'CURVE_RGB':
1304 | exp = exp_curvergb(node, exp_list)
1305 | return {"expression": exp, "OutputIndex": 0}
1306 |
1307 | # Add > Vector
1308 |
1309 | if node.type == 'BUMP':
1310 | return exp_bump(node, exp_list)
1311 | # if node.type == 'DISPLACEMENT':
1312 | if node.type == 'MAPPING':
1313 | return exp_mapping(node, exp_list)
1314 | # if node.type == 'NORMAL':
1315 | if node.type == 'NORMAL_MAP':
1316 | return exp_normal_map(socket, exp_list)
1317 | # if node.type == 'CURVE_VEC':
1318 | # if node.type == 'VECTOR_DISPLACEMENT':
1319 | # if node.type == 'VECT_TRANSFORM':
1320 |
1321 | # Add > Converter
1322 |
1323 | # if node.type == 'WAVELENGTH':
1324 | if node.type == 'BLACKBODY':
1325 | return exp_blackbody(node, exp_list)
1326 | if node.type == 'VALTORGB':
1327 | exp = exp_color_ramp(node, exp_list)
1328 | return {"expression": exp, "OutputIndex": 0}
1329 |
1330 | if node.type == 'COMBRGB':
1331 | return exp_make_vec3(socket, exp_list)
1332 | if node.type == 'COMBXYZ':
1333 | return exp_make_vec3(socket, exp_list)
1334 | if node.type == 'COMBHSV':
1335 | return exp_make_hsv(socket, exp_list)
1336 |
1337 | if node.type == 'SEPRGB':
1338 | return exp_break_vec3(socket, exp_list)
1339 | if node.type == 'SEPXYZ':
1340 | return exp_break_vec3(socket, exp_list)
1341 | if node.type == 'SEPHSV':
1342 | return exp_break_hsv(socket, exp_list)
1343 |
1344 | if node.type == 'RGBTOBW':
1345 | return exp_rgb_to_bw(socket, exp_list)
1346 | if node.type == 'MATH':
1347 | return exp_math(node, exp_list)
1348 | if node.type == 'VECT_MATH':
1349 | return exp_vect_math(node, exp_list)
1350 |
1351 | # if node.type == 'SHADERTORGB':
1352 |
1353 | # Others:
1354 |
1355 | # if node.type == 'SCRIPT':
1356 |
1357 |
1358 | log.error("node not handled" + node.type)
1359 | exp = exp_scalar(0, exp_list)
1360 | return {"expression": exp}
1361 |
1362 |
1363 | def pbr_nodetree_material(material):
1364 | log.info("Collecting material: "+material.name)
1365 | n = Node("UEPbrMaterial")
1366 | n['name'] = sanitize_name(material.name)
1367 | exp_list = Node("Expressions")
1368 | n.push(exp_list)
1369 |
1370 | output_node = (
1371 | material.node_tree.get_output_node('EEVEE')
1372 | or material.node_tree.get_output_node('ALL')
1373 | or material.node_tree.get_output_node('CYCLES')
1374 | )
1375 |
1376 | if not output_node:
1377 | log.warn("material %s with use_nodes does not have nodes" % material.name)
1378 | return n
1379 |
1380 | surface_field = output_node.inputs['Surface']
1381 | if not surface_field.links:
1382 | log.warn("material %s with use_nodes does not have nodes" % material.name)
1383 | return n
1384 |
1385 | global reverse_expressions
1386 | reverse_expressions = dict()
1387 |
1388 | expressions = get_expression(surface_field, exp_list)
1389 | for key, value in expressions.items():
1390 | n.push(Node(key, value))
1391 |
1392 | # apparently this happens automatically, we may want to
1393 | # choose if we export with masked blend mode
1394 | #if "Opacity" in expressions:
1395 | # n.push(Node("Blendmode", {"value": "2.0"}))
1396 |
1397 | return n
1398 |
1399 |
1400 | def pbr_default_material():
1401 | n = Node("UEPbrMaterial")
1402 | n["name"] = "DefaultMaterial"
1403 | exp_list = Node("Expressions")
1404 | grey = 0.906332
1405 | basecolor_idx = exp_color((grey, grey, grey, 1.0), exp_list)
1406 | roughness_idx = exp_scalar(0.4, exp_list)
1407 | n.push(exp_list)
1408 | n.push(Node("BaseColor", {
1409 | "expression": basecolor_idx,
1410 | "OutputIndex": "0"
1411 | }))
1412 | n.push(Node("Roughness", {
1413 | "expression": roughness_idx,
1414 | "OutputIndex": "0"
1415 | }))
1416 | return n
1417 |
1418 | def pbr_basic_material(material):
1419 | n = Node("UEPbrMaterial")
1420 | n['name'] = sanitize_name(material.name)
1421 | exp_list = Node("Expressions")
1422 | n.push(exp_list)
1423 |
1424 | basecolor_idx = exp_color(material.diffuse_color, exp_list)
1425 | roughness_idx = exp_scalar(material.roughness, exp_list)
1426 | metallic_idx = exp_scalar(material.metallic, exp_list)
1427 | specular_idx = exp_scalar(material.specular_intensity, exp_list)
1428 |
1429 | n.push(Node("BaseColor", {
1430 | "expression": basecolor_idx,
1431 | "OutputIndex": "0"
1432 | }))
1433 | n.push(Node("Roughness", {
1434 | "expression": roughness_idx,
1435 | "OutputIndex": "0"
1436 | }))
1437 | n.push(Node("Metallic", {
1438 | "expression": metallic_idx,
1439 | "OutputIndex": "0"
1440 | }))
1441 | n.push(Node("Specular", {
1442 | "expression": specular_idx,
1443 | "OutputIndex": "0"
1444 | }))
1445 |
1446 | return n
1447 |
1448 |
1449 | cached_nodes = {}
1450 | def collect_pbr_material(mat_with_owner):
1451 | datasmith_context["material_owner"] = mat_with_owner[1]
1452 | global cached_nodes
1453 | cached_nodes = {}
1454 | material = mat_with_owner[0]
1455 | if material is None:
1456 | log.debug("creating default material")
1457 | return pbr_default_material()
1458 | if not material.use_nodes:
1459 | log.debug("creating material %s without nodes" % material.name)
1460 | return pbr_basic_material(material)
1461 | log.debug("creating material %s with node_tree " % material.name)
1462 | return pbr_nodetree_material(material)
1463 |
1464 | import numpy as np
1465 |
1466 |
1467 |
1468 |
1469 | def fill_umesh(umesh, bl_mesh):
1470 | # create copy to triangulate
1471 | m = bl_mesh.copy()
1472 | bm = bmesh.new()
1473 | bm.from_mesh(m)
1474 | bmesh.ops.triangulate(bm, faces=bm.faces[:])
1475 | # this is just to make sure a UV layer exists
1476 | bm.loops.layers.uv.verify()
1477 | bm.to_mesh(m)
1478 | bm.free()
1479 | # not sure if this is the best way to read normals
1480 | m.calc_normals_split()
1481 |
1482 | loops = m.loops
1483 | num_loops = len(loops)
1484 |
1485 | normals = np.empty(num_loops* 3, np.float32)
1486 | loops.foreach_get("normal", normals)
1487 | normals = normals.reshape((num_loops, 3))
1488 | normals = normals @ matrix_normals
1489 |
1490 | m.transform(matrix_datasmith)
1491 |
1492 | #finish inline mesh_copy_triangulate
1493 | if len(bl_mesh.materials) == 0:
1494 | umesh.materials[0] = 'DefaultMaterial'
1495 | else:
1496 | for idx, mat in enumerate(bl_mesh.materials):
1497 | umesh.materials[idx] = sanitize_name(getattr(mat, 'name', 'DefaultMaterial'))
1498 |
1499 | polygons = m.polygons
1500 | num_polygons = len(polygons)
1501 | material_slots = np.empty(num_polygons, np.uint32)
1502 |
1503 | polygons.foreach_get("material_index", material_slots)
1504 | umesh.tris_material_slot = material_slots # [p.material_index for p in m.polygons]
1505 |
1506 | smoothing_groups = m.calc_smooth_groups()[0];
1507 | umesh.tris_smoothing_group = np.array(smoothing_groups, np.uint32)
1508 |
1509 | vertices = m.vertices
1510 | num_vertices = len(vertices)
1511 |
1512 | vertices_array = np.empty(num_vertices* 3, np.float32)
1513 | vertices.foreach_get("co", vertices_array)
1514 |
1515 | umesh.vertices = vertices_array.reshape(-1, 3)
1516 |
1517 | loops = m.loops
1518 | num_loops = len(loops)
1519 |
1520 | triangles = np.empty(num_loops, np.uint32)
1521 | loops.foreach_get("vertex_index", triangles)
1522 |
1523 | umesh.triangles = triangles
1524 |
1525 | umesh.vertex_normals = np.ascontiguousarray(normals, " 0:
1677 | children_node = Node("children");
1678 | # strange, this visibility flag is read from the "children" node. . .
1679 | children_node["visible"] = not bl_obj.hide_render
1680 | for child in child_nodes:
1681 | if child:
1682 | children_node.push(child)
1683 | n.push(children_node)
1684 |
1685 |
1686 | return n
1687 |
1688 |
1689 | def collect_object_custom_data(bl_obj, n, apply_modifiers, obj_mat, depsgraph, export_metadata=False):
1690 | # I think that these should be ordered by how common they are
1691 | if bl_obj.type == 'EMPTY':
1692 | pass
1693 | elif bl_obj.type == 'MESH':
1694 | bl_mesh = bl_obj.data
1695 | bl_mesh_name = bl_mesh.name
1696 |
1697 | if bl_obj.modifiers and apply_modifiers:
1698 | bl_mesh = bl_obj.evaluated_get(depsgraph).to_mesh()
1699 | bl_mesh_name = "%s__%s" % (bl_obj.name, bl_mesh.name)
1700 |
1701 | if bl_mesh.library:
1702 | libraries_dict = datasmith_context["libraries"]
1703 | prefix = libraries_dict.get(bl_mesh.library)
1704 |
1705 | if prefix is None:
1706 | lib_filename = bpy.path.basename(bl_mesh.library.filepath)
1707 | lib_clean_name = bpy.path.clean_name(lib_filename)
1708 | prefix = lib_clean_name.strip("_")
1709 | if prefix.endswith("_blend"):
1710 | prefix = prefix[:-5] # leave the underscore
1711 | next_prefix = prefix
1712 | try_count = 1
1713 | libraries_prefixes = libraries_dict.values()
1714 | # just to reaaally make sure there are no collisions
1715 | while next_prefix in libraries_prefixes:
1716 | next_prefix = "%s%d_" % (prefix, try_count)
1717 | try_count += 1
1718 | libraries_dict[bl_mesh.library] = next_prefix
1719 | prefix = next_prefix
1720 | bl_mesh_name = prefix + bl_mesh_name
1721 |
1722 |
1723 | bl_mesh_name = sanitize_name(bl_mesh_name)
1724 | meshes = datasmith_context["meshes"]
1725 | umesh = None
1726 | for mesh in meshes:
1727 | if bl_mesh_name == mesh.name:
1728 | umesh = mesh
1729 |
1730 | if umesh == None:
1731 | if len(bl_mesh.polygons) > 0:
1732 | umesh = UDMesh(bl_mesh_name)
1733 | meshes.append(umesh)
1734 | fill_umesh(umesh, bl_mesh)
1735 |
1736 | if export_metadata:
1737 | collect_object_metadata(n["name"], "StaticMesh", bl_mesh)
1738 |
1739 | material_list = datasmith_context["materials"]
1740 | if len(bl_obj.material_slots) == 0:
1741 | material_list.append((None, bl_obj))
1742 | else:
1743 | for slot in bl_obj.material_slots:
1744 | material_list.append((slot.material, bl_obj))
1745 |
1746 | if umesh:
1747 | n.name = 'ActorMesh'
1748 | n.push(Node('mesh', {'name': umesh.name}))
1749 |
1750 | for idx, slot in enumerate(bl_obj.material_slots):
1751 | if slot.link == 'OBJECT':
1752 | #collect_materials([slot.material], uscene)
1753 | safe_name = sanitize_name(slot.material.name)
1754 | n.push(Node('material', {'id':idx, 'name':safe_name}))
1755 |
1756 | elif bl_obj.type == 'CURVE':
1757 |
1758 | # as we cannot get geometry before evaluating depsgraph,
1759 | # we better evaluate first, and check if it has polygons.
1760 | # this might end with repeated geometry, gotta find solution.
1761 | # maybe cache "evaluated curve without modifiers"?
1762 |
1763 | bl_mesh = bl_obj.evaluated_get(depsgraph).to_mesh()
1764 | if bl_mesh and len(bl_mesh.polygons) > 0:
1765 | bl_curve = bl_obj.data
1766 | bl_curve_name = "%s_%s" % (bl_curve.name, bl_obj.name)
1767 | bl_curve_name = sanitize_name(bl_curve_name)
1768 |
1769 | umesh = UDMesh(bl_curve_name)
1770 | meshes = datasmith_context["meshes"]
1771 | meshes.append(umesh)
1772 |
1773 | fill_umesh(umesh, bl_mesh)
1774 | material_list = datasmith_context["materials"]
1775 |
1776 | n.name = 'ActorMesh'
1777 | n.push(Node('mesh', {'name': umesh.name}))
1778 |
1779 | if len(bl_obj.material_slots) == 0:
1780 | material_list.append((None, bl_obj))
1781 | else:
1782 | for idx, slot in enumerate(bl_obj.material_slots):
1783 | material_list.append((slot.material, bl_obj))
1784 | if slot.link == 'OBJECT':
1785 | #collect_materials([slot.material], uscene)
1786 | safe_name = sanitize_name(slot.material.name)
1787 | n.push(Node('material', {'id':idx, 'name':safe_name}))
1788 |
1789 | elif bl_obj.type == 'CAMERA':
1790 |
1791 | bl_cam = bl_obj.data
1792 | n.name = 'Camera'
1793 |
1794 | # TODO
1795 | # look_at_actor = sanitize_name(bl_cam.dof.focus_object.name)
1796 |
1797 | use_dof = "1" if bl_cam.dof.use_dof else "0"
1798 | n.push(Node("DepthOfField", {"enabled": use_dof}))
1799 | n.push(node_value('SensorWidth', bl_cam.sensor_width))
1800 | # blender doesn't have per-camera aspect ratio
1801 | sensor_aspect_ratio = 1.777778
1802 | n.push(node_value('SensorAspectRatio', sensor_aspect_ratio))
1803 | n.push(node_value('FocusDistance', bl_cam.dof.focus_distance * 100)) # to centimeters
1804 | n.push(node_value('FStop', bl_cam.dof.aperture_fstop))
1805 | n.push(node_value('FocalLength', bl_cam.lens))
1806 | n.push(Node('Post'))
1807 | # maybe move up as lights are more common?
1808 | elif bl_obj.type == 'LIGHT':
1809 |
1810 | bl_light = bl_obj.data
1811 | n.name = 'Light'
1812 |
1813 | n['type'] = 'PointLight'
1814 | n['enabled'] = '1'
1815 | n.push(node_value('SourceSize', bl_light.shadow_soft_size * 100))
1816 | light_intensity = bl_light.energy
1817 | light_attenuation_radius = 100 * math.sqrt(bl_light.energy)
1818 | light_color = bl_light.color
1819 | light_intensity_units = 'Lumens' # can also be 'Candelas' or 'Unitless'
1820 | light_use_custom_distance = bl_light.use_custom_distance
1821 |
1822 | if bl_light.type == 'SUN':
1823 | n['type'] = 'DirectionalLight'
1824 | light_use_custom_distance = False
1825 | # light_intensity = bl_light.energy # suns are in lux
1826 |
1827 | elif bl_light.type == 'SPOT':
1828 | n['type'] = 'SpotLight'
1829 | outer_cone_angle = bl_light.spot_size * 180 / (2*math.pi)
1830 | inner_cone_angle = outer_cone_angle * (1 - bl_light.spot_blend)
1831 | if inner_cone_angle < 0.0001:
1832 | inner_cone_angle = 0.0001
1833 | n.push(node_value('InnerConeAngle', inner_cone_angle))
1834 | n.push(node_value('OuterConeAngle', outer_cone_angle))
1835 |
1836 | spot_use_candelas = False # TODO: test this thoroughly
1837 | if spot_use_candelas:
1838 | light_intensity_units = 'Candelas'
1839 | light_intensity = bl_light.energy * 0.08 # came up with this constant by brute force
1840 | # blender watts unit match ue4 lumens unit, but in spot lights the brightness
1841 | # changes with the spot angle when using lumens while candelas do not.
1842 |
1843 | elif bl_light.type == 'AREA':
1844 | n['type'] = 'AreaLight'
1845 |
1846 | size_w = size_h = bl_light.size
1847 | if bl_light.shape == 'RECTANGLE' or bl_light.shape == 'ELLIPSE':
1848 | size_h = bl_light.size_y
1849 |
1850 | n.push(Node('Shape', {
1851 | "type": 'None', # can be Rectangle, Disc, Sphere, Cylinder, None
1852 | "width": size_w * 100, # convert to cm
1853 | "length": size_h * 100,
1854 | "LightType": "Rect", # can be "Point", "Spot", "Rect"
1855 | }))
1856 | if light_use_custom_distance:
1857 | light_attenuation_radius = 100 * bl_light.cutoff_distance
1858 | # TODO: check how lights work when using a node tree
1859 | # if bl_light.use_nodes and bl_light.node_tree:
1860 |
1861 | # node = bl_light.node_tree.nodes['Emission']
1862 | # light_color = node.inputs['Color'].default_value
1863 | # light_intensity = node.inputs['Strength'].default_value # have to check how to relate to candelas
1864 | # log.error("unsupported: using nodetree for light " + bl_obj.name)
1865 |
1866 | n.push(node_value('Intensity', light_intensity))
1867 | n.push(node_value('AttenuationRadius', light_attenuation_radius))
1868 | n.push(Node('IntensityUnits', {'value': light_intensity_units}))
1869 | n.push(Node('Color', {
1870 | 'usetemp': '0',
1871 | 'temperature': '6500.0',
1872 | 'R': f(light_color[0]),
1873 | 'G': f(light_color[1]),
1874 | 'B': f(light_color[2]),
1875 | }))
1876 | elif bl_obj.type == 'LIGHT_PROBE':
1877 | # TODO: LIGHT PROBE
1878 | n.name = 'CustomActor'
1879 | bl_probe = bl_obj.data
1880 | if bl_probe.type == 'PLANAR':
1881 | n["PathName"] = "/DatasmithBlenderContent/Blueprints/BP_BlenderPlanarReflection"
1882 |
1883 | elif bl_probe.type == 'CUBEMAP':
1884 | ## we could also try using min/max if it makes a difference
1885 | _, _, obj_scale = obj_mat.decompose()
1886 | avg_scale = (obj_scale.x + obj_scale.y + obj_scale.z) * 0.333333
1887 |
1888 | if bl_probe.influence_type == 'BOX':
1889 | n["PathName"] = "/DatasmithBlenderContent/Blueprints/BP_BlenderBoxReflection"
1890 |
1891 |
1892 | falloff = bl_probe.falloff # this value is 0..1
1893 | transition_distance = falloff * avg_scale
1894 | prop = Node("KeyValueProperty", {"name": "TransitionDistance", "type":"Float", "val": "%.6f"%transition_distance})
1895 | n.push(prop)
1896 | else: # if bl_probe.influence_type == 'ELIPSOID'
1897 | n["PathName"] = "/DatasmithBlenderContent/Blueprints/BP_BlenderSphereReflection"
1898 | probe_radius = bl_probe.influence_distance * 100 * avg_scale
1899 | radius = Node("KeyValueProperty", {"name": "Radius", "type":"Float", "val": "%.6f"%probe_radius})
1900 | n.push(radius)
1901 | elif bl_probe.type == 'GRID':
1902 | # for now we just export to custom object, but it doesn't affect the render on
1903 | # the unreal side. would be cool if it made a difference by setting volumetric importance volume
1904 | n["PathName"] = "/DatasmithBlenderContent/Blueprints/BP_BlenderGridProbe"
1905 |
1906 | # blender influence_distance is outwards, maybe we should grow the object to match?
1907 | # outward_influence would be 1.0 + influence_distance / size maybe?
1908 | # obj_mat = obj_mat @ Matrix.Scale(outward_influence, 4)
1909 |
1910 | else:
1911 | log.error("unhandled light probe")
1912 | elif bl_obj.type == 'ARMATURE':
1913 | pass
1914 | else:
1915 | log.error("unrecognized object type: %s" % bl_obj.type)
1916 |
1917 |
1918 |
1919 | def collect_object_transform(bl_obj, instance_matrix=None):
1920 | mat_basis = instance_matrix or bl_obj.matrix_world
1921 | obj_mat = matrix_datasmith @ mat_basis @ matrix_datasmith.inverted()
1922 |
1923 | if bl_obj.type in 'CAMERA' or bl_obj.type == 'LIGHT':
1924 | obj_mat = obj_mat @ matrix_forward
1925 | elif bl_obj.type == 'LIGHT_PROBE':
1926 | bl_probe = bl_obj.data
1927 | if bl_probe.type == 'PLANAR':
1928 | obj_mat = obj_mat @ Matrix.Scale(0.05, 4)
1929 | elif bl_probe.type == 'CUBEMAP':
1930 | if bl_probe.influence_type == 'BOX':
1931 | size = bl_probe.influence_distance * 100
1932 | obj_mat = obj_mat @ Matrix.Scale(size, 4)
1933 |
1934 | obj_mat.freeze() # TODO: check if this is needed
1935 | return obj_mat
1936 |
1937 |
1938 | def collect_object_metadata(obj_name, obj_type, obj):
1939 | metadata = None
1940 | found_metadata = False
1941 | obj_props = obj.keys()
1942 | for prop_name in obj_props:
1943 | if prop_name in {"_RNA_UI", "cycles", "cycles_visibility"}:
1944 | continue
1945 | if prop_name.startswith("archipack_"):
1946 | continue
1947 | if metadata is None:
1948 | names = (obj_type, obj_name)
1949 | metadata = Node("MetaData", {"name": "%s_%s"%names, "reference":"%s.%s"%names } )
1950 |
1951 | out_value = prop_value = obj[prop_name]
1952 | prop_type = type(prop_value)
1953 | out_type = None
1954 | if prop_type is str:
1955 | out_type = "String"
1956 | elif prop_type in {float, int}:
1957 | out_type = "Float"
1958 | out_value = f(prop_value)
1959 | elif prop_type is idprop.types.IDPropertyArray:
1960 | out_type = "Vector"
1961 | out_value = ",".join(f(v) for v in prop_value)
1962 | elif prop_type is idprop.types.IDPropertyGroup:
1963 | if len(out_value) == 0:
1964 | continue
1965 | out_type = "String"
1966 | out_value = str(prop_value.to_dict())
1967 | # elif prop_type is list:
1968 | # archipack uses some list props, I don't think these are useful
1969 | # but we should check if there's something specific we should do.
1970 | else:
1971 | log.error("%s: %s has unsupported metadata with type:%s" % (obj_type, obj_name, prop_type))
1972 | # write as string, and sanitize output
1973 | out_type = "String"
1974 | out_value = str(out_value)
1975 |
1976 | if out_type == "String":
1977 | out_value = out_value.replace("<", "<")
1978 | out_value = out_value.replace(">", ">")
1979 | out_value = out_value.replace('"', """)
1980 |
1981 | kvp = Node("KeyValueProperty", {"name": prop_name, "val": out_value, "type": out_type } )
1982 | metadata.push(kvp)
1983 | found_metadata = True
1984 | if found_metadata:
1985 | datasmith_context["metadata"].append(metadata)
1986 |
1987 | def node_value(name, value):
1988 | return Node(name, {'value': '{:6f}'.format(value)})
1989 | def f(value):
1990 | return '{:6f}'.format(value)
1991 |
1992 | def collect_environment(world):
1993 |
1994 | if not world.use_nodes:
1995 | return
1996 |
1997 | log.info("Collecting environment")
1998 | nodes = world.node_tree
1999 | output = nodes.get_output_node('EEVEE') or nodes.get_output_node('ALL') or nodes.get_output_node('CYCLES')
2000 | background_node = output.inputs['Surface'].links[0].from_node
2001 | if not 'Color' in background_node.inputs:
2002 | return
2003 | if not background_node.inputs['Color'].links:
2004 | return
2005 | source_node = background_node.inputs['Color'].links[0].from_node
2006 | if source_node.type != 'TEX_ENVIRONMENT':
2007 | log.info("Background texture is "+ source_node.type)
2008 | return
2009 |
2010 | log.info("found environment, collecting...")
2011 | image = source_node.image
2012 |
2013 | tex_name = sanitize_name(image.name)
2014 | get_or_create_texture(tex_name, image)
2015 |
2016 | tex_node = Node("Texture", {
2017 | "tex": tex_name,
2018 | })
2019 |
2020 | n2 = Node("Environment", {
2021 | "name": "world_environment_lighting",
2022 | "label": "world_environment_lighting",
2023 | })
2024 | n2.push(tex_node)
2025 | n2.push(Node("Illuminate", {
2026 | "enabled": "1"
2027 | }))
2028 | n = Node("Environment", {
2029 | "name": "world_environment_background",
2030 | "label": "world_environment_background",
2031 | })
2032 | n.push(tex_node)
2033 | n.push(Node("Illuminate", {
2034 | "enabled": "0"
2035 | }))
2036 |
2037 | return [n, n2]
2038 |
2039 |
2040 |
2041 | def get_file_header():
2042 |
2043 | n = Node('DatasmithUnrealScene')
2044 |
2045 | from . import bl_info
2046 | plugin_version = bl_info['version']
2047 | plugin_version_string = "%s.%s.%s" % plugin_version
2048 | n.push(Node('Version', children=[plugin_version_string]))
2049 | n.push(Node('SDKVersion', children=['4.24E0']))
2050 | n.push(Node('Host', children=['Blender']))
2051 |
2052 | blender_version = bpy.app.version_string
2053 | n.push(Node('Application', {
2054 | 'Vendor': 'Blender Foundation',
2055 | 'ProductName': 'Blender',
2056 | 'ProductVersion': blender_version,
2057 | }))
2058 |
2059 | import os, platform
2060 | os_name = "%s %s" % (platform.system(), platform.release())
2061 | user_name = os.getlogin()
2062 |
2063 | n.push(Node('User', {
2064 | 'ID': user_name,
2065 | 'OS': os_name,
2066 | }))
2067 | return n
2068 |
2069 |
2070 | # in_type can be SRGB, LINEAR or NORMAL
2071 | def get_or_create_texture(in_name, in_image, in_type='SRGB'):
2072 | textures = datasmith_context["textures"]
2073 | for name, tex, _ in textures:
2074 | if name == in_name:
2075 | return tex
2076 | log.debug("collecting texture:%s" % in_name)
2077 |
2078 | new_tex = (in_name, in_image, in_type)
2079 | textures.append(new_tex)
2080 | return new_tex
2081 |
2082 | def get_datasmith_curves_image():
2083 | log.info("baking curves")
2084 |
2085 | curve_list = datasmith_context["material_curves"]
2086 | if curve_list is None:
2087 | return None
2088 |
2089 | curves_image = None
2090 | if "datasmith_curves" in bpy.data.images:
2091 | curves_image = bpy.data.images["datasmith_curves"]
2092 | else:
2093 | curves_image = bpy.data.images.new(
2094 | "datasmith_curves",
2095 | DATASMITH_TEXTURE_SIZE,
2096 | DATASMITH_TEXTURE_SIZE,
2097 | alpha=True,
2098 | float_buffer=True
2099 | )
2100 | curves_image.colorspace_settings.is_data = True
2101 | curves_image.file_format = 'OPEN_EXR'
2102 |
2103 | curves_image.pixels[:] = curve_list.reshape((-1,))
2104 | return curves_image
2105 |
2106 |
2107 | TEXTURE_MODE_DIFFUSE = "0"
2108 | TEXTURE_MODE_SPECULAR = "1"
2109 | TEXTURE_MODE_NORMAL = "2"
2110 | TEXTURE_MODE_NORMAL_GREEN_INV = "3"
2111 | TEXTURE_MODE_DISPLACE = "4"
2112 | TEXTURE_MODE_OTHER = "5"
2113 | TEXTURE_MODE_BUMP = "6" # this converts textures to normal maps automatically
2114 |
2115 | # saves image, and generates node with image description to add to export
2116 | def save_texture(texture, basedir, folder_name, minimal_export = False, use_gamma_hack=False):
2117 | name, image, img_type = texture
2118 |
2119 | log.info("writing texture:"+name)
2120 |
2121 | ext = ".png"
2122 | if image.file_format == 'JPEG':
2123 | ext = ".jpg"
2124 | elif image.file_format == 'HDR':
2125 | ext = ".hdr"
2126 | elif image.file_format == 'OPEN_EXR':
2127 | ext = ".exr"
2128 | elif image.file_format == 'TARGA' or image.file_format == 'TARGA_RAW':
2129 | ext = ".tga"
2130 |
2131 | safe_name = sanitize_name(name) + ext
2132 | image_path = path.join(basedir, folder_name, safe_name)
2133 | skip_image = minimal_export and not path.exists(image_path)
2134 |
2135 | # fix for invalid images, like one in mr_elephant sample.
2136 | valid_image = (image.channels != 0)
2137 | if valid_image and not skip_image:
2138 | source_path = image.filepath_from_user()
2139 |
2140 | if image.packed_file:
2141 | with open(image_path, "wb") as f:
2142 | f.write(image.packed_file.data)
2143 | elif source_path and source_path != image_path:
2144 | shutil.copyfile(source_path, image_path)
2145 | else:
2146 | image.filepath_raw = image_path
2147 | image.save()
2148 | if source_path:
2149 | image.filepath_raw = source_path
2150 |
2151 | n = Node('Texture')
2152 | n['name'] = name
2153 | n['file'] = path.join(folder_name, safe_name)
2154 | n['rgbcurve'] = 0.0
2155 | n['srgb'] = "1" # this parameter is only read on 4.25 onwards
2156 |
2157 | n['texturemode'] = TEXTURE_MODE_DIFFUSE
2158 | if image.file_format == 'HDR':
2159 | n['texturemode'] = TEXTURE_MODE_OTHER
2160 | n['rgbcurve'] = "1.000000"
2161 | elif img_type == 'NORMAL':
2162 | n['texturemode'] = TEXTURE_MODE_NORMAL_GREEN_INV
2163 | n['srgb'] = "2" # only read on 4.25 onwards, but we can still write it
2164 | elif image.colorspace_settings.is_data:
2165 | n['texturemode'] = TEXTURE_MODE_SPECULAR
2166 | n['srgb'] = "2" # only read on 4.25 onwards, but we can still write it
2167 | if use_gamma_hack:
2168 | n['rgbcurve'] = "0.454545"
2169 |
2170 | n['texturefilter'] = "3"
2171 | if valid_image:
2172 | img_hash = calc_hash(image_path)
2173 | n.push(Node('Hash', {'value': img_hash}))
2174 | return n
2175 |
2176 |
2177 | def calc_hash(image_path):
2178 | hash_md5 = hashlib.md5()
2179 | with open(image_path, "rb") as f:
2180 | for chunk in iter(lambda: f.read(4096), b""):
2181 | hash_md5.update(chunk)
2182 | return hash_md5.hexdigest()
2183 |
2184 |
2185 | datasmith_context = None
2186 | def collect_and_save(context, args, save_path):
2187 |
2188 | start_time = time.monotonic()
2189 |
2190 | global datasmith_context
2191 | datasmith_context = {
2192 | "objects": [],
2193 | "anim_objects": [],
2194 | "textures": [],
2195 | "meshes": [],
2196 | "materials": [],
2197 | "material_curves": None,
2198 | "metadata": [],
2199 | "compatibility_mode": args["compatibility_mode"],
2200 | "libraries": {},
2201 | }
2202 |
2203 | log.info("collecting objects")
2204 | datasmith_context['depsgraph'] = context.evaluated_depsgraph_get()
2205 | all_objects = context.scene.objects
2206 | root_objects = [obj for obj in all_objects if obj.parent is None]
2207 |
2208 | objects = []
2209 |
2210 | selected_only = args["export_selected"]
2211 | apply_modifiers = args["apply_modifiers"]
2212 | minimal_export = args["minimal_export"]
2213 | export_animations = args["export_animations"]
2214 |
2215 | if export_animations:
2216 | frame_at_export_time = context.scene.frame_current
2217 | frame_start = context.scene.frame_start
2218 | frame_end = context.scene.frame_end
2219 |
2220 | write_metadata = args["write_metadata"]
2221 |
2222 | for obj in root_objects:
2223 | uobj = collect_object(obj,
2224 | selected_only=selected_only,
2225 | apply_modifiers=apply_modifiers,
2226 | export_animations=export_animations,
2227 | export_metadata=write_metadata,
2228 | )
2229 | if uobj:
2230 | objects.append(uobj)
2231 |
2232 | log.info("collecting animations")
2233 | anims = []
2234 | if export_animations:
2235 |
2236 | # TODO: found a bit late about this: we need to test and profile
2237 | # https://docs.blender.org/api/current/bpy_extras.anim_utils.html
2238 |
2239 | anim_objs = datasmith_context["anim_objects"]
2240 |
2241 | num_frames = frame_end - frame_start + 1
2242 | num_objects = len(anim_objs)
2243 | object_timelines = [[Matrix() for frame in range(num_frames)] for obj in range(num_objects)]
2244 | object_animates = [False for num in range(num_objects)]
2245 | # collect phase?
2246 |
2247 | for arr_idx, frame_idx in enumerate(range(frame_start, frame_end+1)):
2248 |
2249 | context.scene.frame_set(frame_idx)
2250 |
2251 | for obj_idx, obj in enumerate(anim_objs):
2252 |
2253 | obj_mat = collect_object_transform(obj[0])
2254 | object_timelines[obj_idx][arr_idx] = obj_mat
2255 |
2256 | if arr_idx == 0:
2257 | continue
2258 |
2259 | if not object_animates[obj_idx]:
2260 | changed = obj_mat != object_timelines[obj_idx][arr_idx -1]
2261 | if changed:
2262 | object_animates[obj_idx] = True
2263 |
2264 | anims_strings = []
2265 | # write phase:
2266 | to_deg = 360 / math.tau
2267 | rot_fix = np.array((to_deg, -to_deg, to_deg))
2268 | for idx, timeline in enumerate(object_timelines):
2269 | if not object_animates[idx]:
2270 | continue
2271 | log.error(f"writing obj:{idx}")
2272 |
2273 | timeline_repr = ['''{
2274 | "actor": "''', anim_objs[idx][1], '",'
2275 | ]
2276 |
2277 | translations = np.empty((num_frames, 4), dtype=np.float32)
2278 | rotations = np.empty((num_frames, 4), dtype=np.float32)
2279 | scales = np.empty((num_frames, 4), dtype=np.float32)
2280 | translations[:, 0] = np.arange(frame_start, frame_end+1)
2281 | rotations[:, 0] = np.arange(frame_start, frame_end+1)
2282 | scales[:, 0] = np.arange(frame_start, frame_end+1)
2283 |
2284 | for frame_idx, frame_mat in enumerate(timeline):
2285 | loc, rot, scale = frame_mat.decompose()
2286 | tx_slice = (frame_idx, slice(1,4))
2287 | translations[frame_idx, 1:4] = loc
2288 | rotations[frame_idx, 1:4] = rot_fix * rot.to_euler('XYZ')
2289 | scales[frame_idx, 1:4] = scale
2290 |
2291 | trans_expression = ",".join(
2292 | '{"id":%d,"x":%f,"y":%f,"z":%f}'% tuple(v)
2293 | for v in translations
2294 | )
2295 | timeline_repr.extend(('"trans":[', trans_expression, '],'))
2296 |
2297 | rot_expression = ",".join(
2298 | '{"id":%d,"x":%f,"y":%f,"z":%f}'% tuple(v)
2299 | for v in rotations
2300 | )
2301 | timeline_repr.extend(('"rot":[', rot_expression, '],'))
2302 |
2303 | scale_expression = ",".join(
2304 | '{"id":%d,"x":%f,"y":%f,"z":%f}'% tuple(v)
2305 | for v in scales
2306 | )
2307 | timeline_repr.extend(('"scl":[', scale_expression, '],'))
2308 |
2309 | timeline_repr.append('"type":"transform"}')
2310 | result = "".join(timeline_repr)
2311 | anims_strings.append(result)
2312 |
2313 | if anims_strings:
2314 | output = ["""
2315 | {
2316 | "version": "0.1",
2317 | "fps": """,
2318 | str(context.scene.render.fps),
2319 | """,
2320 | "animations": [""",
2321 | ",".join(anims_strings),
2322 | "]}"
2323 | ]
2324 |
2325 | output_text = "".join(output)
2326 | anims.append(output_text)
2327 |
2328 | # cleanup
2329 | context.scene.frame_set(frame_at_export_time)
2330 |
2331 |
2332 | environment = collect_environment(context.scene.world)
2333 |
2334 | log.info("Collecting materials")
2335 | materials = datasmith_context["materials"]
2336 | unique_materials = []
2337 | for material in materials:
2338 | found = False
2339 | for mat in unique_materials:
2340 | if material[0] is mat[0]:
2341 | found = True
2342 | break
2343 | if not found:
2344 | unique_materials.append(material)
2345 | material_nodes = [collect_pbr_material(mat) for mat in unique_materials]
2346 |
2347 | curves_image = get_datasmith_curves_image()
2348 | if curves_image:
2349 | get_or_create_texture("datasmith_curves", curves_image)
2350 |
2351 | log.info("finished collecting, now saving")
2352 |
2353 | basedir, file_name = path.split(save_path)
2354 | folder_name = file_name + '_Assets'
2355 | # make sure basepath_Assets directory exists
2356 | try:
2357 | os.makedirs(path.join(basedir, folder_name))
2358 | except FileExistsError as e:
2359 | pass
2360 |
2361 | log.info("writing anims")
2362 | anim_nodes = []
2363 | for anim in anims:
2364 |
2365 | filename = path.join(basedir, folder_name, "anim_new.json")
2366 | log.info("writing to file:%s" % filename)
2367 | with open(filename, 'w') as f:
2368 | f.write(output_text)
2369 |
2370 | anim = Node("LevelSequence", {"name": "anim_new"})
2371 | anim.push(Node("File", {"path": f"{folder_name}/anim_new.json"}))
2372 | anim_nodes.append(anim)
2373 |
2374 |
2375 |
2376 |
2377 | log.info("writing meshes")
2378 | for mesh in datasmith_context["meshes"]:
2379 | mesh.save(basedir, folder_name)
2380 |
2381 |
2382 |
2383 | log.info("writing textures")
2384 |
2385 | tex_nodes = []
2386 | use_gamma_hack = args["use_gamma_hack"]
2387 | for tex in datasmith_context["textures"]:
2388 | tex_node = save_texture(tex, basedir, folder_name, minimal_export, use_gamma_hack)
2389 | tex_nodes.append(tex_node)
2390 |
2391 | log.info("building XML tree")
2392 |
2393 | n = get_file_header()
2394 |
2395 | for anim in anim_nodes:
2396 | n.push(anim)
2397 |
2398 | for obj in objects:
2399 | n.push(obj)
2400 |
2401 | if environment:
2402 | for env in environment:
2403 | n.push(env)
2404 |
2405 | for mesh in datasmith_context["meshes"]:
2406 | n.push(mesh.node())
2407 | for mat in material_nodes:
2408 | n.push(mat)
2409 |
2410 | for tex in tex_nodes:
2411 | n.push(tex)
2412 |
2413 | for metadata in datasmith_context["metadata"]:
2414 | n.push(metadata)
2415 |
2416 | end_time = time.monotonic()
2417 | total_time = end_time - start_time
2418 |
2419 | log.info("generating datasmith data took:%f"%total_time)
2420 | n.push(
2421 | Node("Export", {"Duration":total_time})
2422 | )
2423 |
2424 | log.info("generating xml")
2425 | result = n.string_rep(first=True)
2426 |
2427 | filename = path.join(basedir, file_name + '.udatasmith')
2428 | log.info("writing to file: %s" % filename)
2429 |
2430 | with open(filename, 'w') as f:
2431 | f.write(result)
2432 | log.info("export finished")
2433 |
2434 |
2435 |
2436 | def save(context, *, filepath, **kwargs):
2437 |
2438 | handler = None
2439 | use_logging = bool(kwargs["use_logging"])
2440 |
2441 | if use_logging:
2442 | log_path = filepath + ".log"
2443 | handler = logging.FileHandler(log_path, mode='w')
2444 |
2445 | formatter = logging.Formatter(
2446 | fmt='%(asctime)s.%(msecs)03d %(levelname)-8s %(message)s',
2447 | datefmt='%Y-%m-%d %H:%M:%S'
2448 | )
2449 | handler.setFormatter(formatter)
2450 | log.addHandler(handler)
2451 | log.setLevel(logging.DEBUG)
2452 | handler.setLevel(logging.DEBUG)
2453 | try:
2454 | from os import path
2455 | basepath, ext = path.splitext(filepath)
2456 |
2457 | log.info("Starting Datasmith Export")
2458 | collect_and_save(context, kwargs, basepath)
2459 | log.info("Finished Datasmith Export")
2460 |
2461 | except Exception as error:
2462 | log.error("Datasmith export error:")
2463 | log.error(error)
2464 | raise
2465 |
2466 | finally:
2467 | if use_logging:
2468 | log.info("Finished logging to path:" + log_path)
2469 | handler.close()
2470 | log.removeHandler(handler)
2471 |
2472 | return {'FINISHED'}
2473 |
2474 |
--------------------------------------------------------------------------------
/testing/README.md:
--------------------------------------------------------------------------------
1 | # Testing tools
2 | In this folder there is a python script that runs the export command, with some
3 | extra steps for testing, and a powershell script that runs the command on
4 | different test files. you can use these as sample scripts for your convenience.
5 |
6 |
--------------------------------------------------------------------------------
/testing/datasmith.prof:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Meisoftcoltd/blender-datasmith-export/ea4e5146b8e34e5f828c556781f40710919852bf/testing/datasmith.prof
--------------------------------------------------------------------------------
/testing/export_all.ps1:
--------------------------------------------------------------------------------
1 |
2 | param (
3 | [switch] $benchmark = $false
4 | )
5 |
6 | Push-Location $PSScriptRoot
7 |
8 | $test_files = (
9 | "archiviz/archiviz.blend",
10 | "barbershop/barbershop_interior_cpu.blend",
11 | "blender_splash_fishy_cat/fishy_cat.blend",
12 | "classroom/classroom.blend",
13 | "forest/forest.blend",
14 | "mr_elephant/mr_elephant.blend",
15 | "pabellon_barcelona/pavillon_barcelone_v1_2.blend",
16 | "pokedstudio/splash-pokedstudio.blend",
17 | "race_spaceship/race_spaceship.blend",
18 | "stylized_levi/stylized_levi.blend",
19 | "temple/temple.blend",
20 | "the_junk_shop/the_junk_shop.blend",
21 | "tree_creature/tree_creature.blend",
22 | "wanderer/wanderer.blend",
23 | "wasp_bot/wasp_bot.blend"
24 | )
25 |
26 | $args = @()
27 |
28 | if ($benchmark) {
29 | $args += "-benchmark"
30 | }
31 | $env:blender_args = $args
32 |
33 | Measure-Command -Expression {
34 | foreach ($file in $test_files) {
35 | blender -b $file -P test_datasmith_export.py -- $env:blender_args
36 | }
37 | }
38 |
39 | # best time: 9:05, intel i7 4790k
40 |
41 |
42 | Pop-Location
43 |
--------------------------------------------------------------------------------
/testing/test_datasmith_export.py:
--------------------------------------------------------------------------------
1 | #
2 | #
3 | # datasmith export test suite
4 | # run this file with the following command:
5 | # blender -b sample_file.blend -P test_datasmith_export.py
6 |
7 | import bpy
8 | import bpy.ops
9 | import logging
10 | import os
11 | import shutil
12 | import sys
13 | import time
14 |
15 | is_benchmark = "-benchmark" in sys.argv
16 |
17 | logging_level = logging.DEBUG # INFO
18 |
19 | if is_benchmark:
20 | logging_level = logging.WARNING
21 |
22 | logging.basicConfig(
23 | level=logging_level,
24 | # format='%(asctime)s.%(msecs)03d %(name)-12s %(levelname)-8s %(message)s',
25 | format='%(asctime)s.%(msecs)03d %(levelname)-8s %(message)s',
26 | datefmt='%Y-%m-%d %H:%M:%S'
27 | )
28 | log = logging.getLogger()
29 |
30 | clean_path = os.path.normpath(bpy.data.filepath)
31 |
32 | base_dir, file_name = os.path.split(clean_path)
33 | name, ext = os.path.splitext(file_name)
34 | target_path = os.path.join(base_dir, name + ".udatasmith")
35 |
36 |
37 | log.info("basedir %s", base_dir)
38 | use_diff = True
39 | backup_path = None
40 | if use_diff and os.path.isfile(target_path):
41 | log.info("backing up previous test")
42 | last_modification_time = os.path.getmtime(target_path)
43 | time_str = time.strftime('%Y%m%d_%H%M%S', time.localtime(last_modification_time))
44 | backup_path = os.path.join(base_dir, "%s_%s.udatasmith" % (name, time_str))
45 | log.debug("last modification was:%s", backup_path)
46 | shutil.copy(target_path, backup_path)
47 |
48 | log.info("Starting automated export")
49 |
50 | custom_args = {}
51 | custom_args["use_gamma_hack"] = False
52 | custom_args["apply_modifiers"] = True
53 | custom_args["export_animations"] = True
54 | custom_args["compatibility_mode"] = False
55 | custom_args["minimal_export"] = False
56 | custom_args["use_logging"] = True
57 | custom_args["use_profiling"] = False
58 | custom_args["write_metadata"] = False
59 |
60 | if "-benchmark" in sys.argv:
61 | custom_args["use_logging"] = False
62 |
63 |
64 | bpy.ops.export_scene.datasmith(filepath=target_path, **custom_args)
65 | log.info("Ended automated export")
66 |
67 | # right now this is not so useful as the export is non deterministic
68 | # i guess it is because the usage of dictionaries
69 | do_file_diff = True
70 |
71 | if "-benchmark" in sys.argv:
72 | do_file_diff = False
73 |
74 | # todo: if size is less than 2MB
75 | if backup_path and do_file_diff:
76 | log.info("writing diff file")
77 | import difflib
78 |
79 | with open(backup_path) as ff:
80 | from_lines = ff.readlines()
81 | with open(target_path) as tf:
82 | to_lines = tf.readlines()
83 |
84 | diff = difflib.unified_diff(from_lines, to_lines, backup_path, target_path)
85 |
86 | new_modification_time = os.path.getmtime(target_path)
87 | new_time_str = time.strftime('%Y%m%d_%H%M%S', time.localtime(new_modification_time))
88 | diff_path = os.path.join(base_dir, "export_diff_%s.diff" % new_time_str)
89 | with open(diff_path, 'w') as diff_file:
90 | diff_file.writelines(diff)
91 | static_diff_path = os.path.join(base_dir, "export_diff.diff")
92 | shutil.copy(diff_path, static_diff_path)
93 |
94 |
95 |
--------------------------------------------------------------------------------