-
Notifications
You must be signed in to change notification settings - Fork 49
/
loadldraw.py
4489 lines (3745 loc) · 205 KB
/
loadldraw.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
# -*- coding: utf-8 -*-
"""Load LDraw GPLv2 license.
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.
"""
"""
Import LDraw
This module loads LDraw compatible files into Blender. Set the
Options first, then call loadFromFile() function with the full
filepath of a file to load.
Accepts .mpd, .ldr, .l3b, and .dat files.
Toby Nelson - tobymnelson@gmail.com
"""
import os
import sys
import math
import mathutils
import traceback
import glob
import bpy
import datetime
import struct
import re
import bmesh
import copy
import platform
import itertools
import operator
from pprint import pprint
# **************************************************************************************
def matmul(a, b):
"""Perform matrix multiplication in a blender 2.7 and 2.8 safe way"""
if isBlender28OrLater:
return operator.matmul(a, b) # the same as writing a @ b, but parses ok in 2.7
else:
return a * b
# **************************************************************************************
def matvecmul(a, b):
"""Perform matrix multiplication in a blender 2.7 and 2.8 safe way"""
if isBlender28OrLater:
return operator.matmul(a, b) # the same as writing a @ b, but parses ok in 2.7
else:
return a * b
# **************************************************************************************
def linkToScene(ob):
if isBlender28OrLater:
if bpy.context.collection.objects.find(ob.name) < 0:
bpy.context.collection.objects.link(ob)
else:
if bpy.context.scene.objects.find(ob.name) < 0:
bpy.context.scene.objects.link(ob)
# **************************************************************************************
def linkToCollection(collectionName, ob):
# Add object to the appropriate collection
if hasCollections:
if bpy.data.collections[collectionName].objects.find(ob.name) < 0:
bpy.data.collections[collectionName].objects.link(ob)
else:
bpy.data.groups[collectionName].objects.link(ob)
# **************************************************************************************
def unlinkFromScene(ob):
if isBlender28OrLater:
if bpy.context.collection.objects.find(ob.name) >= 0:
bpy.context.collection.objects.unlink(ob)
else:
if bpy.context.scene.objects.find(ob.name) >= 0:
bpy.context.scene.objects.unlink(ob)
# **************************************************************************************
def selectObject(ob):
if isBlender28OrLater:
ob.select_set(state=True)
bpy.context.view_layer.objects.active = ob
else:
ob.select = True
bpy.context.scene.objects.active = ob
# **************************************************************************************
def deselectObject(ob):
if isBlender28OrLater:
ob.select_set(state=False)
bpy.context.view_layer.objects.active = None
else:
ob.select = False
bpy.context.scene.objects.active = None
# **************************************************************************************
def addPlane(location, size):
if isBlender28OrLater:
bpy.ops.mesh.primitive_plane_add(size=size, enter_editmode=False, location=location)
else:
bpy.ops.mesh.primitive_plane_add(radius=size, view_align=False, enter_editmode=False, location=location)
# **************************************************************************************
def useDenoising(scene, useDenoising):
if hasattr(getLayers(scene)[0], "cycles"):
getLayers(scene)[0].cycles.use_denoising = useDenoising
# **************************************************************************************
def getLayerNames(scene):
return list(map((lambda x: x.name), getLayers(scene)))
# **************************************************************************************
def deleteEdge(bm, edge):
if isBlender28OrLater:
bmesh.ops.delete(bm, geom=edge, context='EDGES')
else:
bmesh.ops.delete(bm, geom=[edge], context=2)
# **************************************************************************************
def getLayers(scene):
# Get the render/view layers we are interested in:
if isBlender28OrLater:
return scene.view_layers
else:
return scene.render.layers
# **************************************************************************************
def getDiffuseColor(color):
if isBlender28OrLater:
return color + (1.0,)
else:
return color
# **************************************************************************************
# **************************************************************************************
class Options:
"""User Options"""
# Full filepath to ldraw folder. If empty, some standard locations are attempted
ldrawDirectory = r"" # Full filepath to the ldraw parts library (searches some standard locations if left blank)
instructionsLook = False # Set up scene to look like Lego Instruction booklets
scale = 0.01 # Size of the lego model to create. (0.04 is LeoCAD scale)
useUnofficialParts = True # Additionally searches <ldraw-dir>/unofficial/parts and /p for files
resolution = "Standard" # Choose from "High", "Standard", or "Low"
defaultColour = "4" # Default colour ("4" = red)
createInstances = True # Multiple bricks share geometry (recommended)
useColourScheme = "lgeo" # "ldraw", "alt", or "lgeo". LGEO gives the most true-to-life colours.
numberNodes = True # Each node's name has a numerical prefix eg. 00001_car.dat (keeps nodes listed in a fixed order)
removeDoubles = True # Remove duplicate vertices (recommended)
smoothShading = True # Smooth the surface normals (recommended)
edgeSplit = True # Edge split modifier (recommended if you use smoothShading)
gaps = True # Introduces a tiny space between each brick
gapWidth = 0.01 # Width of gap between bricks (in Blender units)
curvedWalls = True # Manipulate normals to make surfaces look slightly concave
importCameras = True # LeoCAD can specify cameras within the ldraw file format. Choose to load them or ignore them.
positionObjectOnGroundAtOrigin = True # Centre the object at the origin, sitting on the z=0 plane
flattenHierarchy = False # All parts are under the root object - no sub-models
flattenGroups = False # All LEOCad groups are ignored - no groups
usePrincipledShaderWhenAvailable = True # Use the new principled shader
scriptDirectory = os.path.dirname( os.path.realpath(__file__) )
# We have the option of including the 'LEGO' logo on each stud
useLogoStuds = False # Use the studs with the 'LEGO' logo on them
logoStudVersion = "4" # Which version of the logo to use ("3" (flat), "4" (rounded) or "5" (subtle rounded))
instanceStuds = False # Each stud is a new Blender object (slow)
# LSynth (http://www.holly-wood.it/lsynth/tutorial-en.html) is a collection of parts used to render string, hoses, cables etc
useLSynthParts = True # LSynth is used to render string, hoses etc.
LSynthDirectory = r"" # Full path to the lsynth parts (Defaults to <ldrawdir>/unofficial/lsynth if left blank)
studLogoDirectory = r"" # Optional full path to the stud logo parts (if not found in unofficial directory)
# Ambiguous Normals
# Older LDraw parts (parts not yet BFC certified) have ambiguous normals.
# We resolve this by creating double sided faces ("double") or by taking a best guess ("guess")
resolveAmbiguousNormals = "guess" # How to resolve ambiguous normals
overwriteExistingMaterials = True # If there's an existing material with the same name, do we overwrite it, or use it?
overwriteExistingMeshes = True # If there's an existing mesh with the same name, do we overwrite it, or use it?
verbose = 1 # 1 = Show messages while working, 0 = Only show warnings/errors
addBevelModifier = True # Adds a bevel modifier to each part (for rounded edges)
bevelWidth = 0.5 # Width of bevel
addWorldEnvironmentTexture = True # Add an environment texture
addGroundPlane = True # Add a ground plane
setRenderSettings = True # Set render percentage, denoising
removeDefaultObjects = True # Remove cube and lamp
positionCamera = True # Position the camera where so we get the whole object in shot
cameraBorderPercent = 0.05 # Add a border gap around the positioned object (0.05 = 5%) for the rendered image
def meshOptionsString():
"""These options change the mesh, so if they change, a new mesh needs to be cached"""
return "_".join([str(Options.scale),
str(Options.useUnofficialParts),
str(Options.instructionsLook),
str(Options.resolution),
str(Options.defaultColour),
str(Options.createInstances),
str(Options.useColourScheme),
str(Options.removeDoubles),
str(Options.smoothShading),
str(Options.gaps),
str(Options.gapWidth),
str(Options.curvedWalls),
str(Options.flattenHierarchy),
str(Options.useLogoStuds),
str(Options.logoStudVersion),
str(Options.instanceStuds),
str(Options.useLSynthParts),
str(Options.LSynthDirectory),
str(Options.studLogoDirectory),
str(Options.resolveAmbiguousNormals),
str(Options.addBevelModifier),
str(Options.bevelWidth)])
# **************************************************************************************
# Globals
globalBrickCount = 0
globalObjectsToAdd = [] # Blender objects to add to the scene
globalCamerasToAdd = [] # Camera data to add to the scene
globalContext = None
globalWeldDistance = 0.0005
globalPoints = []
isBlender28OrLater = None
hasCollections = None
if isBlender28OrLater:
lightName = "Light"
else:
lightName = "Lamp"
# **************************************************************************************
# Dictionary with as keys the part numbers (without any extension for decorations)
# of pieces that have grainy slopes, and as values a set containing the angles (in
# degrees) of the face's normal to the horizontal plane. Use a tuple to represent a
# range within which the angle must lie.
globalSlopeBricks = {
'962':{45},
'2341':{-45},
'2449':{-16},
'2875':{45},
'2876':{(40, 63)},
'3037':{45},
'3038':{45},
'3039':{45},
'3040':{45},
'3041':{45},
'3042':{45},
'3043':{45},
'3044':{45},
'3045':{45},
'3046':{45},
'3048':{45},
'3049':{45},
'3135':{45},
'3297':{63},
'3298':{63},
'3299':{63},
'3300':{63},
'3660':{-45},
'3665':{-45},
'3675':{63},
'3676':{-45},
'3678b':{24},
'3684':{15},
'3685':{16},
'3688':{15},
'3747':{-63},
'4089':{-63},
'4161':{63},
'4286':{63},
'4287':{-63},
'4445':{45},
'4460':{16},
'4509':{63},
'4854':{-45},
'4856':{(-60, -70), -45},
'4857':{45},
'4858':{72},
'4861':{45, 63},
'4871':{-45},
'4885':{72},
'6069':{72, 45},
'6153':{(60, 70), (26, 34)},
'6227':{45},
'6270':{45},
'13269':{(40, 63)},
'13548':{45},
'15571':{45},
'18759':{-45},
'22390':{(40, 55)},
'22391':{(40, 55)},
'22889':{-45},
'28192':{45},
'30180':{47},
'30182':{45},
'30183':{-45},
'30249':{35},
'30283':{-45},
'30363':{72},
'30373':{-24},
'30382':{11, 45},
'30390':{-45},
'30499':{16},
'32083':{45},
'43708':{72},
'43710':{72, 45},
'43711':{72, 45},
'47759':{(40, 63)},
'52501':{-45},
'60219':{-45},
'60477':{72},
'60481':{24},
'63341':{45},
'72454':{-45},
'92946':{45},
'93348':{72},
'95188':{65},
'99301':{63},
'303923':{45},
'303926':{45},
'304826':{45},
'329826':{64},
'374726':{-64},
'428621':{64},
'4162628':{17},
'4195004':{45},
}
globalLightBricks = {
'62930.dat':(1.0,0.373,0.059,1.0),
'54869.dat':(1.0,0.052,0.017,1.0)
}
# Create a regular dictionary of parts with ranges of angles to check
margin = 5 # Allow 5 degrees either way to compensate for measuring inaccuracies
globalSlopeAngles = {}
for part in globalSlopeBricks:
globalSlopeAngles[part] = {(c-margin, c+margin) if type(c) is not tuple else (min(c)-margin,max(c)+margin) for c in globalSlopeBricks[part]}
# **************************************************************************************
def internalPrint(message):
"""Debug print with identification timestamp."""
# Current timestamp (with milliseconds trimmed to two places)
timestamp = datetime.datetime.now().strftime("%H:%M:%S.%f")[:-4]
message = "{0} [importldraw] {1}".format(timestamp, message)
print("{0}".format(message))
global globalContext
if globalContext is not None:
globalContext.report({'INFO'}, message)
# **************************************************************************************
def debugPrint(message):
"""Debug print with identification timestamp."""
if Options.verbose > 0:
internalPrint(message)
# **************************************************************************************
def printWarningOnce(key, message=None):
if message is None:
message = key
if key not in Configure.warningSuppression:
internalPrint("WARNING: {0}".format(message))
Configure.warningSuppression[key] = True
global globalContext
if globalContext is not None:
globalContext.report({'WARNING'}, message)
# **************************************************************************************
def printError(message):
internalPrint("ERROR: {0}".format(message))
global globalContext
if globalContext is not None:
globalContext.report({'ERROR'}, message)
# **************************************************************************************
# **************************************************************************************
class Math:
identityMatrix = mathutils.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)
))
rotationMatrix = mathutils.Matrix.Rotation(math.radians(-90), 4, 'X')
reflectionMatrix = mathutils.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 clamp01(value):
return max(min(value, 1.0), 0.0)
def __init__(self):
# Rotation and scale matrices that convert LDraw coordinate space to Blender coordinate space
Math.scaleMatrix = mathutils.Matrix((
(Options.scale, 0.0, 0.0, 0.0),
(0.0, Options.scale, 0.0, 0.0),
(0.0, 0.0, Options.scale, 0.0),
(0.0, 0.0, 0.0, 1.0)
))
# **************************************************************************************
# **************************************************************************************
class Configure:
"""Configuration.
Attempts to find the ldraw directory (platform specific directories are searched).
Stores the list of paths to parts libraries that we search for individual parts.
Stores warning messages we have already seen so we don't see them again.
"""
searchPaths = []
warningSuppression = {}
def __appendPath(path):
if os.path.exists(path):
Configure.searchPaths.append(path)
def __setSearchPaths():
Configure.searchPaths = []
# Always search for parts in the 'models' folder
Configure.__appendPath(os.path.join(Configure.ldrawInstallDirectory, "models"))
# Search for stud logo parts
if Options.useLogoStuds and Options.studLogoDirectory != "":
if Options.resolution == "Low":
Configure.__appendPath(os.path.join(Options.studLogoDirectory, "8"))
Configure.__appendPath(Options.studLogoDirectory)
# Search unofficial parts
if Options.useUnofficialParts:
Configure.__appendPath(os.path.join(Configure.ldrawInstallDirectory, "unofficial", "parts"))
if Options.resolution == "High":
Configure.__appendPath(os.path.join(Configure.ldrawInstallDirectory, "unofficial", "p", "48"))
elif Options.resolution == "Low":
Configure.__appendPath(os.path.join(Configure.ldrawInstallDirectory, "unofficial", "p", "8"))
Configure.__appendPath(os.path.join(Configure.ldrawInstallDirectory, "unofficial", "p"))
# Search LSynth parts
if Options.useLSynthParts:
if Options.LSynthDirectory != "":
Configure.__appendPath(Options.LSynthDirectory)
else:
Configure.__appendPath(os.path.join(Configure.ldrawInstallDirectory, "unofficial", "lsynth"))
debugPrint("Use LSynth Parts requested")
# Search official parts
Configure.__appendPath(os.path.join(Configure.ldrawInstallDirectory, "parts"))
if Options.resolution == "High":
Configure.__appendPath(os.path.join(Configure.ldrawInstallDirectory, "p", "48"))
debugPrint("High-res primitives selected")
elif Options.resolution == "Low":
Configure.__appendPath(os.path.join(Configure.ldrawInstallDirectory, "p", "8"))
debugPrint("Low-res primitives selected")
else:
debugPrint("Standard-res primitives selected")
Configure.__appendPath(os.path.join(Configure.ldrawInstallDirectory, "p"))
def isWindows():
return platform.system() == "Windows"
def isMac():
return platform.system() == "Darwin"
def isLinux():
return platform.system() == "Linux"
def findDefaultLDrawDirectory():
result = ""
# Get list of possible ldraw installation directories for the platform
if Configure.isWindows():
ldrawPossibleDirectories = [
"C:\\LDraw",
"C:\\Program Files\\LDraw",
"C:\\Program Files (x86)\\LDraw",
"C:\\Program Files\\Studio 2.0\\ldraw",
]
elif Configure.isMac():
ldrawPossibleDirectories = [
"~/ldraw/",
"/Applications/LDraw/",
"/Applications/ldraw/",
"/usr/local/share/ldraw",
]
else: # Default to Linux if not Windows or Mac
ldrawPossibleDirectories = [
"~/LDraw",
"~/ldraw",
"~/.LDraw",
"~/.ldraw",
"/usr/local/share/ldraw",
]
# Search possible directories
for dir in ldrawPossibleDirectories:
dir = os.path.expanduser(dir)
if os.path.isfile(os.path.join(dir, "LDConfig.ldr")):
result = dir
break
return result
def setLDrawDirectory():
if Options.ldrawDirectory == "":
Configure.ldrawInstallDirectory = Configure.findDefaultLDrawDirectory()
else:
Configure.ldrawInstallDirectory = os.path.expanduser(Options.ldrawDirectory)
debugPrint("The LDraw Parts Library path to be used is: {0}".format(Configure.ldrawInstallDirectory))
Configure.__setSearchPaths()
def __init__(self):
Configure.setLDrawDirectory()
# **************************************************************************************
# **************************************************************************************
class LegoColours:
"""Parses and stores a table of colour / material definitions. Converts colour space."""
colours = {}
def __getValue(line, value):
"""Parses a colour value from the ldConfig.ldr file"""
if value in line:
n = line.index(value)
return line[n + 1]
def __sRGBtoRGBValue(value):
# See https://en.wikipedia.org/wiki/SRGB#The_reverse_transformation
if value < 0.04045:
return value / 12.92
return ((value + 0.055)/1.055)**2.4
def isDark(colour):
R = colour[0]
G = colour[1]
B = colour[2]
# Measure the perceived brightness of colour
brightness = math.sqrt( 0.299*R*R + 0.587*G*G + 0.114*B*B )
# Dark colours have white lines
if brightness < 0.02:
return True
return False
def sRGBtoLinearRGB(sRGBColour):
# See https://en.wikipedia.org/wiki/SRGB#The_reverse_transformation
(sr, sg, sb) = sRGBColour
r = LegoColours.__sRGBtoRGBValue(sr)
g = LegoColours.__sRGBtoRGBValue(sg)
b = LegoColours.__sRGBtoRGBValue(sb)
return (r,g,b)
def hexDigitsToLinearRGBA(hexDigits, alpha):
# String is "RRGGBB" format
int_tuple = struct.unpack('BBB', bytes.fromhex(hexDigits))
sRGB = tuple([val / 255 for val in int_tuple])
linearRGB = LegoColours.sRGBtoLinearRGB(sRGB)
return (linearRGB[0], linearRGB[1], linearRGB[2], alpha)
def hexStringToLinearRGBA(hexString):
"""Convert colour hex value to RGB value."""
# Handle direct colours
# Direct colours are documented here: http://www.hassings.dk/l3/l3p.html
match = re.fullmatch(r"0x0*([0-9])((?:[A-F0-9]{2}){3})", hexString)
if match is not None:
digit = match.group(1)
rgb_str = match.group(2)
interleaved = False
if digit == "2": # Opaque
alpha = 1.0
elif digit == "3": # Transparent
alpha = 0.5
elif digit == "4": # Opaque
alpha = 1.0
interleaved = True
elif digit == "5": # More Transparent
alpha = 0.333
interleaved = True
elif digit == "6": # Less transparent
alpha = 0.666
interleaved = True
elif digit == "7": # Invisible
alpha = 0.0
interleaved = True
else:
alpha = 1.0
if interleaved:
# Input string is six hex digits of two colours "RGBRGB".
# This was designed to be a dithered colour.
# Take the average of those two colours (R+R,G+G,B+B) * 0.5
r = float(int(rgb_str[0], 16)) / 15
g = float(int(rgb_str[1], 16)) / 15
b = float(int(rgb_str[2], 16)) / 15
colour1 = LegoColours.sRGBtoLinearRGB((r,g,b))
r = float(int(rgb_str[3], 16)) / 15
g = float(int(rgb_str[4], 16)) / 15
b = float(int(rgb_str[5], 16)) / 15
colour2 = LegoColours.sRGBtoLinearRGB((r,g,b))
return (0.5 * (colour1[0] + colour2[0]),
0.5 * (colour1[1] + colour2[1]),
0.5 * (colour1[2] + colour2[2]), alpha)
# String is "RRGGBB" format
return LegoColours.hexDigitsToLinearRGBA(rgb_str, alpha)
return None
def __overwriteColour(index, colour):
if index in LegoColours.colours:
LegoColours.colours[index]["colour"] = colour
def __readColourTable():
"""Reads the colour values from the LDConfig.ldr file. For details of the
Ldraw colour system see: http://www.ldraw.org/article/547"""
if Options.useColourScheme == "alt":
configFilename = "LDCfgalt.ldr"
else:
configFilename = "LDConfig.ldr"
configFilepath = os.path.join(Configure.ldrawInstallDirectory, configFilename)
ldconfig_lines = ""
if os.path.exists(configFilepath):
with open(configFilepath, "rt", encoding="utf_8") as ldconfig:
ldconfig_lines = ldconfig.readlines()
for line in ldconfig_lines:
if len(line) > 3:
if line[2:4].lower() == '!c':
line_split = line.split()
name = line_split[2]
code = int(line_split[4])
linearRGBA = LegoColours.hexDigitsToLinearRGBA(line_split[6][1:], 1.0)
colour = {
"name": name,
"colour": linearRGBA[0:3],
"alpha": linearRGBA[3],
"luminance": 0.0,
"material": "BASIC"
}
if "ALPHA" in line_split:
colour["alpha"] = int(LegoColours.__getValue(line_split, "ALPHA")) / 256.0
if "LUMINANCE" in line_split:
colour["luminance"] = int(LegoColours.__getValue(line_split, "LUMINANCE"))
if "CHROME" in line_split:
colour["material"] = "CHROME"
if "PEARLESCENT" in line_split:
colour["material"] = "PEARLESCENT"
if "RUBBER" in line_split:
colour["material"] = "RUBBER"
if "METAL" in line_split:
colour["material"] = "METAL"
if "MATERIAL" in line_split:
subline = line_split[line_split.index("MATERIAL"):]
colour["material"] = LegoColours.__getValue(subline, "MATERIAL")
hexDigits = LegoColours.__getValue(subline, "VALUE")[1:]
colour["secondary_colour"] = LegoColours.hexDigitsToLinearRGBA(hexDigits, 1.0)
colour["fraction"] = LegoColours.__getValue(subline, "FRACTION")
colour["vfraction"] = LegoColours.__getValue(subline, "VFRACTION")
colour["size"] = LegoColours.__getValue(subline, "SIZE")
colour["minsize"] = LegoColours.__getValue(subline, "MINSIZE")
colour["maxsize"] = LegoColours.__getValue(subline, "MAXSIZE")
LegoColours.colours[code] = colour
if Options.useColourScheme == "lgeo":
# LGEO is a parts library for rendering LEGO using the povray rendering software.
# It has a list of LEGO colours suitable for realistic rendering.
# I've extracted the following colours from the LGEO file: lg_color.inc
# LGEO is downloadable from http://ldraw.org/downloads-2/downloads.html
# We overwrite the standard LDraw colours if we have better LGEO colours.
LegoColours.__overwriteColour(0, ( 33/255, 33/255, 33/255))
LegoColours.__overwriteColour(1, ( 13/255, 105/255, 171/255))
LegoColours.__overwriteColour(2, ( 40/255, 127/255, 70/255))
LegoColours.__overwriteColour(3, ( 0/255, 143/255, 155/255))
LegoColours.__overwriteColour(4, (196/255, 40/255, 27/255))
LegoColours.__overwriteColour(5, (205/255, 98/255, 152/255))
LegoColours.__overwriteColour(6, ( 98/255, 71/255, 50/255))
LegoColours.__overwriteColour(7, (161/255, 165/255, 162/255))
LegoColours.__overwriteColour(8, (109/255, 110/255, 108/255))
LegoColours.__overwriteColour(9, (180/255, 210/255, 227/255))
LegoColours.__overwriteColour(10, ( 75/255, 151/255, 74/255))
LegoColours.__overwriteColour(11, ( 85/255, 165/255, 175/255))
LegoColours.__overwriteColour(12, (242/255, 112/255, 94/255))
LegoColours.__overwriteColour(13, (252/255, 151/255, 172/255))
LegoColours.__overwriteColour(14, (245/255, 205/255, 47/255))
LegoColours.__overwriteColour(15, (242/255, 243/255, 242/255))
LegoColours.__overwriteColour(17, (194/255, 218/255, 184/255))
LegoColours.__overwriteColour(18, (249/255, 233/255, 153/255))
LegoColours.__overwriteColour(19, (215/255, 197/255, 153/255))
LegoColours.__overwriteColour(20, (193/255, 202/255, 222/255))
LegoColours.__overwriteColour(21, (224/255, 255/255, 176/255))
LegoColours.__overwriteColour(22, (107/255, 50/255, 123/255))
LegoColours.__overwriteColour(23, ( 35/255, 71/255, 139/255))
LegoColours.__overwriteColour(25, (218/255, 133/255, 64/255))
LegoColours.__overwriteColour(26, (146/255, 57/255, 120/255))
LegoColours.__overwriteColour(27, (164/255, 189/255, 70/255))
LegoColours.__overwriteColour(28, (149/255, 138/255, 115/255))
LegoColours.__overwriteColour(29, (228/255, 173/255, 200/255))
LegoColours.__overwriteColour(30, (172/255, 120/255, 186/255))
LegoColours.__overwriteColour(31, (225/255, 213/255, 237/255))
LegoColours.__overwriteColour(32, ( 0/255, 20/255, 20/255))
LegoColours.__overwriteColour(33, (123/255, 182/255, 232/255))
LegoColours.__overwriteColour(34, (132/255, 182/255, 141/255))
LegoColours.__overwriteColour(35, (217/255, 228/255, 167/255))
LegoColours.__overwriteColour(36, (205/255, 84/255, 75/255))
LegoColours.__overwriteColour(37, (228/255, 173/255, 200/255))
LegoColours.__overwriteColour(38, (255/255, 43/255, 0/225))
LegoColours.__overwriteColour(40, (166/255, 145/255, 130/255))
LegoColours.__overwriteColour(41, (170/255, 229/255, 255/255))
LegoColours.__overwriteColour(42, (198/255, 255/255, 0/255))
LegoColours.__overwriteColour(43, (193/255, 223/255, 240/255))
LegoColours.__overwriteColour(44, (150/255, 112/255, 159/255))
LegoColours.__overwriteColour(46, (247/255, 241/255, 141/255))
LegoColours.__overwriteColour(47, (252/255, 252/255, 252/255))
LegoColours.__overwriteColour(52, (156/255, 149/255, 199/255))
LegoColours.__overwriteColour(54, (255/255, 246/255, 123/255))
LegoColours.__overwriteColour(57, (226/255, 176/255, 96/255))
LegoColours.__overwriteColour(65, (236/255, 201/255, 53/255))
LegoColours.__overwriteColour(66, (202/255, 176/255, 0/255))
LegoColours.__overwriteColour(67, (255/255, 255/255, 255/255))
LegoColours.__overwriteColour(68, (243/255, 207/255, 155/255))
LegoColours.__overwriteColour(69, (142/255, 66/255, 133/255))
LegoColours.__overwriteColour(70, (105/255, 64/255, 39/255))
LegoColours.__overwriteColour(71, (163/255, 162/255, 164/255))
LegoColours.__overwriteColour(72, ( 99/255, 95/255, 97/255))
LegoColours.__overwriteColour(73, (110/255, 153/255, 201/255))
LegoColours.__overwriteColour(74, (161/255, 196/255, 139/255))
LegoColours.__overwriteColour(77, (220/255, 144/255, 149/255))
LegoColours.__overwriteColour(78, (246/255, 215/255, 179/255))
LegoColours.__overwriteColour(79, (255/255, 255/255, 255/255))
LegoColours.__overwriteColour(80, (140/255, 140/255, 140/255))
LegoColours.__overwriteColour(82, (219/255, 172/255, 52/255))
LegoColours.__overwriteColour(84, (170/255, 125/255, 85/255))
LegoColours.__overwriteColour(85, ( 52/255, 43/255, 117/255))
LegoColours.__overwriteColour(86, (124/255, 92/255, 69/255))
LegoColours.__overwriteColour(89, (155/255, 178/255, 239/255))
LegoColours.__overwriteColour(92, (204/255, 142/255, 104/255))
LegoColours.__overwriteColour(100, (238/255, 196/255, 182/255))
LegoColours.__overwriteColour(115, (199/255, 210/255, 60/255))
LegoColours.__overwriteColour(134, (174/255, 122/255, 89/255))
LegoColours.__overwriteColour(135, (171/255, 173/255, 172/255))
LegoColours.__overwriteColour(137, (106/255, 122/255, 150/255))
LegoColours.__overwriteColour(142, (220/255, 188/255, 129/255))
LegoColours.__overwriteColour(148, ( 62/255, 60/255, 57/255))
LegoColours.__overwriteColour(151, ( 14/255, 94/255, 77/255))
LegoColours.__overwriteColour(179, (160/255, 160/255, 160/255))
LegoColours.__overwriteColour(183, (242/255, 243/255, 242/255))
LegoColours.__overwriteColour(191, (248/255, 187/255, 61/255))
LegoColours.__overwriteColour(212, (159/255, 195/255, 233/255))
LegoColours.__overwriteColour(216, (143/255, 76/255, 42/255))
LegoColours.__overwriteColour(226, (253/255, 234/255, 140/255))
LegoColours.__overwriteColour(232, (125/255, 187/255, 221/255))
LegoColours.__overwriteColour(256, ( 33/255, 33/255, 33/255))
LegoColours.__overwriteColour(272, ( 32/255, 58/255, 86/255))
LegoColours.__overwriteColour(273, ( 13/255, 105/255, 171/255))
LegoColours.__overwriteColour(288, ( 39/255, 70/255, 44/255))
LegoColours.__overwriteColour(294, (189/255, 198/255, 173/255))
LegoColours.__overwriteColour(297, (170/255, 127/255, 46/255))
LegoColours.__overwriteColour(308, ( 53/255, 33/255, 0/255))
LegoColours.__overwriteColour(313, (171/255, 217/255, 255/255))
LegoColours.__overwriteColour(320, (123/255, 46/255, 47/255))
LegoColours.__overwriteColour(321, ( 70/255, 155/255, 195/255))
LegoColours.__overwriteColour(322, (104/255, 195/255, 226/255))
LegoColours.__overwriteColour(323, (211/255, 242/255, 234/255))
LegoColours.__overwriteColour(324, (196/255, 0/255, 38/255))
LegoColours.__overwriteColour(326, (226/255, 249/255, 154/255))
LegoColours.__overwriteColour(330, (119/255, 119/255, 78/255))
LegoColours.__overwriteColour(334, (187/255, 165/255, 61/255))
LegoColours.__overwriteColour(335, (149/255, 121/255, 118/255))
LegoColours.__overwriteColour(366, (209/255, 131/255, 4/255))
LegoColours.__overwriteColour(373, (135/255, 124/255, 144/255))
LegoColours.__overwriteColour(375, (193/255, 194/255, 193/255))
LegoColours.__overwriteColour(378, (120/255, 144/255, 129/255))
LegoColours.__overwriteColour(379, ( 94/255, 116/255, 140/255))
LegoColours.__overwriteColour(383, (224/255, 224/255, 224/255))
LegoColours.__overwriteColour(406, ( 0/255, 29/255, 104/255))
LegoColours.__overwriteColour(449, (129/255, 0/255, 123/255))
LegoColours.__overwriteColour(450, (203/255, 132/255, 66/255))
LegoColours.__overwriteColour(462, (226/255, 155/255, 63/255))
LegoColours.__overwriteColour(484, (160/255, 95/255, 52/255))
LegoColours.__overwriteColour(490, (215/255, 240/255, 0/255))
LegoColours.__overwriteColour(493, (101/255, 103/255, 97/255))
LegoColours.__overwriteColour(494, (208/255, 208/255, 208/255))
LegoColours.__overwriteColour(496, (163/255, 162/255, 164/255))
LegoColours.__overwriteColour(503, (199/255, 193/255, 183/255))
LegoColours.__overwriteColour(504, (137/255, 135/255, 136/255))
LegoColours.__overwriteColour(511, (250/255, 250/255, 250/255))
# Colour Space Management: Convert these sRGB colour values to Blender's linear RGB colour space
for key in LegoColours.colours:
LegoColours.colours[key]["colour"] = LegoColours.sRGBtoLinearRGB(LegoColours.colours[key]["colour"])
def lightenRGBA(colour, scale):
# Moves the linear RGB values closer to white
# scale = 0 means full white
# scale = 1 means color stays same
colour = ((1.0 - colour[0]) * scale,
(1.0 - colour[1]) * scale,
(1.0 - colour[2]) * scale,
colour[3])
return (Math.clamp01(1.0 - colour[0]),
Math.clamp01(1.0 - colour[1]),
Math.clamp01(1.0 - colour[2]),
colour[3])
def isFluorescentTransparent(colName):
if (colName == "Trans_Neon_Orange"):
return True
if (colName == "Trans_Neon_Green"):
return True
if (colName == "Trans_Neon_Yellow"):
return True
if (colName == "Trans_Bright_Green"):
return True
return False
def __init__(self):
LegoColours.__readColourTable()
# **************************************************************************************
# **************************************************************************************
class FileSystem:
"""
Reads text files in different encodings. Locates full filepath for a part.
"""
# Takes a case-insensitive filepath and constructs a case sensitive version (based on an actual existing file)
# See https://stackoverflow.com/questions/8462449/python-case-insensitive-file-name/8462613#8462613
def pathInsensitive(path):
"""
Get a case-insensitive path for use on a case sensitive system.
>>> path_insensitive('/Home')
'/home'
>>> path_insensitive('/Home/chris')
'/home/chris'
>>> path_insensitive('/HoME/CHris/')
'/home/chris/'
>>> path_insensitive('/home/CHRIS')
'/home/chris'
>>> path_insensitive('/Home/CHRIS/.gtk-bookmarks')
'/home/chris/.gtk-bookmarks'
>>> path_insensitive('/home/chris/.GTK-bookmarks')
'/home/chris/.gtk-bookmarks'
>>> path_insensitive('/HOME/Chris/.GTK-bookmarks')
'/home/chris/.gtk-bookmarks'
>>> path_insensitive("/HOME/Chris/I HOPE this doesn't exist")
"/HOME/Chris/I HOPE this doesn't exist"
"""
return FileSystem.__path_insensitive(path) or path
def __path_insensitive(path):
"""
Recursive part of path_insensitive to do the work.
"""
if path == '' or os.path.exists(path):
return path
base = os.path.basename(path) # may be a directory or a file
dirname = os.path.dirname(path)
suffix = ''
if not base: # dir ends with a slash?
if len(dirname) < len(path):
suffix = path[:len(path) - len(dirname)]
base = os.path.basename(dirname)
dirname = os.path.dirname(dirname)
if not os.path.exists(dirname):
dirname = FileSystem.__path_insensitive(dirname)
if not dirname:
return
# at this point, the directory exists but not the file
try: # we are expecting dirname to be a directory, but it could be a file
files = CachedDirectoryFilenames.getCached(dirname)
if files is None:
files = os.listdir(dirname)
CachedDirectoryFilenames.addToCache(dirname, files)
except OSError:
return
baselow = base.lower()
try:
basefinal = next(fl for fl in files if fl.lower() == baselow)
except StopIteration:
return
if basefinal:
return os.path.join(dirname, basefinal) + suffix
else:
return
def __checkEncoding(filepath):
"""Check the encoding of a file for Endian encoding."""
filepath = FileSystem.pathInsensitive(filepath)
# Open it, read just the area containing a possible byte mark
with open(filepath, "rb") as encode_check:
encoding = encode_check.readline(3)
# The file uses UCS-2 (UTF-16) Big Endian encoding
if encoding == b"\xfe\xff\x00":
return "utf_16_be"
# The file uses UCS-2 (UTF-16) Little Endian
elif encoding == b"\xff\xfe0":
return "utf_16_le"
# Use LDraw model standard UTF-8
else:
return "utf_8"
def readTextFile(filepath):
"""Read a text file, with various checks for type of encoding"""
filepath = FileSystem.pathInsensitive(filepath)
lines = None
if os.path.exists(filepath):
# Try to read using the suspected encoding
file_encoding = FileSystem.__checkEncoding(filepath)
try:
with open(filepath, "rt", encoding=file_encoding) as f_in:
lines = f_in.readlines()
except:
# If all else fails, read using Latin 1 encoding
with open(filepath, "rt", encoding="latin_1") as f_in:
lines = f_in.readlines()
return lines
def locate(filename, rootPath = None):
"""Given a file name of an ldraw file, find the full path"""
partName = filename.replace("\\", os.path.sep)
partName = os.path.expanduser(partName)
if rootPath is None:
rootPath = os.path.dirname(filename)
allSearchPaths = Configure.searchPaths[:]
if rootPath not in allSearchPaths:
allSearchPaths.append(rootPath)
for path in allSearchPaths:
fullPathName = os.path.join(path, partName)
fullPathName = FileSystem.pathInsensitive(fullPathName)