-
Notifications
You must be signed in to change notification settings - Fork 5
/
__init__.py
1381 lines (1264 loc) · 58.6 KB
/
__init__.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": "AssetLibraryTools",
"description": "AssetLibraryTools is a free addon which aims to speed up the process of creating asset libraries with the asset browser, This addon is currently very much experimental as is the asset browser in blender.",
"author": "Lucian James (LJ3D)",
"version": (0, 2, 2),
"blender": (3, 0, 0),
"location": "3D View > Tools",
"warning": "Developed in 3.0, primarily the alpha. May be unstable or broken in future versions", # used for warning icon and text in addons panel
"wiki_url": "https://github.com/LJ3D/AssetLibraryTools/wiki",
"tracker_url": "https://github.com/LJ3D/AssetLibraryTools",
"category": "3D View"
}
import bpy
from bpy.props import (StringProperty,
BoolProperty,
IntProperty,
FloatProperty,
FloatVectorProperty,
EnumProperty,
PointerProperty,
)
from bpy.types import (Panel,
Menu,
Operator,
PropertyGroup,
)
import pathlib
import re
import os
import time
import random
# ------------------------------------------------------------------------
# Stuff
# ------------------------------------------------------------------------
diffNames = ["diffuse", "diff", "albedo", "base", "col", "color"]
sssNames = ["sss", "subsurface"]
metNames = ["metallic", "metalness", "metal", "mtl", "met"]
specNames = ["specularity", "specular", "spec", "spc"]
roughNames = ["roughness", "rough", "rgh", "gloss", "glossy", "glossiness"]
normNames = ["normal", "nor", "nrm", "nrml", "norm"]
dispNames = ["displacement", "displace", "disp", "dsp", "height", "heightmap", "bump", "bmp"]
alphaNames = ["alpha", "opacity"]
emissiveNames = ["emissive", "emission"]
nameLists = [diffNames, sssNames, metNames, specNames, roughNames, normNames, dispNames, alphaNames, emissiveNames]
texTypes = ["diff", "sss", "met", "spec", "rough", "norm", "disp", "alpha", "emission"]
# Find the type of PBR texture a file is based on its name
def FindPBRTextureType(fname):
PBRTT = None
# Remove digits
fname = ''.join(i for i in fname if not i.isdigit())
# Separate CamelCase by space
fname = re.sub("([a-z])([A-Z])","\g<1> \g<2>",fname)
# Replace common separators with SPACE
seperators = ['_', '.', '-', '__', '--', '#']
for sep in seperators:
fname = fname.replace(sep, ' ')
# Set entire string to lower case
fname = fname.lower()
# Find PBRTT
i = 0
for nameList in nameLists:
for name in nameList:
if name in fname:
PBRTT = texTypes[i]
i+=1
return PBRTT
# Display a message in the blender UI
def DisplayMessageBox(message = "", title = "Info", icon = 'INFO'):
def draw(self, context):
self.layout.label(text=message)
bpy.context.window_manager.popup_menu(draw, title = title, icon = icon)
# Class with functions for setting up shaders
class shaderSetup():
def createNode(mat, type, name="newNode", location=(0,0)):
nodes = mat.node_tree.nodes
n = nodes.new(type=type)
n.name = name
n.location = location
return n
def setMapping(node):
tool = bpy.context.scene.assetlibrarytools
if tool.texture_mapping == 'Object':
node.projection = 'BOX'
node.projection_blend = 1
def simplePrincipledSetup(name, files):
tool = bpy.context.scene.assetlibrarytools
# Create a new empty material
mat = bpy.data.materials.new(name)
mat.use_nodes = True
nodes = mat.node_tree.nodes
links = mat.node_tree.links
nodes.clear() # Delete all nodes
# Load textures
diffuseTexture = None
sssTexture = None
metallicTexture = None
specularTexture = None
roughnessTexture = None
emissionTexture = None
alphaTexture = None
normalTexture = None
displacementTexture = None
for i in files:
t = FindPBRTextureType(i.name)
if t == "diff":
diffuseTexture = bpy.data.images.load(str(i))
elif t == "sss":
sssTexture = bpy.data.images.load(str(i))
sssTexture.colorspace_settings.name = 'Non-Color'
elif t == "met":
metallicTexture = bpy.data.images.load(str(i))
metallicTexture.colorspace_settings.name = 'Non-Color'
elif t == "spec":
specularTexture = bpy.data.images.load(str(i))
specularTexture.colorspace_settings.name = 'Non-Color'
elif t == "rough":
roughnessTexture = bpy.data.images.load(str(i))
roughnessTexture.colorspace_settings.name = 'Non-Color'
elif t == "emission":
emissionTexture = bpy.data.images.load(str(i))
elif t == "alpha":
alphaTexture = bpy.data.images.load(str(i))
alphaTexture.colorspace_settings.name = 'Non-Color'
elif t == "norm":
normalTexture = bpy.data.images.load(str(i))
normalTexture.colorspace_settings.name = 'Non-Color'
elif t == "disp":
displacementTexture = bpy.data.images.load(str(i))
displacementTexture.colorspace_settings.name = 'Non-Color'
# Create base nodes
node_output = shaderSetup.createNode(mat, "ShaderNodeOutputMaterial", "node_output", (250,0))
node_principled = shaderSetup.createNode(mat, "ShaderNodeBsdfPrincipled", "node_principled", (-300,0))
links.new(node_principled.outputs['BSDF'], node_output.inputs['Surface'])
node_mapping = shaderSetup.createNode(mat, "ShaderNodeMapping", "node_mapping", (-1300,0))
node_texCoord = shaderSetup.createNode(mat, "ShaderNodeTexCoord", "node_texCoord", (-1500,0))
links.new(node_texCoord.outputs[tool.texture_mapping], node_mapping.inputs['Vector'])
if tool.add_extranodes:
node_scaleValue = shaderSetup.createNode(mat, "ShaderNodeValue", "node_scaleValue", (-1500, -300))
node_scaleValue.outputs['Value'].default_value = 1
links.new(node_scaleValue.outputs['Value'], node_mapping.inputs['Scale'])
# Create, fill, and link texture nodes
imported_tex_nodes = 0
if diffuseTexture != None and tool.import_diff != False:
node_imTexDiffuse = shaderSetup.createNode(mat, "ShaderNodeTexImage", "node_imTexDiffuse", (-800,300-(300*imported_tex_nodes)))
node_imTexDiffuse.image = diffuseTexture
links.new(node_imTexDiffuse.outputs['Color'], node_principled.inputs['Base Color'])
links.new(node_mapping.outputs['Vector'], node_imTexDiffuse.inputs['Vector'])
shaderSetup.setMapping(node_imTexDiffuse)
imported_tex_nodes += 1
if sssTexture != None and tool.import_sss != False:
node_imTexSSS = shaderSetup.createNode(mat, "ShaderNodeTexImage", "node_imTexSSS", (-800,300-(300*imported_tex_nodes)))
node_imTexSSS.image = sssTexture
links.new(node_imTexSSS.outputs['Color'], node_principled.inputs['Subsurface'])
links.new(node_mapping.outputs['Vector'], node_imTexSSS.inputs['Vector'])
shaderSetup.setMapping(node_imTexSSS)
imported_tex_nodes += 1
if metallicTexture != None and tool.import_met != False:
node_imTexMetallic = shaderSetup.createNode(mat, "ShaderNodeTexImage", "node_imTexMetallic", (-800,300-(300*imported_tex_nodes)))
node_imTexMetallic.image = metallicTexture
links.new(node_imTexMetallic.outputs['Color'], node_principled.inputs['Metallic'])
links.new(node_mapping.outputs['Vector'], node_imTexMetallic.inputs['Vector'])
shaderSetup.setMapping(node_imTexMetallic)
imported_tex_nodes += 1
if specularTexture != None and tool.import_spec != False:
node_imTexSpecular = shaderSetup.createNode(mat, "ShaderNodeTexImage", "node_imTexSpecular", (-800,300-(300*imported_tex_nodes)))
node_imTexSpecular.image = specularTexture
links.new(node_imTexSpecular.outputs['Color'], node_principled.inputs['Specular'])
links.new(node_mapping.outputs['Vector'], node_imTexSpecular.inputs['Vector'])
shaderSetup.setMapping(node_imTexSpecular)
imported_tex_nodes += 1
if roughnessTexture != None and tool.import_rough != False:
node_imTexRoughness = shaderSetup.createNode(mat, "ShaderNodeTexImage", "node_imTexRoughness", (-800,300-(300*imported_tex_nodes)))
node_imTexRoughness.image = roughnessTexture
if tool.add_extranodes:
node_imTexRoughnessColourRamp = shaderSetup.createNode(mat, "ShaderNodeValToRGB", "node_imTexRoughnessColourRamp", (-550,300-(300*imported_tex_nodes)))
links.new(node_imTexRoughness.outputs['Color'], node_imTexRoughnessColourRamp.inputs['Fac'])
links.new(node_imTexRoughnessColourRamp.outputs['Color'], node_principled.inputs['Roughness'])
else:
links.new(node_imTexRoughness.outputs['Color'], node_principled.inputs['Roughness'])
links.new(node_mapping.outputs['Vector'], node_imTexRoughness.inputs['Vector'])
shaderSetup.setMapping(node_imTexRoughness)
imported_tex_nodes += 1
if emissionTexture != None and tool.import_emission != False:
node_imTexEmission = shaderSetup.createNode(mat, "ShaderNodeTexImage", "node_imTexEmission", (-800,300-(300*imported_tex_nodes)))
node_imTexEmission.image = emissionTexture
links.new(node_imTexEmission.outputs['Color'], node_principled.inputs['Emission'])
links.new(node_mapping.outputs['Vector'], node_imTexEmission.inputs['Vector'])
shaderSetup.setMapping(node_imTexEmission)
imported_tex_nodes += 1
if alphaTexture != None and tool.import_alpha != False:
node_imTexAlpha = shaderSetup.createNode(mat, "ShaderNodeTexImage", "node_imTexAlpha", (-800,300-(300*imported_tex_nodes)))
node_imTexAlpha.image = alphaTexture
links.new(node_imTexAlpha.outputs['Color'], node_principled.inputs['Alpha'])
links.new(node_mapping.outputs['Vector'], node_imTexAlpha.inputs['Vector'])
shaderSetup.setMapping(node_imTexAlpha)
imported_tex_nodes += 1
if normalTexture != None and tool.import_norm != False:
node_imTexNormal = shaderSetup.createNode(mat, "ShaderNodeTexImage", "node_imTexNormal", (-800,300-(300*imported_tex_nodes)))
node_imTexNormal.image = normalTexture
node_normalMap = shaderSetup.createNode(mat, "ShaderNodeNormalMap", "node_normalMap", (-500,300-(300*imported_tex_nodes)))
links.new(node_imTexNormal.outputs['Color'], node_normalMap.inputs['Color'])
links.new(node_normalMap.outputs['Normal'], node_principled.inputs['Normal'])
links.new(node_mapping.outputs['Vector'], node_imTexNormal.inputs['Vector'])
shaderSetup.setMapping(node_imTexNormal)
imported_tex_nodes += 1
if displacementTexture != None and tool.import_disp != False:
node_imTexDisplacement = shaderSetup.createNode(mat, "ShaderNodeTexImage", "node_imTexDisplacement", (-800,300-(300*imported_tex_nodes)))
node_imTexDisplacement.image = displacementTexture
node_imTexDisplacement.interpolation = 'Smart'
node_displacement = shaderSetup.createNode(mat, "ShaderNodeDisplacement", "node_displacement", (-200,-600))
links.new(node_imTexDisplacement.outputs['Color'], node_displacement.inputs['Height'])
links.new(node_displacement.outputs['Displacement'], node_output.inputs['Displacement'])
links.new(node_mapping.outputs['Vector'], node_imTexDisplacement.inputs['Vector'])
shaderSetup.setMapping(node_imTexDisplacement)
imported_tex_nodes += 1
return mat
# This code is bad!!!!
# But i dont want to fix it!!!!
def listDownloadAttribs(scene, context):
scene = context.scene
tool = scene.assetlibrarytools
if tool.showAllDownloadAttribs == True:
attribs = ['None', '1K-JPG', '1K-PNG', '2K-JPG', '2K-PNG', '4K-JPG', '4K-PNG', '8K-JPG', '8K-PNG', '12K-HDR', '16K-HDR', '1K-HDR', '2K-HDR', '4K-HDR', '8K-HDR', '12K-TONEMAPPED', '16K-TONEMAPPED', '1K-TONEMAPPED', '2K-TONEMAPPED', '4K-TONEMAPPED', '8K-TONEMAPPED', '12K-JPG', '12K-PNG', '16K-JPG', '16K-PNG', '1K-HQ-JPG', '1K-HQ-PNG', '1K-LQ-JPG', '1K-LQ-PNG', '1K-SQ-JPG', '1K-SQ-PNG', '2K-HQ-JPG', '2K-HQ-PNG', '2K-LQ-JPG', '2K-LQ-PNG', '2K-SQ-JPG', '2K-SQ-PNG', '4K-HQ-JPG', '4K-HQ-PNG', '4K-LQ-JPG', '4K-LQ-PNG', '4K-SQ-JPG', '4K-SQ-PNG', 'HQ', 'LQ', 'SQ', '24K-JPG', '24K-PNG', '32K-JPG', '32K-PNG', '6K-JPG', '6K-PNG', '2K', '4K', '8K', '1K', 'CustomImages', '16K', '9K', '1000K', '250K', '25K', '5K-JPG', '5K-PNG', '2kPNG', '4kPNG', '2kPNG-PNG', '4kPNG-PNG', '9K-JPG', '10K-JPG', '7K-JPG', '7K-PNG', '3K-JPG', '3K-PNG', '9K-PNG', '33K-JPG', '33K-PNG', '15K-JPG', '15K-PNG']
else:
attribs = ['None', '1K-JPG', '1K-PNG', '2K-JPG', '2K-PNG', '4K-JPG', '4K-PNG', '8K-JPG', '8K-PNG']
items = []
for a in attribs:
items.append((a, a, ""))
return items
# ------------------------------------------------------------------------
# Properties
# ------------------------------------------------------------------------
class properties(PropertyGroup):
# Material import properties
mat_import_path : StringProperty(
name = "Import directory",
description = "Choose a directory to batch import PBR texture sets from.\nFormat your files like this: ChosenDirectory/PBRTextureName/textureFiles",
default = "",
maxlen = 1024,
subtype = 'DIR_PATH'
)
skip_existing : BoolProperty(
name = "Skip existing",
description = "Dont import materials if a material with the same name already exists",
default = True
)
tex_ignore_filter : StringProperty(
name = "Tex name filter",
description = "Filter unwanted textures by a common string in the name (such as DX, which denotes a directX normal map)",
default = "",
maxlen = 1024,
)
use_fake_user : BoolProperty(
name = "Use fake user",
description = "Use fake user on imported materials",
default = True
)
use_real_displacement : BoolProperty(
name = "Use real displacement",
description = "Enable real geometry displacement in the material settings (cycles only)",
default = False
)
add_extranodes : BoolProperty(
name = "Add utility nodes",
description = "Adds nodes to the imported materials for easy control",
default = False
)
texture_mapping : EnumProperty(
name='Mapping',
default='UV',
items=[('UV', 'UV', 'Use UVs to control mapping'),
('Object', 'Object', 'Wrap texture along world coords')])
import_diff : BoolProperty(
name = "Import diffuse",
description = "",
default = True
)
import_sss : BoolProperty(
name = "Import SSS",
description = "",
default = True
)
import_met : BoolProperty(
name = "Import metallic",
description = "",
default = True
)
import_spec : BoolProperty(
name = "Import specularity",
description = "",
default = True
)
import_rough : BoolProperty(
name = "Import roughness",
description = "",
default = True
)
import_emission : BoolProperty(
name = "Import emission",
description = "",
default = True
)
import_alpha : BoolProperty(
name = "Import alpha",
description = "",
default = True
)
import_norm : BoolProperty(
name = "Import normal",
description = "",
default = True
)
import_disp : BoolProperty(
name = "Import displacement",
description = "",
default = True
)
# Model import properties
model_import_path : StringProperty(
name = "Import directory",
description = "Choose a directory to batch import models from.\nSubdirectories are checked recursively",
default = "",
maxlen = 1024,
subtype = 'DIR_PATH'
)
hide_after_import : BoolProperty(
name = "Hide models after import",
description = "Reduces viewport polycount, prevents low framerate/crashes.\nHides each model individually straight after import",
default = False
)
move_to_new_collection_after_import : BoolProperty(
name = "Move models to new collection after import",
description = "",
default = False
)
join_new_objects : BoolProperty(
name = "Join all models in each file together after import",
description = "",
default = False
)
import_fbx : BoolProperty(
name = "Import FBX files",
description = "",
default = True
)
import_gltf : BoolProperty(
name = "Import GLTF files",
description = "",
default = True
)
import_obj : BoolProperty(
name = "Import OBJ files",
description = "",
default = True
)
import_x3d : BoolProperty(
name = "Import X3D files",
description = "",
default = True
)
# Batch append properties
append_path : StringProperty(
name = "Import directory",
description = "Choose a directory to batch append from.",
default = "",
maxlen = 1024,
subtype = 'DIR_PATH'
)
append_recursive_search : BoolProperty(
name = "Search for .blend files in subdirs recursively",
description = "",
default = False
)
append_move_to_new_collection_after_import : BoolProperty(
name = "Move objects to new collection after import",
description = "",
default = False
)
append_join_new_objects : BoolProperty(
name = "Join all objects in each file together after import",
description = "",
default = False
)
appendType : EnumProperty(
name="Append",
description="Choose type to append",
items=[ ('objects', "Objects", ""),
('materials', "Materials", ""),
]
)
deleteLights : BoolProperty(
name = "Dont append lights",
description = "",
default = True
)
deleteCameras : BoolProperty(
name = "Dont append cameras",
description = "",
default = True
)
# Asset management properties
markunmark : EnumProperty(
name="Operation",
description="Choose whether to mark assets, or unmark assets",
items=[ ('mark', "Mark assets", ""),
('unmark', "Unmark assets", ""),
]
)
assettype : EnumProperty(
name="On type",
description="Choose a type of asset to mark/unmark",
items=[ ('objects', "Objects", ""),
('materials', "Materials", ""),
('images', "Images", ""),
('textures', "Textures", ""),
('meshes', "Meshes", ""),
]
)
previewgentype : EnumProperty(
name="Asset type",
description="Choose a type of asset to mark/unmark",
items=[ ('objects', "Objects", ""),
('materials', "Materials", ""),
('images', "Images", ""),
('textures', "Textures", ""),
('meshes', "Meshes", ""),
]
)
# Utilities panel properties
deleteType : EnumProperty(
name="Delete all",
description="Choose type to batch delete",
items=[ ('objects', "Objects", ""),
('materials', "Materials", ""),
('images', "Images", ""),
('textures', "Textures", ""),
('meshes', "Meshes", ""),
]
)
dispNewScale: FloatProperty(
name = "New Displacement Scale",
description = "A float property",
default = 0.1,
min = 0.0001
)
# Asset snapshot panel properties
resolution : IntProperty(
name="Preview Resolution",
description="Resolution to render the preview",
min=1,
soft_max=500,
default=256
)
# CC0AssetDownloader properties
downloader_save_path : StringProperty(
name = "Save location",
description = "Choose a directory to save assets to",
default = "",
maxlen = 1024,
subtype = 'DIR_PATH'
)
keywordFilter : StringProperty(
name = "Keyword filter",
description = "Enter a keyword to filter assets by, leave empty if you do not wish to filter.",
default = "",
maxlen = 1024,
)
showAllDownloadAttribs: BoolProperty(
name = "Show all download attributes",
description = "",
default = True
)
attributeFilter : EnumProperty(
name="Attribute filter",
description="Choose attribute to filter assets by",
items=listDownloadAttribs
)
extensionFilter : EnumProperty(
name="Extension filter",
description="Choose file extension to filter assets by",
items=[ ('None', "None", ""),
('zip', "ZIP", ""),
('obj', "OBJ", ""),
('exr', "EXR", ""),
('sbsar', "SBSAR", ""),
]
)
unZip : BoolProperty(
name = "Unzip downloaded zip files",
description = "",
default = True
)
deleteZips : BoolProperty(
name = "Delete zip files after they have been unzipped",
description = "",
default = True
)
skipDuplicates : BoolProperty(
name = "Dont download files which already exist",
description = "",
default = True
)
terminal : EnumProperty(
name="Terminal",
description="Choose terminal to run script with",
items=[ ('cmd', "cmd", ""),
('gnome-terminal', "gnome-terminal", ""),
('konsole', 'konsole', ""),
('xterm', 'xterm', ""),
]
)
# SBSAR import properties
sbsar_import_path : StringProperty(
name = "Import directory",
description = "Choose a directory to batch import sbsar files from.\nSubdirectories are checked recursively",
default = "",
maxlen = 1024,
subtype = 'DIR_PATH'
)
# UI properties
matImport_expanded : BoolProperty(
name = "Click to expand",
description = "",
default = False
)
matImportOptions_expanded : BoolProperty(
name = "Click to expand",
description = "",
default = False
)
append_expanded : BoolProperty(
name = "Click to expand",
description = "",
default = False
)
modelImport_expanded : BoolProperty(
name = "Click to expand",
description = "",
default = False
)
modelImportOptions_expanded : BoolProperty(
name = "Click to expand",
description = "",
default = False
)
assetBrowserOpsRow_expanded : BoolProperty(
name = "Click to expand",
description = "",
default = False
)
utilRow_expanded : BoolProperty(
name = "Click to expand",
description = "",
default = False
)
snapshotRow_expanded : BoolProperty(
name = "Click to expand",
description = "",
default = False
)
assetDownloaderRow_expanded : BoolProperty(
name = "Click to expand",
description = "",
default = False
)
sbsarImport_expanded : BoolProperty(
name = "Click to expand",
description = "",
default = False
)
# ------------------------------------------------------------------------
# Operators
# ------------------------------------------------------------------------
class OT_BatchImportPBR(Operator):
bl_label = "Import PBR textures"
bl_idname = "alt.batchimportpbr"
def execute(self, context):
scene = context.scene
tool = scene.assetlibrarytools
n_imp = 0 # Number of materials imported
n_del = 0 # Number of materials deleted (due to no textures after import)
n_skp = 0 # Number of materials skipped due to them already existing
existing_mat_names = []
subdirectories = [x for x in pathlib.Path(tool.mat_import_path).iterdir() if x.is_dir()] # Get subdirs in directory selected in UI
for sd in subdirectories:
filePaths = [x for x in pathlib.Path(sd).iterdir() if x.is_file()] # Get filepaths of textures
if tool.tex_ignore_filter != "": # Remove filepaths of textures which contain a filtered string, if a filter is chosen.
for fp in filePaths:
if tool.tex_ignore_filter in fp.name:
filePaths.pop(filePaths.index(fp))
# Get existing material names if skipping existing materials is turned on
if tool.skip_existing == True:
existing_mat_names = []
for mat in bpy.data.materials:
existing_mat_names.append(mat.name)
# check if the material thats about to be imported exists or not, or if we dont care about skipping existing materials.
if (sd.name not in existing_mat_names) or (tool.skip_existing != True):
mat = shaderSetup.simplePrincipledSetup(sd.name, filePaths) # Create shader using filepaths of textures
if tool.use_fake_user == True: # Enable fake user (if desired)
mat.use_fake_user = True
if tool.use_real_displacement == True: # Enable real displacement (if desired)
mat.cycles.displacement_method = 'BOTH'
# Delete the material if it contains no textures
hasTex = False
for n in mat.node_tree.nodes:
if n.type == 'TEX_IMAGE': # Check if shader contains textures, if yes, then its worth keeping
hasTex = True
if hasTex == False:
bpy.data.materials.remove(mat) # Delete material if it contains no textures
n_del += 1
else:
n_imp += 1
else:
n_skp += 1
if (n_del > 0) and (n_skp > 0):
DisplayMessageBox("Complete, {0} materials imported, {1} were deleted after import because they contained no textures (No recognised textures were found in the folder), {2} skipped because they already exist".format(n_imp,n_del,n_skp))
elif n_skp > 0:
DisplayMessageBox("Complete, {0} materials imported. {1} skipped because they already exist".format(n_imp, n_skp))
elif n_del > 0:
DisplayMessageBox("Complete, {0} materials imported, {1} were deleted after import because they contained no textures (No recognised textures were found in the folder)".format(n_imp,n_del))
else:
DisplayMessageBox("Complete, {0} materials imported".format(n_imp))
return{'FINISHED'}
class OT_ImportModels(Operator):
bl_label = "Import models"
bl_idname = "alt.importmodels"
# Hide new objects works by comparing a list of objects before (x) happened with the current list via bpy.context.scene.objects to get the list of new objects, then hides those new objects
def hideNewObjects(old_objects):
scene = bpy.context.scene
tool = scene.assetlibrarytools
if tool.hide_after_import == True:
imported_objects = set(bpy.context.scene.objects) - old_objects
for object in imported_objects:
object.hide_set(True)
def moveNewObjectsToNewCollection(old_objects, collName):
scene = bpy.context.scene
tool = scene.assetlibrarytools
if tool.move_to_new_collection_after_import == True:
imported_objects = set(bpy.context.scene.objects) - old_objects
newCollection = bpy.data.collections.new(collName)
bpy.context.scene.collection.children.link(newCollection)
for obj in imported_objects:
for uc in obj.users_collection:
uc.objects.unlink(obj)
newCollection.objects.link(obj)
def joinAllNewObjects(old_objects):
scene = bpy.context.scene
tool = scene.assetlibrarytools
if tool.join_new_objects == True:
imported_objects = set(bpy.context.scene.objects) - old_objects
bpy.ops.object.select_all(action='DESELECT')
for obj in imported_objects:
bpy.context.view_layer.objects.active = obj
obj.select_set(True)
bpy.ops.object.join()
def execute(self, context):
scene = context.scene
tool = scene.assetlibrarytools
p = pathlib.Path(str(tool.model_import_path))
imported = 0 # Number of imported objects
errors = 0 # Number of import errors
# Import FBX files
if tool.import_fbx == True:
fbxFilePaths = [x for x in p.glob('**/*.fbx') if x.is_file()] # Get filepaths of files with the extension .fbx in the selected directory (and subdirs, recursively)
for filePath in fbxFilePaths:
old_objects = set(context.scene.objects)
try:
bpy.ops.import_scene.fbx(filepath=str(filePath))
imported += 1
except:
print("FBX import error")
errors += 1
OT_ImportModels.hideNewObjects(old_objects)
OT_ImportModels.moveNewObjectsToNewCollection(old_objects, filePath.name)
OT_ImportModels.joinAllNewObjects(old_objects)
# Import GLTF files
if tool.import_gltf == True:
gltfFilePaths = [x for x in p.glob('**/*.gltf') if x.is_file()] # Get filepaths of files with the extension .gltf in the selected directory (and subdirs, recursively)
for filePath in gltfFilePaths:
old_objects = set(context.scene.objects)
try:
bpy.ops.import_scene.gltf(filepath=str(filePath))
imported += 1
except:
print("GLTF import error")
errors += 1
OT_ImportModels.hideNewObjects(old_objects)
OT_ImportModels.moveNewObjectsToNewCollection(old_objects, filePath.name)
OT_ImportModels.joinAllNewObjects(old_objects)
# Import OBJ files
if tool.import_obj == True:
objFilePaths = [x for x in p.glob('**/*.obj') if x.is_file()] # Get filepaths of files with the extension .obj in the selected directory (and subdirs, recursively)
for filePath in objFilePaths:
old_objects = set(context.scene.objects)
try:
bpy.ops.import_scene.obj(filepath=str(filePath))
imported += 1
except:
print("OBJ import error")
errors += 1
OT_ImportModels.hideNewObjects(old_objects)
OT_ImportModels.moveNewObjectsToNewCollection(old_objects, filePath.name)
OT_ImportModels.joinAllNewObjects(old_objects)
# Import X3D files
if tool.import_x3d == True:
x3dFilePaths = [x for x in p.glob('**/*.x3d') if x.is_file()] # Get filepaths of files with the extension .x3d in the selected directory (and subdirs, recursively)
for filePath in x3dFilePaths:
old_objects = set(context.scene.objects)
try:
bpy.ops.import_scene.x3d(filepath=str(filePath))
imported += 1
except:
print("X3D import error")
errors += 1
OT_ImportModels.hideNewObjects(old_objects)
OT_ImportModels.moveNewObjectsToNewCollection(old_objects, filePath.name)
OT_ImportModels.joinAllNewObjects(old_objects)
if errors == 0:
DisplayMessageBox("Complete, {0} models imported".format(imported))
else:
DisplayMessageBox("Complete, {0} models imported. {1} import errors".format(imported, errors))
return{'FINISHED'}
class OT_BatchAppend(Operator):
bl_label = "Append"
bl_idname = "alt.batchappend"
def execute(self, context):
scene = context.scene
tool = scene.assetlibrarytools
p = pathlib.Path(str(tool.append_path))
link = False # append, set to true to keep the link to the original file
if tool.append_recursive_search == True:
blendFilePaths = [x for x in p.glob('**/*.blend') if x.is_file()] # Get filepaths of files with the extension .blend in the selected directory (and subdirs, recursively)
else:
blendFilePaths = [x for x in p.glob('*.blend') if x.is_file()] # Get filepaths of files with the extension .blend in the selected directory
for path in blendFilePaths:
if tool.appendType == 'objects':
# link all objects
with bpy.data.libraries.load(str(path), link=link) as (data_from, data_to):
data_to.objects = data_from.objects
# Create new collection
if tool.append_move_to_new_collection_after_import:
newCollection = bpy.data.collections.new(str(path.name))
bpy.context.scene.collection.children.link(newCollection)
#link object to collection
for obj in data_to.objects:
removed = False
if obj != None:
if tool.append_move_to_new_collection_after_import:
newCollection.objects.link(obj)
else:
bpy.context.collection.objects.link(obj)
# remove cameras
if removed == False and tool.deleteCameras == True: # This stops an error from occuring if obj is already deleted
if obj.type == 'CAMERA':
bpy.data.objects.remove(obj)
removed = True
# remove lights
if removed == False and tool.deleteLights == True: # This stops an error from occuring if obj is already deleted
if obj.type == 'LIGHT':
bpy.data.objects.remove(obj)
removed = True
# Join objects if option turned on
if tool.append_join_new_objects:
bpy.ops.object.select_all(action='DESELECT')
for obj in data_to.objects:
bpy.context.view_layer.objects.active = obj
obj.select_set(True)
bpy.ops.object.join()
if tool.appendType == 'materials':
with bpy.data.libraries.load(str(path), link=link) as (data_from, data_to):
data_to.materials = data_from.materials
if tool.appendType == 'objects':
DisplayMessageBox("Complete, objects appended")
if tool.appendType == 'materials':
DisplayMessageBox("Complete, materials appended")
return{'FINISHED'}
class OT_ManageAssets(Operator):
bl_label = "Go"
bl_idname = "alt.manageassets"
def execute(self, context):
scene = context.scene
tool = scene.assetlibrarytools
i = 0 # Number of assets modified
# Mark assets
if tool.markunmark == 'mark':
if tool.assettype == 'objects':
for object in bpy.data.objects:
object.asset_mark()
i += 1
if tool.assettype == 'materials':
for mat in bpy.data.materials:
mat.asset_mark()
i += 1
if tool.assettype == 'images':
for image in bpy.data.images:
image.asset_mark()
i += 1
if tool.assettype == 'textures':
for texture in bpy.data.textures:
texture.asset_mark()
i += 1
if tool.assettype == 'meshes':
for mesh in bpy.data.meshes:
mesh.asset_mark()
i += 1
DisplayMessageBox("Complete, {0} assets marked".format(i))
# Unmark assets
if tool.markunmark == 'unmark':
if tool.assettype == 'objects':
for object in bpy.data.objects:
object.asset_clear()
i += 1
if tool.assettype == 'materials':
for mat in bpy.data.materials:
mat.asset_clear()
i += 1
if tool.assettype == 'images':
for image in bpy.data.images:
image.asset_clear()
i += 1
if tool.assettype == 'textures':
for texture in bpy.data.textures:
texture.asset_clear()
i += 1
if tool.assettype == 'meshes':
for mesh in bpy.data.meshes:
mesh.asset_clear()
i += 1
DisplayMessageBox("Complete, {0} assets unmarked".format(i))
return {'FINISHED'}
class OT_GenerateAssetPreviews(Operator):
bl_label = "Generate previews"
bl_idname = "alt.generateassetpreviews"
def execute(self, context):
scene = context.scene
tool = scene.assetlibrarytools
if tool.previewgentype == 'objects':
for obj in bpy.data.objects:
if obj.asset_data:
obj.asset_generate_preview()
if tool.previewgentype == 'materials':
for mat in bpy.data.materials:
if mat.asset_data:
mat.asset_generate_preview()
if tool.previewgentype == 'images':
for img in bpy.data.images:
if img.asset_data:
img.asset_generate_preview()
if tool.previewgentype == 'textures':
for tex in bpy.data.textures:
if tex.asset_data:
tex.asset_generate_preview()
if tool.previewgentype == 'meshes':
for mesh in bpy.data.meshes:
if mesh.asset_data:
mesh.asset_generate_preview()
return {'FINISHED'}
class OT_BatchDelete(Operator):
bl_label = "Go"
bl_idname = "alt.batchdelete"
def execute(self, context):
scene = context.scene
tool = scene.assetlibrarytools
i = 0 # Number of items deleted
if tool.deleteType == 'objects':
for object in bpy.data.objects:
bpy.data.objects.remove(object)
i += 1
if tool.deleteType == 'materials':
for mat in bpy.data.materials:
bpy.data.materials.remove(mat)
i += 1
if tool.deleteType == 'images':
while len(bpy.data.images) > 0: # Cant use a for loop like the other "delete all" operations for some reason
bpy.data.images.remove(bpy.data.images[0])
i += 1
if tool.deleteType == 'textures':
for tex in bpy.data.textures:
bpy.data.textures.remove(tex)
i += 1
if tool.deleteType == 'meshes':
for mesh in bpy.data.meshes:
bpy.data.meshes.remove(mesh)
i += 1
DisplayMessageBox("Done, {0} {1} deleted".format(i, tool.deleteType))
return {'FINISHED'}
class OT_SimpleDelDupeMaterials(Operator):
bl_label = "Clean up duplicate materials (simple)"
bl_idname = "alt.simpledeldupemats"
def execute(self, context):
for obj in bpy.data.objects:
for slt in obj.material_slots:
part = slt.name.rpartition('.')
if part[2].isnumeric() and part[0] in bpy.data.materials:
slt.material = bpy.data.materials.get(part[0])
DisplayMessageBox("Done")
return {'FINISHED'}
class OT_CleanupUnusedMaterials(Operator):
bl_label = "Clean up unused materials"
bl_idname = "alt.cleanupunusedmats"
def execute(self, context):
i = 0
for mat in bpy.data.materials:
if mat.users == 0:
bpy.data.materials.remove(mat)
i += 1
DisplayMessageBox("Done, {0} unused materials deleted".format(i))
return {'FINISHED'}
class OT_UseDisplacementOnAll(Operator):
bl_label = "Use real displacement on all materials"
bl_idname = "alt.userealdispall"
def execute(self, context):
for mat in bpy.data.materials:
mat.cycles.displacement_method = 'BOTH'
DisplayMessageBox("Done")
return {'FINISHED'}
class OT_ChangeAllDisplacementScale(Operator):
bl_label = "Change displacement scale on all materials"
bl_idname = "alt.changealldispscale"
def execute(self, context):
tool = context.scene.assetlibrarytools
i = 0 # number of nodes changed
for mat in bpy.data.materials:
if mat is not None and mat.use_nodes and mat.node_tree is not None:
for node in mat.node_tree.nodes:
if node.type == 'DISPLACEMENT':
node.inputs[2].default_value = tool.dispNewScale
i += 1