Repository navigation
Expand file tree
/
Copy pathutils.py
More file actions
714 lines (643 loc) · 28.2 KB
/
Copy pathutils.py
File metadata and controls
714 lines (643 loc) · 28.2 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
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This file is part of the Blender addon "Renderlayer Manager".
#
# The addon "Renderlayer Manager" 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 version 3 of the License or
# any later version.
#
# The addon "Renderlayer Manager" 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 the addon. If not, see <http://www.gnu.org/licenses/>.
#
# ##### END GPL LICENSE BLOCK #####
import os
import bpy
VIEWLAYER_SETTINGS = {}
OCIO_SETTINGS = {}
NODE_GROUP_BASE_NAME = "Renderlayer Manager"
def sanitize_scene_name_for_group(name):
safe = []
for c in name:
if c.isalnum() or c in "._ ":
safe.append(c)
else:
safe.append("_")
safe_name = "".join(safe).replace(" ", "_")
if not safe_name:
safe_name = "Scene"
return safe_name
def get_rlm_node_groups():
groups = []
for node_group in bpy.data.node_groups:
if getattr(node_group, "type", "") != "CompositorNodeTree" and getattr(node_group, "type", "") != "COMPOSITOR":
continue
name = node_group.name
if name == NODE_GROUP_BASE_NAME:
groups.append(node_group)
elif name.endswith("_" + NODE_GROUP_BASE_NAME):
groups.append(node_group)
return groups
def get_or_create_rlm_node_group(scene):
scene_name = sanitize_scene_name_for_group(scene.name)
desired_name = scene_name + "_" + NODE_GROUP_BASE_NAME
groups = get_rlm_node_groups()
for node_group in groups:
if node_group.name == desired_name:
return node_group
if groups:
node_group = groups[0]
if node_group.name != desired_name and desired_name not in bpy.data.node_groups:
try:
node_group.name = desired_name
except Exception:
pass
return node_group
base_name = desired_name
name = base_name
if name in bpy.data.node_groups:
suffix = 1
candidate = base_name + "_" + str(suffix)
while candidate in bpy.data.node_groups:
suffix += 1
candidate = base_name + "_" + str(suffix)
name = candidate
return bpy.data.node_groups.new(name, "CompositorNodeTree")
def get_ocio_settings():
'''Parse ocio config file for a list of active display devices and active view transforms
:return: dict
'''
global OCIO_SETTINGS
displays = []
views = []
# return global variable if already set
if OCIO_SETTINGS:
return OCIO_SETTINGS
# check user defined ocio path
ocio_path = os.environ.get('OCIO')
# get blender default ocio path
if not ocio_path or not os.path.isfile(ocio_path):
bl_dir = os.path.dirname(bpy.app.binary_path)
bl_version = bpy.app.version
ocio_dir = os.path.join(bl_dir, '{}.{}'.format(bl_version[0], bl_version[1]), 'datafiles', 'colormanagement')
ocio_path = os.path.join(ocio_dir, 'config.ocio')
# parse ocio file for active displays and active views
if os.path.isfile(ocio_path):
with open(ocio_path) as f:
for line in f.readlines():
if 'active_displays: ' in line:
string = line.strip('active_displays: ').strip()
displays = ''.join(filter(lambda x: x not in '[]', string)).split(', ')
elif 'active_views: ' in line:
string = line.strip('active_views: ').strip()
views = ''.join(filter(lambda x: x not in '[]', string)).split(', ')
# add displays and views to dictionary
OCIO_SETTINGS['displays'] = displays
OCIO_SETTINGS['views'] = views
return OCIO_SETTINGS
def set_output_paths(context, selection=False):
'''Sets the file output paths for the given file outputs depending
on the current output settings
:param context: <bpy_struct, Context>
:param selection: Filter selected file output nodes
:return: boolean
'''
def filter_scene_viewlayers():
all_view_layers = []
for scn in bpy.data.scenes:
for vlayer in scn.view_layers:
if vlayer.name in all_view_layers:
return True
all_view_layers.append(vlayer.name)
return False
view_layers = context.scene.view_layers
node_tree = getattr(context.scene, "compositing_node_group", None)
if node_tree not in bpy.data.node_groups.values():
groups = get_rlm_node_groups()
if not groups:
return False
node_tree = groups[0]
nodes = node_tree.nodes
file_outputs = [node for node in nodes if node.type == 'OUTPUT_FILE' and node.name.endswith('-RLM')]
if selection:
file_outputs = [node for node in file_outputs if node.select]
# get output directory
output_dir = context.scene.rlm.output_dir.replace(os.sep, '/')
# get output name
# add rlayer token as first directory to output_name if it is not set to prevent equal paths
# for multiple view_layers
output_name = context.scene.rlm.output_name.replace(os.sep, '/')
if not r'{rlayer}' in output_name:
if len(view_layers) > 1 or context.scene.rlm.include_all_scenes:
output_name = r'{rlayer}/' + output_name
# add scene token if include_all_scenes is enabled and there are multiple viewlayers in different scenes with the same name
if context.scene.rlm.include_all_scenes and filter_scene_viewlayers():
output_name = r'{scene_name}/' + output_name
version = 'v%02d' % context.scene.rlm.version
# list every file output node and start setting the output paths
for file_output in file_outputs:
# get media type and file format
media_type = file_output.format.media_type
file_format = file_output.format.file_format
# get rlayer token for every file output node
if not [i for i in file_output.inputs if i.links]:
continue
# update composite file output node different
if '-Composite_FileOutput-' in file_output.name:
file_output.directory = output_dir
comp_path = f'comp/{version}/'
if context.scene.rlm.include_all_scenes:
comp_path = f'comp/{scene_name}/{version}/'
file_output.file_name = comp_path
continue
rlayer = file_output.inputs[0].links[0].from_node.layer
if '_Crypto' in rlayer:
rlayer = rlayer.replace('_Crypto', '')
# set the directory
file_output.directory = output_dir
# set the file name and file output items name
if media_type != 'IMAGE':
file_name = output_name
if file_output.name.endswith('_Crypto_FileOutput-RLM'):
file_name = os.path.join(os.path.dirname(output_name), "Cryptomattes", os.path.basename(output_name))
try:
file_name = file_name.format(
ext='EXR',
version=version,
rlayer=rlayer,
camera_name="{camera_name}",
blend_name="{blend_name}",
scene_name="{scene_name}",
)
file_output.file_name = file_name.replace(os.sep, '/')+'####'
except (KeyError, ValueError):
return False
else:
file_name = os.path.dirname(output_name)+'/'
ext = file_format
ext = convert_ext(ext)
try:
file_name = file_name.format(
ext=ext,
version=version,
rlayer=rlayer,
camera_name="{camera_name}",
blend_name="{blend_name}",
scene_name="{scene_name}",
)
file_output.file_name = file_name.replace(os.sep, '/')
except (KeyError, ValueError):
return False
# change the paths for every file output item based on the tokens in the output_name
for item in file_output.file_output_items:
# get custom name
addon_prefs = bpy.context.preferences.addons[__package__].preferences
view_layer = context.scene.view_layers[rlayer]
rl_passes = view_layer.passes
rpass = file_output.inputs[item.name].links[0].from_socket.name
number = None
if rpass.startswith('Crypto'):
number = rpass[-2:]
rpass = rpass[:-2]
if rpass == 'Image':
custom_name = view_layer.image.custom_name
elif rpass in rl_passes.keys():
custom_name = rl_passes[rpass].custom_name
if number:
custom_name += number
elif rpass.startswith('Combined_'):
custom_name = rpass.replace('Combined', addon_prefs.output_passes['Lightgroup'].custom_name)
else:
custom_name = rpass
# get file format for file output item
if item.override_node_format:
ext = item.format.file_format
else:
ext = file_format
# get the short string of the file format
ext = convert_ext(ext)
# generate renderlayer pass with tokens and replace item name with it
item_name = os.path.basename(output_name)
try:
item_name = item_name.format(
ext=ext,
version=version,
rlayer=rlayer,
camera_name="{camera_name}",
blend_name="{blend_name}",
scene_name="{scene_name}",
)
item.name = item_name + custom_name + '_####'
except (KeyError, ValueError):
return False
return True
def convert_ext(ext):
'''Convert extension string in short string
:param ext: string e.g. 'OPEN_EXR'
:return: string
'''
if 'OPEN_EXR' in ext:
ext = 'EXR'
elif 'CINEON' in ext:
ext = 'CIN'
elif 'TARGA' in ext:
ext = 'TGA'
elif 'JPEG' in ext:
ext = 'JPG'
return ext
def list_excluded_file_formats():
'''List of all file formats that must not be used
:return: list
'''
exclusion_list = [
'AVI_JPEG',
'AVI_RAW',
'FFMPEG',
]
return exclusion_list
def list_data_passes():
'''List all data passes strings
:return: list of data passes
'''
data_passes = [
'Depth', 'Mist', 'Normal', 'Vector', 'UV', 'IndexOB', 'IndexMA',
'CryptoObject00', 'CryptoObject01', 'CryptoObject02', 'CryptoObject03',
'CryptoObject04', 'CryptoObject05', 'CryptoObject06', 'CryptoObject07',
'CryptoMaterial00', 'CryptoMaterial01', 'CryptoMaterial02', 'CryptoMaterial03',
'CryptoMaterial04', 'CryptoMaterial05', 'CryptoMaterial06', 'CryptoMaterial07',
'CryptoAsset00', 'CryptoAsset01', 'CryptoAsset02', 'CryptoAsset03',
'CryptoAsset04', 'CryptoAsset05', 'CryptoAsset06', 'CryptoAsset07',
'Denoising Normal', 'Denoising Depth'
]
if bpy.app.version >= (3,0):
data_passes.append('Position')
return data_passes
def list_tokens():
'''List all render tokens as enum
:return: enum
'''
token_enum = (
('{camera_name}', 'Camera Name', ''),
('{ext}', 'Extension', ''),
#('{rpass}', 'Pass', ''),
('{rlayer}', 'Renderlayer', ''),
('{scene_name}', 'Scene Name', ''),
('{version}', 'Version', ''),
('{blend_name}', 'File Name', ''),
('/', '/', ''),
('_', '_', ''),
('CLEAR', 'Clear', '')
)
return token_enum
def exclude_settings():
'''List viewlayer properties that should be excluded
:return: list
'''
settings = ['name', 'color', 'use', 'composite', 'order', 'active_pass_idx', 'include_all_scenes']
return settings
def list_renderpasses():
'''List all possible renderpasses
:return: dict{'AOV': 'name', 'type'}
'''
passes = {
'Image': ['Beauty', 'light', ''],
'Alpha': ['Alpha', 'data', ''],
'Depth': ['Depth', 'data', 'use_pass_z'],
'Mist': ['Mist', 'data', 'use_pass_mist'],
'Position': ['Position', 'data', 'use_pass_position'],
'Normal': ['Normal', 'data', 'use_pass_normal'],
'Vector': ['Vector', 'data', 'use_pass_vector'],
'UV': ['UV', 'data', 'use_pass_uv'],
'Object Index': ['ObjectIndex', 'data', 'use_pass_object_index'],
'Material Index': ['MaterialIndex', 'data', 'use_pass_material_index'],
'Diffuse Direct': ['DiffuseDirect', 'light', 'use_pass_diffuse_direct'],
'Diffuse Indirect': ['DiffuseIndirect', 'light', 'use_pass_diffuse_indirect'],
'Diffuse Color': ['DiffuseColor', 'light', 'use_pass_diffuse_color'],
'Glossy Direct': ['GlossyDirect', 'light', 'use_pass_glossy_direct'],
'Glossy Indirect': ['GlossyIndirect', 'light', 'use_pass_glossy_indirect'],
'Glossy Color': ['GlossyColor', 'light', 'use_pass_glossy_color'],
'Transmission Direct': ['TransmissionDirect', 'light', 'use_pass_transmission_direct'],
'Transmission Indirect': ['TransmissionIndirect', 'light', 'use_pass_transmission_indirect'],
'Transmission Color': ['TransmissionColor', 'light', 'use_pass_transmission_color'],
'Volume Direct': ['VolumeDirect', 'light', 'use_pass_volume_direct'],
'Volume Indirect': ['VolumeIndirect', 'light', 'cycles.use_pass_volume_indirect'],
'Emission': ['Emission', 'light', 'use_pass_emit'],
'Environment': ['Environment', 'light', 'use_pass_environment'],
'Shadow': ['Shadow', 'light', 'use_pass_shadow'],
'Ambient Occlusion': ['AmbientOcclusion', 'light', 'use_pass_ambient_occlusion'],
'Transparent': ['Transparent', 'light', 'eevee.use_pass_transparent'],
'Shadow Catcher': ['ShadowCatcher', 'light', 'cycles.use_pass_shadow_catcher'],
'Debug Sample Count': ['DebugSampleCount', 'data', 'cycles.pass_debug_sample_count'],
'CryptoObject': ['CryptoObject', 'misc', 'use_pass_cryptomatte_object'],
'CryptoMaterial': ['CryptoMaterial', 'misc', 'use_pass_cryptomatte_material'],
'CryptoAsset': ['CryptoAsset', 'misc', 'use_pass_cryptomatte_asset'],
'Noisy Image': ['NoisyImage', 'data', ''],
'Noisy Shadow Catcher': ['NoisyShadowCatcher', 'light', ''],
'Denoising Data': ['DenoisingData', 'data', 'cycles.denoising_store_passes'],
'Lightgroup': ['Combined', 'misc', ''],
'Grease Pencil': ['GreasePencil', 'misc', 'use_grease_pencil'],
}
return passes
def sync_lightgroups(view_layer=None):
try:
import bpy
except Exception:
return
if not view_layer:
view_layer = bpy.context.view_layer if bpy.context and bpy.context.view_layer else None
if not view_layer:
return
if bpy.app.version < (3, 2, 0):
return
if not hasattr(view_layer, 'lightgroups') or not hasattr(view_layer, 'lightgroup_settings'):
return
try:
present = set(view_layer.lightgroups.keys())
if not present:
return
except Exception:
return
settings = view_layer.lightgroup_settings
for idx in reversed(range(len(settings))):
lg = settings[idx]
if lg.name not in present:
settings.remove(idx)
existing = {lg.name for lg in settings}
for name in sorted(present - existing):
lg = settings.add()
lg.name = name
try:
lg.denoise = True
lg.file_format = '---'
except Exception:
pass
try:
view_layer.rlm_active_lightgroup_index = min(view_layer.rlm_active_lightgroup_index, max(0, len(settings) - 1))
except Exception:
pass
def are_lightgroups_in_sync(view_layer=None):
try:
import bpy
except Exception:
return False
if not view_layer:
view_layer = bpy.context.view_layer if bpy.context and bpy.context.view_layer else None
if not view_layer:
return False
if bpy.app.version < (3, 2, 0):
return True
if not hasattr(view_layer, 'lightgroups') or not hasattr(view_layer, 'lightgroup_settings'):
return True
try:
present = set(view_layer.lightgroups.keys())
except Exception:
return False
settings = view_layer.lightgroup_settings
names = {lg.name for lg in settings}
return present == names
def set_cycles_lightgroups_from_settings(view_layer=None):
try:
import bpy
except Exception:
return
if not view_layer:
view_layer = bpy.context.view_layer if bpy.context and bpy.context.view_layer else None
if not view_layer:
return
if bpy.app.version < (3, 2, 0):
return
if not hasattr(view_layer, 'lightgroups') or not hasattr(view_layer, 'lightgroup_settings'):
return
try:
view_layer_names = set()
for lg in view_layer.lightgroup_settings:
name = getattr(lg, 'name', '')
if name:
view_layer_names.add(name)
if not view_layer_names:
return
try:
cycles_names = set(view_layer.lightgroups.keys())
except Exception:
cycles_names = set()
for name in view_layer_names:
if name not in cycles_names:
try:
if hasattr(view_layer.lightgroups, 'new'):
view_layer.lightgroups.new(name=name)
else:
item = view_layer.lightgroups.add()
item.name = name
except Exception:
pass
for name in list(cycles_names):
if name not in view_layer_names:
try:
if hasattr(view_layer.lightgroups, 'remove'):
view_layer.lightgroups.remove(view_layer.lightgroups[name])
elif hasattr(view_layer.lightgroups, 'clear'):
view_layer.lightgroups.clear()
break
except Exception:
pass
except Exception:
pass
def get_viewlayer_settings(context, settings={}):
'''Get all viewlayer settings and list them in a dictionary
:param context: <bpy_struct, Context>
:param settings (optional): dictionary of viewlayer settings
:return: dict
'''
scenes = bpy.data.scenes
for scn in scenes:
rlm = scn.rlm
viewlayers = scn.view_layers
settings[scn.name] = {}
settings[scn.name]['Renderer'] = scn.render.engine
image_settings = [x.identifier for x in scn.render.image_settings.bl_rna.properties if x.identifier not in {'rna_type'} and not x.is_readonly]
settings[scn.name]['Image Settings'] = [getattr(scn.render.image_settings, x) for x in image_settings]
rlm_settings = [
x.identifier for x in rlm.rna_type.properties if x.identifier not in ['rna_type', 'name', 'active_renderlayer_index', 'output_dir', \
'output_name', 'version', 'write_noisy_image', 'active_pass_idx', 'auto_update_paths']
]
settings[scn.name]['RLM'] = [getattr(rlm, x) for x in rlm_settings]
# add true for write_noisy_image only if use_denoising is also enabled
if scn.cycles.use_denoising and rlm.write_noisy_image:
settings[scn.name]['RLM'].extend([True])
else:
settings[scn.name]['RLM'].extend([False])
settings[scn.name]['Viewlayer'] = {}
for viewlayer in viewlayers:
viewlayer_settings = []
rlm_settings = [
list(viewlayer.color),
viewlayer.composite,
viewlayer.override_file_format,
viewlayer.order,
]
rlm_settings.extend(getattr(viewlayer.image.image_settings, x.identifier) for x in viewlayer.image.image_settings.bl_rna.properties if x.identifier not in {'rna_type'} and not x.is_readonly)
rlm_settings.extend(getattr(viewlayer.image_settings, x.identifier) for x in viewlayer.image_settings.bl_rna.properties if x.identifier not in {'rna_type'} and not x.is_readonly)
general_settings = [
getattr(viewlayer, x.identifier) for x in viewlayer.rna_type.properties if x.identifier.startswith('use_pass_') or x.identifier.startswith('pass_')
]
cycles_settings = [
getattr(viewlayer.cycles, x.identifier) for x in viewlayer.cycles.rna_type.properties if x.identifier.startswith('use_pass_')
]
cycles_settings.extend([viewlayer.cycles.denoising_store_passes])
eevee_settings = [
getattr(viewlayer.eevee, x.identifier) for x in viewlayer.eevee.rna_type.properties if x.identifier.startswith('use_pass_')
]
aovs = [(x.name, x.type) for x in viewlayer.aovs]
rl_passes = []
for rl_pass in viewlayer.passes:
rl_passes.append([
rl_pass.custom_name,
[getattr(rl_pass.image_settings, x.identifier) for x in rl_pass.image_settings.bl_rna.properties if x.identifier not in {'rna_type'} and not x.is_readonly]
])
viewlayer_settings = [rlm_settings, general_settings, cycles_settings, eevee_settings, aovs, rl_passes]
if bpy.app.version >= (3, 2, 0):
light_grps = viewlayer.lightgroups.keys()
viewlayer_settings.append(light_grps)
settings[scn.name]['Viewlayer'][viewlayer.name] = viewlayer_settings
return settings
def check_viewlayer_settings(context):
'''Compares stored viewlayer settings with current viewlayer settings.
Returns True if they match, False otherwise.
:param context: <bpy_struct, Context>
:return: bool
'''
cur_settings = get_viewlayer_settings(context)
if context.scene.name in VIEWLAYER_SETTINGS.keys():
if not context.scene.rlm.include_all_scenes:
if cur_settings[context.scene.name] == VIEWLAYER_SETTINGS[context.scene.name]:
return True
else:
if cur_settings == VIEWLAYER_SETTINGS:
return True
return False
def normalize_viewlayer_order():
'''Remove all gaps in the viewlayer order with range starting at 0
'''
viewlayers = bpy.context.scene.view_layers
viewlayers = sorted(viewlayers, key=lambda l: l.order)
count = 0
for vlayer in viewlayers:
vlayer.order = count
count += 1
return
def move_viewlayer_order(vlayer, direction=None):
'''Move viewlayer up or down in order. If no direction is given, viewlayer gets moved at the end of the list.
Returns True if viewlayer was moved, False if not.
:param vlayer: <bpy_struct, ViewLayer>
:param direction (optional): str "UP" or "DOWN"
:return: bool
'''
viewlayers = bpy.context.scene.view_layers
last_idx = len(viewlayers)-1
cur_idx = vlayer.order
normalize_viewlayer_order()
if not direction:
vlayer.order = last_idx
else:
new_idx = cur_idx + (-1 if direction == 'UP' else 1)
if new_idx < 0 or new_idx > last_idx:
return False
vlayer_b = [x for x in viewlayers if x.order == new_idx][0]
vlayer_b.order = vlayer_b.order + (1 if direction == 'UP' else -1)
vlayer.order = new_idx
return True
def set_renderpasses(rlayer):
'''Set all renderpasses for the given viewlayer based on the items in its renderpass collection property.
:param rlayer: <bpy_struct, ViewLayer>
'''
renderpasses = list_renderpasses()
rl_passes = rlayer.passes
for rl_pass in renderpasses.keys():
value = True if rl_pass in rl_passes else False
attr = renderpasses[rl_pass][2]
if not attr:
continue
if '.' in attr:
if attr.split('.')[0] == 'cycles':
setattr(rlayer.cycles, attr.split('.')[1], value)
elif attr.split('.')[0] == 'eevee':
setattr(rlayer.eevee, attr.split('.')[1], value)
elif attr == 'use_pass_volume_direct':
setattr(rlayer.cycles, attr, value)
setattr(rlayer.eevee, attr, value)
else:
setattr(rlayer, attr, value)
return
def get_image_format_settings(rl_pass):
'''Read all image format settings attributes of the given property "rl_pass" and returns them in a dictionary.
:param rl_pass: Property with ImageFormatSettings attribute
:return: dict {attribute_name: value}
'''
img_settings = {}
attrs = [x.identifier for x in rl_pass.image_settings.bl_rna.properties if x.identifier not in {'bl_rna', 'name'} and not x.is_readonly]
for attr in attrs:
img_settings[attr] = getattr(rl_pass.image_settings, attr)
# get color management settings from a different path if given property is scene.render
if rl_pass == bpy.context.scene.render:
img_settings['view_transform'] = rl_pass.image_settings.view_settings.view_transform
img_settings['display_device'] = rl_pass.image_settings.display_settings.display_device
img_settings['color_space'] = rl_pass.image_settings.linear_colorspace_settings.name
return img_settings
def set_image_format_settings(prop, img_settings, item=False):
'''Set image format settings of the given property "prop" from the entries of the given dictionary "img_settings".
If property is a file output item, set item to True.
:param prop: Property with ImageFormatSettings attribute
:param img_settings: dict {attribute_name: value}
:param item: bool (optional)
'''
# set image format settings from dictionary
for key in [*img_settings]:
# set 'save_as_render' only for file output node items
if key == 'save_as_render':
if item:
setattr(prop, key, img_settings[key])
continue
# ignore color management settings
elif key in ['view_transform', 'display_device', 'color_space']:
continue
# set color mode to RGB if not supported by current file format
elif key == 'color_mode':
try:
prop.format.color_mode = img_settings['color_mode']
except TypeError:
prop.format.color_mode = 'RGB'
continue
# set color depth to next lower depth if not supported by current file format
elif key == 'color_depth':
color_depth_list = ['8', '10', '12', '16', '32']
color_depth = img_settings['color_depth']
while prop.format.color_depth != color_depth:
try:
prop.format.color_depth = color_depth
except TypeError:
idx = color_depth_list.index(color_depth)-1
color_depth = color_depth_list[idx]
continue
# set image format setting
if hasattr(prop.format, key):
setattr(prop.format, key, img_settings[key])
# set color management settings
if img_settings['file_format'] in ['CINEON', 'DPX', 'OPEN_EXR_MULTILAYER', 'OPEN_EXR', 'HDR']:
if img_settings['color_space'] != '---':
if item:
prop.override_node_format = True
prop.format.color_management = img_settings['color_management'] if 'color_management' in img_settings.keys() else 'OVERRIDE'
prop.format.linear_colorspace_settings.name = img_settings['color_space']
else:
if img_settings['view_transform'] != '---' and img_settings['display_device'] != '---':
if item:
prop.override_node_format = True
prop.format.color_management = img_settings['color_management'] if 'color_management' in img_settings.keys() else 'OVERRIDE'
prop.format.view_settings.view_transform = img_settings['view_transform']
prop.format.display_settings.display_device = img_settings['display_device']
return