-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathimporter.py
executable file
·2170 lines (1777 loc) · 82.9 KB
/
importer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
""" This files contains classes that interpret the .egg object model and write
out the appropriate Blender structures. """
from .eggparser import parse_egg, parse_number
import sys, os
import bpy
import io, zlib
from mathutils import Matrix, Vector
from math import radians, sqrt
DEFAULT_UV_NAME = "UVMap"
if bpy.app.version >= (2, 80):
def matmul(a, b):
return a.__matmul__(b)
else:
def matmul(a, b):
return a * b
class EggContext:
# These matrices are used for coordinate system conversion.
y_to_z_up_mat = Matrix(((1.0, 0.0, 0.0, 0.0),
(0.0, 0.0, 1.0, 0.0),
(0.0,-1.0, 0.0, 0.0),
(0.0, 0.0, 0.0, 1.0)))
flip_y_mat = Matrix(((1.0, 0.0, 0.0, 0.0),
(0.0,-1.0, 0.0, 0.0),
(0.0, 0.0, 1.0, 0.0),
(0.0, 0.0, 0.0, 1.0)))
def __init__(self):
self.vertex_pools = {}
self.materials = {}
self.textures = {}
self.search_dir = None
self.current_file = None
self.duplicate_faces = 0
self.degenerate_faces = 0
# For presumably historical reasons, .egg defaults to Y-Up-Right.
self.coord_system = None
self.up_vector = Vector((0, 0, 0))
self.right_vector = Vector((1, 0, 0))
self.forward_vector = Vector((0, 0, 0))
self.cs_matrix = self.y_to_z_up_mat
self.inv_cs_matrix = self.y_to_z_up_mat.inverted()
# Remember external references.
self.external_groups = {}
# We remember all the Group/VertexRef entries, so we can assign them
# in a separate pass.
self.group_vertex_refs = []
self.joints = {}
self.bundle_actions = {}
self.character_objects = {}
def read_file(self, path):
""" Reads an .egg file, returning a root EggGroupNode. """
if path.endswith('.pz') or path.endswith('.gz'):
data = zlib.decompress(open(path, 'rb').read(), 32 + 15).decode('utf-8')
elif not os.path.isfile(path) and not os.path.splitext(path)[1]:
# Implicit .egg extension.
data = open(path + '.egg', 'r').read()
else:
data = open(path, 'r').read()
buffer = io.StringIO(data)
root = EggGroupNode()
self.current_file = buffer
try:
parse_egg(buffer, root, self)
except Exception as ex:
lineno = self.get_current_lineno()
self.current_file = None
msg = "Encountered %s at line %d of %s: %s" % (type(ex).__name__, lineno, os.path.basename(path), ex)
print(msg, file=sys.stderr)
self.error(msg)
raise
finally:
self.current_file = None
buffer.close()
return root
def get_current_lineno(self):
""" Returns the current line number. """
if self.current_file:
charno = self.current_file.tell()
lineno = self.current_file.getvalue()[:charno].count('\n') + 1
return lineno
def prefix_message(self, msg):
""" Returns a formatted error message, possibly prefixed with line
number. """
lineno = self.get_current_lineno()
if lineno:
msg = "At line %d: %s" % (lineno, msg)
return msg
def info(self, message):
""" Called when the importer wants to report something. This can be
overridden to do something useful, such as report to the user. """
pass
def warn(self, message):
""" Called when the importer wants to warn about something. This can
be overridden to do something useful, such as report to the user. """
pass
def error(self, message):
""" Called when the importer wants to error about something. This can
be overridden to do something useful, such as report to the user. """
pass
def set_coordinate_system(self, coordsys):
""" Called when a <CoordinateSystem> entry is encountered in the .egg
file. This can occur anywhere in the .egg file, but there may not be
two mismatching entries. """
# Canonicalise coordinate system value.
canonical = coordsys.strip().upper().replace('-', '').replace('_', '').replace('RIGHT', '')
if canonical == 'ZUP':
self.cs_matrix = Matrix.Identity(4)
self.up_vector = Vector((0, 0, 1))
self.forward_vector = Vector((0, 1, 0))
elif canonical == 'YUP':
self.cs_matrix = self.y_to_z_up_mat
self.up_vector = Vector((0, 1, 0))
self.forward_vector = Vector((0, 0, -1))
elif canonical == 'ZUPLEFT':
self.cs_matrix = self.flip_y_mat
self.up_vector = Vector((0, 0, 1))
self.forward_vector = Vector((0, -1, 0))
elif canonical == 'YUPLEFT':
self.cs_matrix = matmul(self.y_to_z_up_mat, self.flip_y_mat)
self.up_vector = Vector((0, 1, 0))
self.forward_vector = Vector((0, 0, 1))
else:
self.error("Invalid coordinate system '{}' in .egg file.".format(coordsys))
return
if self.coord_system is not None and self.coord_system != coordsys:
self.error("Mismatching <CoordinateSystem> tags in .egg file.")
return
self.inv_cs_matrix = self.cs_matrix.inverted()
self.coord_system = coordsys
def transform_matrix(self, matrix):
""" Transforms the given matrix from the egg file's coordinate system
into the Z-Up-Right coordinate system. """
if self.coord_system == 'ZUP':
return matrix
else:
return matmul(matmul(self.inv_cs_matrix, matrix), self.cs_matrix)
def final_report(self):
""" Makes error messages about things that are tallied up, such as
duplicate faces. Called after importing is done. """
if self.duplicate_faces > 0:
self.warn("Removed {} duplicate faces".format(self.duplicate_faces))
if self.degenerate_faces > 0:
self.warn("Removed {} degenerate faces".format(self.degenerate_faces))
def load_image(self, path):
""" Loads an image from disk as Blender image. """
if sys.platform == 'win32':
# Convert an absolute Panda-style path to a Windows path.
if len(path) > 3 and path[0] == '/' and path[2] == '/':
path = path.replace('/', '\\')
path = path[1].upper() + ':' + path[2:]
path = path.replace('/', os.sep)
# If it's a relative path, search in the location of the .egg first.
if not os.path.isabs(path) and self.search_dir and os.path.exists(os.path.join(self.search_dir, path)):
path = os.path.join(self.search_dir, path)
path = path.replace(os.sep + '.' + os.sep, os.sep)
image = bpy.data.images.load(path)
#image.filepath = path
else:
try:
# If the user has set a backup texture path in preferences, we should check there.
backup_path = bpy.context.preferences.addons[__package__].preferences.backup_texpath
if backup_path and os.path.exists(os.path.join(backup_path, path)):
image = bpy.data.images.load(os.path.join(backup_path, path))
else:
# Try loading it with the original path, just in case.
image = bpy.data.images.load(path)
except RuntimeError:
# That failed, of course. OK, create a new image with this
# filename, and issue an error.
image = bpy.data.images.new(os.path.basename(path), 1, 1)
image.source = 'FILE'
image.filepath = path
self.error("Unable to find texture {}".format(path))
return image
def assign_vertex_groups(self):
""" Called at the end, to assign all of the vertex groups. """
for name, vertex_ref in self.group_vertex_refs:
vpool = self.vertex_pools[vertex_ref.pool]
for group in vpool.groups:
vertex_groups = group.mesh_object.vertex_groups
if name in vertex_groups:
vertex_group = vertex_groups[name]
else:
vertex_group = vertex_groups.new(name=name)
# Remap the indices to this object.
indices = set()
for index in vertex_ref.indices:
vertex = vpool[index]
if vertex in group.vertices:
indices.add(group.vertices[vertex])
if indices:
vertex_group.add(tuple(indices), vertex_ref.membership, 'ADD')
self.group_vertex_refs.clear()
def get_external_group(self, path):
""" Returns the group used for an external reference. """
if path in self.external_groups:
return self.external_groups[path]
group = bpy.data.groups.new(path)
self.external_groups[path] = group
return group
def load_external_references(self):
""" Resolves external file references. """
if not self.external_groups:
pass
orig_scene = bpy.context.scene
orig_search_dir = self.search_dir
# Please note that things may be added to self.external_groups
# recursively.
for path, group in self.external_groups.items():
# Create a separate scene for this model.
scene = bpy.data.scenes.new(path)
# XXX New blender API breaks this
# https://blender.stackexchange.com/a/179196
if bpy.app.version <= (2, 79, 7):
bpy.context.screen.scene = scene
else:
bpy.context.window.scene = scene
# Convert the external scene.
path = os.path.join(orig_search_dir, path)
self.search_dir = os.path.dirname(path)
root = self.read_file(path)
root.build_tree(self)
self.assign_vertex_groups()
# Assign all objects in the loaded scene to the group.
for obj in scene.objects:
group.objects.link(obj)
if bpy.app.version <= (2, 79, 7):
bpy.context.screen.scene = orig_scene
else:
bpy.context.window.scene = orig_scene
self.search_dir = orig_search_dir
def auto_bind(self):
""" Automatically binds animations to actors. """
for name, object in self.character_objects.items():
if name in self.bundle_actions:
if not object.animation_data:
object.animation_data_create()
object.animation_data.action = self.bundle_actions[name]
class EggRenderMode:
""" Accumulates render state attributes. """
def __init__(self, parent):
if parent is None:
self.alpha_mode = None
self.depth_write_mode = None
self.depth_test_mode = None
self.visibility_mode = None
self.depth_offset = None
self.draw_order = None
self.bin = None
else:
self.alpha_mode = parent.alpha_mode
self.depth_write_mode = parent.depth_write_mode
self.depth_test_mode = parent.depth_test_mode
self.visibility_mode = parent.visibility_mode
self.depth_offset = parent.depth_offset
self.draw_order = parent.draw_order
self.bin = parent.bin
def parse_scalar(self, name, value):
pass
class EggMaterial:
__slots__ = 'name', 'base', 'diff', 'amb', 'emit', 'spec', 'shininess', 'roughness', 'metallic', 'ior', 'materials'
def __init__(self, name):
self.name = name
self.base = [1, 1, 1, 1]
self.diff = None
self.amb = [1, 1, 1, 1]
self.emit = [0, 0, 0, 1]
self.spec = [0, 0, 0, 1]
self.shininess = 0
self.roughness = None
self.metallic = 0
self.ior = None
self.materials = {}
def begin_child(self, context, type, name, values):
if type.upper() in ('SCALAR', 'CHAR*'):
name = name.lower()
value = parse_number(values[0])
if name == 'baser':
self.base[0] = value
elif name == 'baseg':
self.base[1] = value
elif name == 'baseb':
self.base[2] = value
elif name == 'basea':
self.base[3] = value
elif name == 'diffr':
if not self.diff:
self.diff = [1, 1, 1, 1]
self.diff[0] = value
elif name == 'diffg':
if not self.diff:
self.diff = [1, 1, 1, 1]
self.diff[1] = value
elif name == 'diffb':
if not self.diff:
self.diff = [1, 1, 1, 1]
self.diff[2] = value
elif name == 'diffa':
if not self.diff:
self.diff = [1, 1, 1, 1]
self.diff[3] = value
elif name == 'ambr':
self.amb[0] = value
elif name == 'ambg':
self.amb[1] = value
elif name == 'ambb':
self.amb[2] = value
elif name == 'amba':
self.amb[3] = value
elif name == 'emitr':
self.emit[0] = value
elif name == 'emitg':
self.emit[1] = value
elif name == 'emitb':
self.emit[2] = value
elif name == 'emita':
self.emit[3] = value
elif name == 'specr':
self.spec[0] = value
elif name == 'specg':
self.spec[1] = value
elif name == 'specb':
self.spec[2] = value
elif name == 'speca':
self.spec[3] = value
elif name == 'shininess':
self.shininess = value
elif name == 'roughness':
self.roughness = value
elif name == 'metallic':
self.metallic = value
elif name == 'ior':
self.ior = value
def _get_material_28(self, group, prim):
""" Returns the material for the indicated primitive. """
bface = prim.bface
textures = prim.textures
alpha = prim.alpha_mode
if group.have_vertex_colors:
flat_color = None
else:
flat_color = prim.color or (1, 1, 1, 1)
if len(textures) == 0 and self is EggPrimitive.default_material \
and not bface \
and not alpha \
and tuple(flat_color) == (1, 1, 1, 1) \
and not group.blend_mode:
return None
# Uniquify equivalent materials.
key = (tuple(textures), flat_color, bface, alpha, group.blend_mode,
group.blend_operands[0], group.blend_operands[1])
if key in self.materials:
return self.materials[key]
# <Polygon> objects may have more the one <TRef> assigned to them.
# However, EGG files most commonly have either 1 or 0 TRefs associated with them.
# If a <Polygon> has two <TRefs> registered, regardless if that TRef is used in
# another area, it will become its own unique material.
# If there is a Polygon with two+ TRefs, a new material will be made with the TRef names aggregated.
self.name = '_'.join(tex.name for tex in textures)
bmat = bpy.data.materials.new(self.name)
bmat.specular_intensity = 1.0
use_vertex_color = False
if self.diff:
bmat.diffuse_color = self.diff
elif flat_color:
bmat.diffuse_color = flat_color
else:
# There are vertex colors. Apply via nodes, below.
bmat.diffuse_color = [1, 1, 1, 1]
use_vertex_color = True
bmat.specular_color = self.spec[:3]
if self.roughness is not None:
bmat.roughness = self.roughness
else:
bmat.roughness = sqrt(sqrt(2.0 / (self.shininess + 2.0)))
bmat.metallic = self.metallic
if self.ior is not None and hasattr(bmat, "ior"):
bmat.ior = self.ior
if (group.blend_mode in ('add', 'subtract') and group.blend_operands == ['fbuffer_color', 'zero']) or \
(group.blend_mode in ('add', 'inv_subtract') and group.blend_operands == ['zero', 'incoming_color']):
bmat.blend_method = 'MULTIPLY'
elif group.blend_mode == 'add':
bmat.blend_method = 'ADD'
elif alpha:
alpha = alpha.lower()
if alpha == 'off':
bmat.blend_method = 'OPAQUE'
elif alpha.startswith('ms'):
bmat.blend_method = 'HASHED'
elif alpha == 'binary':
bmat.blend_method = 'CLIP'
else:
bmat.blend_method = 'BLEND'
bmat.use_backface_culling = not bface
# If we have an emission color, or any textures, we need to build up
# a node graph.
if textures or any(self.emit[:3]) or use_vertex_color:
self._make_nodes(bmat, textures, use_vertex_color)
self.materials[key] = bmat
return bmat
def _make_nodes(self, bmat, textures, use_vertex_color):
bmat.use_nodes = True
want_bsdf = bpy.context.preferences.addons[__package__].preferences.want_bsdf
if want_bsdf:
bsdf = bmat.node_tree.nodes["Principled BSDF"]
bsdf.inputs["Roughness"].default_value = bmat.roughness
bsdf.inputs["Metallic"].default_value = bmat.metallic
if self.ior is not None:
bsdf.inputs["IOR"].default_value = self.ior
if self.emit and bsdf.inputs.get("Emission"):
bsdf.inputs["Emission"].default_value = self.emit
if not any(self.spec[:3]) and bsdf.inputs.get("Specular"):
bsdf.inputs["Specular"].default_value = 0.0
color_out = bsdf.inputs['Base Color']
alpha_out = bsdf.inputs['Alpha']
else:
bsdf = bmat.node_tree.nodes["Principled BSDF"]
bmat.node_tree.nodes.remove(bsdf)
trans_bsdf = bmat.node_tree.nodes.new("ShaderNodeBsdfTransparent")
mix_shader_node = bmat.node_tree.nodes.new("ShaderNodeMixShader")
bmat.node_tree.links.new(mix_shader_node.inputs[1], trans_bsdf.outputs[0])
color_out = mix_shader_node.inputs[2]
alpha_out = mix_shader_node.inputs[0]
alpha_out.default_value = 1.0
if use_vertex_color:
col_node = bmat.node_tree.nodes.new("ShaderNodeAttribute")
col_node.attribute_name = "Col"
bmat.node_tree.links.new(color_out, col_node.outputs["Color"])
uv_nodes = {}
# Create nodes to sample and combine the various texture stages.
for i, texture in enumerate(textures):
tex_node = bmat.node_tree.nodes.new("ShaderNodeTexImage")
tex_node.image = texture.texture.image
tex_node.extension = texture.texture.extension
if texture.minfilter and texture.minfilter.startswith("nearest"):
tex_node.interpolation = "Closest"
# Determine whether the texture contributes to color and alpha.
has_color = texture.format != 'alpha'
if texture.format == 'alpha':
has_alpha = True
elif texture.format in ('red', 'green', 'blue', 'luminance', 'sluminance', 'rgb', 'rgb12', 'rgb8', 'rgb5', 'rgb332', 'srgb'):
has_alpha = False
elif texture.texture.image.channels < 4:
has_alpha = False
else:
# Determine whether the image has an alpha channel.
has_alpha = False
for alpha in tuple(texture.texture.image.pixels)[3::4]:
if alpha != 1.0:
has_alpha = True
break
if has_alpha and not want_bsdf:
bmat.blend_method = 'BLEND'
# Create an UVMap node, if none already exists for this UV set.
uv_layer = texture.uv_name or "UVMap"
if uv_layer not in uv_nodes:
uv_node = bmat.node_tree.nodes.new("ShaderNodeUVMap")
uv_node.uv_map = uv_layer
uv_nodes[uv_layer] = uv_node
else:
uv_node = uv_nodes[uv_layer]
# Convert the Panda texture transform to the equivalent Blender
# transform. Ignores rotation, shear, or axis remap.
m = texture.matrix
if m is not None:
map_node = bmat.node_tree.nodes.new("ShaderNodeMapping")
if bpy.app.version >= (2, 81):
map_node.inputs['Scale'].default_value = (m[0][0], m[1][1], m[2][2])
map_node.inputs['Location'].default_value = Vector((m[0][3], m[1][3], m[2][3]))
else:
map_node.scale = (m[0][0], m[1][1], m[2][2])
map_node.translation = Vector((m[0][3], m[1][3], m[2][3]))
bmat.node_tree.links.new(map_node.inputs['Vector'], uv_node.outputs['UV'])
bmat.node_tree.links.new(tex_node.inputs['Vector'], map_node.outputs['Vector'])
else:
bmat.node_tree.links.new(tex_node.inputs['Vector'], uv_node.outputs['UV'])
color = tex_node.outputs['Color']
alpha = tex_node.outputs['Alpha']
if texture.envtype == 'replace':
if has_color:
if color_out.is_linked:
bmat.node_tree.links.remove(color_out.links[0])
bmat.node_tree.links.new(color_out, color)
if has_alpha:
if alpha_out.is_linked:
bmat.node_tree.links.remove(alpha_out.links[0])
bmat.node_tree.links.new(alpha_out, color)
if texture.envtype in ('add', 'decal', 'blend', 'modulate', 'modulate_glow', 'modulate_gloss'):
if has_color and color_out.is_linked:
# We already have something mapped; add a mixing node.
mix_node = bmat.node_tree.nodes.new("ShaderNodeMixRGB")
mix_node.inputs["Fac"].default_value = 1.0
old_socket = color_out.links[0].from_socket
bmat.node_tree.links.remove(color_out.links[0])
bmat.node_tree.links.new(old_socket, mix_node.inputs['Color1'])
if texture.envtype == 'add':
mix_node.blend_type = 'ADD'
bmat.node_tree.links.new(color, mix_node.inputs['Color2'])
elif texture.envtype == 'decal':
mix_node.blend_type = 'MIX'
bmat.node_tree.links.new(color, mix_node.inputs['Color2'])
bmat.node_tree.links.new(alpha, mix_node.inputs['Fac'])
elif texture.envtype == 'blend':
mix_node.blend_type = 'MIX'
mix_node.inputs['Color2'].default_value = texture.color
bmat.node_tree.links.new(color, mix_node.inputs['Fac'])
else:
mix_node.blend_type = 'MULTIPLY'
bmat.node_tree.links.new(color, mix_node.inputs['Color2'])
color = mix_node.outputs['Color']
if has_color:
bmat.node_tree.links.new(color_out, color)
if has_alpha and texture.envtype != 'decal':
if alpha_out.is_linked:
# Add a node to multiply the alpha values.
mul_node = bmat.node_tree.nodes.new("ShaderNodeMath")
mul_node.operation = 'MULTIPLY'
old_socket = alpha_out.links[0].from_socket
bmat.node_tree.links.remove(alpha_out.links[0])
bmat.node_tree.links.new(old_socket, mul_node.inputs[0])
bmat.node_tree.links.new(alpha, mul_node.inputs[1])
alpha = mul_node.outputs['Value']
bmat.node_tree.links.new(alpha_out, alpha)
if want_bsdf:
if texture.envtype in ('normal', 'normal_height', 'normal_gloss'):
bmat.node_tree.links.new(bsdf.inputs['Normal'], color)
if texture.envtype in ('gloss', 'modulate_gloss', 'normal_gloss'):
bmat.node_tree.links.new(bsdf.inputs['Specular'], alpha)
if texture.envtype in ('glow', 'modulate_glow'):
bmat.node_tree.links.new(bsdf.inputs['Emission Strength'], alpha)
if texture.envtype == 'emission':
# Multiply in the emission color, if we have one.
if self.emit and tuple(self.emit[:3]) != (1, 1, 1):
mul_node = bmat.node_tree.nodes.new('ShaderNodeMixRGB')
mul_node.blend_type = 'MULTIPLY'
mul_node.inputs['Fac'].default_value = 1.0
mul_node.inputs['Color2'].default_value = self.emit
bmat.node_tree.links.new(mul_node.inputs['Color1'], color)
bmat.node_tree.links.new(bsdf.inputs['Emission'], mul_node.outputs[0])
else:
bmat.node_tree.links.new(bsdf.inputs['Emission'], mul_node.outputs[0])
if texture.envtype == 'selector' and \
(bmat.metallic != 0.0 or bmat.roughness is None or bmat.roughness != 0.0):
# This slot is, by convention, used for metallic-roughness.
sep_node = bmat.node_tree.nodes.new('ShaderNodeSeparateRGB')
bmat.node_tree.links.new(sep_node.inputs[0], color)
if bmat.metallic != 1.0:
mul_node = bmat.node_tree.nodes.new("ShaderNodeMath")
mul_node.operation = 'MULTIPLY'
mul_node.inputs[1].default_value = bmat.metallic
bmat.node_tree.links.new(mul_node.inputs[0], sep_node.outputs['B'])
bmat.node_tree.links.new(bsdf.inputs['Metallic'], mul_node.outputs[0])
else:
bmat.node_tree.links.new(bsdf.inputs['Metallic'], sep_node.outputs['B'])
if bmat.roughness is not None and bmat.roughness != 1.0:
mul_node = bmat.node_tree.nodes.new("ShaderNodeMath")
mul_node.operation = 'MULTIPLY'
mul_node.inputs[1].default_value = bmat.roughness
bmat.node_tree.links.new(mul_node.inputs[0], sep_node.outputs['G'])
bmat.node_tree.links.new(bsdf.inputs['Roughness'], mul_node.outputs[0])
else:
bmat.node_tree.links.new(bsdf.inputs['Roughness'], sep_node.outputs['G'])
# Assign each node to a column. The method below ensures that
# connections always flow from left to right, never right to left.
node_column = {}
column_widths = {}
def r_assign_nodes_to_column(node, col):
if node in node_column:
col = min(node_column[node], col)
node_column[node] = col
width = node.width
if col in column_widths:
width = max(width, column_widths[col])
column_widths[col] = width
for socket in node.inputs.values():
for link in socket.links:
if link.from_node != node:
r_assign_nodes_to_column(link.from_node, col - 1)
mat_out_node = bmat.node_tree.nodes["Material Output"]
mat_in = mat_out_node.inputs[0]
if not want_bsdf:
if mat_in.is_linked:
bmat.node_tree.links.remove(mat_in.links[0])
bmat.node_tree.links.new(mat_in, mix_shader_node.outputs[0])
# The "Material Output" node is to the right of the BSDF node.
r_assign_nodes_to_column(mat_out_node, 1)
column_rows = {}
for node, col in node_column.items():
if col not in column_rows:
column_rows[col] = 0
row = column_rows[col]
column_rows[col] += 1
# Determine the x for the column.
x = 300.0
col2 = col
while col2 <= 0:
x -= column_widths[col2] + 50.0
col2 += 1
node.location = (x, -300.0 * (row - 1))
def _get_material_27(self, group, prim):
""" Returns the material for the indicated primitive. """
if group.have_vertex_colors:
flat_color = None
else:
flat_color = prim.color or (1, 1, 1, 1)
bface = prim.bface
textures = prim.textures
alpha = prim.alpha_mode
if len(textures) == 0 and self is EggPrimitive.default_material and not bface and not alpha:
return None
key = (tuple(textures), flat_color, bface, alpha)
if key in self.materials:
return self.materials[key]
bmat = bpy.data.materials.new(self.name)
bmat.diffuse_intensity = 1.0
bmat.specular_intensity = 1.0
bmat.specular_hardness = self.shininess * 2
if not any(self.spec) and self.diff and not any(self.diff) and not any(self.amb):
# This is YABEE's way of making a shadeless material.
bmat.use_shadeless = True
bmat.diffuse_color = self.emit[:3]
else:
if self.diff:
bmat.diffuse_color = self.diff[:3]
elif flat_color:
bmat.diffuse_color = flat_color[:3]
else:
bmat.diffuse_color = [1, 1, 1]
bmat.specular_color = self.spec[:3]
bmat.specular_alpha = self.spec[3]
# Blender only supports one ambient value, so we average it.
bmat.ambient = (self.amb[0] + self.amb[1] + self.amb[2]) / 3
# Same for emission, except that it specifes the emission as a product
# of the diffuse color, so we have to divide it.
if any(bmat.diffuse_color):
bmat.emit = sum(self.emit[:3]) / sum(bmat.diffuse_color)
if group.blend_mode and group.blend_mode == 'add':
bmat.game_settings.alpha_blend = 'ADD'
elif alpha:
alpha = alpha.lower()
if alpha == 'off':
bmat.game_settings.alpha_blend = 'OPAQUE'
elif alpha.startswith('ms'):
bmat.game_settings.alpha_blend = 'ALPHA_ANTIALIASING'
elif alpha == 'binary':
bmat.game_settings.alpha_blend = 'CLIP'
else:
bmat.game_settings.alpha_blend = 'ALPHA'
bmat.game_settings.use_backface_culling = not bface
for i, texture in enumerate(textures):
slot = bmat.texture_slots.add()
slot.texture = texture.texture
slot.uv_layer = texture.uv_name or "UVMap"
# Convert the Panda texture transform to the equivalent Blender
# transform. Ignores rotation, shear, or axis remap.
m = texture.matrix
if m is not None:
pos = Vector((m[0][3], m[1][3], m[2][3]))
slot.scale = (m[0][0], m[1][1], m[2][2])
slot.offset = pos + (slot.scale - Vector((1, 1, 1))) * 0.5
if texture.envtype == 'modulate':
slot.use_map_color_diffuse = True
elif texture.envtype == 'normal':
slot.use_map_color_diffuse = False
slot.use_map_normal = True
elif texture.envtype == 'glow':
slot.use_map_color_diffuse = True
slot.use_map_emit = True
elif texture.envtype == 'gloss':
slot.use_map_color_diffuse = True
slot.use_map_specular = True
# Should probably be more sophisticated; right now this is to
# support what YABEE generates.
if texture.blend == 'add' and not alpha:
bmat.game_settings.alpha_blend = 'ADD'
self.materials[key] = bmat
return bmat
if bpy.app.version >= (2, 80):
get_material = _get_material_28
else:
get_material = _get_material_27
class EggTexture:
def __init__(self, name, image):
self.texture = bpy.data.textures.new(name, 'IMAGE')
self.name = name
self.texture.image = image
self.format = None
self.envtype = 'modulate'
self.uv_name = None
self.matrix = None
self.priority = 0
self.blend = None
self.warned_vpools = set()
self.color = [0, 0, 0, 1]
self.minfilter = None
self.magfilter = None
def begin_child(self, context, type, name, values):
type = type.upper()
if type in ('SCALAR', 'CHAR*'):
name = name.lower()
if name == 'wrap':
value = values[0].lower()
if value == 'repeat':
self.texture.extension = 'REPEAT'
elif value == 'clamp':
self.texture.extension = 'EXTEND'
elif value in ('border_color', 'border-color'):
self.texture.extension = 'CLIP'
elif name == 'format':
self.format = values[0].lower().replace('-', '_')
elif name == 'envtype':
self.envtype = values[0].lower().replace('-', '_')
if self.envtype in ('normal', 'normal_height', 'normal_gloss'):
self.texture.use_normal_map = True
self.texture.image.colorspace_settings.name = 'Non-Color'
elif name == 'minfilter':
self.minfilter = values[0].lower()
if 'mipmap' in self.minfilter:
self.texture.use_mipmap = True
elif name == 'alpha':
if values[0].lower() == 'premultiplied':
self.texture.image.alpha_mode = 'PREMUL'
elif name == 'blend':
self.blend = values[0].lower()
elif name == 'uv_name' or name == 'uv-name':
self.uv_name = values[0]
elif name == 'priority':
self.priority = int(values[0])
elif name == 'blendr':
self.color[0] = parse_number(values[0])
elif name == 'blendg':
self.color[1] = parse_number(values[0])
elif name == 'blendb':
self.color[2] = parse_number(values[0])
elif name == 'blenda':
self.color[3] = parse_number(values[0])
elif type == 'TRANSFORM':
return EggTransform()
def end_child(self, context, type, name, child):
if isinstance(child, EggTransform):
if self.matrix is not None:
self.matrix = matmul(self.matrix, child.matrix)
else:
self.matrix = child.matrix
class EggTransform:
__slots__ = 'matrix',
def __init__(self):
self.matrix = Matrix()
def begin_child(self, context, type, name, values):
v = [parse_number(v) for v in values]
type = type.upper()
if type == 'TRANSLATE':
if len(values) == 2:
self.matrix = matmul(Matrix.Translation(v + [0]), self.matrix)
else:
self.matrix = matmul(Matrix.Translation(v), self.matrix)
elif type == 'ROTATE':
self.matrix = matmul(Matrix.Rotation(radians(v[0]), 4, v[1:] or (0, 0, 1)), self.matrix)
elif type == 'ROTX':
self.matrix = matmul(Matrix.Rotation(radians(v[0]), 4, 'X'), self.matrix)
elif type == 'ROTY':
self.matrix = matmul(Matrix.Rotation(radians(v[0]), 4, 'Y'), self.matrix)
elif type == 'ROTZ':
self.matrix = matmul(Matrix.Rotation(radians(v[0]), 4, 'Z'), self.matrix)
elif type == 'SCALE':
if len(v) == 1:
x = y = z = v[0]
elif len(v) == 2:
x, y = v
z = 1
else:
x, y, z = v
self.matrix = matmul(Matrix(((x, 0, 0, 0), (0, y, 0, 0), (0, 0, z, 0), (0, 0, 0, 1))), self.matrix)
elif type == 'MATRIX3':
self.matrix = matmul(
Matrix(((v[0], v[3], 0.0, v[6]),
(v[1], v[4], 0.0, v[7]),
( 0.0, 0.0, 1.0, 0.0),
(v[2], v[5], 0.0, v[8]))), self.matrix)
elif type == 'MATRIX4':
self.matrix = matmul(
Matrix(((v[0], v[4], v[8], v[12]),
(v[1], v[5], v[9], v[13]),
(v[2], v[6], v[10], v[14]),
(v[3], v[7], v[11], v[15]))), self.matrix)
class EggVertex:
__slots__ = 'pos', 'normal', 'color', 'uv_map', 'aux_map', 'dxyzs'
def __init__(self, pos):
self.pos = pos
self.normal = None
self.color = None
self.uv_map = {}
self.aux_map = {}
self.dxyzs = {}
def begin_child(self, context, type, name, values):
type = type.upper()
if type == 'NORMAL':
self.normal = tuple(parse_number(v) for v in values)
elif type == 'RGBA':
self.color = tuple(parse_number(v) for v in values)
elif type == 'UV':
self.uv_map[name or DEFAULT_UV_NAME] = [parse_number(v) for v in values]
elif type == 'AUX':
self.aux_map[name] = [parse_number(v) for v in values]
elif type == 'DXYZ':
if not name:
name = values.pop(0)
self.dxyzs[name] = tuple(parse_number(v) for v in values)
def __hash__(self):
return hash(self.pos)
def __eq__(self, other):
return self.pos == other.pos
def __ne__(self, other):
return self.pos != other.pos
class EggVertexPool:
def __init__(self, name):
self.name = name