-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy paththumbMate.py
1039 lines (818 loc) · 35.5 KB
/
thumbMate.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
"""
thumbMate
Copyright (C) 2022, Ingo Clemens, brave rabbit, www.braverabbit.com
GNU GENERAL PUBLIC LICENSE Version 3
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 <https://www.gnu.org/licenses/>.
------------------------------------------------------------------------
Description:
Thumb Mate helps with creating customizable thumbnail previews for
object assets in the asset browser.
By default these asset previews are only rendered using the workbench
render engine and therefore are often insufficient for representing the
object due to it's limitations.
Thumb Mate renders the asset preview using Eevee with full control over
the used environment and viewing angle. The previews can either be
created upon marking an object as an asset or when updating the image.
------------------------------------------------------------------------
Usage:
Thumb Mate is accessible through the Render menu item in the Asset
Browser's main menu:
Render Custom Preview: Creates a rendered preview for all selected mesh
objects in the scene. If nothing is selected all
objects of the currently active collection will
be rendered.
All rendered objects will automatically be marked
as assets.
Update Custom Preview: Re-renders the preview image for the currently
selected asset.
Additionally the metadata panel of the asset browser features a new
button in the preview folder which allows for updating the custom
preview for the selected asset.
All settings responsible for the rendering of the previews can be found
in the add-on preferences in the Blender preferences window.
By default the city.exr of the built-in environment images of Blender is
used for the background, but any custom image can be used as well.
Other settings include the camera angle, focus length, clipping and
frame padding.
------------------------------------------------------------------------
Changelog:
0.4.0 - 2024-11-28
- Added rendering of preview images for geometry node assets.
0.3.3 - 2024-11-27
- Unregistering the default metadata class when registering the
add-on for a cleaner startup.
0.3.2 - 2024-11-13
- Fixed an issue with the updated Eevee render engine name in
Blender 4.2
0.3.1 - 2023-10-18
- Fixed a context issue when rendering the selection collection
which is not already marked as an asset.
0.3.0 - 2023-10-17
- Added compatibility with Blender 4.0.
0.2.0 - 2022-11-03
- Added support for creating collection asset previews.
0.1.0 - 2022-03-24
- First public release
------------------------------------------------------------------------
"""
bl_info = {"name": "Thumb Mate",
"author": "Ingo Clemens",
"version": (0, 4, 0),
"blender": (3, 0, 0),
"category": "Import-Export",
"location": "Asset Browser",
"description": "Create rendered beauty previews for the asset browser",
"warning": "",
"doc_url": "https://github.com/IngoClemens/blender/wiki/Thumb-Mate",
"tracker_url": ""}
import bpy
from bpy_extras.asset_utils import AssetMetaDataPanel, SpaceAssetInfo
from bl_operators.assets import AssetBrowserMetadataOperator
import bl_ui
import inspect
import os
import math
from mathutils import Euler, Vector
import shutil
import types
# ----------------------------------------------------------------------
# Defaults
# ----------------------------------------------------------------------
NAME = "thumbMate"
IMAGE_NAME = "{}_render".format(NAME)
IMAGE_SIZE = 256
CAM_NAME = "camera_{}".format(NAME)
CAM_ANGLE = (60, 0, 25)
CLIP_START = 0.001
CLIP_END = 1000
FOCAL_LENGTH = 85
WORLD_NAME = "world_{}".format(NAME)
HDRI = "city.exr"
ROTATION = 0
PADDING = 5
ANN_RENDER_OPERATOR = "Render a custom preview for the selected objects or active collection"
ANN_COLLECTION_OPERATOR = "Render a custom preview for the active collection"
ANN_UPDATE_OPERATOR = "Create a custom preview for the selected data-block"
ANN_PATH = ("The path containing HDRI images to be used for the rendering environment.\n"
"The default is the built-in world images path.")
ANN_IMAGE = "The image used for the rendering environment"
ANN_CAM_ANGLE = "The viewing angle of the camera. Tilt, Roll and Orientation"
ANN_FOCAL = ("The focal length for rendering the previews.\n"
"The effective focal length is slightly reduced to allow for border padding\n"
"and depends on the frame padding value.")
ANN_CLIP_START = ("The min clip distance for the camera.\n"
"Should be small enough to not cut-off smaller objects.")
ANN_CLIP_END = "The max clip distance for the camera"
ANN_WORLD_ROTATION = "The orientation of the environment image"
ANN_PADDING = ("The frame padding in percent to allow some space between the images.\n"
"Effectively reduces the camera focal length.")
# ----------------------------------------------------------------------
# Storage
# ----------------------------------------------------------------------
class Cache(object):
"""Class for storing the scene state in order to be able to revert
it back after rendering.
"""
def __init__(self):
self.values = {}
cache = Cache()
# ----------------------------------------------------------------------
# General
# ----------------------------------------------------------------------
def currentSelection():
"""Return the current object selection. If nothing is selected
return all mesh objects from the current collection.
:return: A list with selected objects or collection objects.
:rtype: list(bpy.types.Object) or None
"""
sel = bpy.context.selected_objects
if sel:
return sel
else:
col = activeCollection()
if col is not None:
# Filter only mesh objects.
return collectionMeshes(col)
def setSelection(objects):
"""Select the given list of objects.
:param objects: The list of objects to select.
:type objects: list(bpy.types.Object or bpy.types.Collection)
"""
for obj in objects:
if isinstance(obj, bpy.types.Object):
obj.select_set(True)
bpy.context.view_layer.objects.active = obj
elif isinstance(obj, bpy.types.Collection):
# Deselect all collection meshes.
for mesh in collectionMeshes(obj):
mesh.select_set(False)
else:
pass
def activeCollection():
"""Return the currently active collection.
:return: The active collection.
:rtype: bpy.types.Collection or None
"""
col = bpy.context.view_layer.active_layer_collection
if col:
# If the selected collection is the master scene collection
# it cannot be queried directly since it's of type
# LayerCollection.
# In this case get the wrapped collection which then can
# be queried just like any other collection.
if type(col) is bpy.types.LayerCollection:
return col.collection
return col
def collectionMeshes(collection):
"""Return the list of mesh objects of the given collection.
:param collection: The collection to get the meshes from.
:type collection: bpy.types.Collection
:return: The list of mesh objects of the collection.
:rtype: list(bpy.types.Object)
"""
return [o for o in collection.all_objects if o.type == 'MESH']
def environmentImagesPath():
"""Return the built-in images path for studio light world HDRIs.
Since this path depends on the current system it's procedurally
retrieved through the location of the application binary file.
:return: The absolute path to the included world HDRIs.
:rtype: str or None
"""
# A recursion counter to make sure that the loop ends.
count = 0
# Get the path to the Blender executable.
filePath = os.path.dirname(bpy.app.binary_path)
# Find the lowest path level which contains Blender.
while "blender" not in os.path.basename(filePath).lower():
filePath = os.path.dirname(filePath)
if not filePath or count == 20:
break
count += 1
# Search all subpaths for the datafiles folder. Based on this folder
# the path can be completed.
for dirPath, dirs, fileList in os.walk(filePath):
if os.path.basename(dirPath) == "datafiles":
return os.path.join(os.path.join(dirPath, "studiolights"), "world")
def environmentImages(dirPath):
"""Return a list of images which are located at the given path.
:param dirPath: The file path to search for images.
:type dirPath: str
:return: The list of images at the given path.
:rtype: list(str)
"""
images = []
for f in os.listdir(dirPath):
if os.path.isfile(os.path.join(dirPath, f)):
name, ext = os.path.splitext(f)
if ext.lower().replace(".", "") in ["hdr", "exr", "rad", "tif", "tiff"]:
images.append(f)
return sorted(images)
def setRenderable(objects, hidden=True):
"""Set all given objects to be invisible when rendering.
:param objects: The list of objects to process.
:type objects: list(bpy.types.Object)
:param hidden: The hidden state for rendering.
:type hidden: bool
:return: A list of tuples with the object and the previous
visibility setting.
:rtype: list(tuple(bpy.types.Object, bool))
"""
state = []
for obj in objects:
state.append((obj, obj.hide_render))
obj.hide_render = hidden
return state
def resetRenderable(objects):
"""Set the rendering visibility for each object based on their given
state.
:param objects: A list of tuples with the object and the visibility
setting.
:rtype: list(tuple(bpy.types.Object, bool))
"""
for obj, state in objects:
obj.hide_render = state
# ----------------------------------------------------------------------
# Render settings
# ----------------------------------------------------------------------
def outputPath():
"""Return the output path based on the current scene path.
:return: The absolute render output path.
:rtype: str
"""
scenePath = bpy.data.filepath
# If the scene hasn't been saved yet the path is empty.
# Returning an empty path prompts the user for saving the scene.
if not scenePath:
return
renderPath = os.path.join(os.path.dirname(scenePath), "{}_thumbs".format(NAME))
return renderPath
def deleteOutputPath(filePath):
"""Delete the given directory and all of it's content.
:param filePath: The path to the directory to delete.
:type filePath: str
"""
if os.path.exists(filePath):
shutil.rmtree(filePath)
def setEevee():
"""Set the render engine to Eevee.
"""
for engine in ["BLENDER_EEVEE_NEXT", "BLENDER_EEVEE"]:
try:
bpy.context.scene.render.engine = engine
return
except (Exception, ):
pass
def setRenderSettings(filePath):
"""Store the previous render settings and define the settings for
rendering the previews.
:param filePath: The path to render the images to.
:type filePath: str
"""
cache.values["engine"] = bpy.context.scene.render.engine
cache.values["transparent"] = bpy.context.scene.render.film_transparent
cache.values["filepath"] = bpy.context.scene.render.filepath
cache.values["format"] = bpy.context.scene.render.image_settings.file_format
cache.values["mode"] = bpy.context.scene.render.image_settings.color_mode
cache.values["depth"] = bpy.context.scene.render.image_settings.color_depth
cache.values["resolutionX"] = bpy.context.scene.render.resolution_x
cache.values["resolutionY"] = bpy.context.scene.render.resolution_y
cache.values["percentage"] = bpy.context.scene.render.resolution_percentage
cache.values["aspectX"] = bpy.context.scene.render.pixel_aspect_x
cache.values["aspectY"] = bpy.context.scene.render.pixel_aspect_y
# Define the necessary render settings.
setEevee()
bpy.context.scene.render.film_transparent = True
bpy.context.scene.render.filepath = filePath
bpy.context.scene.render.image_settings.file_format = 'PNG'
bpy.context.scene.render.image_settings.color_mode = 'RGBA'
bpy.context.scene.render.image_settings.color_depth = '8'
bpy.context.scene.render.resolution_x = IMAGE_SIZE
bpy.context.scene.render.resolution_y = IMAGE_SIZE
bpy.context.scene.render.resolution_percentage = 100
bpy.context.scene.render.pixel_aspect_x = 1.0
bpy.context.scene.render.pixel_aspect_y = 1.0
# Store the current world.
cache.values["world"] = bpy.context.scene.world
def restoreRenderSettings():
"""Restore the previous render settings
"""
bpy.context.scene.render.engine = cache.values["engine"]
bpy.context.scene.render.film_transparent = cache.values["transparent"]
bpy.context.scene.render.filepath = cache.values["filepath"]
bpy.context.scene.render.image_settings.file_format = cache.values["format"]
bpy.context.scene.render.image_settings.color_mode = cache.values["mode"]
bpy.context.scene.render.image_settings.color_depth = cache.values["depth"]
bpy.context.scene.render.resolution_x = cache.values["resolutionX"]
bpy.context.scene.render.resolution_y = cache.values["resolutionY"]
bpy.context.scene.render.resolution_percentage = cache.values["percentage"]
bpy.context.scene.render.pixel_aspect_x = cache.values["aspectX"]
bpy.context.scene.render.pixel_aspect_y = cache.values["aspectY"]
if cache.values["world"]:
bpy.context.scene.world = cache.values["world"]
# ----------------------------------------------------------------------
# Camera
# ----------------------------------------------------------------------
def get3dView():
"""Return the SpaceView3D to be able to access the current viewing
camera.
:return: The current view space.
:rtype: bpy.types.SpaceView3D or None
"""
for area in bpy.context.screen.areas:
if area.type == 'VIEW_3D':
return bpy.types.SpaceView3D(area.spaces[0])
def createCamera():
"""Create the camera for rendering the preview images.
"""
prefs = getPreferences()
# Remove any pre-existing preview camera.
if CAM_NAME in bpy.data.cameras:
bpy.data.cameras.remove(bpy.data.cameras[CAM_NAME], do_unlink=True)
# Store the current scene camera.
cache.values["sceneCamera"] = bpy.context.scene.camera
# Create a new camera and name it accordingly.
bpy.ops.object.camera_add()
cam = bpy.context.object
cam.name = CAM_NAME
cam.data.name = CAM_NAME
cache.values["camera"] = cam
# Set the camera properties.
cam.location = Vector((10, -10, 10))
rot = prefs.camAngle_value
cam.rotation_euler = Euler((math.radians(rot[0]),
math.radians(rot[1]),
math.radians(rot[2])))
cam.data.clip_start = prefs.clipStart_value
cam.data.clip_end = prefs.clipEnd_value
cam.data.lens = prefs.focal_value
view3d = get3dView()
# Store the current view camera, if any.
cache.values["viewCamera"] = view3d.camera if view3d.camera else None
# Set the render camera for the view.
view3d.camera = cam
bpy.context.scene.camera = cam
def cleanupCamera():
"""Set the camera settings back to the previous state.
"""
# Delete the preview camera.
bpy.data.cameras.remove(cache.values["camera"].data, do_unlink=True)
# Reset the scene camera.
if cache.values["sceneCamera"]:
bpy.context.scene.camera = cache.values["sceneCamera"]
# Reset the view camera.
view3d = get3dView()
try:
if cache.values["viewCamera"]:
view3d.camera = cache.values["viewCamera"]
except ReferenceError:
pass
# ----------------------------------------------------------------------
# World node
# ----------------------------------------------------------------------
def createWorld(filePath):
"""Create a new world node.
"""
prefs = getPreferences()
# Remove any previously created data.
cleanupWorld()
# Create a new world and make it current.
world = bpy.data.worlds.new(WORLD_NAME)
bpy.context.scene.world = world
world.use_nodes = True
# Create the necessary shading nodes for the environment map.
coord = world.node_tree.nodes.new(type="ShaderNodeTexCoord")
mapping = world.node_tree.nodes.new(type="ShaderNodeMapping")
texture = world.node_tree.nodes.new(type="ShaderNodeTexEnvironment")
coord.location = (-740, 300)
mapping.location = (-520, 300)
texture.location = (-300, 300)
world.node_tree.links.new(coord.outputs['Generated'], mapping.inputs[0])
world.node_tree.links.new(mapping.outputs[0], texture.inputs[0])
world.node_tree.links.new(texture.outputs[0], world.node_tree.nodes["Background"].inputs[0])
# Create the image for the environment and link it to the texture
# node.
image = bpy.data.images.load(os.path.join(filePath, prefs.image_value), check_existing=True)
cache.values["environmentImage"] = image
texture.image = image
# Adjust the horizontal rotation.
mapping.inputs[2].default_value[2] = math.radians(prefs.worldRotation_value)
def cleanupWorld():
"""Delete all created data blocks for the world and reset to the
previous world.
"""
prefs = getPreferences()
if WORLD_NAME in bpy.data.worlds:
bpy.data.worlds.remove(bpy.data.worlds[WORLD_NAME], do_unlink=True)
if prefs.image_value in bpy.data.images:
bpy.data.images.remove(bpy.data.images[prefs.image_value], do_unlink=True)
# ----------------------------------------------------------------------
# Thumbnail creation
# ----------------------------------------------------------------------
def renderPreviews(objects, imagePath, setAsset=False):
"""Create the preview images for the given objects.
:param objects: The list of objects or collections to create
previews for.
:type objects: list(bpy.types.Object) or list(bpy.types.Collection)
:param imagePath: The render output path.
:type imagePath: str
:param setAsset: True, if the given objects shoould be marked as an
asset.
:type setAsset: bool
:return: None or an error message
:rtype: None or tuple(dict(), str)
"""
prefs = getPreferences()
paddingFactor = 1 - (prefs.padding_value * 0.01)
if objects:
# Set all objects to be invisible for rendering and store their
# previous state.
renderState = setRenderable(bpy.data.objects, hidden=True)
for obj in objects:
# Select the current object that the camera can focus on it.
if isinstance(obj, bpy.types.Collection):
for mesh in collectionMeshes(obj):
setObjectRenderable(mesh, True)
else:
setObjectRenderable(obj, True)
# Frame the selection and adjust the focal length to allow
# for a safe framing area.
bpy.ops.view3d.camera_to_view_selected()
cache.values["camera"].data.lens = prefs.focal_value * paddingFactor
# Render the preview.
bpy.ops.render.render(write_still=True)
# Rename the output file to match the object's name.
tempFile = ".".join((os.path.join(imagePath, IMAGE_NAME), "png"))
thumbFile = ".".join((os.path.join(imagePath, obj.name), "png"))
os.rename(tempFile, thumbFile)
# Reset the focal length of the camera.
cache.values["camera"].data.lens = prefs.focal_value
# Deselect the object and hide it from rendering.
if isinstance(obj, bpy.types.Collection):
for mesh in collectionMeshes(obj):
setObjectRenderable(mesh, False)
else:
setObjectRenderable(obj, False)
# Reset the previous render state for all objects.
resetRenderable(renderState)
# Mark the selected objects as assets and assign their custom
# preview image.
# Usually copying the context shouldn't cause an error but just
# for safety an error gets intercepted.
try:
override = bpy.context.copy()
except TypeError:
return ({'ERROR'}, ("An error occurred while trying to access the context " +
"for loading the custom preview"))
sel = currentSelection()
for obj in objects:
if not obj.asset_data and setAsset:
obj.asset_mark()
setSelection([obj])
try:
override['id'] = obj
thumbFile = ".".join((os.path.join(imagePath, obj.name), "png"))
if bpy.app.version < (4, 0, 0):
bpy.ops.ed.lib_id_load_custom_preview(override, filepath=thumbFile)
else:
bpy.ops.ed.lib_id_load_custom_preview(filepath=thumbFile)
except (Exception,):
# Restore the selection.
setSelection(sel)
return {'WARNING'}, ("The collection is marked as an asset " +
"but the preview needs to be created manually")
# Restore the selection.
setSelection(sel)
def setupRender():
"""Prepare the scene for rendering the preview images.
Return the render output path if the setup was successful.
Return None, if the build-in images could not be found.
:return: The output path or a warning message.
:rtype: str or tuple(dict(), str)
"""
prefs = getPreferences()
# Check of the built-in environment maps path can be located.
# Discontinue if it cannot be found.
envPath = prefs.path_value
if not envPath:
return {'WARNING'}, "No environment images path defined"
# Discontinue if there is no output path defined.
renderPath = outputPath()
if not renderPath:
return {'WARNING'}, "The scene needs to be saved before rendering"
if prefs.image_value == 'NONE':
return {'WARNING'}, "No environment image defined"
setRenderSettings(os.path.join(renderPath, IMAGE_NAME))
createCamera()
createWorld(envPath)
return renderPath
def cleanup(filePath):
"""Restore all previous settings and delete all data blocks used for
rendering the preview images.
:param filePath: The path to render the images to.
:type filePath: str
"""
restoreRenderSettings()
cleanupCamera()
cleanupWorld()
deleteOutputPath(filePath)
def createAssetPreview(objects, setAsset=False):
"""Create asset preview images for the current selection or the
currently active collection.
:param objects: The object or list of objects to process.
:type objects: bpy.types.Object or bpy.types.Collection or
list(bpy.types.Object)
:param setAsset: True, if the given objects shoould be marked as an
asset.
:type setAsset: bool
"""
if not type(objects) is list:
objects = [objects]
bpy.ops.object.select_all(action='DESELECT')
if objects:
# Return if there is no 3d view available.
if not get3dView():
return {'WARNING'}, "No 3d view found"
result = setupRender()
# If the resulting path contains an error no rendering is
# performed.
# Cleanup is not necessary in this case.
if type(result) is tuple:
return result
renderError = renderPreviews(objects, result, setAsset=setAsset)
cleanup(result)
if renderError:
return renderError
# Restore the selection.
setSelection(objects)
def setObjectRenderable(obj, state):
"""Set the given object to the given renderable state. If the render
state is True, the object gets also selected.
:param obj: The object to set the renderable state for.
:type obj: bpy.types.Object
:param state: True, if the object should be set to renderable.
:type state: bool
"""
obj.select_set(state)
# Only make the object active if it's also selected.
if state:
bpy.context.view_layer.objects.active = obj
# Set the object to be renderable.
obj.hide_render = not state
# ----------------------------------------------------------------------
# Operators
# ----------------------------------------------------------------------
class THUMBMATE_OT_renderPreview(bpy.types.Operator):
"""Operator class for rendering custom preview images for either
the currently selected objects or all meshes of the active
collection.
"""
bl_idname = "thumbmate.render_preview"
bl_label = "Render asset preview"
bl_description = ANN_RENDER_OPERATOR
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
"""Execute the operator.
:param context: The current context.
:type context: bpy.context
"""
objects = currentSelection()
result = createAssetPreview(objects, setAsset=True)
if result:
self.report(result[0], result[1])
return {'CANCELLED'}
return {'FINISHED'}
class THUMBMATE_OT_renderCollectionPreview(bpy.types.Operator):
"""Operator class for rendering a custom preview image for the
active collection.
"""
bl_idname = "thumbmate.render_collection_preview"
bl_label = "Render collection asset preview"
bl_description = ANN_COLLECTION_OPERATOR
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
"""Execute the operator.
:param context: The current context.
:type context: bpy.context
"""
collection = activeCollection()
if collection is not None:
result = createAssetPreview(collection, setAsset=True)
if result:
self.report(result[0], result[1])
return {'CANCELLED'}
return {'FINISHED'}
class THUMBMATE_OT_updatePreview(AssetBrowserMetadataOperator, bpy.types.Operator):
"""Operator class for rendering a custom preview image for the
currently selected asset.
"""
bl_idname = "thumbmate.update_preview"
bl_label = "Update asset preview"
bl_description = ANN_UPDATE_OPERATOR
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
active_asset = SpaceAssetInfo.get_active_asset(context)
# Only render the image if the asset is a mesh.
if (isinstance(active_asset.id_data, bpy.types.Collection) or
active_asset.id_data.type == 'MESH'):
result = createAssetPreview(active_asset.id_data, setAsset=False)
if result:
self.report(result[0], result[1])
return {'CANCELLED'}
elif active_asset.id_data.type == 'GEOMETRY':
objects = currentSelection()
if len(objects):
result = createAssetPreview(objects, setAsset=False)
if result:
self.report(result[0], result[1])
return {'CANCELLED'}
else:
self.report({'ERROR'}, "Select an object to be used for rendering a preview image")
return {'CANCELLED'}
return {'FINISHED'}
# ----------------------------------------------------------------------
# Menu
# ----------------------------------------------------------------------
class THUMBMATE_MT_menu(bpy.types.Menu):
bl_idname = "THUMBMATE_MT_menu"
bl_label = "Render"
def draw(self, context):
self.layout.operator(THUMBMATE_OT_renderPreview.bl_idname,
text="Render Selected Objects",
icon="OUTLINER_OB_MESH")
self.layout.operator(THUMBMATE_OT_renderCollectionPreview.bl_idname,
text="Render Selected Collection",
icon="OUTLINER_COLLECTION")
self.layout.operator(THUMBMATE_OT_updatePreview.bl_idname,
text="Update Selected Asset",
icon="RENDER_STILL")
def menu_item(self, context):
"""Draw the menu.
:param context: The current context.
:type context: bpy.context
"""
self.layout.menu(THUMBMATE_MT_menu.bl_idname)
# ----------------------------------------------------------------------
# Customize the data panel
# ----------------------------------------------------------------------
def metadataPanelOverride(restore=False):
"""Create a new class as an override to
ASSETBROWSER_PT_metadata_preview from space_filebrowser.py.
The override is necessary in order to be able to add a new button
below the existing since these are in a separate layout.
Simply appending a new button would position it below the preview
image, which is not intended.
:return: The class instance for registering with the add-on.
:rtype: class instance
"""
# Get the content from the original class as a string.
data = inspect.getsource(bl_ui.space_filebrowser.ASSETBROWSER_PT_metadata_preview)
lines = data.split("\n")
# Add new lines for the override.
# Skip, if the original class should get restored.
if not restore:
# Add the new lines for adding the button.
lines.append(" col.separator()")
lines.append(" col.operator('{}',\n"
" text='',\n"
" icon='RENDER_STILL')".format(THUMBMATE_OT_updatePreview.bl_idname))
# Get the class name from the first line which is needed for
# registering the override.
className = lines[0].split("(")[0].replace("class ", "")
# Get the content for bl_label from the second line.
label = lines[1].split(" = ")[1].replace("\"", "")
# Remove the class line.
lines.pop(0)
# Remove the bl_label line.
lines.pop(0)
# Remove the empty line.
lines.pop(0)
# Overwrite the draw method because the original contains tabs at
# the beginning.
lines[0] = "def draw(self, context):"
# print("\n".join(lines))
# Register the method within the scope of the add-on.
module = types.ModuleType("operatorDraw")
exec("\n".join(lines), module.__dict__)
# Create the class.
panelClass = type(className,
(AssetMetaDataPanel, bpy.types.Panel, ),
{"bl_label": label,
"draw": module.draw})
return panelClass
# ----------------------------------------------------------------------
# Preferences
# ----------------------------------------------------------------------
def getPreferences():
"""Return the preferences of the add-on.
:return: The add-on preferences.
:rtype: bpy.types.AddonPreferences
"""
prefs = bpy.context.preferences.addons[NAME].preferences
return prefs
def imageItems(self, context):
"""Callback for populating the enum property with the HDRI names
based on the current world images path.
:param context: The current context.
:type context: bpy.context
"""
prefs = getPreferences()
images = [('NONE', "––– Select –––", "")]
if prefs.path_value:
for img in environmentImages(prefs.path_value):
images.append((img, img, ""))
return images
class THUMBMATEPreferences(bpy.types.AddonPreferences):
"""Create the layout for the preferences.
"""
bl_idname = NAME
path_value: bpy.props.StringProperty(name="World Images",
description=ANN_PATH,
default=environmentImagesPath(),
subtype='DIR_PATH',
update=imageItems)
image_value: bpy.props.EnumProperty(name="HDRI",
description=ANN_IMAGE,
items=imageItems,
default=1)
camAngle_value: bpy.props.FloatVectorProperty(name="Camera Rotation",
description=ANN_CAM_ANGLE,
default=CAM_ANGLE)
focal_value: bpy.props.FloatProperty(name="Camera Focal Length",
description=ANN_FOCAL,
default=FOCAL_LENGTH)
clipStart_value: bpy.props.FloatProperty(name="Clip Min",
description=ANN_CLIP_START,
default=CLIP_START,
precision=3)
clipEnd_value: bpy.props.FloatProperty(name="Clip Max",
description=ANN_CLIP_END,
default=CLIP_END)
worldRotation_value: bpy.props.FloatProperty(name="World Rotation",
description=ANN_WORLD_ROTATION,
default=ROTATION)
padding_value: bpy.props.IntProperty(name="Edge Padding %",
description=ANN_PADDING,
default=PADDING)
def draw(self, context):
"""Draw the panel and it's properties.
:param context: The current context.
:type context: bpy.context
"""
self.layout.use_property_split = True
col = self.layout.column(align=True)
col.prop(self, "path_value")
col.prop(self, "image_value")
col.separator()
row = col.row(align=True)
row.prop(self, "camAngle_value")
col = self.layout.column(align=True)
col.prop(self, "focal_value")
col.prop(self, "clipStart_value")
col.prop(self, "clipEnd_value")
col.separator()
col.prop(self, "worldRotation_value")
col.separator()
col.prop(self, "padding_value")
# ----------------------------------------------------------------------
# Registration
# ----------------------------------------------------------------------
# Collect all classes in a list for easier access.
classes = [THUMBMATE_OT_renderPreview,