-
Notifications
You must be signed in to change notification settings - Fork 18
/
shared.py
2235 lines (1852 loc) · 87.4 KB
/
shared.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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
from typing import Iterable
import bpy
import mathutils
import random
import math
# from bpy_extras import io_utils
from os import path
from bpy_extras import image_utils
from . import im
lodEnum = [
("0", "None", "LOD has no effect"),
("1", "Low", "LOD cutoff or reduction takes effect if graphics are Low"),
("2", "Medium", "LOD cutoff or reduction takes effect if graphics are Medium"),
("3", "High", "LOD cutoff or reduction takes effect if graphics are High"),
("4", "Ultra", "LOD cutoff or reduction takes effect if graphics are Ultra")
]
materialNames = [
"No Material",
"Standard",
"Displacement",
"Composite",
"Terrain",
"Volume",
"Unknown [6]",
"Creep",
"Volume Noise",
"Splat Terrain Bake",
"Reflection",
"Lens Flare",
"Shader (MADD)",
]
standardMaterialTypeIndex = 1
displacementMaterialTypeIndex = 2
compositeMaterialTypeIndex = 3
terrainMaterialTypeIndex = 4
volumeMaterialTypeIndex = 5
creepMaterialTypeIndex = 7
volumeNoiseMaterialTypeIndex = 8
stbMaterialTypeIndex = 9
reflectionMaterialMaterialTypeIndex = 10
lensFlareMaterialTypeIndex = 11
bufferMaterialTypeIndex = 12
emissionAreaTypePoint = "0"
emissionAreaTypePlane = "1"
emissionAreaTypeSphere = "2"
emissionAreaTypeCuboid = "3"
emissionAreaTypeCylinder = "4"
emissionAreaTypeDisc = "5"
emissionAreaTypeMesh = "6"
attachmentVolumeNone = "-1"
attachmentVolumeCuboid = "0"
attachmentVolumeSphere = "1"
attachmentVolumeCapsule = "2"
forceShapeSphere = "0"
forceShapeCylinder = "1"
forceShapeBox = "2"
forceShapeHemisphere = "3"
forceShapeConeDome = "4"
lightTypePoint = "1"
lightTypeSpot = "2"
physicsJointSphere = "0"
physicsJointRevolute = "1"
physicsJointCone = "2"
physicsJointWeld = "3"
colorChannelSettingRGB = "0"
colorChannelSettingRGBA = "1"
colorChannelSettingA = "2"
colorChannelSettingR = "3"
colorChannelSettingG = "4"
colorChannelSettingB = "5"
defaultDepthBlendFalloff = 0.2 # default if it is enabled
tightHitTestBoneName = "HitTestTight"
rotFixMatrix = mathutils.Matrix(((0, 1, 0, 0),
(-1, 0, 0, 0),
(0, 0, 1, 0),
(0, 0, 0, 1)))
rotFixMatrixInverted = rotFixMatrix.transposed()
animFlagsForAnimatedProperty = 6
star2ParticlePrefix = "Star2Part"
star2RibbonPrefix = "Star2Ribbon"
star2ForcePrefix = "Star2Force"
star2ProjectionPrefix = "Star2 projector"
# Ref_ is the bone prefix for attachment points without volume and
# the prefix for all attachment point names (for volume attachment point names too)
attachmentPointPrefix = "Ref_"
attachmentVolumePrefix = "Vol_"
star2WarpPrefix = "SC2VertexWarp"
animObjectIdModel = "MODEL"
animObjectIdArmature = "ARMATURE"
animObjectIdScene = "SCENE"
lightPrefixMap = {"1": "Star2Omni", "2": "Star2Spot"}
layerFieldNameToNameMap = {
"diffuseLayer": "Diffuse",
"decalLayer": "Decal",
"specularLayer": "Specular",
"glossLayer": "Gloss",
"emissiveLayer": "Emissive",
"emissive2Layer": "Emissive 2",
"evioLayer": "Evio",
"evioMaskLayer": "Evio Mask",
"alphaMaskLayer": "Alpha Mask",
"alphaMask2Layer": "Alpha Mask 2",
"normalLayer": "Normal",
"heightLayer": "Height",
"colorDefiningLayer": "Color Defining Layer",
"normalBlendMask1": "Normal Blending Mask 1",
"normalBlendMask2": "Normal Blending Mask 2",
"normalBlendNormal1": "Normal Blending Normal 1",
"normalBlendNormal2": "Normal Blending Normal 2",
"lightMapLayer": "Light Map",
"ambientOcclussionLayer": "Ambient Occlussion",
"strengthLayer": "Strength",
"terrainLayer": "Terrain",
"colorLayer": "Color",
"noise1Layer": "Noise 1",
"noise2Layer": "Noise 2",
"creepLayer": "Creep",
"unknownLayer1": "Unknown Layer 1",
"unknownLayer2": "Unknown Layer 2",
}
exportAmountAllAnimations = "ALL_ANIMATIONS"
exportAmountCurrentAnimation = "CURRENT_ANIMATION"
exportAmountNoAnimations = "NO_ANIMATIONS"
class ExportError(Exception):
def __init__(self, message: str):
super().__init__(message)
self.message = message
def getLayerNameFromFieldName(fieldName):
name = layerFieldNameToNameMap.get(fieldName)
if name is None:
name = fieldName
return name
def layerFieldNamesOfM3Material(m3Material):
for field in m3Material.structureDescription.fields:
if hasattr(field, "referenceStructureDescription"):
if field.historyOfReferencedStructures.name == "LAYR":
yield field.name
def copyBpyProps(dst, src, skip=[]):
assert type(dst) == type(src)
props = type(dst).__annotations__.keys()
# TODO: should probably filter the annotations list to bpy.types.Property
for k in props:
if k in skip:
continue
setattr(dst, k, getattr(src, k))
return dst
def setDefaultValue(defaultAction, path, index, value):
curve = None
for c in defaultAction.fcurves:
if c.data_path == path and c.array_index == index:
curve = c
break
if curve is None:
curve = defaultAction.fcurves.new(path, index=index)
keyFrame = curve.keyframe_points.insert(0, value)
keyFrame.interpolation = "CONSTANT"
def findUnusedPropItemName(propGroups=[], suggestedNames=[], prefix=""):
usedNames = set()
for propGroup in propGroups:
for propItem in propGroup:
usedNames.add(propItem.name)
num = 1
if not prefix and suggestedNames:
for name in suggestedNames:
prefix = name
if name not in usedNames:
break
else:
if prefix.split(' ')[-1].isdigit():
prefix = ''.join(prefix.split(' ')[:-1])
name = prefix if prefix else suggestedNames[-1] if suggestedNames else ''
while True:
if name not in usedNames:
return name
name = prefix + (' 0' if prefix else '0') + str(num) if num < 10 else str(num)
num += 1
def toValidBoneName(name):
maxLength = 63
return name[:maxLength]
def boneNameForAttachmentPoint(attachmentPoint):
bonePrefix = attachmentPointPrefix if attachmentPoint.volumeType == "-1" else attachmentVolumePrefix
return bonePrefix + attachmentPoint.name
def attachmentPointNameFromBoneName(boneName):
if boneName.startswith(attachmentPointPrefix):
return boneName[len(attachmentPointPrefix):]
elif boneName.startswith(attachmentVolumePrefix):
return boneName[len(attachmentVolumePrefix):]
else:
return boneName
def boneNameForParticleSystem(particleSystem):
return toValidBoneName(star2ParticlePrefix + particleSystem.name)
def boneNameForRibbon(ribbon):
return toValidBoneName(star2RibbonPrefix + ribbon.name)
def boneNameForForce(force):
return toValidBoneName(star2ForcePrefix + force.name)
def boneNameForLight(light):
lightPrefix = lightPrefixMap.get(light.lightType)
return toValidBoneName(lightPrefix + light.name)
def boneNameForProjection(projection):
return toValidBoneName(star2ProjectionPrefix + projection.name)
def boneNameForWarp(warp):
return toValidBoneName(star2WarpPrefix + warp.name)
def iterateArmatureObjects(scene):
for obj in scene.objects:
if obj.type == "ARMATURE":
if obj.data is not None:
yield obj
def findArmatureObjectForNewBone(scene):
for obj in iterateArmatureObjects(scene):
return obj
return None
def findBoneWithArmatureObject(scene, boneName):
for armatureObject in iterateArmatureObjects(scene):
armature = armatureObject.data
bone = armature.bones.get(boneName)
if bone is not None:
return (bone, armatureObject)
return (None, None)
def scaleVectorToMatrix(scaleVector):
matrix = mathutils.Matrix()
matrix[0][0] = scaleVector[0]
matrix[1][1] = scaleVector[1]
matrix[2][2] = scaleVector[2]
return matrix
def locRotScaleMatrix(location, rotation, scale):
""" Important: rotation must be a normalized quaternion """
# to_matrix() only works properly with normalized quaternions.
result = rotation.to_matrix().to_4x4()
result.col[0] *= scale.x
result.col[1] *= scale.y
result.col[2] *= scale.z
result.translation = location
return result
def selectBone(scene, boneName):
bone, armature = findBoneWithArmatureObject(scene, boneName)
if bone is None or armature is None:
return
if bpy.ops.object.mode_set.poll():
bpy.ops.object.mode_set(mode='OBJECT')
if bpy.ops.object.select_all.poll():
bpy.ops.object.select_all(action='DESELECT')
armature.select_set(True)
scene.view_layers[0].objects.active = armature
if bpy.ops.object.mode_set.poll():
bpy.ops.object.mode_set(mode='POSE')
for b in armature.data.bones:
b.select = False
bone.select = True
armature.data.bones.active = bone
def removeBone(scene, boneName):
"removes the given bone if it exists"
bone, armatureObject = findBoneWithArmatureObject(scene, boneName)
if bone is None or armatureObject is None:
return
if bpy.ops.object.mode_set.poll():
bpy.ops.object.mode_set(mode='OBJECT')
if bpy.ops.object.select_all.poll():
bpy.ops.object.select_all(action='DESELECT')
armatureObject.select_set(True)
scene.view_layers[0].objects.active = armatureObject
if bpy.ops.object.mode_set.poll():
bpy.ops.object.mode_set(mode='EDIT')
armature = armatureObject.data
edit_bone = armature.edit_bones[boneName]
armature.edit_bones.remove(edit_bone)
if bpy.ops.object.mode_set.poll():
bpy.ops.object.mode_set(mode='POSE')
def selectOrCreateBone(scene, boneName):
"Returns the bone and it's pose variant"
if bpy.ops.object.mode_set.poll():
bpy.ops.object.mode_set(mode='OBJECT')
if bpy.ops.object.select_all.poll():
bpy.ops.object.select_all(action='DESELECT')
bone, armatureObject = findBoneWithArmatureObject(scene, boneName)
boneExists = bone is not None
if boneExists:
armature = armatureObject.data
armatureObject.select_set(True)
scene.view_layers[0].objects.active = armatureObject
else:
armatureObject = findArmatureObjectForNewBone(scene)
if armatureObject is None:
armature = bpy.data.armatures.new(name="Armature")
armatureObject = bpy.data.objects.new("Armature", armature)
scene.collection.objects.link(armatureObject)
else:
armature = armatureObject.data
armatureObject.select_set(True)
scene.view_layers[0].objects.active = armatureObject
bpy.ops.object.mode_set(mode='EDIT')
editBone = armature.edit_bones.new(name=boneName)
editBone.head = (0, 0, 0)
editBone.tail = (1, 0, 0)
if bpy.ops.object.mode_set.poll():
bpy.ops.object.mode_set(mode='POSE')
for boneOfArmature in armature.bones:
isBoneToSelect = boneOfArmature.name == boneName
boneOfArmature.select_head = isBoneToSelect
boneOfArmature.select_tail = isBoneToSelect
boneOfArmature.select = isBoneToSelect
armature.bones.active = bone
scene.view_layers[0].objects.active = armatureObject
armatureObject.select_set(True)
for currentBone in armature.bones:
currentBone.select = currentBone.name == boneName
poseBone = armatureObject.pose.bones[boneName]
bone = armatureObject.data.bones[boneName]
return (bone, poseBone)
def selectBoneIfItExists(scene, boneName):
if bpy.ops.object.mode_set.poll():
bpy.ops.object.mode_set(mode='OBJECT')
if bpy.ops.object.select_all.poll():
bpy.ops.object.select_all(action='DESELECT')
bone, armatureObject = findBoneWithArmatureObject(scene, boneName)
if bone is None:
return
armature = armatureObject.data
armatureObject.select_set(True)
scene.view_layers[0].objects.active = armatureObject
if bpy.ops.object.mode_set.poll():
bpy.ops.object.mode_set(mode='POSE')
scene.view_layers[0].objects.active = armatureObject
armatureObject.select_set(True)
for currentBone in armature.bones:
currentBone.select = currentBone.name == boneName
def selectBonesIfTheyExist(scene, boneNames):
if bpy.ops.object.mode_set.poll():
bpy.ops.object.mode_set(mode='OBJECT')
if bpy.ops.object.select_all.poll():
bpy.ops.object.select_all(action='DESELECT')
bones = []
armatureObjects = []
for ii, boneName in enumerate(boneNames):
r = findBoneWithArmatureObject(scene, boneName)
bones.append(r[0])
armatureObjects.append(r[1])
for ii, bone in enumerate(bones):
if bone is None:
continue
armature = armatureObjects[ii].data
armatureObjects[ii].select_set(True)
scene.view_layers[0].objects.active = armatureObjects[ii]
if bpy.ops.object.mode_set.poll():
bpy.ops.object.mode_set(mode='POSE')
scene.view_layers[0].objects.active = armatureObjects[ii]
armatureObjects[ii].select_set(True)
for currentBone in armature.bones:
currentBone.select = currentBone.name in boneNames
class UniqueNameFinder:
def __init__(self):
self.usedNames = set()
def markNamesOfCollectionAsUsed(self, collection):
for item in collection:
self.usedNames.add(item.name)
def findNameAndMarkAsUsedLike(self, wantedName):
nameWithoutNumberSuffix = self.removeNumberSuffix(wantedName)
namePrefix = nameWithoutNumberSuffix[:25]
# Suffixes of sc2 animations most often start with 01
# For other objects it doesn't hurt do it the same, and often it is even like that
suffixNumber = 1
name = wantedName
while name in self.usedNames:
name = "%s %02d" % (namePrefix, suffixNumber)
suffixNumber += 1
self.usedNames.add(name)
return name
def removeNumberSuffix(self, name):
lastIndex = len(name) - 1
index = lastIndex
while(index > 0 and name[index] in ["0", "1", "2", "3", "4", "5", "6", "7", "9"]):
index -= 1
name = name[:index + 1]
if name.endswith(" ") or name.endswith("_"):
name = name[:-1]
return name
def dump(obj, title=None):
o: List[str] = []
o.append("%s" % (title if title else obj))
if hasattr(obj, '__iter__'):
c = int(len(obj) / 10) + 1
for i, x in enumerate(obj):
o.append(dump(x, "[%0*d]" % (c, i)))
else:
for attr in dir(obj):
if hasattr(obj, attr):
o.append(" %16s = %s" % (attr, getattr(obj, attr)))
return "\n".join(o)
def isVideoFilePath(filePath):
return filePath.endswith(".ogv") or filePath.endswith(".ogg")
def sqr(x):
return x * x
def smoothQuaternionTransition(previousQuaternion, quaternionToFix):
sumOfSquares = sqr(quaternionToFix.x - previousQuaternion.x) + sqr(quaternionToFix.y - previousQuaternion.y) + sqr(quaternionToFix.z - previousQuaternion.z) + sqr(quaternionToFix.w - previousQuaternion.w)
sumOfSquaresMinus = sqr(-quaternionToFix.x - previousQuaternion.x) + sqr(-quaternionToFix.y - previousQuaternion.y) + sqr(-quaternionToFix.z - previousQuaternion.z) + sqr(-quaternionToFix.w - previousQuaternion.w)
if sumOfSquaresMinus < sumOfSquares:
quaternionToFix.negate()
def floatInterpolationFunction(leftInterpolationValue, rightInterpolationValue, rightFactor):
leftFactor = 1.0 - rightFactor
return leftInterpolationValue * leftFactor + rightInterpolationValue * rightFactor
def vectorInterpolationFunction(leftInterpolationValue, rightInterpolationValue, rightFactor):
return leftInterpolationValue.lerp(rightInterpolationValue, rightFactor)
def quaternionInterpolationFunction(leftInterpolationValue, rightInterpolationValue, rightFactor):
return leftInterpolationValue.slerp(rightInterpolationValue, rightFactor)
def floatsAlmostEqual(floatExpected, floatActual):
delta = abs(floatExpected - floatActual)
return delta < 0.00001
def vectorsAlmostEqual(vectorExpected, vectorActual):
diff = vectorExpected - vectorActual
return diff.length < 0.00001
def quaternionsAlmostEqual(q0, q1):
distanceSqr = sqr(q0.x - q1.x) + sqr(q0.y - q1.y) + sqr(q0.z - q1.z) + sqr(q0.w - q1.w)
return distanceSqr < sqr(0.00001)
def simplifyFloatAnimationWithInterpolation(timeValuesInMS, values):
return simplifyAnimationWithInterpolation(timeValuesInMS, values, floatInterpolationFunction, floatsAlmostEqual)
def simplifyVectorAnimationWithInterpolation(timeValuesInMS, vectors):
return simplifyAnimationWithInterpolation(timeValuesInMS, vectors, vectorInterpolationFunction, vectorsAlmostEqual)
def simplifyQuaternionAnimationWithInterpolation(timeValuesInMS, vectors):
return simplifyAnimationWithInterpolation(timeValuesInMS, vectors, quaternionInterpolationFunction, quaternionsAlmostEqual)
def simplifyAnimationWithInterpolation(timeValuesInMS, values, interpolationFunction, almostEqualFunction):
if len(timeValuesInMS) < 2:
return timeValuesInMS, values
leftTimeInMS = timeValuesInMS[0]
leftValue = values[0]
currentTimeInMS = timeValuesInMS[1]
currentValue = values[1]
newTimeValuesInMS = [leftTimeInMS]
newValues = [leftValue]
for rightTimeInMS, rightValue in zip(timeValuesInMS[2:], values[2:]):
timeSinceLeftTime = currentTimeInMS - leftTimeInMS
intervalLength = rightTimeInMS - leftTimeInMS
rightFactor = timeSinceLeftTime / intervalLength
expectedValue = interpolationFunction(leftValue, rightValue, rightFactor)
if almostEqualFunction(expectedValue, currentValue):
# ignore current value since it's interpolatable:
pass
else:
newTimeValuesInMS.append(currentTimeInMS)
newValues.append(currentValue)
leftTimeInMS = currentTimeInMS
leftValue = currentValue
currentValue = rightValue
currentTimeInMS = rightTimeInMS
newTimeValuesInMS.append(timeValuesInMS[-1])
newValues.append(values[-1])
return newTimeValuesInMS, newValues
def findMeshObjects(scene: bpy.types.Scene) -> Iterable[bpy.types.Object]:
for currentObject in scene.objects:
if currentObject.type == 'MESH':
yield currentObject
def convertM3UVSourceValueToUVLayerName(mesh, uvSource):
""" Can return None"""
if uvSource == "0":
uvLayerIndex = 0
elif uvSource == "1":
uvLayerIndex = 1
elif uvSource == "9":
uvLayerIndex = 2
elif uvSource == "10":
uvLayerIndex = 3
else:
return None
if uvLayerIndex < len(mesh.uv_layers):
return mesh.uv_layers[uvLayerIndex].name
else:
return None
def createImageObjetForM3MaterialLayer(blenderM3Layer, directoryList):
if blenderM3Layer is None:
return None
if (blenderM3Layer.imagePath == "") or (blenderM3Layer.imagePath is None):
return None
imagePath = blenderM3Layer.imagePath
blenderImage: bpy.types.Image = None
if path.isabs(imagePath):
if path.isfile(imagePath):
blenderImage = image_utils.load_image(imagePath, check_existing=True)
else:
imagePath = path.basename(imagePath)
if not blenderImage:
targetList = []
for x in directoryList:
targetList.append(path.join(x, path.basename(imagePath)))
targetList.append(path.join(x, imagePath))
for x in targetList:
if path.isfile(x):
blenderImage = image_utils.load_image(x, check_existing=True)
break
if not blenderImage:
print("Failed to load a texture %s. The following paths have been tested: %s" % (imagePath, targetList))
blenderImage = image_utils.load_image(imagePath, place_holder=True, check_existing=True)
return blenderImage
def getStandardMaterialOrNull(scene, mesh):
if mesh.m3_material_name == "":
return None
materialReference = scene.m3_material_references[mesh.m3_material_name]
materialType = materialReference.materialType
materialIndex = materialReference.materialIndex
if materialType not in [standardMaterialTypeIndex, compositeMaterialTypeIndex]:
print("Material generation is only supported for starard materials, but not for material %s" % m3MaterialFieldNames[materialType])
return None
if materialType == compositeMaterialTypeIndex:
compositing_material = scene.m3_composite_materials[materialIndex]
for key in compositing_material.sections.keys():
ref = scene.m3_material_references[key]
if ref.materialType == standardMaterialTypeIndex:
return scene.m3_standard_materials[ref.materialIndex]
return None
else:
return scene.m3_standard_materials[materialIndex]
def createUVNodesFromM3LayerAndReturnSocket(mesh, tree, blenderM3Layer):
""" Returns a socket that provies UVs or None"""
uvLayerName = convertM3UVSourceValueToUVLayerName(mesh, blenderM3Layer.uvSource)
if uvLayerName is None:
return None
uvAttributeNode = tree.nodes.new("ShaderNodeAttribute")
uvAttributeNode.attribute_name = uvLayerName
outputNode = uvAttributeNode.outputs["Vector"]
if (not blenderM3Layer.textureWrapX) and (not blenderM3Layer.textureWrapY):
mappingNode = tree.nodes.new("ShaderNodeMapping")
mappingNode.vector_type = "POINT"
tree.links.new(outputNode, mappingNode.inputs["Vector"])
outputNode = mappingNode.outputs["Vector"]
else:
if (not blenderM3Layer.textureWrapX) or (not blenderM3Layer.textureWrapY):
print("Note: Generated cycles material won't have correct texture clamp. One sided texture wrap is not implemented yet")
return outputNode
def createTextureNodeForM3MaterialLayer(mesh, tree, blenderM3Layer, directoryList):
image = createImageObjetForM3MaterialLayer(blenderM3Layer, directoryList)
if image is None:
return None
textureNode = tree.nodes.new("ShaderNodeTexImage")
textureNode.image = image
uvSocket = createUVNodesFromM3LayerAndReturnSocket(mesh, tree, blenderM3Layer)
if uvSocket is not None:
tree.links.new(uvSocket, textureNode.inputs["Vector"])
return textureNode
def determineTextureDirectoryList(scene):
textureDirectories = []
textureDirectories.append(scene.m3_import_options.rootDirectory)
if path.isfile(scene.m3_import_options.path):
modelDirectory = path.dirname(scene.m3_import_options.path)
textureDirectories.append(modelDirectory)
return textureDirectories
def createNormalMapNode(mesh, tree, standardMaterial, directoryList):
normalLayer = standardMaterial.layers[getLayerNameFromFieldName("normalLayer")]
normalTextureNode = createTextureNodeForM3MaterialLayer(mesh, tree, normalLayer, directoryList)
if normalTextureNode is None:
return None
normalTextureSeparateRGBNode = tree.nodes.new("ShaderNodeSeparateRGB")
tree.links.new(normalTextureNode.outputs["Color"], normalTextureSeparateRGBNode.inputs["Image"])
# Invert Green of normal texture
normalTextureGreenInvertNode = tree.nodes.new("ShaderNodeMath")
normalTextureGreenInvertNode.operation = "SUBTRACT"
normalTextureGreenInvertNode.inputs[0].default_value = 1.0
tree.links.new(normalTextureSeparateRGBNode.outputs["G"], normalTextureGreenInvertNode.inputs[1])
# Bring green of normal texture to range [-0.5,0.5]
normalTextureGreenSubZeroDotFiveNode = tree.nodes.new("ShaderNodeMath")
normalTextureGreenSubZeroDotFiveNode.operation = "SUBTRACT"
normalTextureGreenSubZeroDotFiveNode.inputs[1].default_value = 0.5
tree.links.new(normalTextureGreenInvertNode.outputs["Value"], normalTextureGreenSubZeroDotFiveNode.inputs[0])
# Bring green of normal texture to range [-1,1]
normalTextureGreenMul2Node = tree.nodes.new("ShaderNodeMath")
normalTextureGreenMul2Node.operation = "ADD"
tree.links.new(normalTextureGreenSubZeroDotFiveNode.outputs["Value"], normalTextureGreenMul2Node.inputs[0])
tree.links.new(normalTextureGreenSubZeroDotFiveNode.outputs["Value"], normalTextureGreenMul2Node.inputs[1])
# Calculate (normal green in range [-1,1]) ^ 2
normalTextureGreenPower2Node = tree.nodes.new("ShaderNodeMath")
normalTextureGreenPower2Node.operation = "MULTIPLY"
tree.links.new(normalTextureGreenMul2Node.outputs["Value"], normalTextureGreenPower2Node.inputs[0])
tree.links.new(normalTextureGreenMul2Node.outputs["Value"], normalTextureGreenPower2Node.inputs[1])
# Bring alpha of normal texture to range [-0.5,0.5]
normalTextureAlphaSubZeroDotFiveNode = tree.nodes.new("ShaderNodeMath")
normalTextureAlphaSubZeroDotFiveNode.operation = "SUBTRACT"
normalTextureAlphaSubZeroDotFiveNode.inputs[1].default_value = 0.5
tree.links.new(normalTextureNode.outputs["Alpha"], normalTextureAlphaSubZeroDotFiveNode.inputs[0])
# Bring alpha of normal texture to range [-1,1]
normalTextureAlphaMul2Node = tree.nodes.new("ShaderNodeMath")
normalTextureAlphaMul2Node.operation = "MULTIPLY"
tree.links.new(normalTextureAlphaSubZeroDotFiveNode.outputs["Value"], normalTextureAlphaMul2Node.inputs[0])
tree.links.new(normalTextureAlphaSubZeroDotFiveNode.outputs["Value"], normalTextureAlphaMul2Node.inputs[1])
# Calculate (normal alpha in range [-1,1]) ^ 2
normalTextureAlphaPower2Node = tree.nodes.new("ShaderNodeMath")
normalTextureAlphaPower2Node.operation = "MULTIPLY"
tree.links.new(normalTextureAlphaMul2Node.outputs["Value"], normalTextureAlphaPower2Node.inputs[0])
tree.links.new(normalTextureAlphaMul2Node.outputs["Value"], normalTextureAlphaPower2Node.inputs[1])
# Calculate (green in range [-1,1])^2 + (alpha in range [-1,1]) ^ 2
normalTextureAddGreenAndAlphaNode = tree.nodes.new("ShaderNodeMath")
normalTextureAddGreenAndAlphaNode.operation = "ADD"
tree.links.new(normalTextureGreenPower2Node.outputs["Value"], normalTextureAddGreenAndAlphaNode.inputs[0])
tree.links.new(normalTextureAlphaPower2Node.outputs["Value"], normalTextureAddGreenAndAlphaNode.inputs[1])
# Calculate (new blue)^2 == 1 - (new red)^2 + (new green)^2
# == 1- ((green in range [-1,1])^2 to (alpha in range [-1,1])^2)
normalTextureNewBluePower2Node = tree.nodes.new("ShaderNodeMath")
normalTextureNewBluePower2Node.operation = "SUBTRACT"
normalTextureNewBluePower2Node.inputs[0].default_value = 1.0
tree.links.new(normalTextureAddGreenAndAlphaNode.outputs["Value"], normalTextureNewBluePower2Node.inputs[1])
# Calculate new blue in range [0,1] via = sqrt (1- ((green in range [-1,1])^2 to (alpha in range [-1,1])^2))
# Based on the assumtion that sqrt(r^2+ g^2 + b^2) == 1
normalTextureNewBlueNode = tree.nodes.new("ShaderNodeMath")
normalTextureNewBlueNode.operation = "POWER"
normalTextureNewBlueNode.inputs[1].default_value = 0.5
tree.links.new(normalTextureNewBluePower2Node.outputs["Value"], normalTextureNewBlueNode.inputs[0])
normalTextureConvertedNode = tree.nodes.new("ShaderNodeCombineRGB")
tree.links.new(normalTextureNode.outputs["Alpha"], normalTextureConvertedNode.inputs["R"])
tree.links.new(normalTextureGreenInvertNode.outputs["Value"], normalTextureConvertedNode.inputs["G"])
tree.links.new(normalTextureNewBlueNode.outputs["Value"], normalTextureConvertedNode.inputs["B"])
normalMapNode = tree.nodes.new('ShaderNodeNormalMap')
normalMapNode.space = "TANGENT"
normalMapNode.inputs["Strength"].default_value = 0.5
normalMapNode.uv_map = convertM3UVSourceValueToUVLayerName(mesh, normalLayer.uvSource)
tree.links.new(normalTextureConvertedNode.outputs["Image"], normalMapNode.inputs["Color"])
return normalMapNode
def createCyclesMaterialForMeshObject(scene, meshObject):
mesh = meshObject.data
standardMaterial = getStandardMaterialOrNull(scene, mesh)
if standardMaterial is None:
return
realMaterial = bpy.data.materials.new(standardMaterial.name)
directoryList = determineTextureDirectoryList(scene)
diffuseLayer = standardMaterial.layers[getLayerNameFromFieldName("diffuseLayer")]
specularLayer = standardMaterial.layers[getLayerNameFromFieldName("specularLayer")]
realMaterial.use_nodes = True
tree = realMaterial.node_tree
tree.links.clear()
tree.nodes.clear()
diffuseTextureNode = createTextureNodeForM3MaterialLayer(mesh, tree, diffuseLayer, directoryList)
if diffuseTextureNode is not None:
if diffuseLayer.colorChannelSetting == colorChannelSettingRGBA:
diffuseTeamColorMixNode = tree.nodes.new("ShaderNodeMixRGB")
diffuseTeamColorMixNode. blend_type = "MIX"
teamColor = scene.m3_import_options.teamColor
diffuseTeamColorMixNode.inputs["Color1"].default_value = (teamColor[0], teamColor[1], teamColor[2], 1.0)
tree.links.new(diffuseTextureNode.outputs["Alpha"], diffuseTeamColorMixNode.inputs["Fac"])
tree.links.new(diffuseTextureNode.outputs["Color"], diffuseTeamColorMixNode.inputs["Color2"])
finalDiffuseColorOutputSocket = diffuseTeamColorMixNode.outputs["Color"]
else:
finalDiffuseColorOutputSocket = diffuseTextureNode.outputs["Color"]
else:
rgbNode = tree.nodes.new("ShaderNodeRGB")
rgbNode.outputs[0].default_value = (0, 0, 0, 1)
finalDiffuseColorOutputSocket = rgbNode.outputs[0]
decalLayer = standardMaterial.layers[getLayerNameFromFieldName("decalLayer")]
decalTextureNode = createTextureNodeForM3MaterialLayer(mesh, tree, decalLayer, directoryList)
if decalTextureNode is not None:
decalAddingNode = tree.nodes.new("ShaderNodeMixRGB")
decalAddingNode. blend_type = "SCREEN"
tree.links.new(decalTextureNode.outputs["Alpha"], decalAddingNode.inputs["Fac"])
tree.links.new(decalTextureNode.outputs["Color"], decalAddingNode.inputs["Color2"])
tree.links.new(finalDiffuseColorOutputSocket, decalAddingNode.inputs["Color1"])
finalDiffuseColorOutputSocket = decalAddingNode.outputs["Color"]
normalMapNode = createNormalMapNode(mesh, tree, standardMaterial, directoryList)
diffuseShaderNode = tree.nodes.new("ShaderNodeBsdfDiffuse")
if normalMapNode is not None:
tree.links.new(normalMapNode.outputs["Normal"], diffuseShaderNode.inputs["Normal"])
tree.links.new(finalDiffuseColorOutputSocket, diffuseShaderNode.inputs["Color"])
finalShaderOutputSocket = diffuseShaderNode.outputs["BSDF"]
specularTextureNode = createTextureNodeForM3MaterialLayer(mesh, tree, specularLayer, directoryList)
glossyShaderNode.inputs["Roughness"].default_value = 0.2
if specularTextureNode is not None:
glossyShaderNode = tree.nodes.new("ShaderNodeBsdfGlossy")
glossyShaderNode.distribution = "BECKMANN"
if normalMapNode is not None:
tree.links.new(normalMapNode.outputs["Normal"], glossyShaderNode.inputs["Normal"])
tree.links.new(specularTextureNode.outputs["Color"], glossyShaderNode.inputs["Color"])
mixShaderNode = tree.nodes.new("ShaderNodeMixShader")
tree.links.new(specularTextureNode.outputs["Color"], mixShaderNode.inputs["Fac"])
tree.links.new(finalShaderOutputSocket, mixShaderNode.inputs[1])
tree.links.new(glossyShaderNode.outputs["BSDF"], mixShaderNode.inputs[2])
finalShaderOutputSocket = mixShaderNode.outputs["Shader"]
else:
glossyShaderNode.inputs["Specular"].default_value = 0.1
emissiveLayer = standardMaterial.layers[getLayerNameFromFieldName("emissiveLayer")]
emissiveTextureNode = createTextureNodeForM3MaterialLayer(mesh, tree, emissiveLayer, directoryList)
if emissiveTextureNode is not None:
emissiveShaderNode = tree.nodes.new("ShaderNodeEmission")
emissiveShaderNode.inputs[1].default_value = 10.0 # Strength
tree.links.new(emissiveTextureNode.outputs["Color"], emissiveShaderNode.inputs["Color"])
print("Adding emissive to %s" % standardMaterial.name)
mixShaderNode = tree.nodes.new("ShaderNodeMixShader")
tree.links.new(emissiveTextureNode.outputs["Color"], mixShaderNode.inputs["Fac"])
tree.links.new(finalShaderOutputSocket, mixShaderNode.inputs[1])
tree.links.new(emissiveShaderNode.outputs["Emission"], mixShaderNode.inputs[2])
finalShaderOutputSocket = mixShaderNode.outputs["Shader"]
alphaLayer = standardMaterial.layers[getLayerNameFromFieldName("alphaMaskLayer")]
alphaTextureNode = createTextureNodeForM3MaterialLayer(mesh, tree, alphaLayer, directoryList)
if alphaTextureNode is not None and alphaLayer.colorChannelSetting in [colorChannelSettingA, colorChannelSettingR, colorChannelSettingG, colorChannelSettingB]:
transparencyShaderNode = tree.nodes.new("ShaderNodeBsdfTransparent")
mixShaderNode = tree.nodes.new("ShaderNodeMixShader")
tree.links.new(transparencyShaderNode.outputs["BSDF"], mixShaderNode.inputs[1])
tree.links.new(finalShaderOutputSocket, mixShaderNode.inputs[2])
if alphaLayer.colorChannelSetting == colorChannelSettingA:
tree.links.new(alphaTextureNode.outputs["Alpha"], mixShaderNode.inputs["Fac"])
else:
separateRGBNode = tree.nodes.new("ShaderNodeSeparateRGB")
tree.links.new(alphaTextureNode.outputs["Color"], separateRGBNode.inputs["Image"])
if alphaLayer.colorChannelSetting == colorChannelSettingR:
tree.links.new(separateRGBNode.outputs["R"], mixShaderNode.inputs["Fac"])
elif alphaLayer.colorChannelSetting == colorChannelSettingG:
tree.links.new(separateRGBNode.outputs["G"], mixShaderNode.inputs["Fac"])
elif alphaLayer.colorChannelSetting == colorChannelSettingB:
tree.links.new(separateRGBNode.outputs["B"], mixShaderNode.inputs["Fac"])
else:
raise Exception("alpha texture setting not handled properly earilier")
finalShaderOutputSocket = mixShaderNode.outputs["Shader"]
outputNode = tree.nodes.new("ShaderNodeOutputMaterial")
outputNode.location = (500.0, 000.0)
tree.links.new(finalShaderOutputSocket, outputNode.inputs["Surface"])
layoutInputNodesOf(tree)
# Remove old materials:
while len(mesh.materials) > 0:
mesh.materials.pop(0, update_data=True)
mesh.materials.append(realMaterial)
def createNodeNameToInputNodesMap(tree):
nodeNameToInputNodesMap = {}
for link in tree.links:
inputNodes = nodeNameToInputNodesMap.get(link.to_node.name)
if inputNodes is None:
inputNodes = set()
nodeNameToInputNodesMap[link.to_node.name] = inputNodes
inputNodes.add(link.from_node)
return nodeNameToInputNodesMap
def createNodeNameToOutputNodesMap(tree):
nodeNameToOutputNodesMap = {}
for link in tree.links:
outputNodes = nodeNameToOutputNodesMap.get(link.from_node.name)
if outputNodes is None:
outputNodes = set()
nodeNameToOutputNodesMap[link.from_node.name] = outputNodes
outputNodes.add(link.to_node)
return nodeNameToOutputNodesMap
nodeTypeToHeightMap = {
'NORMAL_MAP': 148,
'MATH': 145,
'ATTRIBUTE': 116,
'SEPRGB': 112,
'COMBRGB': 115,
'MIX_RGB': 164,
'TEX_IMAGE': 226,
'OUTPUT_MATERIAL': 87,
'BSDF_DIFFUSE': 112,
'BSDF_GLOSSY': 144,
'MIX_SHADER': 112,
'MAPPING': 270,
'BSDF_TRANSPARENT': 69,
'RGB': 177,
'EMISSION': 93,
}
def getHeightOfNewNode(node):
# due to a blender 2.71 bug the dimensions are 0 for newly created nodes
# due to a blender 2.71 bug the height is always 100.0
return nodeTypeToHeightMap.get(node.type, node.height)
def layoutInputNodesOf(tree):
horizontalDistanceBetweenNodes = 200
verticalDistanceBetweenNodes = 50
nodeNameToInputNodesMap = createNodeNameToInputNodesMap(tree)
nodeNameToOutputNodesMap = createNodeNameToOutputNodesMap(tree)
# Fix x positions of nodes:
namesOfNodesToCheck = set(n.name for n in tree.nodes)
while len(namesOfNodesToCheck) > 0:
nodeName = namesOfNodesToCheck.pop()
node = tree.nodes[nodeName]
inputNodes = nodeNameToInputNodesMap.get(nodeName)
if inputNodes is not None:
for inputNode in inputNodes:
xBasedOnNode = node.location[0] - inputNode.width - horizontalDistanceBetweenNodes
inputNode.location[0] = min(inputNode.location[0], xBasedOnNode)
namesOfNodesToCheck.add(inputNode.name)
xLinkCountNameTuples = list()
for node in tree.nodes:
linkCount = 0
inputNodes = nodeNameToInputNodesMap.get(node.name)
if inputNodes is not None:
linkCount += len(inputNodes)
outputNodes = nodeNameToOutputNodesMap.get(node.name)
if outputNodes is not None:
linkCount += len(outputNodes)
xLinkCountNameTuples.append((node.location[0], linkCount, node.name))
xLinkCountNameTuples.sort(reverse=True)
nodesWithFinalPosition = []
for x, linkCount, name in xLinkCountNameTuples:
node = tree.nodes[name]
outputNodes = nodeNameToOutputNodesMap.get(name)
if outputNodes is not None and len(outputNodes) > 0:
ySum = 0
for outputNode in outputNodes:
ySum += outputNode.location[1]