-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathbake.py
3041 lines (2452 loc) · 124 KB
/
bake.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
# Copyright (C) 2021 Victor Soupday
# This file is part of CC/iC Blender Tools <https://github.com/soupday/cc_blender_tools>
#
# CC/iC Blender Tools 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.
#
# CC/iC Blender Tools 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 CC/iC Blender Tools. If not, see <https://www.gnu.org/licenses/>.
import bpy
import os
from mathutils import Vector
from . import normal, colorspace, imageutils, wrinkle, nodeutils, properties, materials, utils, params, vars
from .exporter import get_export_objects
BAKE_SAMPLES = 4
BAKE_INDEX = 1001
BUMP_BAKE_MULTIPLIER = 2.0
NODE_CURSOR = Vector((0, 0))
def init_bake(id = 1001):
global BAKE_INDEX
BAKE_INDEX = id
def set_cycles_samples(context, samples, adaptive_samples = -1, denoising = False, time_limit = 0, use_gpu = False):
if not context:
context = bpy.context
context.scene.cycles.samples = samples
if utils.B300():
context.scene.cycles.device = 'GPU' if use_gpu else 'CPU'
context.scene.cycles.preview_samples = samples
context.scene.cycles.use_adaptive_sampling = adaptive_samples >= 0
context.scene.cycles.adaptive_threshold = adaptive_samples
context.scene.cycles.use_preview_adaptive_sampling = adaptive_samples >= 0
context.scene.cycles.preview_adaptive_threshold = adaptive_samples
context.scene.cycles.use_denoising = denoising
context.scene.cycles.use_preview_denoising = denoising
context.scene.cycles.use_auto_tile = False
context.scene.cycles.time_limit = time_limit
def prep_bake(context, mat: bpy.types.Material=None, samples=BAKE_SAMPLES, image_format="PNG", make_surface=True):
bake_state = {}
if not context:
context = bpy.context
# cycles settings
bake_state["samples"] = context.scene.cycles.samples
# Blender 3.0
if utils.B300():
bake_state["preview_samples"] = context.scene.cycles.preview_samples
bake_state["use_adaptive_sampling"] = context.scene.cycles.use_adaptive_sampling
bake_state["use_preview_adaptive_sampling"] = context.scene.cycles.use_preview_adaptive_sampling
bake_state["use_denoising"] = context.scene.cycles.use_denoising
bake_state["use_preview_denoising"] = context.scene.cycles.use_preview_denoising
bake_state["use_auto_tile"] = context.scene.cycles.use_auto_tile
# render settings
bake_state["file_format"] = context.scene.render.image_settings.file_format
bake_state["color_depth"] = context.scene.render.image_settings.color_depth
bake_state["color_mode"] = context.scene.render.image_settings.color_mode
bake_state["use_bake_multires"] = context.scene.render.use_bake_multires
bake_state["use_selected_to_active"] = context.scene.render.bake.use_selected_to_active
bake_state["use_pass_direct"] = context.scene.render.bake.use_pass_direct
bake_state["use_pass_indirect"] = context.scene.render.bake.use_pass_indirect
bake_state["margin"] = context.scene.render.bake.margin
bake_state["use_clear"] = context.scene.render.bake.use_clear
bake_state["image_format"] = context.scene.render.image_settings.file_format
# Blender 2.92
if utils.B292():
bake_state["target"] = context.scene.render.bake.target
# color management
bake_state["view_transform"] = context.scene.view_settings.view_transform
bake_state["look"] = context.scene.view_settings.look
bake_state["gamma"] = context.scene.view_settings.gamma
bake_state["exposure"] = context.scene.view_settings.exposure
bake_state["colorspace"] = context.scene.sequencer_colorspace_settings.name
context.scene.cycles.samples = samples
context.scene.render.image_settings.file_format = image_format
context.scene.render.use_bake_multires = False
context.scene.render.bake.use_selected_to_active = False
context.scene.render.bake.use_pass_direct = False
context.scene.render.bake.use_pass_indirect = False
context.scene.render.bake.margin = 16
context.scene.render.bake.use_clear = True
# color management settings affect the baked output so set them to standard/raw defaults:
context.scene.view_settings.view_transform = 'Standard'
context.scene.view_settings.look = 'None'
context.scene.view_settings.gamma = 1
context.scene.view_settings.exposure = 0
colorspace.set_sequencer_color_space("Raw")
# Blender 3.0
if utils.B300():
context.scene.cycles.preview_samples = samples
context.scene.cycles.use_adaptive_sampling = False
context.scene.cycles.use_preview_adaptive_sampling = False
context.scene.cycles.use_denoising = False
context.scene.cycles.use_preview_denoising = False
context.scene.cycles.use_auto_tile = False
# Blender 2.92
if utils.B292():
context.scene.render.bake.target = 'IMAGE_TEXTURES'
# go into wireframe mode (so Blender doesn't update or recompile the material shaders while
# we manipulate them for baking, and also so Blender doesn't fire up the cycles viewport...):
shading: bpy.types.View3DShading = utils.get_view_3d_shading(context)
if shading:
bake_state["shading"] = shading.type
shading.type = 'WIREFRAME'
else:
bake_state["shading"] = 'MATERIAL'
shading.type = 'WIREFRAME'
# set cycles rendering mode for baking
bake_state["engine"] = context.scene.render.engine
context.scene.render.engine = 'CYCLES'
bake_state["cycles_bake_type"] = context.scene.cycles.bake_type
bake_state["render_bake_type"] = context.scene.render.bake_type
context.scene.cycles.bake_type = "COMBINED"
if make_surface:
# deselect everything
bpy.ops.object.select_all(action='DESELECT')
# create the baking plane, a single quad baking surface for an even sampling across the entire texture
bpy.ops.mesh.primitive_plane_add(size=2, enter_editmode=False, align='WORLD', location=(0, 0, 0))
bake_surface = utils.get_active_object()
bake_state["bake_surface"] = bake_surface
set_bake_material(bake_state, mat)
# replicate any material node UV layers in bake surface
if mat and mat.node_tree and mat.node_tree.nodes:
for node in mat.node_tree.nodes:
if node.type == "UVMAP":
uv_name = node.uv_map
mesh: bpy.types.Mesh = bake_surface.data
if uv_name not in mesh.uv_layers:
mesh.uv_layers.new(name=uv_name)
return bake_state
def set_bake_material(bake_state, mat):
if mat and bake_state and "bake_surface" in bake_state:
bake_surface = bake_state["bake_surface"]
if bake_surface:
# attach the material to bake to the baking surface plane
# (the baking plane also ensures that only one material is baked onto only one target image)
if len(bake_surface.data.materials) == 0:
bake_surface.data.materials.append(mat)
else:
bake_surface.data.materials[0] = mat
bake_state["bake_material"] = mat
return True
return False
def post_bake(context, state):
if not context:
context = bpy.context
# cycles settings
context.scene.cycles.samples = state["samples"]
# Blender 3.0
if utils.B300():
context.scene.cycles.preview_samples = state["preview_samples"]
context.scene.cycles.use_adaptive_sampling = state["use_adaptive_sampling"]
context.scene.cycles.use_preview_adaptive_sampling = state["use_preview_adaptive_sampling"]
context.scene.cycles.use_denoising = state["use_denoising"]
context.scene.cycles.use_preview_denoising = state["use_preview_denoising"]
context.scene.cycles.use_auto_tile = state["use_auto_tile"]
# render settings
context.scene.render.image_settings.file_format = state["file_format"]
context.scene.render.image_settings.color_depth = state["color_depth"]
context.scene.render.image_settings.color_mode = state["color_mode"]
context.scene.render.use_bake_multires = state["use_bake_multires"]
context.scene.render.bake.use_selected_to_active = state["use_selected_to_active"]
context.scene.render.bake.use_pass_direct = state["use_pass_direct"]
context.scene.render.bake.use_pass_indirect = state["use_pass_indirect"]
context.scene.render.bake.margin = state["margin"]
context.scene.render.bake.use_clear = state["use_clear"]
context.scene.render.image_settings.file_format = state["image_format"]
# Blender 2.92
if utils.B292():
context.scene.render.bake.target = state["target"]
# color management
context.scene.view_settings.view_transform = state["view_transform"]
context.scene.view_settings.look = state["look"]
context.scene.view_settings.gamma = state["gamma"]
context.scene.view_settings.exposure = state["exposure"]
context.scene.sequencer_colorspace_settings.name = state["colorspace"]
# render engine
context.scene.render.engine = state["engine"]
# viewport shading
shading = utils.get_view_3d_shading(context)
if shading:
shading.type = state["shading"]
# bake type
context.scene.cycles.bake_type = state["cycles_bake_type"]
context.scene.render.bake_type = state["render_bake_type"]
# remove the bake surface
if "bake_surface" in state:
bpy.data.objects.remove(state["bake_surface"])
def get_existing_bake_image(mat, channel_id, width, height,
shader_node, socket,
bake_dir, name_prefix="",
force_srgb=False,
channel_pack=False,
exact_name=False):
return None
def get_bake_image(mat, channel_id, width, height, shader_node, socket, bake_dir,
name_prefix="", force_srgb=False, channel_pack=False,
exact_name=False, underscores=True, unique_name=False, image_format="PNG"):
"""Makes an image and image file to bake the shader socket to and returns the image and image name
"""
global BAKE_INDEX
sep = " "
if underscores:
sep = "_"
prefix_sep = ""
if name_prefix:
prefix_sep = sep
# determine image name and color space
socket_name = nodeutils.safe_socket_name(socket)
if exact_name:
image_name = name_prefix + prefix_sep + mat.name + sep + channel_id
else:
image_name = "EXPORT_BAKE" + sep + name_prefix + prefix_sep + mat.name + sep + channel_id + sep + str(BAKE_INDEX)
BAKE_INDEX += 1
is_data = True
alpha = False
rgb_sockets = [ "Diffuse", "Diffuse Map", "Base Color", "Emission", "Emission Color", "Subsurface Color" ]
rgb_channels = [ "Diffuse", "Emission", "BaseMap", "Base Color", "Glow" ]
if socket_name in rgb_sockets:
is_data = False
if channel_id in rgb_channels:
is_data = False
if force_srgb:
is_data = False
if channel_pack:
alpha = True
# make (and save) the target image
image, exists = get_image_target(image_name, width, height, bake_dir, is_data, alpha,
channel_packed=channel_pack, format=image_format)
# make sure we don't reuse an image as the target, that is also in the nodes we are baking from...
i = 0
base_name = image_name
if shader_node and socket:
while nodeutils.is_image_node_connected_to_socket(shader_node, socket, image, []):
i += 1
old_name = image_name
image_name = base_name + "_" + str(i)
utils.log_info(f"Image: {old_name} in use, trying: {image_name}")
image, exists = get_image_target(image_name, width, height, bake_dir, is_data, alpha,
channel_packed=channel_pack, format=image_format)
return image, image_name, exists
def bake_node_socket_input(context, node, socket, mat, channel_id, bake_dir, name_prefix="",
override_size=0, size_override_node=None, size_override_socket=None,
exact_name=False, underscores=True, unique_name=False,
no_prep=False, image_format="PNG"):
"""Bakes the input to the supplied node and socket to an appropriate image.\n
Image size is determined by the sizes of the connected image nodes (or overriden).\n
Image name and path is determined by the texture channel id and material name and name prefix.\n
An alternative size override node and socket can be supplied to determine the size.
(e.g. matching image sizes with another texture channel)\n
Returns the image baked."""
# determine the size of the image to bake onto
size_node = node
size_socket = socket
if size_override_node:
size_node = size_override_node
if size_override_socket:
size_socket = size_override_socket
width, height = get_connected_texture_size(size_node, override_size, size_socket)
# get the node and output socket to bake from
source_node, source_socket = nodeutils.get_node_and_socket_connected_to_input(node, socket)
# bake the source node output onto the target image and re-save it
image, image_name, exists = get_bake_image(mat, channel_id, width, height, node, socket, bake_dir,
name_prefix=name_prefix, exact_name=exact_name, unique_name=unique_name,
underscores=underscores, image_format=image_format)
image_node = cycles_bake_color_output(context, mat, source_node, source_socket, image, image_name,
no_prep=no_prep, image_format=image_format)
# remove the image node
if image_node:
nodes = mat.node_tree.nodes
nodes.remove(image_node)
return image
def bake_node_socket_output(context, node, socket, mat, channel_id, bake_dir, name_prefix = "",
override_size = 0, size_override_node=None, size_override_socket=None,
exact_name=False, underscores=True, unique_name=False,
no_prep=False, image_format="PNG"):
"""Bakes the output of the supplied node and socket to an appropriate image.\n
Image size is determined by the sizes of the connected image nodes (or overriden).\n
Image name and path is determined by the texture channel id, material name, bake dir and name prefix.\n
An alternative size override node and socket can be supplied to determine the size.
(e.g. matching image sizes with another texture channel)\n
Returns the image baked."""
# determine the size of the image to bake onto
size_node = node
size_socket = socket
if size_override_node:
size_node = size_override_node
if size_override_socket:
size_socket = size_override_socket
width, height = get_connected_texture_size(size_node, override_size, size_socket)
# bake the source node output onto the target image and re-save it
image, image_name, exists = get_bake_image(mat, channel_id, width, height, node, socket, bake_dir,
name_prefix=name_prefix, exact_name=exact_name, unique_name=unique_name,
underscores=underscores, image_format=image_format)
image_node = cycles_bake_color_output(context, mat, node, socket, image, image_name,
no_prep=no_prep, image_format=image_format)
# remove the image node
if image_node:
nodes = mat.node_tree.nodes
nodes.remove(image_node)
return image
def bake_rl_bump_and_normal(context, shader_node, bsdf_node, mat, channel_id, bake_dir,
normal_socket_name="Normal Map", bump_socket_name="Bump Map",
normal_strength_socket_name="Normal Strength",
bump_distance_socket_name="Bump Strength",
name_prefix="", override_size=0, no_prep=False, image_format="PNG"):
"""Bakes the normal map and bump map inputs to the supplied RL master shader node, to a combined
normal map image which takes the normal and bump strengths into account.\n
If supplied socket names are empty they will not be included in the bake.\n
Image size is determined by the sizes of the connected image nodes (or overriden).\n
Image name and path is determined by the texture channel id, material name, bake dir and name prefix.\n
An alternative size override node and socket can be supplied to determine the size.
(e.g. matching image sizes with another texture channel)\n
Returns the normal image baked."""
# determine the size of the image to bake onto
width, height = get_connected_texture_size(shader_node, override_size, normal_socket_name, bump_socket_name)
nodes = mat.node_tree.nodes
links = mat.node_tree.links
# store original links to BSDF normal socket
bsdf_normal_node, bsdf_normal_socket = nodeutils.get_node_and_socket_connected_to_input(bsdf_node, "Normal")
#
normal_source_node = None
normal_source_socket = None
bump_source_node = None
bump_source_socket = None
bump_distance = 0.01
normal_strength = 1.0
bump_map_node = None
normal_map_node = None
if normal_socket_name:
if normal_strength_socket_name:
normal_strength = nodeutils.get_node_input_value(shader_node, normal_strength_socket_name, 1.0)
normal_source_node, normal_source_socket = nodeutils.get_node_and_socket_connected_to_input(shader_node, normal_socket_name)
normal_map_node = nodeutils.make_normal_map_node(nodes, normal_strength)
nodeutils.link_nodes(links, normal_source_node, normal_source_socket, normal_map_node, "Color")
nodeutils.link_nodes(links, normal_map_node, "Normal", bsdf_node, "Normal")
if bump_socket_name:
if bump_distance_socket_name:
bump_distance = nodeutils.get_node_input_value(shader_node, bump_distance_socket_name, 0.01) * BUMP_BAKE_MULTIPLIER
bump_source_node, bump_source_socket = nodeutils.get_node_and_socket_connected_to_input(shader_node, bump_socket_name)
# the bump map bakes to a normal map quite a bit weaker than it looks on the bump node, so increase it's strength here
bump_map_node = nodeutils.make_bump_node(nodes, 1, bump_distance)
nodeutils.link_nodes(links, bump_source_node, bump_source_socket, bump_map_node, "Height")
if normal_map_node:
nodeutils.link_nodes(links, normal_map_node, "Normal", bump_map_node, "Normal")
nodeutils.link_nodes(links, bump_map_node, "Normal", bsdf_node, "Normal")
# bake the source node output onto the target image and re-save it
image, image_name, exists = get_bake_image(mat, channel_id, width, height,
shader_node, normal_socket_name, bake_dir,
name_prefix=name_prefix, image_format=image_format)
image_node = cycles_bake_normal_output(context, mat, bsdf_node, image, image_name,
no_prep=no_prep, image_format=image_format)
# remove the bake nodes and restore the normal links to the bsdf
if bump_map_node:
nodes.remove(bump_map_node)
if normal_map_node:
nodes.remove(normal_map_node)
if image_node:
nodes.remove(image_node)
nodeutils.link_nodes(links, bsdf_normal_node, bsdf_normal_socket, bsdf_node, "Normal")
return image
def bake_bsdf_normal(context, bsdf_node, mat, channel_id, bake_dir,
name_prefix = "", override_size = 0,
no_prep = False, image_format="PNG"):
"""Bakes the normal output of the supplied BSDF shader node, to a normal map image.\n
Image size is determined by the sizes of the connected image nodes (or overriden).\n
Image name and path is determined by the texture channel id, material name, bake dir and name prefix.\n
Returns the normal image baked."""
# determine the size of the image to bake onto
width, height = get_connected_texture_size(bsdf_node, override_size, "Normal")
# get the node and output socket to bake from
nodes = mat.node_tree.nodes
# double the bump distance for baking
bump_distance = 0.01
normal_input_node, normal_input_socket = nodeutils.get_node_and_socket_connected_to_input(bsdf_node, "Normal")
if normal_input_node and normal_input_node.type == "BUMP":
bump_distance = nodeutils.get_node_input_value(normal_input_node, "Distance", bump_distance)
nodeutils.set_node_input_value(normal_input_node, "Distance", bump_distance * BUMP_BAKE_MULTIPLIER)
# bake the source node output onto the target image and re-save it
image, image_name, exists = get_bake_image(mat, channel_id, width, height, bsdf_node, "Normal", bake_dir,
name_prefix=name_prefix, image_format=image_format)
image_node = cycles_bake_normal_output(context, mat, bsdf_node, image, image_name,
no_prep=no_prep, image_format=image_format)
if normal_input_node and normal_input_node.type == "BUMP":
nodeutils.set_node_input_value(normal_input_node, "Distance", bump_distance)
if image_node:
nodes.remove(image_node)
return image
def pack_value_image(value, mat, channel_id, bake_dir,
name_prefix="", size=64, image_format="PNG"):
"""Generates a 64 x 64 texture of a single value. Linear or sRGB depending on channel id.\n
Image name and path is determined by the texture channel id, material name, bake dir and name prefix."""
width = size
height = size
image, image_name, exists = get_bake_image(mat, channel_id, width, height, None, "", bake_dir,
name_prefix=name_prefix, image_format=image_format)
image_pixels = list(image.pixels)
l = len(image_pixels)
for i in range(0, l, 4):
image_pixels[i + 0] = value
image_pixels[i + 1] = value
image_pixels[i + 2] = value
image_pixels[i + 3] = 1
# replace-in-place all the pixels from the list:
image.pixels[:] = image_pixels
image.update()
image.save()
return image
def pack_RGBA(mat, channel_id, pack_mode, bake_dir,
image_r=None, image_g=None, image_b=None, image_a=None,
value_r=0, value_g=0, value_b=0, value_a=0,
name_prefix="", min_size=64, srgb=False, max_size=0,
reuse_existing=False, image_format="PNG"):
"""pack_mode = RGB_A, R_G_B_A"""
width = min_size
height = min_size
# get the largest dimensions
img : bpy.types.Image
for img in [ image_r, image_g, image_b, image_a ]:
if img:
if img.size[0] > width:
width = img.size[0]
if img.size[1] > height:
height = img.size[1]
if max_size > 0:
if width > max_size:
width = max_size
if height > max_size:
height = max_size
utils.log_info(f"Packing {mat.name} for {channel_id} ({width}x{height})")
# get the bake image
image, image_name, exists = get_bake_image(mat, channel_id, width, height, None, "", bake_dir,
name_prefix=name_prefix, force_srgb=srgb,
channel_pack=True, exact_name=True,
image_format=image_format)
# if we are reusing an existing image, return this now
if image and reuse_existing and exists:
utils.log_info(f"Resuing existing texture pack {image.name}, not baking.")
return image
remove_after = []
# if all images are not the same size, use resized copies
if image_r and (image_r.size[0] != width or image_r.size[1] != height):
image_r = image_r.copy()
utils.log_info(f"Resizing {image_r.name} for {channel_id}")
image_r.scale(width, height)
remove_after.append(image_r)
if image_g and (image_g.size[0] != width or image_g.size[1] != height):
image_g = image_g.copy()
utils.log_info(f"Resizing {image_g.name} for {channel_id}")
image_g.scale(width, height)
remove_after.append(image_g)
if image_b and (image_b.size[0] != width or image_b.size[1] != height):
image_b = image_b.copy()
utils.log_info(f"Resizing {image_b.name} for {channel_id}")
image_b.scale(width, height)
remove_after.append(image_b)
if image_a and (image_a.size[0] != width or image_a.size[1] != height):
image_a = image_a.copy()
utils.log_info(f"Resizing {image_a.name} for {channel_id}")
image_a.scale(width, height)
remove_after.append(image_a)
r_data = None
g_data = None
b_data = None
a_data = None
if image_r:
r_data = image_r.pixels[:]
if image_g:
g_data = image_g.pixels[:]
if image_b:
b_data = image_b.pixels[:]
if image_a:
a_data = image_a.pixels[:]
image_pixels = list(image.pixels)
l = len(image_pixels)
if pack_mode == "RGB_A":
for i in range(0, l, 4):
if r_data:
image_pixels[i] = r_data[i]
image_pixels[i + 1] = r_data[i + 1]
image_pixels[i + 2] = r_data[i + 2]
else:
image_pixels[i] = value_r
image_pixels[i + 1] = value_g
image_pixels[i + 2] = value_b
if a_data:
image_pixels[i + 3] = a_data[i]
else:
image_pixels[i + 2] = value_a
elif pack_mode == "R_G_B_A":
for i in range(0, l, 4):
if r_data:
image_pixels[i] = r_data[i]
else:
image_pixels[i] = value_r
if g_data:
image_pixels[i + 1] = g_data[i]
else:
image_pixels[i + 1] = value_g
if b_data:
image_pixels[i + 2] = b_data[i]
else:
image_pixels[i + 2] = value_b
if a_data:
image_pixels[i + 3] = a_data[i]
else:
image_pixels[i + 3] = value_a
image.pixels[:] = image_pixels
image.update()
image.save()
for img in remove_after:
bpy.data.images.remove(img)
return image
def cycles_bake_color_output(context, mat, source_node, source_socket,
image: bpy.types.Image, image_name,
no_prep=False, image_format="PNG"):
"""Runs a cycles bake of the supplied source node and socket output onto the supplied image.\n
Returns a new image node with the image."""
if not (utils.material_exists(mat) and source_node and source_socket and image):
return None
nodes = mat.node_tree.nodes
links = mat.node_tree.links
output_node = nodeutils.find_node_by_type(nodes, "OUTPUT_MATERIAL")
output_source, output_source_socket = nodeutils.get_node_and_socket_connected_to_input(output_node, "Surface")
image_node = nodeutils.make_image_node(nodes, image, "bake")
image_node.name = image_name
utils.log_info(f"Baking: {image_name} / {source_node.name} / {nodeutils.safe_socket_name(source_socket)}")
if not no_prep:
bake_state = prep_bake(context, mat=mat, image_format=image_format, make_surface=True)
nodeutils.link_nodes(links, source_node, source_socket, output_node, "Surface")
image_node.select = True
nodes.active = image_node
bpy.ops.object.bake(type='COMBINED')
context.scene.render.image_settings.color_depth = '8'
context.scene.render.image_settings.color_mode = 'RGB' if image.depth == 24 else 'RGBA'
image.save_render(filepath = bpy.path.abspath(image.filepath), scene = context.scene)
image.reload()
if output_source:
nodeutils.link_nodes(links, output_source, output_source_socket, output_node, "Surface")
if not no_prep:
post_bake(context, bake_state)
return image_node
def cycles_bake_normal_output(context, mat, bsdf_node, image, image_name,
no_prep=False, image_format="PNG"):
"""Runs a cycles bake of the normal output of the supplied BSDF shader node to the supplied image.
Returns a new image node with the image."""
nodes = mat.node_tree.nodes
links = mat.node_tree.links
output_node = nodeutils.find_node_by_type(nodes, "OUTPUT_MATERIAL")
image_node = nodeutils.make_image_node(nodes, image, "bake")
image_node.name = image_name
utils.log_info("Baking normal: " + image_name)
if not no_prep:
bake_state = prep_bake(context, mat=mat, image_format=image_format, make_surface=True)
nodeutils.link_nodes(links, bsdf_node, "BSDF", output_node, "Surface")
image_node.select = True
nodes.active = image_node
bpy.ops.object.bake(type='NORMAL')
context.scene.render.image_settings.color_depth = '8'
context.scene.render.image_settings.color_mode = 'RGB' if image.depth == 24 else 'RGBA'
image.save_render(filepath = bpy.path.abspath(image.filepath), scene = context.scene)
image.reload()
if not no_prep:
post_bake(context, bake_state)
return image_node
def get_largest_texture_to_node(node, done):
"""Recursively traverses the input sockets to the supplied node and
returns the largest found texture dimensions, or [0, 0] if nothing found."""
largest_width = 0
largest_height = 0
for socket in node.inputs:
if socket.is_linked:
width, height = get_largest_texture_to_socket(node, socket, done)
if width > largest_width:
largest_width = width
if height > largest_height:
largest_height = height
return largest_width, largest_height
def get_largest_texture_to_socket(node, socket, done):
"""Recursively traverses the nodes connected to the supplied node's input socket and
returns the largest found texture dimensions, or [0, 0] if nothing found."""
connected_node = nodeutils.get_node_connected_to_input(node, socket)
if not connected_node or connected_node in done:
return 0, 0
done.append(connected_node)
if connected_node.type == "TEX_IMAGE":
if connected_node.image:
return connected_node.image.size[0], connected_node.image.size[1]
else:
return 0, 0
else:
return get_largest_texture_to_node(connected_node, done)
def get_connected_texture_size(node, override_size, *sockets):
"""Recursively searches through all connected image nodes to the supplied node's input socket(s)
and returns the largest image dimensions found.\n
If no connected image nodes found then returns the preferences minimum export texture size.\n
Returned width and height can be overridden with override_size."""
prefs = vars.prefs()
width = 0
height = 0
if override_size > 0:
return override_size, override_size
for socket in sockets:
if socket:
w, h = get_largest_texture_to_socket(node, socket, [])
if w > width:
width = w
if h > height:
height = h
if width == 0:
width = int(prefs.export_texture_size)
if height == 0:
height = int(prefs.export_texture_size)
return width, height
def get_image_target(image_name, width, height, image_dir,
is_data = True, has_alpha = False, force_new = False, channel_packed = False,
format="PNG"):
"""Returns (image, exists)"""
depth = 24
if has_alpha:
depth = 32
color_space = "sRGB"
if is_data:
color_space = "Non-Color"
img : bpy.types.Image
# find an existing image in the same folder, with the same name to reuse:
if not force_new:
for img in bpy.data.images:
# it is expected that the image name is a vary particular prefixed and suffixed name based on the
# material and texture channel and bake index, thus any duplication of this should mean the same intended image.
if img and utils.is_name_or_duplication(img.name, image_name):
img_folder, img_file = os.path.split(bpy.path.abspath(img.filepath))
same_folder = False
try:
if os.path.samefile(image_dir, img_folder):
same_folder = True
except:
same_folder = False
if same_folder:
try:
if img.file_format == format and img.depth == depth and img.size[0] == width and img.size[1] == height:
utils.log_info(f"Reusing image: {image_name} - {color_space} - {img.file_format}")
colorspace.set_image_color_space(img, color_space)
if len(img.pixels) > 0:
return img, True
except:
utils.log_info("Bad image: " + img.name)
if img:
utils.log_info(f"Wrong format: {img.name} / format: {img.file_format} == {format} ? depth: {str(depth)} == {str(img.depth)} ?")
bpy.data.images.remove(img)
# or if the image file exists (but not in blender yet)
file = imageutils.find_file_by_name(image_dir, image_name)
if file:
img = imageutils.load_image(file, color_space, reuse_existing = False)
try:
if img.file_format == format and img.depth == depth and img.size[0] == width and img.size[1] == height:
colorspace.set_image_color_space(img, color_space)
utils.log_info(f"Reusing found image file: {img.filepath} - {img.colorspace_settings.name} - {img.format}")
if len(img.pixels) > 0:
return img, True
except:
utils.log_info("Bad found image file: " + img.name)
if img:
utils.log_info(f"Wrong format: {img.name} / format: {img.file_format} == {format} ? depth: {str(depth)} == {str(img.depth)} ?")
bpy.data.images.remove(img)
# or just make a new one:
utils.log_info(f"Creating new image: {image_name} size: {str(width)} format: {format}")
img = imageutils.make_new_image(image_name, width, height, format, image_dir, is_data, has_alpha, channel_packed)
colorspace.set_image_color_space(img, color_space)
return img, False
def get_bake_dir(chr_cache):
bake_path = os.path.join(chr_cache.get_import_dir(), "textures", chr_cache.get_character_id(), "Blender_Baked")
return bake_path
def combine_normal(context, chr_cache, mat_cache):
"""Combines the normal and bump maps by baking and connecting a new normal map."""
init_bake(5001)
mat = mat_cache.material
nodes = mat.node_tree.nodes
links = mat.node_tree.links
mat_name = utils.strip_name(mat.name)
shader = params.get_shader_name(mat_cache)
bsdf_node, shader_node, mix_node = nodeutils.get_shader_nodes(mat, shader)
bake_path = get_bake_dir(chr_cache)
selection = context.selected_objects.copy()
active = utils.get_active_object()
if mat_cache.material_type == "DEFAULT" or mat_cache.material_type == "SSS":
nodeutils.clear_cursor()
normal_node, normal_socket = nodeutils.get_node_and_socket_connected_to_input(shader_node, "Normal Map")
bump_node, bump_socket = nodeutils.get_node_and_socket_connected_to_input(shader_node, "Bump Map")
if normal_node and bump_node:
normal_image = bake_rl_bump_and_normal(context, shader_node, bsdf_node, mat, "Normal", bake_path)
normal_image_name = utils.unique_name("(NORMAL)")
normal_image_node = nodeutils.make_image_node(nodes, normal_image, normal_image_name)
nodeutils.link_nodes(links, normal_image_node, "Color", shader_node, "Normal Map")
nodeutils.unlink_node_output(links, shader_node, "Bump Map")
mat_cache.parameters.default_normal_strength = 1.0
nodeutils.set_node_input_value(shader_node, "Normal Strength", 1.0)
elif bump_node:
normal_image = bake_rl_bump_and_normal(context, shader_node, bsdf_node, mat, "Normal", bake_path,
normal_socket_name = "", bump_socket_name = "")
normal_image_name = utils.unique_name("(NORMAL)")
normal_image_node = nodeutils.make_image_node(nodes, normal_image, normal_image_name)
nodeutils.link_nodes(links, normal_image_node, "Color", shader_node, "Normal Map")
nodeutils.unlink_node_output(links, shader_node, "Bump Map")
mat_cache.parameters.default_normal_strength = 1.0
nodeutils.set_node_input_value(shader_node, "Normal Strength", 1.0)
elif normal_node and normal_node.type != "TEX_IMAGE":
normal_image = bake_rl_bump_and_normal(context, shader_node, bsdf_node, mat, "Normal", bake_path,
bump_socket_name = "", bump_distance_socket_name = "")
normal_image_name = utils.unique_name("(NORMAL)")
normal_image_node = nodeutils.make_image_node(nodes, normal_image, normal_image_name)
nodeutils.link_nodes(links, normal_image_node, "Color", shader_node, "Normal Map")
mat_cache.parameters.default_normal_strength = 1.0
nodeutils.set_node_input_value(shader_node, "Normal Strength", 1.0)
utils.try_select_objects(selection, True)
if active:
utils.set_active_object(active)
def bake_flow_to_normal(context, chr_cache, mat_cache):
"""Convert's a hair shader's flow map into an approximate normal map."""
init_bake(4001)
mat = mat_cache.material
nodes = mat.node_tree.nodes
links = mat.node_tree.links
mat_name = utils.strip_name(mat.name)
shader = params.get_shader_name(mat_cache)
bsdf_node, shader_node, mix_node = nodeutils.get_shader_nodes(mat, shader)
bake_dir = mat_cache.get_tex_dir(chr_cache)
if mat_cache.material_type == "HAIR":
nodeutils.clear_cursor()
mode_selection = utils.store_mode_selection_state()
# get the flow map
flow_node = nodeutils.get_node_connected_to_input(shader_node, "Flow Map")
flow_image: bpy.types.Image = flow_node.image
width = flow_image.size[0]
height = flow_image.size[1]
normal_node = None
normal_image = None
# try to re-use normal map
if nodeutils.has_connected_input(shader_node, "Normal Map"):
normal_node = nodeutils.get_node_connected_to_input(shader_node, "Normal Map")
if normal_node and normal_node.image:
normal_image: bpy.types.Image = normal_node.image
try:
utils.log_info("Found existing normal image: " + normal_image.name + ": " + normal_image.filepath)
if normal_image.size[0] != width or normal_image.size[1] != height:
utils.log_info("Resizing normal image: " + str(width) + " x " + str(height))
normal_image.scale(width, height)
except:
utils.log_info("Removing bad normal image: " + normal_image.name)
bpy.data.images.remove(normal_image)
# if no existing normal image, create one and link it to the shader
if not normal_image:
utils.log_info("Creating new normal image.")
normal_image = imageutils.make_new_image(mat_name + "_Normal", width, height, "PNG", bake_dir, True, False, False)
if not normal_node:
utils.log_info("Creating new normal image node.")
normal_node = nodeutils.make_image_node(nodes, normal_image, "Generated Normal Map")
nodeutils.link_nodes(links, normal_node, "Color", shader_node, "Normal Map")
# convert the flow map to a normal map
tangent = mat_cache.parameters.hair_tangent_vector
flip_y = mat_cache.parameters.hair_tangent_flip_green > 0
utils.log_info("Converting Flow Map to Normal Map...")
convert_flow_to_normal(flow_image, normal_image, tangent, flip_y)
utils.restore_mode_selection_state(mode_selection)
def convert_flow_to_normal(flow_image: bpy.types.Image, normal_image: bpy.types.Image, tangent, flip_y):
# fetching a copy of the normal pixels as a list gives us the fastest write speed:
normal_pixels = list(normal_image.pixels)
# fetching the flow pixels as a tuple with slice notation gives the fastest read speed:
flow_pixels = flow_image.pixels[:]
#tangent_vector = Vector(tangent)
if flip_y:
flip = -1
else:
flip = 1
l = len(flow_pixels)
for i in range(0, l, 4):
# rgb -> flow_vector
flow_vector = Vector((flow_pixels[i + 0] * 2 - 1,
(flow_pixels[i + 1] * 2 - 1) * flip,
flow_pixels[i + 2] * 2 - 1))
tangent_vector = Vector((-flow_vector.y, flow_vector.x, 0))
# calculate normal vector
normal_vector = flow_vector.cross(tangent_vector)
normal_vector.x *= 0.35
normal_vector.y *= 0.35
normal_vector.normalize()
# normal_vector -> rgb
normal_pixels[i + 0] = (normal_vector[0] + 1) / 2
normal_pixels[i + 1] = (normal_vector[1] + 1) / 2
normal_pixels[i + 2] = (normal_vector[2] + 1) / 2
normal_pixels[i + 3] = 1
# replace-in-place all the pixels from the list:
normal_image.pixels[:] = normal_pixels
normal_image.update()
normal_image.save()
def pack_rgb_a(mat, bake_dir, channel_id, shader_node, pack_node_id,
rgb_id, a_id, rgb_socket, a_socket, rgb_default, a_default,
srgb=False, max_size=0, reuse_existing=False, image_format="PNG"):
"""Pack 2 textures into the RGB and A channels of a single texture."""
global NODE_CURSOR
nodes = mat.node_tree.nodes
links = mat.node_tree.links
rgb_node = None
a_node = None