-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy path__init__.py
More file actions
1611 lines (1368 loc) · 57.8 KB
/
Copy path__init__.py
File metadata and controls
1611 lines (1368 loc) · 57.8 KB
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
# ##### BEGIN GPL LICENSE BLOCK #####
#
# Copyright (C) 2018 Amir Shehata
# http://www.openmovie.com
# amir.shehata@gmail.com
# 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 3 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, see <http://www.gnu.org/licenses/>.
#
# ##### END GPL LICENSE BLOCK #####
import bpy
import pathlib
import glob
import shutil
import subprocess
import sys
from gpu_extras.batch import batch_for_shader
import os
import fnmatch
import json
import random
from math import sin, cos, atan2, pi
from mathutils import Vector, Matrix
from bpy_extras import view3d_utils, object_utils
from bpy.types import Panel, Operator, Menu, Macro, WindowManager
from bpy.utils import previews
from bpy.props import EnumProperty, StringProperty, BoolVectorProperty
bl_info = {
"name": "YAAM",
"version": (0, 1),
"blender": (2, 80, 0),
"location": "View3D > TOOLS > YAAM",
"author": "Amir Shehata <amir.shehata@gmail.com>",
"description": "Yet Another Asset Manager",
"category": "Add Assets"
}
# Preview collections
preview_collections = {}
OBJ_dir_name = 'Obj'
FBX_dir_name = 'Fbx'
TEXTURES_dir_name = 'Textures'
BLEND_dir_name = 'Blend'
M3DS_dir_name = '3ds'
TRASH_dir_name = 'Trash'
class YAAMAstMgrSettings(object):
def __init__(self):
self.version = (0, 1)
self.astMgr_settings_fname = 'yaam.json'
self.astMgr_addon_dir = os.path.dirname(__file__)
self.settings_abs_file = os.path.join(self.astMgr_addon_dir,
self.astMgr_settings_fname)
# Add-on settings
self.astMgr_settings = {
'favs': [],
'version': (0, 1),
'cur_assets_dir': "",
'previous_assets_directory': "",
'cur_selected_asset_category': "",
'cur_selected_asset_abs_path': "",
'cur_assets_filter' : "",
'cur_blend_import_op': "",
'cur_selected_asset_mode' : "astmgrmode.browse_assets",
'save_asset_dir': "",
'save_asset_name': "",
'org_src_dir': "",
'org_dst_dir': "",
'blender_bin_path': "",
}
self.supported_img_formats_match = ['*.jpg', '*.jpeg', '*.png', '*.svg', '*.bmp', '*.hdr']
self.supported_img_formats = ['jpg', 'jpeg', 'png', 'svg', 'bmp', 'hdr']
if os.path.exists(self.settings_abs_file):
with open(self.settings_abs_file, 'r') as f:
settings = json.load(f)
if 'version' not in settings or tuple(settings['version']) != self.version:
with open(self.settings_abs_file, 'w') as f:
json.dump(self.astMgr_settings, f, ensure_ascii=False)
else:
self.astMgr_settings = settings
else:
with open(self.settings_abs_file, 'w') as f:
json.dump(self.astMgr_settings, f, ensure_ascii=False)
if not self.get_cur_assets_dir():
# try and find the default assets dir
default_assets = os.path.join(os.path.dirname(__file__), "Assets")
if os.path.isdir(default_assets):
self.set_cur_assets_dir(default_assets)
def get_supported_img_formats(self):
return self.supported_img_formats
def get_supported_img_formats_match(self):
return self.supported_img_formats_match
def get_addon_dir(self):
return self.astMgr_addon_dir
def get_favs(self):
return self.astMgr_settings['favs']
def set_favs(self, e):
if e not in self.astMgr_settings['favs']:
self.astMgr_settings['favs'].append(e)
self.write_settings()
def rm_favs(self, e):
if e in self.astMgr_settings['favs']:
self.astMgr_settings['favs'].remove(e)
def get_cur_selected_asset_category(self):
return self.astMgr_settings['cur_selected_asset_category']
def set_cur_selected_asset_category(self, val):
self.astMgr_settings['cur_selected_asset_category'] = val
self.write_settings()
def get_cur_selected_asset_mode(self):
return self.astMgr_settings['cur_selected_asset_mode']
def set_cur_selected_asset_mode(self, val):
self.astMgr_settings['cur_selected_asset_mode'] = val
self.write_settings()
def get_cur_selected_asset_abs_path(self):
return self.astMgr_settings['cur_selected_asset_abs_path']
def set_cur_selected_asset_abs_path(self, val):
self.astMgr_settings['cur_selected_asset_abs_path'] = val
self.write_settings()
def get_cur_assets_dir(self):
return self.astMgr_settings['cur_assets_dir']
def set_cur_assets_dir(self, val):
self.astMgr_settings['cur_assets_dir'] = val
self.write_settings()
def get_previous_assets_directory(self):
return self.astMgr_settings['previous_assets_directory']
def set_previous_assets_directory(self, val):
self.astMgr_settings['previous_assets_directory'] = val
self.write_settings()
def get_cur_assets_filter(self):
return self.astMgr_settings['cur_assets_filter']
def set_cur_assets_filter(self, val):
self.astMgr_settings['cur_assets_filter'] = val
self.write_settings()
def get_cur_blend_import_op(self):
return self.astMgr_settings['cur_blend_import_op']
def set_cur_blend_import_op(self, val):
self.astMgr_settings['cur_blend_import_op'] = val
self.write_settings()
def get_save_asset_name(self):
return self.astMgr_settings['save_asset_name']
def set_save_asset_name(self, val):
self.astMgr_settings['save_asset_name'] = val
self.write_settings()
def get_save_asset_dir(self):
return self.astMgr_settings['save_asset_dir']
def set_save_asset_dir(self, val):
self.astMgr_settings['save_asset_dir'] = val
self.write_settings()
def get_org_src_dir(self):
return self.astMgr_settings['org_src_dir']
def set_org_src_dir(self, val):
self.astMgr_settings['org_src_dir'] = val
self.write_settings()
def get_org_dst_dir(self):
return self.astMgr_settings['org_dst_dir']
def set_org_dst_dir(self, val):
self.astMgr_settings['org_dst_dir'] = val
self.write_settings()
def get_blender_bin_path(self):
return self.astMgr_settings['blender_bin_path']
def set_blender_bin_path(self, val):
self.astMgr_settings['blender_bin_path'] = val
self.write_settings()
def write_settings(self):
with open(self.settings_abs_file, 'w') as f:
json.dump(self.astMgr_settings, f, ensure_ascii=False)
def read_settings(self):
return self.astMgr_settings
def translate_category(self, cat):
if cat == 'asset.all':
return ''
if cat == 'asset.fbx_file':
return FBX_dir_name
if cat == 'asset.3ds_file':
return M3DS_dir_name
if cat == 'asset.obj_file':
return OBJ_dir_name
if cat == 'asset.blend':
return BLEND_dir_name
if cat == 'asset.trash':
return TRASH_dir_name
return ''
def get_or_create_asset_subdir(self, cat, create=False):
category = self.translate_category(cat)
if not category:
return ''
cur_dir = yaam.get_cur_assets_dir()
if not cur_dir:
return ''
directory = os.path.join(yaam.get_cur_assets_dir(), category)
if os.path.exists(directory) and not os.path.isdir(directory):
return ''
if not os.path.exists(directory):
if create:
os.makedirs(directory, exist_ok=True)
else:
return ''
return directory
yaam = YAAMAstMgrSettings()
def get_favs_enum(self, context):
favs = yaam.get_favs()
if favs:
return [(f, f, '') for f in favs]
return [('Empty', 'Nothing to list', '')]
def handle_favs_update(self, context):
scn = context.scene
favs = scn.list_favorites
if favs not in ['Empyt', '']:
scn.assets_dir = favs
return None
def update_dir(self, context):
yaam.set_cur_assets_dir(context.scene.assets_dir)
return None
def update_filter(self, context):
yaam.set_cur_assets_filter(context.scene.assets_filter.decode("utf-8"))
# force an update by setting the previous assets directory to ''
# This way when we check it while building, we'll continue to build
# there by the filter taking effect
yaam.set_previous_assets_directory("")
return None
def update_blender_bin_path(self, context):
yaam.set_blender_bin_path(context.scene.yaam_blender_bin_path)
return None
def update_save_asset_name(self, context):
yaam.set_save_asset_name(context.scene.save_asset_name)
return None
def update_save_asset_dir(self, context):
yaam.set_save_asset_dir(context.scene.save_asset_dir)
return None
class YAAM_OT_AddToFav(Operator):
bl_idname = "yaam.add_to_fav"
bl_label = "Add to favorites"
bl_description = "Add the current folder to the favorites"
def execute(self, context):
scn = context.scene
yaam.set_favs(scn.assets_dir)
return {'FINISHED'}
class YAAM_OT_RmFromFav(Operator):
bl_idname = "yaam.remove_from_fav"
bl_label = "Remove from favorites"
bl_description = "Remove the current folder from the favorites"
def execute(self, context):
scn = context.scene
yaam.rm_favs(scn.assets_dir)
return {'FINISHED'}
# When the append button is hit, display a subset of the items we
# can append/link. And then when you select that, we display yet again
# a list of other items available under the particular category.
# For example, say we have multiple collections, the first menu will look
# like:
# collections
# Objects
# Meshes
# Materials
#
# Then we select Collections. A second menu will pop up:
# Collection 1
# Collection 2
# Collection 3
#
# The one selected will be appended to the scene and moved to the
# imported_assets collection.
#
# The Append or Link buttons will be menus.
# They drop down the list of options in the first menu above
# Each entry will have its own property class, which will
# attempt to import the selected item from the blend file
#
class YAAM_MT_blend_append_menu(Menu):
#bl_idname = "yaam.blend_MT_append"
bl_label = "Append"
bl_description = "Append from a blend library"
def draw(self, context):
layout = self.layout
yaam.set_cur_blend_import_op("append")
layout.operator_context = 'INVOKE_REGION_WIN'
layout.operator("astblend.append_collections")
layout.operator("astBlend.append_materials")
layout.operator("astBlend.append_objects")
layout.operator("astBlend.append_textures")
layout.operator("astBlend.append_scenes")
class YAAM_MT_blend_link_menu(Menu):
bl_label = "Link"
bl_description = "Link from a blend library"
def draw(self, context):
yaam.set_cur_blend_import_op("link")
layout = self.layout
layout.operator_context = 'INVOKE_REGION_WIN'
layout.operator("astblend.append_collections")
layout.operator("astBlend.append_materials")
layout.operator("astBlend.append_objects")
layout.operator("astBlend.append_textures")
layout.operator("astBlend.append_scenes")
def setActiveCollection(layer_collection, name):
if not layer_collection.children:
return
for c in layer_collection.children:
if c.name == name:
bpy.context.view_layer.active_layer_collection = c
return
setActiveCollection(c, name)
def createAndSetImportCollection():
if bpy.context.view_layer.layer_collection.children:
main = bpy.context.view_layer.layer_collection.children[0]
bpy.context.view_layer.active_layer_collection = main
collection_name = "imported_assets"
c = bpy.data.collections.get(collection_name)
scene = bpy.context.scene
if c is None:
c = bpy.data.collections.new(collection_name)
scene.collection.children.link(c)
setActiveCollection(bpy.context.view_layer.layer_collection,
collection_name)
def blendAppendLinkElement(abs_path, elem_type, name, link=False):
filepath = abs_path + "\\" + elem_type + "\\" + name
directory = abs_path + "\\" + elem_type + "\\"
action = bpy.ops.wm.link if link else bpy.ops.wm.append
action(filepath=filepath, filename=name, directory=directory)
@classmethod
def poll_general(cls, context):
if not yaam.get_cur_selected_asset_abs_path():
return False
elif os.path.isdir(yaam.get_cur_selected_asset_abs_path()):
return False
return True
def invoke_general(self, context, event):
wm = context.window_manager
wm.invoke_props_dialog(self)
return {'RUNNING_MODAL'}
class YAAM_OT_AppendCollections(Operator):
bl_idname = "astblend.append_collections"
bl_label = "Collections"
bl_description = "Append collections from a blend library"
selection: BoolVectorProperty(size=32, options={'SKIP_SAVE'})
poll = poll_general
invoke = invoke_general
def __init__(self):
self.collections_list = []
def openBlendFileAndRead(self):
self.collections_list = []
asset_path = yaam.get_cur_selected_asset_abs_path()
with bpy.data.libraries.load(asset_path) as (data_from, data_to):
for name in data_from.collections:
self.collections_list.append(name)
def draw(self, conext):
# open the blend file and read the collections
# Make a list of all the collections in the file
# Display them in the menu
self.openBlendFileAndRead()
layout = self.layout
for idx, const in enumerate(self.collections_list):
layout.prop(self, "selection", index=idx, text=const, toggle=False)
def execute(self, context):
bpy.ops.view3d.snap_cursor_to_center()
for index, flag in enumerate(self.selection):
if flag:
createAndSetImportCollection()
link = False
if yaam.get_cur_blend_import_op() == 'link':
link = True
try:
blendAppendLinkElement(
yaam.get_cur_selected_asset_abs_path(),
"Collection",
self.collections_list[index],
link=link)
except RuntimeError as e:
self.report({'ERROR'}, str(e))
return {'FINISHED'}
class YAAM_OT_AppendMaterials(Operator):
bl_idname = "astblend.append_materials"
bl_label = "Materials"
bl_description = "Append materials from a blend library"
selection: BoolVectorProperty(size=32, options={'SKIP_SAVE'})
poll = poll_general
invoke = invoke_general
def __init__(self):
self.materials_list = []
def openBlendFileAndRead(self):
self.materials_list = []
asset_path = yaam.get_cur_selected_asset_abs_path()
with bpy.data.libraries.load(asset_path) as (data_from, data_to):
for name in data_from.materials:
self.materials_list.append(name)
def draw(self, conext):
# open the blend file and read the materials
# Make a list of all the materials in the file
# Display them in the menu
self.openBlendFileAndRead()
layout = self.layout
for idx, const in enumerate(self.materials_list):
layout.prop(self, "selection", index=idx, text=const, toggle=False)
def execute(self, context):
bpy.ops.view3d.snap_cursor_to_center()
for index, flag in enumerate(self.selection):
if flag:
createAndSetImportCollection()
link = False
if yaam.get_cur_blend_import_op() == 'link':
link = True
try:
blendAppendLinkElement(
yaam.get_cur_selected_asset_abs_path(),
"Material",
self.materials_list[index],
link=link)
except RuntimeError as e:
self.report({'ERROR'}, str(e))
return {'FINISHED'}
class YAAM_OT_AppendObjects(Operator):
bl_idname = "astblend.append_objects"
bl_label = "Objects"
bl_description = "Append objects from a blend library"
selection: BoolVectorProperty(size=32, options={'SKIP_SAVE'})
poll = poll_general
invoke = invoke_general
def __init__(self):
self.objects_list = []
def openBlendFileAndRead(self):
self.objects_list = []
asset_path = yaam.get_cur_selected_asset_abs_path()
with bpy.data.libraries.load(asset_path) as (data_from, data_to):
for name in data_from.objects:
self.objects_list.append(name)
def draw(self, conext):
# open the blend file and read the objects
# Make a list of all the objects in the file
# Display them in the menu
# TODO: don't open and read the file every draw cycle. do it only
# once. Maybe have a flag and check if it has been set
self.openBlendFileAndRead()
layout = self.layout
for idx, const in enumerate(self.objects_list):
layout.prop(self, "selection", index=idx, text=const, toggle=False)
def execute(self, context):
bpy.ops.view3d.snap_cursor_to_center()
for index, flag in enumerate(self.selection):
if flag:
createAndSetImportCollection()
link = False
if yaam.get_cur_blend_import_op() == 'link':
link = True
try:
blendAppendLinkElement(
yaam.get_cur_selected_asset_abs_path(),
"Object",
self.objects_list[index],
link=link)
except RuntimeError as e:
self.report({'ERROR'}, str(e))
return {'FINISHED'}
class YAAM_OT_AppendTextures(Operator):
bl_idname = "astblend.append_textures"
bl_label = "Textures"
bl_description = "Append textures from a blend library"
selection: BoolVectorProperty(size=32, options={'SKIP_SAVE'})
poll = poll_general
invoke = invoke_general
def __init__(self):
self.textures_list = []
def openBlendFileAndRead(self):
self.textures_list = []
asset_path = yaam.get_cur_selected_asset_abs_path()
with bpy.data.libraries.load(asset_path) as (data_from, data_to):
for name in data_from.textures:
self.textures_list.append(name)
def draw(self, conext):
# open the blend file and read the textures
# Make a list of all the textures in the file
# Display them in the menu
self.openBlendFileAndRead()
layout = self.layout
for idx, const in enumerate(self.textures_list):
layout.prop(self, "selection", index=idx, text=const, toggle=False)
def execute(self, context):
bpy.ops.view3d.snap_cursor_to_center()
for index, flag in enumerate(self.selection):
if flag:
createAndSetImportCollection()
link = False
if yaam.get_cur_blend_import_op() == 'link':
link = True
try:
blendAppendLinkElement(
yaam.get_cur_selected_asset_abs_path(),
TEXTURES_dir_name,
self.textures_list[index],
link=link)
except RuntimeError as e:
self.report({'ERROR'}, str(e))
return {'FINISHED'}
class YAAM_OT_AppendScenes(Operator):
bl_idname = "astblend.append_scenes"
bl_label = "Scenes"
bl_description = "Append a collection from a blend library"
selection: BoolVectorProperty(size=32, options={'SKIP_SAVE'})
poll = poll_general
invoke = invoke_general
def __init__(self):
self.scenes_list = []
def openBlendFileAndRead(self):
self.scenes_list = []
asset_path = yaam.get_cur_selected_asset_abs_path()
with bpy.data.libraries.load(asset_path) as (data_from, data_to):
for name in data_from.scenes:
self.scenes_list.append(name)
def draw(self, conext):
# open the blend file and read the scenes
# Make a list of all the scenes in the file
# Display them in the menu
self.openBlendFileAndRead()
layout = self.layout
for idx, const in enumerate(self.scenes_list):
layout.prop(self, "selection", index=idx, text=const, toggle=False)
def execute(self, context):
bpy.ops.view3d.snap_cursor_to_center()
for index, flag in enumerate(self.selection):
if flag:
createAndSetImportCollection()
link = False
if yaam.get_cur_blend_import_op() == 'link':
link = True
try:
blendAppendLinkElement(
yaam.get_cur_selected_asset_abs_path(),
"Scene",
self.scenes_list[index],
link=link)
except RuntimeError as e:
self.report({'ERROR'}, str(e))
return {'FINISHED'}
class YAAM_OT_import_ext(Operator):
bl_idname = "yaam.import_ext"
bl_label = "Import"
bl_description = "Import external format"
def import_scene(self, cb):
if not yaam.get_cur_selected_asset_abs_path():
return {'FINISHED'}
if os.path.isdir(yaam.get_cur_selected_asset_abs_path()):
self.report({'ERROR'}, "Can not import a folder")
return {'FINISHED'}
try:
cb(filepath=yaam.get_cur_selected_asset_abs_path())
except:
self.report({'ERROR'}, "Failed to import file: ")
return {'FINISHED'}
bpy.ops.view3d.snap_cursor_to_center()
collection_name = "imported_assets"
c = bpy.data.collections.get(collection_name)
scene = bpy.context.scene
if c is not None:
c.objects.link(bpy.context.selected_objects[0])
else:
c = bpy.data.collections.new(collection_name)
scene.collection.children.link(c)
c.objects.link(bpy.context.selected_objects[0])
return {'FINISHED'}
def import_obj(self):
return self.import_scene(bpy.ops.import_scene.obj)
def import_blend(self):
self.report({'ERROR'}, "Please explicitly select blend from category")
return {'FINISHED'}
def import_3ds(self):
self.report({'ERROR'}, "File type currently unsupported")
return {'FINISHED'}
def import_fbx(self):
return self.import_scene(bpy.ops.import_scene.fbx)
def import_texture(self):
img_path = yaam.get_cur_selected_asset_abs_path()
if not img_path:
self.report({'ERROR'}, "No image selected")
return {'CANCELLED'}
fname = pathlib.Path(img_path).parts[-1]
if fname in bpy.data.images:
self.report({'ERROR'}, "Asset is already imported")
return {'CANCELLED'}
bpy.data.images.load(img_path)
bpy.data.images[fname].use_fake_user = True
self.report({'INFO'}, "Successfully imported imaged and set fake user")
return {'FINISHED'}
def execute(self, context):
if yaam.get_cur_selected_asset_category() == 'asset.all':
cur_abs_path = yaam.get_cur_selected_asset_abs_path()
if not cur_abs_path:
self.report({'ERROR'}, "no asset selected to import")
return {'CANCELLED'}
fname = pathlib.Path(cur_abs_path).parts[-1]
if fname.lower().endswith(tuple(yaam.get_supported_img_formats())):
self.import_texture()
elif fname.lower().endswith(('.blend')):
self.import_blend()
elif fname.lower().endswith(('.obj')):
self.import_obj()
elif fname.lower().endswith(('.3ds')):
self.import_3ds()
elif fname.lower().endswith(('.fbx')):
self.import_fbx()
else:
self.report({'ERROR'}, "Unsupported File Format")
elif yaam.get_cur_selected_asset_category() == 'asset.texture':
self.import_texture()
elif yaam.get_cur_selected_asset_category() == 'asset.3ds_file':
self.import_3ds()
elif yaam.get_cur_selected_asset_category() == 'asset.fbx_file':
self.import_fbx()
elif yaam.get_cur_selected_asset_category() == 'asset.obj_file':
self.import_obj()
elif yaam.get_cur_selected_asset_category() == 'asset.blend':
self.import_blend()
else:
self.report({'ERROR'}, "Unsupported File Format")
return {'FINISHED'}
class YAAM_OT_add_asset(Operator):
bl_idname = "yaam.add_asset"
bl_label = "Add"
bl_description = "Add asset to selected Category"
def save_asset(self, base_path, cat):
if cat == 'asset.all':
self.report({'ERROR'}, "Must specify category to save in")
elif cat == 'asset.fbx_file':
filename = base_path + ".fbx"
bpy.ops.export_scene.fbx(filepath=filename)
elif cat == 'asset.3ds_file':
self.report({'ERROR'}, "3DS files are currently unsupported")
elif cat == 'asset.obj_file':
filename = base_path + ".obj"
bpy.ops.export_scene.obj(filepath=filename)
elif cat == 'asset.blend':
filename = base_path + ".blend"
bpy.ops.wm.save_as_mainfile(filepath=filename)
def execute(self, context):
# make sure the structure we need is there
directory = yaam.get_or_create_asset_subdir(
yaam.get_cur_selected_asset_category())
if not directory:
self.report({'ERROR'}, "Couldn't create asset directory")
return ({'CANCELLED'})
save_name = yaam.get_save_asset_name()
if not save_name:
self.report({'ERROR'}, "Must specify an asset name")
return ({'CANCELLED'})
if os.path.sep in save_name:
self.report({'ERROR'}, "File name can not contain slashes")
return ({'CANCELLED'})
if '.' in save_name:
self.report({'ERROR'}, "File name can not contain '.'")
return ({'CANCELLED'})
asset_save_dir = yaam.get_save_asset_dir()
if asset_save_dir and directory not in asset_save_dir:
self.report({'ERROR'},
"Specified save dir does not match category selected")
return ({'CANCELLED'})
abs_save_base_name = os.path.join(asset_save_dir, save_name)
# get the active camera
for obj in bpy.data.objects:
if obj.type == 'CAMERA':
camera = obj
if camera is None:
self.report({'ERROR'}, "No Camera in Scene")
return ({'CANCELLED'})
# store original values
res_x = bpy.context.scene.render.resolution_x
res_y = bpy.context.scene.render.resolution_y
percentage = bpy.context.scene.render.resolution_percentage
engine = bpy.context.scene.render.engine
output = bpy.context.scene.render.filepath
# set to EEVEE
bpy.context.scene.render.engine = 'BLENDER_EEVEE'
# change the output to 128x128 100% resolution
bpy.context.scene.render.resolution_x = 128
bpy.context.scene.render.resolution_y = 128
bpy.context.scene.render.resolution_percentage = 100
bpy.context.scene.render.filepath = abs_save_base_name + ".png"
# Save the image and the file in the blend asset directory
bpy.ops.render.render(write_still=True)
# save according to category
self.save_asset(abs_save_base_name,
yaam.get_cur_selected_asset_category())
# restore original values
bpy.context.scene.render.resolution_x = res_x
bpy.context.scene.render.resolution_y = res_y
bpy.context.scene.render.resolution_percentage = percentage
bpy.context.scene.render.engine = engine
bpy.context.scene.render.filepath = output
self.report({'INFO'}, "Added asset successfully")
# force an update
yaam.set_previous_assets_directory("")
return {'FINISHED'}
class YAAM_OT_rm_asset(Operator):
bl_idname = "yaam.rm_asset"
bl_label = "Remove"
bl_description = "Remove asset from selected Category"
def execute(self, context):
# get or create the Trash directory
asset_trash = yaam.get_or_create_asset_subdir(
'asset.trash', create=True)
if asset_trash is None:
self.report({'ERROR'}, "Couldn't create trash directory")
rm = False
base_path_no_ext = os.path.splitext(
yaam.get_cur_selected_asset_abs_path())[0]
wildcard = base_path_no_ext + '.*'
for file in glob.glob(wildcard):
# move the asset and the png
new_path = os.path.join(asset_trash, pathlib.Path(file).parts[-1])
os.rename(file, new_path)
rm = True
if rm:
self.report({'INFO'}, "Asset moved to trash successfully")
# force an update
yaam.set_previous_assets_directory("")
else:
self.report({'INFO'}, "Failed to remove Asset")
return {'FINISHED'}
class YAAM_OT_refresh_asset(Operator):
bl_idname = "yaam.refresh_asset"
bl_label = "Refresh"
bl_description = "Refresh assets"
def execute(self, context):
# force an update by setting the previous assets directory to ''
# This way when we check it while building, we'll continue to build
# there by the filter taking effect
yaam.set_previous_assets_directory("")
return {'FINISHED'}
class YAAM_OT_snap_image(Operator):
bl_idname = "yaam.snap_picture"
bl_label = "snap image"
bl_description = "snap an image of the current asset"
def execute(self, context):
abs_path = yaam.get_cur_selected_asset_abs_path()
if not abs_path:
self.report({'ERROR'}, "no asset selected.")
return ({'FINISHED'})
for f in yaam.get_supported_img_formats_match():
if fnmatch.fnmatch(abs_path, f):
self.report({'ERROR'}, "Operation not allowed for images")
return ({'FINISHED'})
png_path = os.path.splitext(abs_path)[0]
# store original values
res_x = bpy.context.scene.render.resolution_x
res_y = bpy.context.scene.render.resolution_y
percentage = bpy.context.scene.render.resolution_percentage
engine = bpy.context.scene.render.engine
output = bpy.context.scene.render.filepath
# set to EEVEE
bpy.context.scene.render.engine = 'BLENDER_EEVEE'
# change the output to 128x128 100% resolution
bpy.context.scene.render.resolution_x = 128
bpy.context.scene.render.resolution_y = 128
bpy.context.scene.render.resolution_percentage = 100
bpy.context.scene.render.filepath = png_path+".png"
# Save the image and the file in the blend asset directory
bpy.ops.render.render(write_still=True)
# restore original values
bpy.context.scene.render.resolution_x = res_x
bpy.context.scene.render.resolution_y = res_y
bpy.context.scene.render.resolution_percentage = percentage
bpy.context.scene.render.engine = engine
bpy.context.scene.render.filepath = output
self.report({'INFO'}, "Image snapped successfully")
# force an update by setting the previous assets directory to ''
# This way when we check it while building, we'll continue to build
# there by the filter taking effect
yaam.set_previous_assets_directory("")
return {'FINISHED'}
def asset_type_handler(self, context):
yaam.set_cur_selected_asset_category(self.asset_type_dropdown)
# force an update by setting the previous assets directory to ''
# This way when we check it while building, we'll continue to build
# there by the filter taking effect
yaam.set_previous_assets_directory("")
def asset_mode_handler(self, context):
yaam.set_cur_selected_asset_mode(self.asset_mode_expand)
# Asset Manager Mode
# Can be in browse or manage mode.
# In browse mode, you can browse and import
# In add mode, you can add assets to the library
class AstMgrMode(bpy.types.PropertyGroup):
mode = [
("astmgrmode.browse_assets", "Browse", "Browse assets", '', 0),
("astmgrmode.mng_assets", "Manage", "Manage assets", '', 1),
]
if yaam.get_cur_selected_asset_mode() == "":
yaam.set_cur_selected_asset_mode("astmgrmode.browse_assets")
asset_mode_expand: EnumProperty(
items=mode,
description="Asset Manager Mode",
name="Asset Manager Mode",
default=yaam.get_cur_selected_asset_mode(),
update=asset_mode_handler,
options={'HIDDEN'})
# Asset type drop down list
class AssetTypes(bpy.types.PropertyGroup):
# The last entry int he array is displayed first
asset_types = [
("asset.all", "all 3D assets", "all 3D assets", '', 5),
("asset.texture", "textures", "import textures", '', 4),
("asset.3ds_file", "3ds", "import 3ds into scene", '', 3),
("asset.fbx_file", "fbx", "import fbx into scene", '', 2),
("asset.obj_file", "obj", "import obj into scene", '', 1),
("asset.blend", "blend", "link or append blends", '', 0),
]
if yaam.get_cur_selected_asset_category() == "":
yaam.set_cur_selected_asset_category("asset.all")
asset_type_dropdown: EnumProperty(
items=asset_types,
description="select asset type to import",
name="Category",
default=yaam.get_cur_selected_asset_category(),
update=asset_type_handler)
class YAAM_OT_organize(Operator):
bl_idname = "yaam_gen.organize"
bl_label = "Organize"
bl_description = "Organize assets"
def __init__(self):
self.src = ''
self.dst = ''
def get_fnames(self, dirName, fname, file_type):
subdir = dirName.replace(self.src, '')
old_fname = os.path.join(dirName, fname)
new_fname = ''
if subdir:
new_subdir = os.path.join(self.dst, file_type, subdir)
try: