-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathimportldd.py
1494 lines (1246 loc) · 84.9 KB
/
importldd.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
bl_info = {
"name": "Import LEGO Digital Designer",
"description": "Import LEGO Digital Designer scenes in .lxf and .lxfml formats",
"author": "123 <[email protected]>",
"version": (0, 0, 1),
"blender": (2, 90, 0),
"location": "File > Import",
"warning": "Alpha",
"wiki_url": "https://github.com/",
"tracker_url": "https://github.com/",
"category": "Import-Export"
}
import bpy
import mathutils
from bpy_extras.io_utils import (
ImportHelper,
orientation_helper,
axis_conversion,
)
#!/usr/bin/env python
# pylddlib version 0.4.9.7
# based on pyldd2obj version 0.4.8 - Copyright (c) 2019 by jonnysp
#
# Updates:
# 0.4.9.7 corrected bug of incorrectly parsing the primitive xml file, specifically with comments. Add support LDDLIFTREE envirnment variable to set location of db.lif.
# 0.4.9.6 preliminary Linux support
# 0.4.9.5 corrected bug of incorrectly Bounding / GeometryBounding parsing the primitive xml file.
# 0.4.9.4 improved lif.db checking for crucial files (because of the infamous botched 4.3.12 LDD Windows update).
# 0.4.9.3 improved Windows and Python 3 compatibility
# 0.4.9.2 changed handling of material = 0 for a part. Now a 0 will choose the 1st material (the base material of a part) and not the previous material of the subpart before. This will fix "Chicken Helmet Part 11262". It may break other parts and this change needs further regression.
# 0.4.9.1 improved custom2DField handling, fixed decorations bug, improved material assignments handling
# 0.4.9 updates to support reading extracted db.lif from db folder
#
# License: MIT License
#
import os
import platform
import sys
import math
import struct
import zipfile
from xml.dom import minidom
import uuid
import random
import time
if sys.version_info < (3, 0):
reload(sys)
sys.setdefaultencoding('utf-8')
PRIMITIVEPATH = '/Primitives/'
GEOMETRIEPATH = PRIMITIVEPATH + 'LOD0/'
DECORATIONPATH = '/Decorations/'
MATERIALNAMESPATH = '/MaterialNames/'
LOGOONSTUDSCONNTYPE = {"0:4", "0:4:1", "0:4:2", "0:4:33", "2:4:1", "2:4:34"}
class Matrix3D:
def __init__(self, n11=1,n12=0,n13=0,n14=0,n21=0,n22=1,n23=0,n24=0,n31=0,n32=0,n33=1,n34=0,n41=0,n42=0,n43=0,n44=1):
self.n11 = n11
self.n12 = n12
self.n13 = n13
self.n14 = n14
self.n21 = n21
self.n22 = n22
self.n23 = n23
self.n24 = n24
self.n31 = n31
self.n32 = n32
self.n33 = n33
self.n34 = n34
self.n41 = n41
self.n42 = n42
self.n43 = n43
self.n44 = n44
def __str__(self):
return '[{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15}]'.format(self.n11, self.n12, self.n13,self.n14,self.n21, self.n22, self.n23,self.n24,self.n31, self.n32, self.n33,self.n34,self.n41, self.n42, self.n43,self.n44)
def rotate(self,angle=0,axis=0):
c = math.cos(angle)
s = math.sin(angle)
t = 1 - c
tx = t * axis.x
ty = t * axis.y
tz = t * axis.z
sx = s * axis.x
sy = s * axis.y
sz = s * axis.z
self.n11 = c + axis.x * tx
self.n12 = axis.y * tx + sz
self.n13 = axis.z * tx - sy
self.n14 = 0
self.n21 = axis.x * ty - sz
self.n22 = c + axis.y * ty
self.n23 = axis.z * ty + sx
self.n24 = 0
self.n31 = axis.x * tz + sy
self.n32 = axis.y * tz - sx
self.n33 = c + axis.z * tz
self.n34 = 0
self.n41 = 0
self.n42 = 0
self.n43 = 0
self.n44 = 1
def __mul__(self, other):
return Matrix3D(
self.n11 * other.n11 + self.n21 * other.n12 + self.n31 * other.n13 + self.n41 * other.n14,
self.n12 * other.n11 + self.n22 * other.n12 + self.n32 * other.n13 + self.n42 * other.n14,
self.n13 * other.n11 + self.n23 * other.n12 + self.n33 * other.n13 + self.n43 * other.n14,
self.n14 * other.n11 + self.n24 * other.n12 + self.n34 * other.n13 + self.n44 * other.n14,
self.n11 * other.n21 + self.n21 * other.n22 + self.n31 * other.n23 + self.n41 * other.n24,
self.n12 * other.n21 + self.n22 * other.n22 + self.n32 * other.n23 + self.n42 * other.n24,
self.n13 * other.n21 + self.n23 * other.n22 + self.n33 * other.n23 + self.n43 * other.n24,
self.n14 * other.n21 + self.n24 * other.n22 + self.n34 * other.n23 + self.n44 * other.n24,
self.n11 * other.n31 + self.n21 * other.n32 + self.n31 * other.n33 + self.n41 * other.n34,
self.n12 * other.n31 + self.n22 * other.n32 + self.n32 * other.n33 + self.n42 * other.n34,
self.n13 * other.n31 + self.n23 * other.n32 + self.n33 * other.n33 + self.n43 * other.n34,
self.n14 * other.n31 + self.n24 * other.n32 + self.n34 * other.n33 + self.n44 * other.n34,
self.n11 * other.n41 + self.n21 * other.n42 + self.n31 * other.n43 + self.n41 * other.n44,
self.n12 * other.n41 + self.n22 * other.n42 + self.n32 * other.n43 + self.n42 * other.n44,
self.n13 * other.n41 + self.n23 * other.n42 + self.n33 * other.n43 + self.n43 * other.n44,
self.n14 * other.n41 + self.n24 * other.n42 + self.n34 * other.n43 + self.n44 * other.n44
)
class Point3D:
def __init__(self, x=0,y=0,z=0):
self.x = x
self.y = y
self.z = z
def __str__(self):
return '[{0},{1},{2}]'.format(self.x, self.y,self.z)
def string(self,prefix = "v"):
return '{0} {1:f} {2:f} {3:f}\n'.format(prefix ,self.x , self.y, self.z)
def transformW(self,matrix):
x = matrix.n11 * self.x + matrix.n21 * self.y + matrix.n31 * self.z
y = matrix.n12 * self.x + matrix.n22 * self.y + matrix.n32 * self.z
z = matrix.n13 * self.x + matrix.n23 * self.y + matrix.n33 * self.z
self.x = x
self.y = y
self.z = z
def transform(self,matrix):
x = matrix.n11 * self.x + matrix.n21 * self.y + matrix.n31 * self.z + matrix.n41
y = matrix.n12 * self.x + matrix.n22 * self.y + matrix.n32 * self.z + matrix.n42
z = matrix.n13 * self.x + matrix.n23 * self.y + matrix.n33 * self.z + matrix.n43
self.x = x
self.y = y
self.z = z
def copy(self):
return Point3D(x=self.x,y=self.y,z=self.z)
class Point2D:
def __init__(self, x=0,y=0):
self.x = x
self.y = y
def __str__(self):
return '[{0},{1}]'.format(self.x, self.y * -1)
def string(self,prefix="t"):
return '{0} {1:f} {2:f}\n'.format(prefix , self.x, self.y * -1 )
def copy(self):
return Point2D(x=self.x,y=self.y)
class Face:
def __init__(self,a=0,b=0,c=0):
self.a = a
self.b = b
self.c = c
def string(self,prefix="f", indexOffset=0 ,textureoffset=0):
if textureoffset == 0:
return prefix + ' {0}//{0} {1}//{1} {2}//{2}\n'.format(self.a + indexOffset, self.b + indexOffset, self.c + indexOffset)
else:
return prefix + ' {0}/{3}/{0} {1}/{4}/{1} {2}/{5}/{2}\n'.format(self.a + indexOffset, self.b + indexOffset, self.c + indexOffset,self.a + textureoffset, self.b + textureoffset, self.c + textureoffset)
def __str__(self):
return '[{0},{1},{2}]'.format(self.a, self.b, self.c)
class Group:
def __init__(self, node):
self.partRefs = node.getAttribute('partRefs').split(',')
class Bone:
def __init__(self, node):
self.refID = node.getAttribute('refID')
(a, b, c, d, e, f, g, h, i, x, y, z) = map(float, node.getAttribute('transformation').split(','))
self.matrix = Matrix3D(n11=a,n12=b,n13=c,n14=0,n21=d,n22=e,n23=f,n24=0,n31=g,n32=h,n33=i,n34=0,n41=x,n42=y,n43=z,n44=1)
class Part:
def __init__(self, node):
self.isGrouped = False
self.GroupIDX = 0
self.Bones = []
self.refID = node.getAttribute('refID')
self.designID = node.getAttribute('designID')
self.materials = list(map(str, node.getAttribute('materials').split(',')))
lastm = '0'
for i, m in enumerate(self.materials):
if (m == '0'):
# self.materials[i] = lastm
self.materials[i] = self.materials[0] #in case of 0 choose the 'base' material
else:
lastm = m
if node.hasAttribute('decoration'):
self.decoration = list(map(str,node.getAttribute('decoration').split(',')))
for childnode in node.childNodes:
if childnode.nodeName == 'Bone':
self.Bones.append(Bone(node=childnode))
class Brick:
def __init__(self, node):
self.refID = node.getAttribute('refID')
self.designID = node.getAttribute('designID')
self.Parts = []
for childnode in node.childNodes:
if childnode.nodeName == 'Part':
self.Parts.append(Part(node=childnode))
class SceneCamera:
def __init__(self, node):
self.refID = node.getAttribute('refID')
(a, b, c, d, e, f, g, h, i, x, y, z) = map(float, node.getAttribute('transformation').split(','))
self.matrix = Matrix3D(n11=a,n12=b,n13=c,n14=0,n21=d,n22=e,n23=f,n24=0,n31=g,n32=h,n33=i,n34=0,n41=x,n42=y,n43=z,n44=1)
self.fieldOfView = float(node.getAttribute('fieldOfView'))
self.distance = float(node.getAttribute('distance'))
class Scene:
def __init__(self, file):
self.Bricks = []
self.Scenecamera = []
self.Groups = []
if file.endswith('.lxfml'):
with open(file, "rb") as file:
data = file.read()
elif file.endswith('.lxf'):
zf = zipfile.ZipFile(file, 'r')
data = zf.read('IMAGE100.LXFML')
else:
return
xml = minidom.parseString(data)
self.Name = xml.firstChild.getAttribute('name')
for node in xml.firstChild.childNodes:
if node.nodeName == 'Meta':
for childnode in node.childNodes:
if childnode.nodeName == 'BrickSet':
self.Version = str(childnode.getAttribute('version'))
elif node.nodeName == 'Cameras':
for childnode in node.childNodes:
if childnode.nodeName == 'Camera':
self.Scenecamera.append(SceneCamera(node=childnode))
elif node.nodeName == 'Bricks':
for childnode in node.childNodes:
if childnode.nodeName == 'Brick':
self.Bricks.append(Brick(node=childnode))
elif node.nodeName == 'GroupSystems':
for childnode in node.childNodes:
if childnode.nodeName == 'GroupSystem':
for childnode in childnode.childNodes:
if childnode.nodeName == 'Group':
self.Groups.append(Group(node=childnode))
for i in range(len(self.Groups)):
for brick in self.Bricks:
for part in brick.Parts:
if part.refID in self.Groups[i].partRefs:
part.isGrouped = True
part.GroupIDX = i
print('Scene "'+ self.Name + '" Brickversion: ' + str(self.Version))
class GeometryReader:
def __init__(self, data):
self.offset = 0
self.data = data
self.positions = []
self.normals = []
self.textures = []
self.faces = []
self.bonemap = {}
self.texCount = 0
self.outpositions = []
self.outnormals = []
if self.readInt() == 1111961649:
self.valueCount = self.readInt()
self.indexCount = self.readInt()
self.faceCount = int(self.indexCount / 3)
options = self.readInt()
for i in range(0, self.valueCount):
self.positions.append(Point3D(x=self.readFloat(),y= self.readFloat(),z=self.readFloat()))
for i in range(0, self.valueCount):
self.normals.append(Point3D(x=self.readFloat(),y= self.readFloat(),z=self.readFloat()))
if (options & 3) == 3:
self.texCount = self.valueCount
for i in range(0, self.valueCount):
self.textures.append(Point2D(x=self.readFloat(), y=self.readFloat()))
for i in range(0, self.faceCount):
self.faces.append(Face(a=self.readInt(),b=self.readInt(),c=self.readInt()))
if (options & 48) == 48:
num = self.readInt()
self.offset += (num * 4) + (self.indexCount * 4)
num = self.readInt()
self.offset += (3 * num * 4) + (self.indexCount * 4)
bonelength = self.readInt()
self.bonemap = [0] * self.valueCount
if (bonelength > self.valueCount) or (bonelength > self.faceCount):
datastart = self.offset
self.offset += bonelength
for i in range(0, self.valueCount):
boneoffset = self.readInt() + 4
self.bonemap[i] = self.read_Int(datastart + boneoffset)
def read_Int(self,_offset):
if sys.version_info < (3, 0):
return int(struct.unpack_from('i', self.data, _offset)[0])
else:
return int.from_bytes(self.data[_offset:_offset + 4], byteorder='little')
def readInt(self):
if sys.version_info < (3, 0):
ret = int(struct.unpack_from('i', self.data, self.offset)[0])
else:
ret = int.from_bytes(self.data[self.offset:self.offset + 4], byteorder='little')
self.offset += 4
return ret
def readFloat(self):
ret = float(struct.unpack_from('f', self.data, self.offset)[0])
self.offset += 4
return ret
class Geometry:
def __init__(self, designID, database):
self.designID = designID
self.Parts = {}
self.maxGeoBounding = -1
self.studsFields2D = []
GeometryLocation = os.path.normpath('{0}{1}{2}'.format(GEOMETRIEPATH, designID,'.g'))
GeometryCount = 0
while str(GeometryLocation) in database.filelist:
self.Parts[GeometryCount] = GeometryReader(data=database.filelist[GeometryLocation].read())
GeometryCount += 1
GeometryLocation = os.path.normpath('{0}{1}{2}{3}'.format(GEOMETRIEPATH, designID,'.g',GeometryCount))
primitive = Primitive(data = database.filelist[os.path.normpath(PRIMITIVEPATH + designID + '.xml')].read())
self.Partname = primitive.Designname
self.studsFields2D = primitive.Fields2D
try:
geoBoundingList = [abs(float(primitive.Bounding['minX']) - float(primitive.Bounding['maxX'])), abs(float(primitive.Bounding['minY']) - float(primitive.Bounding['maxY'])), abs(float(primitive.Bounding['minZ']) - float(primitive.Bounding['maxZ']))]
geoBoundingList.sort()
self.maxGeoBounding = geoBoundingList[-1]
except KeyError as e:
print('\nBounding errror in part {0}: {1}\n'.format(designID, e))
# preflex
for part in self.Parts:
# transform
for i, b in enumerate(primitive.Bones):
# positions
for j, p in enumerate(self.Parts[part].positions):
if (self.Parts[part].bonemap[j] == i):
self.Parts[part].positions[j].transform(b.matrix)
# normals
for k, n in enumerate(self.Parts[part].normals):
if (self.Parts[part].bonemap[k] == i):
self.Parts[part].normals[k].transformW(b.matrix)
def valuecount(self):
count = 0
for part in self.Parts:
count += self.Parts[part].valueCount
return count
def facecount(self):
count = 0
for part in self.Parts:
count += self.Parts[part].faceCount
return count
def texcount(self):
count = 0
for part in self.Parts:
count += self.Parts[part].texCount
return count
class Bone2:
def __init__(self,boneId=0, angle=0, ax=0, ay=0, az=0, tx=0, ty=0, tz=0):
self.boneId = boneId
rotationMatrix = Matrix3D()
rotationMatrix.rotate(angle = -angle * math.pi / 180.0,axis = Point3D(x=ax,y=ay,z=az))
p = Point3D(x=tx,y=ty,z=tz)
p.transformW(rotationMatrix)
rotationMatrix.n41 -= p.x
rotationMatrix.n42 -= p.y
rotationMatrix.n43 -= p.z
self.matrix = rotationMatrix
class Field2D:
def __init__(self, type=0, width=0, height=0, angle=0, ax=0, ay=0, az=0, tx=0, ty=0, tz=0, field2DRawData='none'):
self.type = type
self.field2DRawData = field2DRawData
rotationMatrix = Matrix3D()
rotationMatrix.rotate(angle = -angle * math.pi / 180.0, axis = Point3D(x=ax,y=ay,z=az))
p = Point3D(x=tx,y=ty,z=tz)
p.transformW(rotationMatrix)
rotationMatrix.n41 -= p.x
rotationMatrix.n42 -= p.y
rotationMatrix.n43 -= p.z
self.matrix = rotationMatrix
self.custom2DField = []
#The height and width are always double the number of studs. The contained text is a 2D array that is always height + 1 and width + 1.
rows_count = height + 1
cols_count = width + 1
# creation looks reverse
# create an array of "cols_count" cols, for each of the "rows_count" rows
# all elements are initialized to 0
self.custom2DField = [[0 for j in range(cols_count)] for i in range(rows_count)]
custom2DFieldString = field2DRawData.replace('\r', '').replace('\n', '').replace(' ', '')
custom2DFieldArr = custom2DFieldString.strip().split(',')
k = 0
for i in range(rows_count):
for j in range(cols_count):
self.custom2DField[i][j] = custom2DFieldArr[k]
k += 1
def __str__(self):
return '[type="{0}" transform="{1}" custom2DField="{2}"]'.format(self.type, self.matrix, self.custom2DField)
class CollisionBox:
def __init__(self, sX=0, sY=0, sZ=0, angle=0, ax=0, ay=0, az=0, tx=0, ty=0, tz=0):
rotationMatrix = Matrix3D()
rotationMatrix.rotate(angle = -angle * math.pi / 180.0, axis = Point3D(x=ax,y=ay,z=az))
p = Point3D(x=tx,y=ty,z=tz)
p.transformW(rotationMatrix)
rotationMatrix.n41 -= p.x
rotationMatrix.n42 -= p.y
rotationMatrix.n43 -= p.z
self.matrix = rotationMatrix
self.corner = Point3D(x=sX,y=sY,z=sZ)
self.positions = []
self.positions.append(Point3D(x=0, y=0, z=0))
self.positions.append(Point3D(x=sX, y=0, z=0))
self.positions.append(Point3D(x=0, y=sY, z=0))
self.positions.append(Point3D(x=sX, y=sY, z=0))
self.positions.append(Point3D(x=0, y=0, z=sZ))
self.positions.append(Point3D(x=0, y=sY, z=sZ))
self.positions.append(Point3D(x=sX ,y=0, z=sZ))
self.positions.append(Point3D(x=sX ,y=sY, z=sZ))
def __str__(self):
return '[0,0,0] [{0},0,0] [0,{1},0] [{0},{1},0] [0,0,{2}] [0,{1},{2}] [{0},0,{2}] [{0},{1},{2}]'.format(self.corner.x, self.corner.y, self.corner.z)
class Primitive:
def __init__(self, data):
self.Designname = ''
self.Bones = []
self.Fields2D = []
self.CollisionBoxes = []
self.PhysicsAttributes = {}
self.Bounding = {}
self.GeometryBounding = {}
xml = minidom.parseString(data)
root = xml.documentElement
for node in root.childNodes:
if node.__class__.__name__.lower() == 'comment':
self.comment = node.nodeValue #'Skip the comment' #node[0].nodeValue
if node.nodeName == 'Flex':
for node in node.childNodes:
if node.nodeName == 'Bone':
self.Bones.append(Bone2(boneId=int(node.getAttribute('boneId')), angle=float(node.getAttribute('angle')), ax=float(node.getAttribute('ax')), ay=float(node.getAttribute('ay')), az=float(node.getAttribute('az')), tx=float(node.getAttribute('tx')), ty=float(node.getAttribute('ty')), tz=float(node.getAttribute('tz'))))
elif node.nodeName == 'Annotations':
for childnode in node.childNodes:
if childnode.nodeName == 'Annotation' and childnode.hasAttribute('designname'):
self.Designname = childnode.getAttribute('designname')
elif node.nodeName == 'Collision':
for childnode in node.childNodes:
if childnode.nodeName == 'Box':
self.CollisionBoxes.append(CollisionBox(sX=float(childnode.getAttribute('sX')), sY=float(childnode.getAttribute('sY')), sZ=float(childnode.getAttribute('sZ')), angle=float(childnode.getAttribute('angle')), ax=float(childnode.getAttribute('ax')), ay=float(childnode.getAttribute('ay')), az=float(childnode.getAttribute('az')), tx=float(childnode.getAttribute('tx')), ty=float(childnode.getAttribute('ty')), tz=float(childnode.getAttribute('tz'))))
elif node.nodeName == 'PhysicsAttributes':
self.PhysicsAttributes = {"inertiaTensor": node.getAttribute('inertiaTensor'),"centerOfMass": node.getAttribute('centerOfMass'),"mass": node.getAttribute('mass'),"frictionType": node.getAttribute('frictionType')}
elif node.nodeName == 'Bounding':
for childnode in node.childNodes:
if childnode.nodeName == 'AABB':
self.Bounding = {"minX": childnode.getAttribute('minX'), "minY": childnode.getAttribute('minY'), "minZ": childnode.getAttribute('minZ'), "maxX": childnode.getAttribute('maxX'), "maxY": childnode.getAttribute('maxY'), "maxZ": childnode.getAttribute('maxZ')}
elif node.nodeName == 'GeometryBounding':
for childnode in node.childNodes:
if childnode.nodeName == 'AABB':
self.GeometryBounding = {"minX": childnode.getAttribute('minX'), "minY": childnode.getAttribute('minY'), "minZ": childnode.getAttribute('minZ'), "maxX": childnode.getAttribute('maxX'), "maxY": childnode.getAttribute('maxY'), "maxZ": childnode.getAttribute('maxZ')}
elif node.nodeName == 'Connectivity':
for childnode in node.childNodes:
if childnode.nodeName == 'Custom2DField':
self.Fields2D.append(Field2D(type=int(childnode.getAttribute('type')), width=int(childnode.getAttribute('width')), height=int(childnode.getAttribute('height')), angle=float(childnode.getAttribute('angle')), ax=float(childnode.getAttribute('ax')), ay=float(childnode.getAttribute('ay')), az=float(childnode.getAttribute('az')), tx=float(childnode.getAttribute('tx')), ty=float(childnode.getAttribute('ty')), tz=float(childnode.getAttribute('tz')), field2DRawData=str(childnode.firstChild.data)))
elif node.nodeName == 'Decoration':
self.Decoration = {"faces": node.getAttribute('faces'), "subMaterialRedirectLookupTable": node.getAttribute('subMaterialRedirectLookupTable')}
class LOCReader:
def __init__(self, data):
self.offset = 0
self.values = {}
self.data = data
if sys.version_info < (3, 0):
if ord(self.data[0]) == 50 and ord(self.data[1]) == 0:
self.offset += 2
while self.offset < len(self.data):
key = self.NextString().replace('Material', '')
value = self.NextString()
self.values[key] = value
else:
if int(self.data[0]) == 50 and int(self.data[1]) == 0:
self.offset += 2
while self.offset < len(self.data):
key = self.NextString().replace('Material', '')
value = self.NextString()
self.values[key] = value
def NextString(self):
out = ''
if sys.version_info < (3, 0):
t = ord(self.data[self.offset])
self.offset += 1
while not t == 0:
out = '{0}{1}'.format(out,chr(t))
t = ord(self.data[self.offset])
self.offset += 1
else:
t = int(self.data[self.offset])
self.offset += 1
while not t == 0:
out = '{0}{1}'.format(out,chr(t))
t = int(self.data[self.offset])
self.offset += 1
return out
class Materials:
def __init__(self, data):
self.Materials = {}
xml = minidom.parseString(data)
for node in xml.firstChild.childNodes:
if node.nodeName == 'Material':
self.Materials[node.getAttribute('MatID')] = Material(node.getAttribute('MatID'),r=int(node.getAttribute('Red')), g=int(node.getAttribute('Green')), b=int(node.getAttribute('Blue')), a=int(node.getAttribute('Alpha')), mtype=str(node.getAttribute('MaterialType')))
def setLOC(self, loc):
for key in loc.values:
if key in self.Materials:
self.Materials[key].name = loc.values[key].replace(" ", "_")
def getMaterialbyId(self, mid):
return self.Materials[mid]
class Materials:
def __init__(self, data):
self.MaterialsRi = {}
material_id_dict = {}
#with open('lego_colors.csv', 'r') as csvfile:
# reader = csv.reader(csvfile, delimiter=',')
# next(csvfile) # skip the first row
# for row in reader:
# material_id_dict[row[0]] = row[6], row[7], row[8], row[9]
xml = minidom.parseString(data)
for node in xml.firstChild.childNodes:
if node.nodeName == 'Material':
usecsvcolors = False
if usecsvcolors == True:
self.MaterialsRi[node.getAttribute('MatID')] = MaterialRi(materialId=node.getAttribute('MatID'), r=int(material_id_dict[node.getAttribute('MatID')][0]), g=int(material_id_dict[node.getAttribute('MatID')][1]), b=int(material_id_dict[node.getAttribute('MatID')][2]), materialType=str(material_id_dict[node.getAttribute('MatID')][3]))
elif usecsvcolors == False:
self.MaterialsRi[node.getAttribute('MatID')] = MaterialRi(materialId=node.getAttribute('MatID'),r=int(node.getAttribute('Red')), g=int(node.getAttribute('Green')), b=int(node.getAttribute('Blue')), a=int(node.getAttribute('Alpha')), materialType=str(node.getAttribute('MaterialType')))
def setLOC(self, loc):
for key in loc.values:
if key in self.MaterialsRi:
self.MaterialsRi[key].name = loc.values[key]
def getMaterialRibyId(self, mid):
return self.MaterialsRi[mid]
class MaterialRi:
def __init__(self, materialId, r, g, b, a, materialType):
self.name = ''
self.materialType = materialType
self.materialId = materialId
self.r = self.sRGBtoLinear(r)
self.g = self.sRGBtoLinear(g)
self.b = self.sRGBtoLinear(b)
self.a = self.sRGBtoLinear(a)
# convert from sRGB luma to linear light: https://entropymine.com/imageworsener/srgbformula/
def sRGBtoLinear(self, rgb):
rgb = float(rgb) / 255
if (rgb <= 0.0404482362771082):
lin = float(rgb / 12.92)
else:
lin = float(pow((rgb + 0.055) / 1.055, 2.4))
return round(lin, 9)
# convert from linear light to sRGB luma
def lineartosRGB(self, linear):
if (linear <= 0.00313066844250063):
rgb = float(linear * 12.92)
else:
rgb = float((1.055 * pow(linear, (1.0 / 2.4)) - 0.055))
return round(rgb, 5)
def string(self, decorationId):
texture_strg = ''
ref_strg = ''
if decorationId != None and decorationId != '0':
# We have decorations
rgb_or_dec_str = '<../diffuseColor_texture.outputs:rgb>'
ref_strg = '.connect'
matId_or_decId = '{0}_{1}'.format(self.materialId, decorationId)
texture_strg = '''
def Shader "stAttrReader"
{{
uniform token info:id = "UsdPrimvarReader_float2"
token inputs:varname = "st"
float2 outputs:result
}}
def Shader "diffuseColor_texture"
{{
uniform token info:id = "UsdUVTexture"
asset inputs:file = @{0}.png@
float2 inputs:st.connect = <../stAttrReader.outputs:result>
float3 outputs:rgb
}}
'''.format(decorationId, round(random.random(), 3))
else:
# We don't have decorations
rgb_or_dec_str = '({0}, {1}, {2})'.format(self.r, self.g, self.b)
matId_or_decId = self.materialId
if self.materialType == 'Transparent':
#bxdf_mat_str = texture_strg +
bxdf_mat_str = '''#usda 1.0
(
defaultPrim = "material_{0}"
)
def Xform "material_{0}" (
assetInfo = {{
asset identifier = @material_{0}.usda@
string name = "material_{0}"
}}
kind = "component"
)
{{
def Material "material_{0}a"
{{
token outputs:surface.connect = <surfaceShader.outputs:surface>
{1}
def Shader "surfaceShader"
{{
uniform token info:id = "UsdPreviewSurface"
color3f inputs:diffuseColor{3} = {2}
float inputs:metallic = 0
float inputs:roughness = 0
float inputs:opacity = 0.2
token outputs:surface
}}
}}
}}\n'''.format(matId_or_decId, texture_strg, rgb_or_dec_str, ref_strg, round(random.random(), 3))
elif self.materialType == 'Metallic':
bxdf_mat_str = '''#usda 1.0
(
defaultPrim = "material_{0}"
)
def Xform "material_{0}" (
assetInfo = {{
asset identifier = @material_{0}.usda@
string name = "material_{0}"
}}
kind = "component"
)
{{
def Material "material_{0}a"
{{
token outputs:surface.connect = <surfaceShader.outputs:surface>
{1}
def Shader "surfaceShader"
{{
uniform token info:id = "UsdPreviewSurface"
color3f inputs:diffuseColor{3} = {2}
float inputs:metallic = 1
float inputs:roughness = 0
token outputs:surface
}}
}}
}}\n'''.format(matId_or_decId, texture_strg, rgb_or_dec_str, ref_strg, round(random.random(), 3))
else:
bxdf_mat_str = '''#usda 1.0
(
defaultPrim = "material_{0}"
)
def Xform "material_{0}" (
assetInfo = {{
asset identifier = @material_{0}.usda@
string name = "material_{0}"
}}
kind = "component"
)
{{
def Material "material_{0}a"
{{
token outputs:surface.connect = <surfaceShader.outputs:surface>
{1}
def Shader "surfaceShader"
{{
uniform token info:id = "UsdPreviewSurface"
color3f inputs:diffuseColor{3} = {2}
float inputs:metallic = 0
float inputs:roughness = 0
token outputs:surface
}}
}}
}}\n'''.format(matId_or_decId, texture_strg, rgb_or_dec_str, ref_strg, round(random.random(), 3))
material = bpy.data.materials.new(matId_or_decId)
material.diffuse_color = (self.r, self.g, self.b, self.a)
material.roughness = 0.1 #Increase roughness for more realistic plastic
material.use_nodes = True #Enable material nodes for working with Cycles
transparents = ['40','41','311','113','111','43','42','126','48','182','44','49'] #List all IDs of transparent Lego colours
if matId_or_decId in transparents: #If our material is transparent, we need to use a different shader to look correct (the Glass BSDF)
material.node_tree.nodes.remove(material.node_tree.nodes.get('Principled BSDF')) #remove default BSDF
out = material.node_tree.nodes.get('Material Output')
glass = material.node_tree.nodes.new('ShaderNodeBsdfGlass') #add Glass BSDF
glass.inputs[0].default_value = (self.r, self.g, self.b, self.a) #set proper color values
material.node_tree.links.new(out.inputs[0], glass.outputs[0]) #set Glass BSDF as the new material output node
else: #If our material is not transparent, the default "Principled BSDF" suffices to capture its properties
material.node_tree.nodes["Principled BSDF"].inputs[0].default_value = (self.r, self.g, self.b, self.a) #set proper color
material.node_tree.nodes["Principled BSDF"].inputs[2].default_value = 0.1 #tweak roughness for realism
metals = ['179','298','145','147','139','310','297','309','315','316'] #list all IDs of metallic Lego colours
if matId_or_decId in metals: #if our material is metallic, we only need to tweak some values of the BSDF to reflect that
material.node_tree.nodes["Principled BSDF"].inputs[1].default_value = 1 #tweak metallic & roughness values for desired look
material.node_tree.nodes["Principled BSDF"].inputs[2].default_value = 0.2
#return bxdf_mat_str
return material
class DBinfo:
def __init__(self, data):
xml = minidom.parseString(data)
self.Version = xml.getElementsByTagName('Bricks')[0].attributes['version'].value
print('DB Version: ' + str(self.Version))
class DBFolderFile:
def __init__(self, name, handle):
self.handle = handle
self.name = name
def read(self):
reader = open(self.handle, "rb")
try:
filecontent = reader.read()
reader.close()
return filecontent
finally:
reader.close()
class LIFFile:
def __init__(self, name, offset, size, handle):
self.handle = handle
self.name = name
self.offset = offset
self.size = size
def read(self):
self.handle.seek(self.offset, 0)
return self.handle.read(self.size)
class DBFolderReader:
def __init__(self, folder):
self.filelist = {}
self.initok = False
self.location = folder
self.dbinfo = None
try:
os.path.isdir(self.location)
except Exception as e:
self.initok = False
print("db folder read FAIL")
return
else:
self.parse()
if self.fileexist(os.path.join(self.location,'Materials.xml')) and self.fileexist(os.path.join(self.location, 'info.xml')) and self.fileexist(os.path.normpath(os.path.join(self.location, MATERIALNAMESPATH, 'EN/localizedStrings.loc'))):
self.dbinfo = DBinfo(data=self.filelist[os.path.join(self.location,'info.xml')].read())
print("DB folder OK.")
self.initok = True
else:
print("DB folder ERROR")
def fileexist(self, filename):
return filename in self.filelist
def parse(self):
for path, subdirs, files in os.walk(self.location):
for name in files:
entryName = os.path.join(path, name)
self.filelist[entryName] = DBFolderFile(name=entryName, handle=entryName)
class LIFReader:
def __init__(self, file):
self.packedFilesOffset = 84
self.filelist = {}
self.initok = False
self.location = file
self.dbinfo = None
try:
self.filehandle = open(self.location, "rb")
self.filehandle.seek(0, 0)
except Exception as e:
self.initok = False
print("Database FAIL")
return
else:
if self.filehandle.read(4).decode() == "LIFF":
self.parse(prefix='', offset=self.readInt(offset=72) + 64)
if self.fileexist(os.path.normpath('/Materials.xml')) and self.fileexist(os.path.normpath('/info.xml')) and self.fileexist(os.path.normpath(MATERIALNAMESPATH + 'EN/localizedStrings.loc')):
self.dbinfo = DBinfo(data=self.filelist[os.path.normpath('/info.xml')].read())
print("Database OK.")
self.initok = True
else:
print("Database ERROR")
else:
print("Database FAIL")
self.initok = False
def fileexist(self,filename):
return filename in self.filelist
def parse(self, prefix='', offset=0):
if prefix == '':
offset += 36
else:
offset += 4
count = self.readInt(offset=offset)
for i in range(0, count):
offset += 4
entryType = self.readShort(offset=offset)
offset += 6
entryName = '{0}{1}'.format(prefix,'/');
self.filehandle.seek(offset + 1, 0)
if sys.version_info < (3, 0):
t = ord(self.filehandle.read(1))
else:
t = int.from_bytes(self.filehandle.read(1), byteorder='big')
while not t == 0:
entryName ='{0}{1}'.format(entryName,chr(t))
self.filehandle.seek(1, 1)
if sys.version_info < (3, 0):
t = ord(self.filehandle.read(1))
else:
t = int.from_bytes(self.filehandle.read(1), byteorder='big')
offset += 2
offset += 6
self.packedFilesOffset += 20
if entryType == 1:
offset = self.parse(prefix=entryName, offset=offset)
elif entryType == 2:
fileSize = self.readInt(offset=offset) - 20
self.filelist[os.path.normpath(entryName)] = LIFFile(name=entryName, offset=self.packedFilesOffset, size=fileSize, handle=self.filehandle)
offset += 24
self.packedFilesOffset += fileSize
return offset
def readInt(self, offset=0):
self.filehandle.seek(offset, 0)
if sys.version_info < (3, 0):
return int(struct.unpack('>i', self.filehandle.read(4))[0])
else:
return int.from_bytes(self.filehandle.read(4), byteorder='big')
def readShort(self, offset=0):
self.filehandle.seek(offset, 0)
if sys.version_info < (3, 0):
return int(struct.unpack('>h', self.filehandle.read(2))[0])
else:
return int.from_bytes(self.filehandle.read(2), byteorder='big')
class Converter:
def LoadDBFolder(self, dbfolderlocation):
self.database = DBFolderReader(folder=dbfolderlocation)
if self.database.initok and self.database.fileexist(os.path.join(dbfolderlocation,'Materials.xml')) and self.database.fileexist(os.path.normpath(MATERIALNAMESPATH + 'EN/localizedStrings.loc')):
self.allMaterials = Materials(data=self.database.filelist[os.path.normpath(os.path.join(dbfolderlocation,'Materials.xml'))].read());
self.allMaterials.setLOC(loc=LOCReader(data=self.database.filelist[os.path.normpath(MATERIALNAMESPATH + 'EN/localizedStrings.loc')].read()))
def LoadDatabase(self,databaselocation):
self.database = LIFReader(file=databaselocation)
if self.database.initok and self.database.fileexist(os.path.normpath('/Materials.xml')) and self.database.fileexist(os.path.normpath(MATERIALNAMESPATH + 'EN/localizedStrings.loc')):
self.allMaterials = Materials(data=self.database.filelist[os.path.normpath('/Materials.xml')].read());
self.allMaterials.setLOC(loc=LOCReader(data=self.database.filelist[os.path.normpath(MATERIALNAMESPATH + 'EN/localizedStrings.loc')].read()))
def LoadScene(self,filename):
if self.database.initok:
self.scene = Scene(file=filename)
def Export(self,filename, useLogoStuds, useLDDCamera):
invert = Matrix3D()
#invert.n33 = -1 #uncomment to invert the Z-Axis
indexOffset = 1
textOffset = 1
usedmaterials = []
geometriecache = {}
writtenribs = []
#usedgeo = [] not used currently
start_time = time.time()
total = len(self.scene.Bricks)
current = 0
currentpart = 0
# miny used for floor plane later
miny = 1000
#useplane = cl.useplane
#usenormal = cl.usenormal
uselogoonstuds = useLogoStuds
useLDDCamera = useLDDCamera
#fstop = cl.args.fstop
#fov = cl.args.fov
global_matrix = axis_conversion(from_forward='-Z', from_up='Y', to_forward='Y',to_up='Z').to_4x4()
#col = bpy.data.collections.get("Collection")
col = bpy.data.collections.new(self.scene.Name)
bpy.context.scene.collection.children.link(col)
if useLDDCamera == True:
for cam in self.scene.Scenecamera:
camera_data = bpy.data.cameras.new(name='Cam_{0}'.format(cam.refID))
camera_object = bpy.data.objects.new('Cam_{0}'.format(cam.refID), camera_data)
transform_matrix = mathutils.Matrix(((cam.matrix.n11, cam.matrix.n21, cam.matrix.n31, cam.matrix.n41),(cam.matrix.n12, cam.matrix.n22, cam.matrix.n32, cam.matrix.n42),(cam.matrix.n13, cam.matrix.n23, cam.matrix.n33, cam.matrix.n43),(cam.matrix.n14, cam.matrix.n24, cam.matrix.n34, cam.matrix.n44)))
camera_object.matrix_world = global_matrix @ transform_matrix
#bpy.context.scene.collection.objects.link(camera_object)
col.objects.link(camera_object)
camera_object.data.lens_unit = 'FOV'
camera_object.data.angle = math.radians(25)
for bri in self.scene.Bricks: