-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathBakeToLayer.py
2855 lines (2287 loc) · 109 KB
/
BakeToLayer.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
import bpy, re, time, math, bmesh
from bpy.props import *
from mathutils import *
from .common import *
from .bake_common import *
from .subtree import *
from .input_outputs import *
from .node_connections import *
from .node_arrangements import *
from . import lib, Layer, Mask, ImageAtlas, UDIM, vector_displacement_lib, vector_displacement
TEMP_VCOL = '__temp__vcol__'
TEMP_EMISSION = '_TEMP_EMI_'
class YTryToSelectBakedVertexSelect(bpy.types.Operator):
bl_idname = "node.y_try_to_select_baked_vertex"
bl_label = "Try to reselect baked selected vertex"
bl_description = "Try to reselect baked selected vertex. It might give you wrong results if mesh number of vertex changed"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return get_active_ypaint_node() and context.object.type == 'MESH'
def execute(self, context):
if not hasattr(context, 'bake_info'):
return {'CANCELLED'}
bi = context.bake_info
if len(bi.selected_objects) == 0:
return {'CANCELLED'}
if context.object.mode != 'OBJECT':
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.select_all(action='DESELECT')
scene_objs = get_scene_objects()
objs = []
for bso in bi.selected_objects:
if is_bl_newer_than(2, 79):
bsoo = bso.object
else: bsoo = scene_objs.get(bso.object_name)
if bsoo and bsoo not in objs:
objs.append(bsoo)
# Get actual selectable objects
actual_selectable_objs = []
for o in objs:
if is_bl_newer_than(2, 80):
layer_cols = get_object_parent_layer_collections([], bpy.context.view_layer.layer_collection, o)
#for lc in layer_cols:
# print(lc.name)
if layer_cols and not any([lc for lc in layer_cols if lc.exclude or lc.hide_viewport or lc.collection.hide_viewport]):
actual_selectable_objs.append(o)
else:
if not o.hide_select and in_active_279_layer(o):
actual_selectable_objs.append(o)
if len(actual_selectable_objs) == 0:
self.report({'ERROR'}, "Cannot select the object!")
return {'CANCELLED'}
for obj in actual_selectable_objs:
set_object_hide(obj, False)
set_object_select(obj, True)
set_active_object(actual_selectable_objs[0])
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.reveal()
bpy.ops.mesh.select_all(action='DESELECT')
for bso in bi.selected_objects:
if is_bl_newer_than(2, 79):
obj = bso.object
else: obj = scene_objs.get(bso.object_name)
if not obj or obj not in actual_selectable_objs: continue
mesh = obj.data
bm = bmesh.from_edit_mesh(mesh)
bm.verts.ensure_lookup_table()
bm.edges.ensure_lookup_table()
bm.faces.ensure_lookup_table()
if bi.selected_face_mode:
context.tool_settings.mesh_select_mode[0] = False
context.tool_settings.mesh_select_mode[1] = False
context.tool_settings.mesh_select_mode[2] = True
for bsv in bso.selected_vertex_indices:
try: bm.faces[bsv.index].select = True
except: pass
else:
context.tool_settings.mesh_select_mode[0] = True
context.tool_settings.mesh_select_mode[1] = False
context.tool_settings.mesh_select_mode[2] = False
for bsv in bso.selected_vertex_indices:
try: bm.verts[bsv.index].select = True
except: pass
return {'FINISHED'}
class YRemoveBakeInfoOtherObject(bpy.types.Operator):
bl_idname = "node.y_remove_bake_info_other_object"
bl_label = "Remove other object info"
bl_description = "Remove other object bake info, so it won't be automatically baked anymore if you choose to rebake"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return get_active_ypaint_node() and context.object.type == 'MESH'
def execute(self, context):
if not hasattr(context, 'other_object') or not hasattr(context, 'bake_info'):
return {'CANCELLED'}
#if len(context.bake_info.other_objects) == 1:
# self.report({'ERROR'}, "Cannot delete, need at least one object!")
# return {'CANCELLED'}
for i, oo in enumerate(context.bake_info.other_objects):
if oo == context.other_object:
context.bake_info.other_objects.remove(i)
break
return {'FINISHED'}
def update_bake_to_layer_uv_map(self, context):
if not UDIM.is_udim_supported(): return
if get_user_preferences().enable_auto_udim_detection:
mat = get_active_material()
objs = get_all_objects_with_same_materials(mat)
self.use_udim = UDIM.is_uvmap_udim(objs, self.uv_map)
class YBakeToLayer(bpy.types.Operator, BaseBakeOperator):
bl_idname = "node.y_bake_to_layer"
bl_label = "Bake To Layer"
bl_description = "Bake something as layer/mask"
bl_options = {'REGISTER', 'UNDO'}
name : StringProperty(default='')
uv_map : StringProperty(default='', update=update_bake_to_layer_uv_map)
uv_map_coll : CollectionProperty(type=bpy.types.PropertyGroup)
uv_map_1 : StringProperty(default='')
interpolation : EnumProperty(
name = 'Image Interpolation Type',
description = 'Image interpolation type',
items = interpolation_type_items,
default = 'Linear'
)
# For choosing overwrite entity from list
overwrite_choice : BoolProperty(
name = 'Overwrite available layer',
description = 'Overwrite available layer',
default = False
)
# For rebake button
overwrite_current : BoolProperty(default=False)
overwrite_name : StringProperty(default='')
overwrite_coll : CollectionProperty(type=bpy.types.PropertyGroup)
overwrite_image_name : StringProperty(default='')
overwrite_segment_name : StringProperty(default='')
type : EnumProperty(
name = 'Bake Type',
description = 'Bake Type',
items = bake_type_items,
default = 'AO'
)
# Other objects props
cage_object_name : StringProperty(
name = 'Cage Object',
description = 'Object to use as cage instead of calculating the cage from the active object with cage extrusion',
default = ''
)
cage_object_coll : CollectionProperty(type=bpy.types.PropertyGroup)
cage_extrusion : FloatProperty(
name = 'Cage Extrusion',
description = 'Inflate the active object by the specified distance for baking. This helps matching to points nearer to the outside of the selected object meshes',
default=0.2, min=0.0, max=1.0
)
max_ray_distance : FloatProperty(
name = 'Max Ray Distance',
description = 'The maximum ray distance for matching points between the active and selected objects. If zero, there is no limit',
default=0.2, min=0.0, max=1.0
)
# AO Props
ao_distance : FloatProperty(default=1.0)
# Bevel Props
bevel_samples : IntProperty(default=4, min=2, max=16)
bevel_radius : FloatProperty(default=0.05, min=0.0, max=1000.0)
multires_base : IntProperty(default=1, min=0, max=16)
target_type : EnumProperty(
name = 'Target Bake Type',
description = 'Target Bake Type',
items = (
('LAYER', 'Layer', ''),
('MASK', 'Mask', '')
),
default='LAYER'
)
fxaa : BoolProperty(
name = 'Use FXAA',
description = "Use FXAA on baked image (doesn't work with float images)",
default = True
)
ssaa : BoolProperty(
name = 'Use SSAA',
description = "Use Supersample AA on baked image",
default = False
)
denoise : BoolProperty(
name = 'Use Denoise',
description = "Use Denoise on baked image",
default = True
)
channel_idx : EnumProperty(
name = 'Channel',
description = 'Channel of new layer, can be changed later',
items = Layer.channel_items
)
blend_type : EnumProperty(
name = 'Blend',
items = blend_type_items,
)
normal_blend_type : EnumProperty(
name = 'Normal Blend Type',
items = normal_blend_items,
default = 'MIX'
)
normal_map_type : EnumProperty(
name = 'Normal Map Type',
description = 'Normal map type of this layer',
items = Layer.get_normal_map_type_items
)
hdr : BoolProperty(name='32 bit Float', default=True)
use_baked_disp : BoolProperty(
name = 'Use Displacement Setup',
description = 'Use displacement setup, this will also apply subdiv setup on object',
default = False
)
flip_normals : BoolProperty(
name = 'Flip Normals',
description = 'Flip normal of mesh',
default = False
)
only_local : BoolProperty(
name = 'Only Local',
description = 'Only bake local ambient occlusion',
default = False
)
subsurf_influence : BoolProperty(
name = 'Subsurf / Multires Influence',
description = 'Take account subsurf or multires when baking cavity',
default = True
)
force_bake_all_polygons : BoolProperty(
name = 'Force Bake all Polygons',
description = 'Force bake all polygons, useful if material is not using direct polygon (ex: solidify material)',
default = False
)
use_image_atlas : BoolProperty(
name = 'Use Image Atlas',
description = 'Use Image Atlas',
default = False
)
use_udim : BoolProperty(
name = 'Use UDIM Tiles',
description = 'Use UDIM Tiles',
default = False
)
@classmethod
def poll(cls, context):
return get_active_ypaint_node() and context.object.type == 'MESH'
@classmethod
def description(self, context, properties):
return get_operator_description(self)
def invoke(self, context, event):
self.invoke_operator(context)
if hasattr(context, 'entity'):
self.entity = context.entity
else: self.entity = None
obj = self.obj = context.object
scene = self.scene = context.scene
node = get_active_ypaint_node()
yp = node.node_tree.yp
ypup = get_user_preferences()
# UDIM is turned off by default
#self.use_udim = False
# Default normal map type is bump
self.normal_map_type = 'BUMP_MAP'
# Default FXAA is on
#self.fxaa = True
# Default samples is 1
self.samples = 1
# Set channel to first one, just in case
if len(yp.channels) > 0:
self.channel_idx = str(0)
# Get height channel
height_root_ch = get_root_height_channel(yp)
# Set default float image
if self.type in {'POINTINESS', 'MULTIRES_DISPLACEMENT', 'BEVEL_MASK'}:
self.hdr = True
else:
self.hdr = False
# Set name
mat = get_active_material()
if self.type == 'AO':
self.blend_type = 'MULTIPLY'
self.samples = 32
# Check Ambient occlusion channel if available
for i, c in enumerate(yp.channels):
if c.name in {'Ambient Occlusion', 'AO'}:
self.channel_idx = str(i)
break
elif self.type == 'POINTINESS':
self.blend_type = 'ADD'
self.fxaa = False
elif self.type == 'CAVITY':
self.blend_type = 'ADD'
elif self.type == 'DUST':
self.blend_type = 'MIX'
elif self.type == 'PAINT_BASE':
self.blend_type = 'MIX'
elif self.type == 'BEVEL_NORMAL':
self.blend_type = 'MIX'
self.normal_blend_type = 'OVERLAY'
self.use_baked_disp = False
self.samples = 32
if height_root_ch:
self.channel_idx = str(get_channel_index(height_root_ch))
self.normal_map_type = 'NORMAL_MAP'
elif self.type == 'BEVEL_MASK':
self.blend_type = 'MIX'
self.use_baked_disp = False
self.samples = 32
elif self.type == 'MULTIRES_NORMAL':
self.blend_type = 'MIX'
if height_root_ch:
self.channel_idx = str(get_channel_index(height_root_ch))
self.normal_map_type = 'NORMAL_MAP'
self.normal_blend_type = 'OVERLAY'
elif self.type == 'MULTIRES_DISPLACEMENT':
self.blend_type = 'MIX'
if height_root_ch:
self.channel_idx = str(get_channel_index(height_root_ch))
self.normal_map_type = 'BUMP_MAP'
self.normal_blend_type = 'OVERLAY'
elif self.type == 'OTHER_OBJECT_EMISSION':
self.subsurf_influence = False
self.margin = 0
elif self.type in {'OTHER_OBJECT_NORMAL', 'OBJECT_SPACE_NORMAL'}:
self.subsurf_influence = False
if height_root_ch:
self.channel_idx = str(get_channel_index(height_root_ch))
self.normal_map_type = 'NORMAL_MAP'
self.normal_blend_type = 'OVERLAY'
if self.type == 'OTHER_OBJECT_NORMAL':
self.margin = 0
elif self.type == 'OTHER_OBJECT_CHANNELS':
self.subsurf_influence = False
self.use_image_atlas = False
self.margin = 0
elif self.type == 'SELECTED_VERTICES':
self.subsurf_influence = False
self.use_baked_disp = False
elif self.type == 'FLOW':
self.blend_type = 'MIX'
# Check flow channel if available
for i, c in enumerate(yp.channels):
if 'flow' in c.name.lower():
self.channel_idx = str(i)
break
suffix = bake_type_suffixes[self.type]
self.name = get_unique_name(mat.name + ' ' + suffix, bpy.data.images)
self.overwrite_choice = False
self.overwrite_name = ''
overwrite_entity = None
if self.overwrite_current:
overwrite_entity = self.entity
# Other object and selected vertices bake will not display overwrite choice
elif not self.type.startswith('OTHER_OBJECT_') and self.type not in {'SELECTED_VERTICES'}:
#else:
# Clear overwrite_coll
self.overwrite_coll.clear()
# Get overwritable layers
if self.target_type == 'LAYER':
for layer in yp.layers:
if layer.type == 'IMAGE':
source = get_layer_source(layer)
if source.image:
img = source.image
if img.y_bake_info.is_baked and img.y_bake_info.bake_type == self.type:
self.overwrite_coll.add().name = layer.name
elif img.yia.is_image_atlas or img.yua.is_udim_atlas:
if img.yia.is_image_atlas:
segment = img.yia.segments.get(layer.segment_name)
else: segment = img.yua.segments.get(layer.segment_name)
if segment and segment.bake_info.is_baked and segment.bake_info.bake_type == self.type:
self.overwrite_coll.add().name = layer.name
# Get overwritable masks
elif len(yp.layers) > 0:
active_layer = yp.layers[yp.active_layer_index]
for mask in active_layer.masks:
if mask.type == 'IMAGE':
source = get_mask_source(mask)
if source.image:
img = source.image
if img.y_bake_info.is_baked and img.y_bake_info.bake_type == self.type:
self.overwrite_coll.add().name = mask.name
elif img.yia.is_image_atlas or img.yua.is_udim_atlas:
if img.yia.is_image_atlas:
segment = img.yia.segments.get(mask.segment_name)
else: segment = img.yua.segments.get(mask.segment_name)
if segment and segment.bake_info.is_baked and segment.bake_info.bake_type == self.type:
self.overwrite_coll.add().name = mask.name
if len(self.overwrite_coll) > 0:
self.overwrite_choice = True
if self.target_type == 'LAYER':
overwrite_entity = yp.layers.get(self.overwrite_coll[0].name)
else:
active_layer = yp.layers[yp.active_layer_index]
overwrite_entity = active_layer.masks.get(self.overwrite_coll[0].name)
else:
self.overwrite_choice = False
self.overwrite_image_name = ''
self.overwrite_segment_name = ''
if overwrite_entity:
if self.target_type == 'LAYER':
source = get_layer_source(overwrite_entity)
else: source = get_mask_source(overwrite_entity)
bi = None
if overwrite_entity.type == 'IMAGE' and source.image:
self.overwrite_image_name = source.image.name
if not source.image.yia.is_image_atlas and not source.image.yua.is_udim_atlas:
self.overwrite_name = source.image.name
self.width = source.image.size[0] if source.image.size[0] != 0 else int(ypup.default_image_resolution)
self.height = source.image.size[1] if source.image.size[1] != 0 else int(ypup.default_image_resolution)
self.use_image_atlas = False
bi = source.image.y_bake_info
else:
self.overwrite_name = overwrite_entity.name
self.overwrite_segment_name = overwrite_entity.segment_name
if source.image.yia.is_image_atlas:
segment = source.image.yia.segments.get(overwrite_entity.segment_name)
self.width = segment.width
self.height = segment.height
else:
segment = source.image.yua.segments.get(overwrite_entity.segment_name)
tilenums = UDIM.get_udim_segment_tilenums(segment)
if len(tilenums) > 0:
tile = source.image.tiles.get(tilenums[0])
self.width = tile.size[0]
self.height = tile.size[1]
bi = segment.bake_info
self.use_image_atlas = True
self.hdr = source.image.is_float
# Fill settings using bake info stored on image
if bi:
for attr in dir(bi):
if attr in {'other_objects', 'selected_objects'}: continue
if attr.startswith('__'): continue
if attr.startswith('bl_'): continue
if attr in {'rna_type'}: continue
#if attr in dir(self):
try: setattr(self, attr, getattr(bi, attr))
except: pass
self.uv_map = overwrite_entity.uv_name
# Use active uv layer name by default
uv_layers = get_uv_layers(obj)
# UV Map collections update
self.uv_map_coll.clear()
for uv in uv_layers:
if not uv.name.startswith(TEMP_UV):
self.uv_map_coll.add().name = uv.name
if len(self.uv_map_coll) > 0 and not overwrite_entity: #len(self.overwrite_coll) == 0:
self.uv_map = self.uv_map_coll[0].name
if len(self.uv_map_coll) > 1:
self.uv_map_1 = self.uv_map_coll[1].name
# Cage object collections update
self.cage_object_coll.clear()
for ob in get_scene_objects():
if ob != obj and ob not in bpy.context.selected_objects and ob.type == 'MESH':
self.cage_object_coll.add().name = ob.name
requires_popup = self.type in {'OTHER_OBJECT_NORMAL', 'OTHER_OBJECT_EMISSION', 'OTHER_OBJECT_CHANNELS', 'FLOW'}
if not requires_popup and get_user_preferences().skip_property_popups and not event.shift:
return self.execute(context)
return context.window_manager.invoke_props_dialog(self, width=320)
def check(self, context):
self.check_operator(context)
ypup = get_user_preferences()
# New image cannot use more pixels than the image atlas
if self.use_image_atlas:
if self.hdr: max_size = ypup.hdr_image_atlas_size
else: max_size = ypup.image_atlas_size
if self.width > max_size: self.width = max_size
if self.height > max_size: self.height = max_size
return True
def draw(self, context):
node = get_active_ypaint_node()
yp = node.node_tree.yp
mat = get_active_material()
channel = yp.channels[int(self.channel_idx)] if self.channel_idx != '-1' else None
height_root_ch = get_root_height_channel(yp)
row = split_layout(self.layout, 0.4)
show_subsurf_influence = not self.type.startswith('MULTIRES_') and self.type not in {'SELECTED_VERTICES'}
show_use_baked_disp = height_root_ch and not self.type.startswith('MULTIRES_') and self.type not in {'SELECTED_VERTICES'}
col = row.column(align=False)
if not self.overwrite_current:
if len(self.overwrite_coll) > 0:
col.label(text='Overwrite:')
if len(self.overwrite_coll) > 0 and self.overwrite_choice:
if self.target_type == 'LAYER':
col.label(text='Overwrite Layer:')
else:
col.label(text='Overwrite Mask:')
else:
col.label(text='Name:')
if self.target_type == 'LAYER':
col.label(text='Channel:')
if channel and channel.type == 'NORMAL':
col.label(text='Type:')
else:
col.label(text='Name:')
if self.type.startswith('OTHER_OBJECT_'):
col.label(text='Cage Object:')
col.label(text='Cage Extrusion:')
if hasattr(bpy.context.scene.render.bake, 'max_ray_distance'):
col.label(text='Max Ray Distance:')
elif self.type == 'AO':
col.label(text='AO Distance:')
col.label(text='')
elif self.type in {'BEVEL_NORMAL', 'BEVEL_MASK'}:
col.label(text='Bevel Samples:')
col.label(text='Bevel Radius:')
elif self.type.startswith('MULTIRES_'):
col.label(text='Base Level:')
#elif self.type.startswith('OTHER_OBJECT_'):
# col.label(text='Source Object:')
col.label(text='')
col.label(text='')
if self.use_custom_resolution == False:
col.label(text='Resolution:')
if self.use_custom_resolution == True:
col.label(text='Width:')
col.label(text='Height:')
col.label(text='Samples:')
col.label(text='UV Map:')
if self.type == 'FLOW':
col.label(text='Straight UV Map:')
col.label(text='Margin:')
if is_bl_newer_than(2, 80):
col.separator()
col.label(text='Bake Device:')
col.label(text='Interpolation:')
col.separator()
col.label(text='')
#col.label(text='')
col.label(text='')
#if not self.type.startswith('MULTIRES_'):
if show_subsurf_influence:
col.label(text='')
#if height_root_ch and not self.type.startswith('MULTIRES_'):
if show_use_baked_disp:
col.label(text='')
col.label(text='')
col.label(text='')
if self.type not in {'OTHER_OBJECT_CHANNELS'}:
col.separator()
col.label(text='')
col = row.column(align=False)
if not self.overwrite_current:
if len(self.overwrite_coll) > 0:
col.prop(self, 'overwrite_choice', text='')
if len(self.overwrite_coll) > 0 and self.overwrite_choice:
col.prop_search(self, "overwrite_name", self, "overwrite_coll", text='', icon='IMAGE_DATA')
else:
col.prop(self, 'name', text='')
if self.target_type == 'LAYER':
rrow = col.row(align=True)
rrow.prop(self, 'channel_idx', text='')
if channel:
if channel.type == 'NORMAL':
rrow.prop(self, 'normal_blend_type', text='')
col.prop(self, 'normal_map_type', text='')
else:
rrow.prop(self, 'blend_type', text='')
else:
col.label(text=self.overwrite_name)
if self.type.startswith('OTHER_OBJECT_'):
col.prop_search(self, "cage_object_name", self, "cage_object_coll", text='', icon='OBJECT_DATA')
rrow = col.row(align=True)
rrow.active = self.cage_object_name == ''
rrow.prop(self, 'cage_extrusion', text='')
if hasattr(bpy.context.scene.render.bake, 'max_ray_distance'):
col.prop(self, 'max_ray_distance', text='')
elif self.type == 'AO':
col.prop(self, 'ao_distance', text='')
col.prop(self, 'only_local')
elif self.type in {'BEVEL_NORMAL', 'BEVEL_MASK'}:
col.prop(self, 'bevel_samples', text='')
col.prop(self, 'bevel_radius', text='')
elif self.type.startswith('MULTIRES_'):
col.prop(self, 'multires_base', text='')
col.prop(self, 'hdr')
col.prop(self, 'use_custom_resolution')
crow = col.row(align=True)
if self.use_custom_resolution == False:
crow.prop(self, 'image_resolution', expand= True,)
elif self.use_custom_resolution == True:
col.prop(self, 'width', text='')
col.prop(self, 'height', text='')
col.prop(self, 'samples', text='')
col.prop_search(self, "uv_map", self, "uv_map_coll", text='', icon='GROUP_UVS')
if self.type == 'FLOW':
col.prop_search(self, "uv_map_1", self, "uv_map_coll", text='', icon='GROUP_UVS')
if is_bl_newer_than(3, 1):
split = split_layout(col, 0.4, align=True)
split.prop(self, 'margin', text='')
split.prop(self, 'margin_type', text='')
else:
col.prop(self, 'margin', text='')
if is_bl_newer_than(2, 80):
col.separator()
col.prop(self, 'bake_device', text='')
col.prop(self, 'interpolation', text='')
col.separator()
if self.type.startswith('OTHER_OBJECT_'):
col.prop(self, 'ssaa')
else: col.prop(self, 'fxaa')
if self.type in {'AO', 'BEVEL_MASK'} and is_bl_newer_than(2, 81):
col.prop(self, 'denoise')
col.separator()
#if not self.type.startswith('MULTIRES_') or self.type not in {'SELECTED_VERTICES'}:
if show_subsurf_influence:
r = col.row()
r.active = not self.use_baked_disp
r.prop(self, 'subsurf_influence')
#if height_root_ch and not self.type.startswith('MULTIRES_'):
if show_use_baked_disp:
col.prop(self, 'use_baked_disp')
col.prop(self, 'flip_normals')
col.prop(self, 'force_bake_all_polygons')
if UDIM.is_udim_supported() or self.type not in {'OTHER_OBJECT_CHANNELS'}:
col.separator()
if UDIM.is_udim_supported():
ccol = col.column(align=True)
ccol.prop(self, 'use_udim')
if self.type not in {'OTHER_OBJECT_CHANNELS'}:
ccol = col.column(align=True)
#ccol.active = not self.use_udim
ccol.prop(self, 'use_image_atlas')
def execute(self, context):
T = time.time()
mat = get_active_material()
node = get_active_ypaint_node()
yp = node.node_tree.yp
tree = node.node_tree
ypui = context.window_manager.ypui
scene = context.scene
obj = context.object
ypup = get_user_preferences()
channel_idx = int(self.channel_idx) if len(yp.channels) > 0 else -1
active_layer = None
if len(yp.layers) > 0:
active_layer = yp.layers[yp.active_layer_index]
if self.type == 'SELECTED_VERTICES' and obj.mode != 'EDIT':
self.report({'ERROR'}, "Should be in edit mode!")
return {'CANCELLED'}
if self.target_type == 'MASK' and not active_layer:
self.report({'ERROR'}, "Mask need active layer!")
return {'CANCELLED'}
if (self.overwrite_choice or self.overwrite_current) and self.overwrite_name == '':
self.report({'ERROR'}, "Overwrite layer/mask cannot be empty!")
return {'CANCELLED'}
if self.type in {'BEVEL_NORMAL', 'BEVEL_MASK'} and not is_bl_newer_than(2, 80):
self.report({'ERROR'}, "Blender 2.80+ is needed to use this feature!")
return {'CANCELLED'}
if self.type in {'MULTIRES_NORMAL', 'MULTIRES_DISPLACEMENT'} and not is_bl_newer_than(2, 80):
#self.report({'ERROR'}, "This feature is not implemented yet in Blender 2.79!")
self.report({'ERROR'}, "Blender 2.80+ is needed to use this feature!")
return {'CANCELLED'}
if (hasattr(context.object, 'hide_viewport') and context.object.hide_viewport) or context.object.hide_render:
self.report({'ERROR'}, "Please unhide render and viewport of active object!")
return {'CANCELLED'}
if self.type == 'FLOW' and (self.uv_map == '' or self.uv_map_1 == '' or self.uv_map == self.uv_map_1):
self.report({'ERROR'}, "UVMap and Straight UVMap are cannot be the same or empty!")
return {'CANCELLED'}
cage_object = None
if self.type.startswith('OTHER_OBJECT_') and self.cage_object_name != '':
cage_object = bpy.data.objects.get(self.cage_object_name)
if cage_object:
if any([mod for mod in cage_object.modifiers if mod.type not in {'ARMATURE'}]) or any([mod for mod in obj.modifiers if mod.type not in {'ARMATURE'}]):
self.report({'ERROR'}, "Mesh modifiers is not working with cage object for now!")
return {'CANCELLED'}
if len(cage_object.data.polygons) != len(obj.data.polygons):
self.report({'ERROR'}, "Invalid cage object, the cage mesh must have the same number of faces as the active object!")
return {'CANCELLED'}
# Get all objects using material
if self.type.startswith('MULTIRES_') and not get_multires_modifier(context.object):
objs = []
meshes = []
multires_count = 0
else:
objs = [context.object]
meshes = [context.object.data]
multires_count = 1
if mat.users > 1:
# Emptying the lists again in case active object is problematic
objs = []
meshes = []
for ob in get_scene_objects():
if ob.type != 'MESH': continue
if hasattr(ob, 'hide_viewport') and ob.hide_viewport: continue
if len(get_uv_layers(ob)) == 0: continue
if len(ob.data.polygons) == 0: continue
if cage_object and cage_object == ob: continue
# Do not bake objects with hide_render on
if ob.hide_render: continue
if not in_renderable_layer_collection(ob): continue
if self.type.startswith('MULTIRES_') and get_multires_modifier(ob):
multires_count += 1
for i, m in enumerate(ob.data.materials):
if m == mat:
ob.active_material_index = i
if ob not in objs and ob.data not in meshes:
objs.append(ob)
meshes.append(ob.data)
if not objs or (self.type.startswith('MULTIRES_') and multires_count == 0):
self.report({'ERROR'}, "No valid objects found to bake!")
return {'CANCELLED'}
do_overwrite = False
overwrite_img = None
if (self.overwrite_choice or self.overwrite_current) and self.overwrite_image_name != '':
overwrite_img = bpy.data.images.get(self.overwrite_image_name)
do_overwrite = True
segment = None
if overwrite_img:
if overwrite_img.yia.is_image_atlas:
segment = overwrite_img.yia.segments.get(self.overwrite_segment_name)
elif overwrite_img.yua.is_udim_atlas:
segment = overwrite_img.yua.segments.get(self.overwrite_segment_name)
# Get other objects for other object baking
other_objs = []
if self.type.startswith('OTHER_OBJECT_'):
# Get other objects based on selected objects with different material
for o in context.selected_objects:
if o in objs or not o.data or not hasattr(o.data, 'materials'): continue
if mat.name not in o.data.materials:
other_objs.append(o)
# Try to get other_objects from bake info
if overwrite_img:
bi = segment.bake_info if segment else overwrite_img.y_bake_info
scene_objs = get_scene_objects()
for oo in bi.other_objects:
if is_bl_newer_than(2, 79):
ooo = oo.object
else: ooo = scene_objs.get(oo.object_name)
if ooo:
if is_bl_newer_than(2, 80):
# Check if object is on current view layer
layer_cols = get_object_parent_layer_collections([], bpy.context.view_layer.layer_collection, ooo)
if ooo not in other_objs and any(layer_cols):
other_objs.append(ooo)
else:
o = scene_objs.get(ooo.name)
if o and o not in other_objs:
other_objs.append(o)
if self.type == 'OTHER_OBJECT_CHANNELS':
ch_other_objects, ch_other_mats, ch_other_sockets, ch_other_defaults, ch_other_alpha_sockets, ch_other_alpha_defaults, ori_mat_no_nodes = prepare_other_objs_channels(yp, other_objs)
if not other_objs:
if overwrite_img:
self.report({'ERROR'}, "No source objects found! They're probably deleted!")
else: self.report({'ERROR'}, "Source objects must be selected and it should have different material!")
return {'CANCELLED'}
# Get tile numbers
tilenums = [1001]
if self.use_udim:
tilenums = UDIM.get_tile_numbers(objs, self.uv_map)
# Remember things
book = remember_before_bake(yp, mat=mat)
# FXAA doesn't work with hdr image
# FXAA also does not works well with baked image with alpha, so other object bake will use SSAA instead
use_fxaa = not self.hdr and self.fxaa and not self.type.startswith('OTHER_OBJECT_')
# For now SSAA only works with other object baking
use_ssaa = self.ssaa and self.type.startswith('OTHER_OBJECT_')
# Denoising only available for AO bake for now
use_denoise = self.denoise and self.type in {'AO', 'BEVEL_MASK'} and is_bl_newer_than(2, 81)
# SSAA will multiply size by 2 then resize it back
if use_ssaa:
width = self.width * 2
height = self.height * 2
else:
width = self.width
height = self.height
# If use baked disp, need to bake normal and height map first
subdiv_setup_changes = False
height_root_ch = get_root_height_channel(yp)
if height_root_ch and self.use_baked_disp and not self.type.startswith('MULTIRES_'):
if not height_root_ch.enable_subdiv_setup:
height_root_ch.enable_subdiv_setup = True
subdiv_setup_changes = True
# To hold temporary objects
temp_objs = []
# Sometimes Cavity bake will create temporary objects
if (self.type == 'CAVITY' and (self.subsurf_influence or self.use_baked_disp)):
# NOTE: Baking cavity with subdiv setup can only happen if there's only one object and no UDIM
if is_bl_newer_than(4, 2) and len(objs) == 1 and not self.use_udim and height_root_ch and height_root_ch.enable_subdiv_setup:
# Check if there's VDM layer
vdm_layer = get_first_vdm_layer(yp)
vdm_uv_name = vdm_layer.uv_name if vdm_layer else self.uv_map
# Get baked combined vdm image
combined_vdm_image = vector_displacement.get_combined_vdm_image(objs[0], vdm_uv_name, width=self.width, height=self.height)
# Bake tangent and bitangent
# NOTE: Only bake the first object tangent since baking combined mesh can cause memory leak at the moment
tanimage, bitimage = vector_displacement.get_tangent_bitangent_images(objs[0], self.uv_map)
# Duplicate object
objs = temp_objs = [get_merged_mesh_objects(scene, objs, True, disable_problematic_modifiers=False)]
# Use VDM loader geometry nodes
# NOTE: Geometry nodes currently does not support UDIM, so using UDIM will cause wrong bake result
set_active_object(objs[0])
vdm_loader = vector_displacement_lib.get_vdm_loader_geotree(self.uv_map, combined_vdm_image, tanimage, bitimage, 1.0)
bpy.ops.object.modifier_add(type='NODES')
geomod = objs[0].modifiers[-1]
geomod.node_group = vdm_loader
bpy.ops.object.modifier_apply(modifier=geomod.name)
# Remove temporary datas
remove_datablock(bpy.data.node_groups, vdm_loader)
remove_datablock(bpy.data.images, combined_vdm_image)
else:
objs = temp_objs = get_duplicated_mesh_objects(scene, objs, True)