forked from denetii/io_thps_scene
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbake.py
2967 lines (2492 loc) · 128 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
#############################################
# AUTO SCENE BAKING TOOLS
#############################################
import bpy
import bmesh
import struct
import mathutils
import math
import os
import numpy
from bpy.props import *
from . helpers import *
from . material import *
from . import prefs
from . prefs import *
from mathutils import Color
# METHODS
#############################################
#----------------------------------------------------------------------------------
#- Returns an inverted/clamped version of the given image - for lightmap bakes
#----------------------------------------------------------------------------------
def invert_image(img, clamp_factor):
pixels = list(img.pixels) # create an editable copy (list)
shadow_clamp = 0.48 * clamp_factor
for i in range(0, len(pixels), 4):
pixels[i] = numpy.clip((1.0 - pixels[i]), 0.0, shadow_clamp)
for i in range(1, len(pixels), 4):
pixels[i] = numpy.clip((1.0 - pixels[i]), 0.0, shadow_clamp)
for i in range(2, len(pixels), 4):
pixels[i] = numpy.clip((1.0 - pixels[i]), 0.0, shadow_clamp)
img.pixels[:] = pixels
img.update()
#return img
#----------------------------------------------------------------------------------
#- Checks for the temp baking material
#----------------------------------------------------------------------------------
def get_filler_mat():
if bpy.data.materials.get("_tmp_bakemat"):
return bpy.data.materials.get("_tmp_bakemat")
def get_empty_tex():
if bpy.data.textures.get("_tmp_fillertex"):
return bpy.data.textures.get("_tmp_fillertex")
blender_tex = bpy.data.textures.new("_tmp_fillertex", "IMAGE")
blender_tex.image = get_empty_image()
blender_tex.thug_material_pass_props.blend_mode = 'vBLEND_MODE_BLEND'
return blender_tex
#----------------------------------------------------------------------------------
#- Creates or returns the transparent texture used for 'filler' texture slots
#----------------------------------------------------------------------------------
def get_empty_image():
if bpy.data.images.get("_tmp_empty"):
return bpy.data.images.get("_tmp_empty")
size = 32, 32
img = bpy.data.images.new(name="_tmp_empty", width=size[0], height=size[1])
pixels = [None] * size[0] * size[1]
for x in range(size[0]):
for y in range(size[1]):
r = 1.0
g = 1.0
b = 1.0
a = 0.0
pixels[(y * size[0]) + x] = [r, g, b, a]
pixels = [chan for px in pixels for chan in px]
img.pixels = pixels
img.use_fake_user = True
return img
#----------------------------------------------------------------------------------
#- Checks for the temp off-white image used for baking onto a surface
#----------------------------------------------------------------------------------
def get_filler_image(color, img_name, img_size, persist=False):
if bpy.data.images.get(img_name):
return bpy.data.images.get(img_name)
size = img_size, img_size
img = bpy.data.images.new(name=img_name, width=size[0], height=size[1])
## For white image
# pixels = [1.0] * (4 * size[0] * size[1])
pixels = [None] * size[0] * size[1]
for x in range(size[0]):
for y in range(size[1]):
# assign RGBA to something useful
r = color[0]
g = color[1]
b = color[2]
a = color[3]
pixels[(y * size[0]) + x] = [r, g, b, a]
# flatten list
pixels = [chan for px in pixels for chan in px]
# assign pixels
img.pixels = pixels
if persist:
img.use_fake_user = True
img.pack(as_png=True)
return img
#----------------------------------------------------------------------------------
#- Collects the materials assigned to an object and stores in original_mats
#----------------------------------------------------------------------------------
def store_materials(obj, remove_mats = False):
stored_mats = []
# We also want to store the names of the materials on the object itself
# This way we can 'un-bake' and restore the original mats later on
if not "is_baked" in obj or obj["is_baked"] == False:
original_mats = []
for mat_slot in obj.material_slots:
if not mat_slot.material.name.startswith('Lightmap_'):
stored_mats.append(mat_slot.material)
if not "is_baked" in obj or obj["is_baked"] == False:
# Make sure it won't be deleted upon close!
mat_slot.material.use_fake_user = True
original_mats.append(mat_slot.material.name)
if remove_mats == True:
for i in range(len(obj.material_slots)):
obj.active_material_index = i
bpy.ops.object.material_slot_remove({'object': obj})
if not "is_baked" in obj or obj["is_baked"] == False:
obj["original_mats"] = original_mats
return stored_mats
#----------------------------------------------------------------------------------
#- Restores materials previously assigned to an object
#----------------------------------------------------------------------------------
def restore_mats(obj, stored_mats):
new_mats = []
for mat_slot in obj.material_slots:
new_mats.append(mat_slot.material)
for i in range(len(obj.material_slots)):
obj.active_material_index = i
bpy.ops.object.material_slot_remove({'object': obj})
for mat in stored_mats:
#mat.use_nodes = False
#obj.data.materials.append(mat.copy())
obj.data.materials.append(mat)
#for mat in new_mats:
# obj.data.materials.append(mat)
#----------------------------------------------------------------------------------
#- Restores face material assignments
#----------------------------------------------------------------------------------
def restore_mat_assignments(obj, orig_polys):
#polys = obj.data.polygons
face_list = [face for face in obj.data.polygons]
bpy.ops.object.mode_set(mode='EDIT')
bm = bmesh.from_edit_mesh(obj.data)
for face in bm.faces:
face.select = False
for face in bm.faces:
face.select = True
face.material_index = orig_polys[face.index]
#print("assigning mat {} to face {}".format(face.material_index, face.index))
obj.data.update()
# toggle to object mode
bpy.ops.object.mode_set(mode='OBJECT')
def mat_get_pass(blender_mat, type):
for p in blender_mat.texture_slots:
if p is None:
continue
if type == 'Diffuse' and p.use_map_color_diffuse:
return p.texture
elif type == 'Normal' and p.use_map_normal:
return p.texture
return None
def get_cycles_node(nodes, name, type, create_if_none=True):
if nodes.get(name):
return nodes.get(name)
if create_if_none:
new_node = nodes.new(type)
new_node.name = name
return new_node
return None
#----------------------------------------------------------------------------------
#- Ensures the Cycles scene is using Cycles materials before baking
#----------------------------------------------------------------------------------
def setup_cycles_scene(use_uglymode = False):
if use_uglymode:
print("USING UGLY MODE!")
for mat in bpy.data.materials:
mat.use_nodes = False
else:
print("TURNING ON CYCLES MAT NODES!")
for mat in bpy.data.materials:
mat.use_nodes = True
def setup_cycles_nodes(node_tree, diffuse_tex = None, normal_tex = None, color = [1.0, 1.0, 1.0, 1.0], uv_map = ""):
nodes = node_tree.nodes
# First, add textures...
# Add dummy diffuse texture node (off white)
node_d = get_cycles_node(nodes, 'Filler Tex', 'ShaderNodeTexImage')
node_d.image = get_filler_image(color, "_tmp_flat", 512)
node_d.location = (-680,40)
node_t = get_cycles_node(nodes, 'Diffuse Texture', 'ShaderNodeTexImage')
if diffuse_tex and hasattr(diffuse_tex, 'image'):
node_t.image = diffuse_tex.image
node_t.location = (-660,320)
node_n = get_cycles_node(nodes, 'Normal Texture', 'ShaderNodeTexImage')
if normal_tex and hasattr(normal_tex, 'image'):
node_n.image = normal_tex
node_n.color_space = 'NONE'
node_n.location = (-680,-220)
# Now, add shaders!
# Add diffuse shader (if it doesn't exist, which it should!)
node_sd = get_cycles_node(nodes, 'Diffuse BSDF', 'ShaderNodeBsdfDiffuse')
node_sd.location = (-160,280)
# Add the transparent BDSF
node_st = get_cycles_node(nodes, 'Transparent BDSF', 'ShaderNodeBsdfTransparent')
node_st.location = (-160,400)
# Add a shader mix node (for transparent and diffuse shaders)
node_sm = get_cycles_node(nodes, 'Mix Shader', 'ShaderNodeMixShader')
node_sm.location = (80,340)
# Add a normal map node
node_sn = get_cycles_node(nodes, 'Normal Map', 'ShaderNodeNormalMap')
node_sn.location = (-420,0)
node_sn.uv_map = uv_map
# Add a UV map node
node_uv = get_cycles_node(nodes, 'UV Map', 'ShaderNodeUVMap')
node_uv.location = (-1060,60)
node_uv.uv_map = uv_map
# Material output (if that somehow doesn't exist already)
node_mo = get_cycles_node(nodes, 'Material Output', 'ShaderNodeOutputMaterial')
node_mo.location = (300, 340)
# Now, add links!
node_tree.links.new(node_t.inputs[0], node_uv.outputs[0]) # Diffuse Texture UV
node_tree.links.new(node_n.inputs[0], node_uv.outputs[0]) # Normal Texture UV
if normal_tex:
node_tree.links.new(node_sn.inputs[1], node_n.outputs[0]) # Normal Map color
node_tree.links.new(node_sd.inputs[0], node_d.outputs[0]) # Diff Shader color
node_tree.links.new(node_sd.inputs[2], node_sn.outputs[0]) # Diff Shader Normal
node_tree.links.new(node_sm.inputs[0], node_t.outputs[1]) # Mix Shader fac
node_tree.links.new(node_sm.inputs[1], node_st.outputs[0]) # Mix Shader Shader1
node_tree.links.new(node_sm.inputs[2], node_sd.outputs[0]) # Mix Shader Shader2
node_tree.links.new(node_mo.inputs[0], node_sm.outputs[0]) # Material Output Surface
def avg_color(color_list):
color = Color()
len_list = len(color_list)
for col in color_list:
color += col
if len_list > 0:
color /= len_list
return color
#----------------------------------------------------------------------------------
#- Removes baked vertex color data on specified objects
#----------------------------------------------------------------------------------
def clear_bake_vcs(scene, meshes):
for obj in meshes:
if obj.data.vertex_colors.get('bake'):
obj.data.vertex_colors.remove(obj.data.vertex_colors.get('bake'))
#----------------------------------------------------------------------------------
#- Converts a baked texture to vertex colors (allows Cycles VC bakes)
#----------------------------------------------------------------------------------
def convert_bake_to_vcs(scene, meshes, layer_name, smooth=True):
for obj in meshes:
bake_vcs = get_vcs(obj, layer_name)
obdata = obj.data
obdata.vertex_colors.active = bake_vcs
if not obdata.uv_layers.get('Lightmap'):
print('Object {} is not baked, skipping...'.format(obj.name))
continue
# Determine what image we are looking for
# If the object is part of a lightmap group, search by group name
if obj.thug_lightmap_group_id > -1 and scene.thug_lightmap_groups[obj.thug_lightmap_group_id]:
group_name = scene.thug_lightmap_groups[obj.thug_lightmap_group_id].name
pbr_lightmap_name = 'PM_{}_{}'.format(scene.thug_bake_slot, group_name)
lightmap_name = 'LM_{}_{}'.format(scene.thug_bake_slot, group_name)
legacy_name = 'LM_{}'.format(group_name)
else:
pbr_lightmap_name = 'PM_{}_{}'.format(scene.thug_bake_slot, obj.name)
lightmap_name = 'LM_{}_{}'.format(scene.thug_bake_slot, obj.name)
legacy_name = 'LM_{}'.format(obj.name)
if not bpy.data.images.get(pbr_lightmap_name):
if not bpy.data.images.get(lightmap_name):
if not bpy.data.images.get(legacy_name):
print('Lightmap texture not found for {}, skipping...'.format(obj.name))
continue
lightmap_img = bpy.data.images.get(legacy_name)
else:
lightmap_img = bpy.data.images.get(lightmap_name)
else:
lightmap_img = bpy.data.images.get(pbr_lightmap_name)
image_size_x = lightmap_img.size[0]
image_size_y = lightmap_img.size[1]
uv_pixels = lightmap_img.pixels[:]
print('Flattening bake for {} into vertex colors from texture {}...'.format(obj.name, lightmap_img.name))
for p in obdata.polygons:
for loop in p.loop_indices:
obdata.uv_textures['Lightmap'].data[p.index].image = get_filler_image([1.0, 1.0, 1.0, 1.0], "_tmp_white", 16, True)
co = obdata.uv_layers['Lightmap'].data[loop].uv
x_co = round(co[0] * (image_size_x - 1))
y_co = round(co[1] * (image_size_y - 1))
col_out = bake_vcs.data[loop].color
pixelNumber = (image_size_x * y_co) + x_co
r = uv_pixels[pixelNumber*4]
g = uv_pixels[pixelNumber*4 + 1]
b = uv_pixels[pixelNumber*4 + 2]
a = uv_pixels[pixelNumber*4 + 3]
col_in = r, g, b # texture-color
col_result = [r,g,b] # existing / 'base' color
col_result = col_in
# Full black is likely a pixel sampled outside the bake result
if r == 0.0 and g == 0.0 and b == 0.0:
bake_vcs.data[loop].color = 0.5, 0.5, 0.5
else:
bake_vcs.data[loop].color = col_result
if smooth:
# Do a second pass to smooth the vertex colors (average the loop colors)
col_map = {}
for l in obdata.loops:
col = bake_vcs.data[l.index].color
try:
col_map[l.vertex_index].append(col)
except KeyError:
col_map[l.vertex_index] = [col]
for i, l in enumerate(obdata.loops):
bake_vcs.data[i].color = avg_color(col_map[l.vertex_index])
obdata.update()
#----------------------------------------------------------------------------------
#- 'Un-bakes' the object (restores the original materials)
#----------------------------------------------------------------------------------
def unbake(obj):
if not "is_baked" in obj or obj["is_baked"] == False:
# Don't try to unbake something that isn't baked to begin with!
return
if not "original_mats" in obj:
raise Exception("Cannot unbake object - unable to find original materials.")
# First, remove the existing mats on the object (these should be lightmapped)
for i in range(len(obj.material_slots)):
obj.active_material_index = i
bpy.ops.object.material_slot_remove({'object': obj})
for mat_name in obj["original_mats"]:
if not bpy.data.materials.get(mat_name):
raise Exception("Material {} no longer exists. Uh oh!".format(mat_name))
_mat = bpy.data.materials.get(mat_name)
obj.data.materials.append(_mat)
obj["is_baked"] = False
obj["thug_last_bake_res"] = 0
def save_baked_texture(img, folder):
img.filepath_raw = "{}/{}.png".format(folder, img.name)
img.file_format = "PNG"
img.save()
print("Saved texture {}.png to {}".format(img.name, folder))
#bpy.path.abspath("//my/file.txt")
#----------------------------------------------------------------------------------
#- Bakes a set of objects to vertex colors (Blender Render only)
#----------------------------------------------------------------------------------
def bake_thug_vcs(meshes, context):
scene = context.scene
# De-select any objects currently selected
if context.selected_objects:
for ob in context.selected_objects:
ob.select = False
# We need to be in Cycles to run the lightmap bake
previous_engine = 'BLENDER_RENDER'
if scene.render.engine != 'BLENDER_RENDER':
previous_engine = scene.render.engine
scene.render.engine = 'BLENDER_RENDER'
# Set up the actual bake (man, this is so easy compared to texture bakes!)
bpy.context.scene.render.bake_type = "FULL"
#bpy.context.scene.render.bake_normal_space = "WORLD"
bpy.context.scene.render.use_bake_to_vertex_color = True
bpy.context.scene.render.use_bake_selected_to_active = False
bpy.context.scene.render.use_bake_multires = False
total_meshes = len(meshes)
mesh_num = 0
baked_obs = []
for ob in meshes:
mesh_num += 1
print("****************************************")
print("BAKING LIGHTING FOR OBJECT #" + str(mesh_num) + " OF " + str(total_meshes) + ": " + ob.name)
print("****************************************")
if ob.thug_export_scene == False:
print("Object {} not marked for export to scene, skipping bake!".format(ob.name))
continue
# Set it to active and go into edit mode
scene.objects.active = ob
ob.select = True
# Add the 'color' vertex color channel (used by THUG) and make sure we are baking onto it
if "color" not in ob.data.vertex_colors:
bpy.ops.mesh.vertex_color_add({"object": ob})
ob.data.vertex_colors[len(ob.data.vertex_colors)-1].name = 'color'
ob.data.vertex_colors["color"].active_render = True
# Also grab the original mesh data so we can remap the material assignments
# - if we have more than one material assigned to our object
if len(ob.data.materials) > 1:
orig_polys = [0] * len(ob.data.polygons)
for f in ob.data.polygons:
orig_polys[f.index] = f.material_index
# Store the materials assigned to the object so we can use a flat color on the mesh (better bake results)
orig_mats = store_materials(ob, True)
orig_index = ob.active_material_index
try:
bpy.ops.object.bake_image()
except RuntimeError:
print("Bake failed on this object! :(")
# Now, for the cleanup! Let's restore the missing mats
restore_mats(ob, orig_mats)
if orig_index != None and orig_index >= 0:
ob.active_material_index = orig_index
# If there is more than one material, restore the per-face material assignment
if len(ob.data.materials) > 1:
restore_mat_assignments(ob, orig_polys)
print("Object " + ob.name + " baked to vertex colors!")
ob.select = False
#----------------------------------------------------------------------------------
#- Bakes directional light maps to 3 textures using the 'Half Life 2' basis
#----------------------------------------------------------------------------------
def bake_hl2_lightmaps(meshes, context):
scene = context.scene
# De-select any objects currently selected
if context.selected_objects:
for ob in context.selected_objects:
ob.select = False
is_cycles = True
previous_engine = 'CYCLES'
if scene.render.engine != 'CYCLES':
previous_engine = scene.render.engine
scene.render.engine = 'CYCLES'
# If the user saved but didn't pack images, the filler image will be black
# so we should get rid of it to ensure the bake result is always correct
if bpy.data.images.get("_tmp_flat"):
bpy.data.images["_tmp_flat"].user_clear()
bpy.data.images.remove(bpy.data.images.get("_tmp_flat"))
# Create destination folder for the baked textures
_lightmap_folder = bpy.path.basename(bpy.context.blend_data.filepath)[:-6] # = Name of blend file
_folder = bpy.path.abspath("//Tx_DirLightmap/{}".format(_lightmap_folder))
os.makedirs(_folder, 0o777, True)
setup_cycles_scene(scene.thug_lightmap_uglymode)
total_meshes = len(meshes)
mesh_num = 0
baked_obs = []
rebake_existing_pass = False
dont_change_resolution = True
for ob in meshes:
mesh_num += 1
print("****************************************")
print("BAKING LIGHTING FOR OBJECT #" + str(mesh_num) + " OF " + str(total_meshes) + ": " + ob.name)
print("****************************************")
if "is_baked" in ob and ob["is_baked"] == True:
print("Object has been previously baked.")
if ob.thug_export_scene == False:
print("Object {} not marked for export to scene, skipping bake!".format(ob.name))
continue
if not ob.data.uv_layers:
print("Object {} has no UV maps. Cannot bake lighting!".format(ob.name))
continue
if not ob.data.materials:
print("Object {} has no materials. Cannot bake lighting!".format(ob.name))
continue
# Check this object for a lightmap group - if it is part of a group we need to tweak
# the bake process slightly to ensure the bake goes to the shared texture
# rather than an object-specific texture
group_name = ''
if ob.thug_lightmap_group_id > -1:
group_name = scene.thug_lightmap_groups[ob.thug_lightmap_group_id].name
# Set it to active and go into edit mode
scene.objects.active = ob
ob.select = True
# Set the desired resolution, both for the UV map and the lightmap texture
img_res = 128
bake_margin = 1.0
lightmap_name_x = 'LM_{}_{}_0'.format(scene.thug_bake_slot, ob.name)
lightmap_name_y = 'LM_{}_{}_1'.format(scene.thug_bake_slot, ob.name)
lightmap_name_z = 'LM_{}_{}_2'.format(scene.thug_bake_slot, ob.name)
if group_name != '':
lightmap_name_x = 'LM_{}_{}_0'.format(scene.thug_bake_slot, group_name)
lightmap_name_y = 'LM_{}_{}_1'.format(scene.thug_bake_slot, group_name)
lightmap_name_z = 'LM_{}_{}_2'.format(scene.thug_bake_slot, group_name)
img_res = int(scene.thug_lightmap_groups[ob.thug_lightmap_group_id].resolution)
print("Lightmap resolution is: {}x{}".format(img_res, img_res))
elif ob.thug_lightmap_resolution:
img_res = int(ob.thug_lightmap_resolution)
print("Object lightmap resolution is: {}x{}".format(img_res, img_res))
if scene.thug_lightmap_scale:
img_res = int(img_res * float(scene.thug_lightmap_scale))
if img_res < 16:
img_res = 16
print("Resolution after scene scale is: {}x{}".format(img_res, img_res))
if dont_change_resolution and "thug_last_bake_res" in ob:
if ob["thug_last_bake_res"] > 0:
print("Re-baking with same resolution as previously used: {}".format(ob["thug_last_bake_res"]))
img_res = ob["thug_last_bake_res"]
lightmap_img_x = get_image(lightmap_name_x, img_res, img_res)
lightmap_img_y = get_image(lightmap_name_y, img_res, img_res)
lightmap_img_z = get_image(lightmap_name_z, img_res, img_res)
# Blender's UV margins seem to scale with resolution, so we need to make them smaller
# as the UV resolution increases
uv_padding = 0.05
if img_res > 2048:
bake_margin = 0.025
uv_padding = 0.002
elif img_res > 1024:
bake_margin = 0.1
uv_padding = 0.005
elif img_res > 512:
bake_margin = 0.25
uv_padding = 0.01
elif img_res > 64:
uv_padding = 0.01
# Grab original UV map, so any diffuse/normal textures are mapped correctly
orig_uv = ob.data.uv_layers[0].name
# Also grab the original mesh data so we can remap the material assignments
# - if we have more than one material assigned to our object
if len(ob.data.materials) > 1:
orig_polys = [0] * len(ob.data.polygons)
for f in ob.data.polygons:
orig_polys[f.index] = f.material_index
uvs_are_new = False
bpy.ops.object.mode_set(mode='OBJECT')
# Recreate the UV map if it's a different resolution than we want now
if group_name == '':
if ("thug_last_bake_res" in ob and ob["thug_last_bake_res"] != img_res) \
or ("thug_last_bake_type" in ob and ob["thug_last_bake_type"] != ob.thug_lightmap_type) \
or ("thug_last_bake_res" not in ob or "thug_last_bake_type" not in ob)\
or scene.thug_bake_force_remake == True:
print("Removing existing images/UV maps.")
if ob.data.uv_layers.get('Lightmap'):
ob.data.uv_textures.remove(ob.data.uv_textures['Lightmap'])
# Create the Lightmap UV layer
if not ob.data.uv_layers.get('Lightmap'):
if group_name != '':
print("ERROR: Object {} is part of group {}, but has no Lightmap UVs. Unable to bake.".format(ob.name, group_name))
continue
uvs_are_new = True
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.mesh.uv_texture_add({"object": ob})
ob.data.uv_layers[len(ob.data.uv_layers)-1].name = 'Lightmap'
ob.data.uv_textures['Lightmap'].active = True
bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='SELECT')
# Unwrap the mesh based on the type specified on the object properties!
if ob.thug_lightmap_type == 'Lightmap':
bpy.ops.uv.lightmap_pack(
PREF_CONTEXT='ALL_FACES', PREF_PACK_IN_ONE=True, PREF_NEW_UVLAYER=False,
PREF_APPLY_IMAGE=False, PREF_IMG_PX_SIZE=img_res,
PREF_BOX_DIV=48, PREF_MARGIN_DIV=bake_margin)
elif ob.thug_lightmap_type == 'Smart':
bpy.ops.uv.smart_project()
else:
raise Exception("Unknown lightmap type specified on object {}".format(ob.name))
else:
ob.data.uv_textures['Lightmap'].active = True
bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
if uvs_are_new and scene.thug_bake_pad_uvs == True:
# Argh, Blender's UV projection sometimes creates seams on the edges of the image!
# Add some padding by scaling the whole thing down a little bit
scale_uvs(ob.data.uv_layers['Lightmap'], mathutils.Vector((1.0-uv_padding, 1.0-uv_padding)))
#-----------------------------------------------------------------------------------------
# Multi-pass bake: render multiple bake textures, then flatten then into a single image
# First, bake each pass to a separate image...
#bake_passes = [ 'X', 'Y', 'Z' ]
orig_index = ob.active_material_index
store_materials(ob)
# Create or retrieve the lightmap texture
tex_name = "Baked_{}".format(ob.name)
if group_name != '':
tex_name = "Baked_{}".format(group_name)
blender_tex = get_texture(tex_name)
blender_tex.thug_material_pass_props.blend_mode = 'vBLEND_MODE_MODULATE'
blender_tex.image = lightmap_img_x
for bakepass in range(4):
print("**********************")
print("Baking pass {}...".format(bakepass))
if bakepass == 0:
image = lightmap_img_x
pass_name = lightmap_name_x
elif bakepass == 1:
image = lightmap_img_y
pass_name = lightmap_name_y
elif bakepass == 2:
image = lightmap_img_z
pass_name = lightmap_name_z
elif bakepass == 3:
# There is no 4th bake pass, this is just used to clean up the normal offsets
# generated by the 3 previous passes
for mat in ob.data.materials:
node_m = get_cycles_node(mat.node_tree.nodes, 'Normal Offset', 'ShaderNodeMapping')
node_m.rotation[0] = 0.0
node_m.rotation[1] = 0.0
node_m.rotation[2] = 0.0
break
image.use_fake_user = True # Ensure it won't be deleted when closing the scene
for mat in ob.data.materials:
# Ensure that we have an input Geometry node, and a Mapping node to rotate the normals
node_g = get_cycles_node(mat.node_tree.nodes, 'Geometry', 'ShaderNodeNewGeometry')
node_m = get_cycles_node(mat.node_tree.nodes, 'Normal Offset', 'ShaderNodeMapping')
node_m.vector_type = 'NORMAL'
# Rotate the normal
if bakepass == 0:
node_m.rotation[0] = 0.955393
node_m.rotation[1] = 0.0
node_m.rotation[2] = 0.0
#new_normal = [ -(1/math.sqrt(6)), -(1/math.sqrt(2)), 1/math.sqrt(3), 1.0 ]
if bakepass == 1:
node_m.rotation[0] = -0.955393
node_m.rotation[1] = 0.0
node_m.rotation[2] = 0.0
#new_normal = [ -(1/math.sqrt(6)), (1/math.sqrt(2)), 1/math.sqrt(3), 1.0 ]
elif bakepass == 2:
node_m.rotation[0] = 0.0
node_m.rotation[1] = 0.955393
node_m.rotation[2] = 0.0
#new_normal = [ math.sqrt(2/3), 0, 1/math.sqrt(3), 1.0 ]
# Link Geometry normal to mapping node
link = mat.node_tree.links.new(node_m.inputs[0], node_g.outputs['Normal'])
# Get the shader node (Diffuse or Principled accepted)
node_shader = get_cycles_node(mat.node_tree.nodes, 'Diffuse BSDF', 'ShaderNodeBsdfDiffuse', create_if_none=False)
if node_shader == None:
node_shader = get_cycles_node(mat.node_tree.nodes, 'Principled BSDF', 'ShaderNodeBsdfPrincipled', create_if_none=False)
if node_shader == None:
raise Exception("Unable to find material output node for {} :(".format(mat.name))
# Link Mapping node (with offset normal) to diffuse/principled shader input normal
link = mat.node_tree.links.new(node_shader.inputs['Normal'], node_m.outputs[0])
node_d = get_cycles_node(mat.node_tree.nodes, 'Bake Result', 'ShaderNodeTexImage')
node_d.image = image
node_d.location = (-880,40)
mat.node_tree.nodes.active = node_d
# Add a UV map node
node_uv = get_cycles_node(mat.node_tree.nodes, 'Bake Result UV', 'ShaderNodeUVMap')
node_uv.location = (-1060,60)
node_uv.uv_map = "Lightmap"
mat.node_tree.links.new(node_d.inputs[0], node_uv.outputs[0]) # Bake Texture UV
# Bake the lightmap for Cycles!
scene.cycles.bake_type = 'DIFFUSE'
bpy.context.scene.render.bake.use_pass_color = False
bpy.context.scene.render.bake.use_pass_indirect = True
bpy.context.scene.render.bake.use_pass_direct = True
if scene.thug_bake_automargin:
scene.render.bake_margin = 2 # Used to be bake_margin
if ob.thug_lightmap_quality != 'Custom':
if ob.thug_lightmap_quality == 'Draft':
scene.cycles.samples = 32
scene.cycles.max_bounces = 2
if ob.thug_lightmap_quality == 'Preview':
scene.cycles.samples = 64
scene.cycles.max_bounces = 2
if ob.thug_lightmap_quality == 'Good':
scene.cycles.samples = 128
scene.cycles.max_bounces = 3
if ob.thug_lightmap_quality == 'High':
scene.cycles.samples = 256
scene.cycles.max_bounces = 3
if ob.thug_lightmap_quality == 'Ultra':
scene.cycles.samples = 512
scene.cycles.max_bounces = 3
print("Using {} bake quality. Samples: {}, bounces: {}".format(ob.thug_lightmap_quality, scene.cycles.samples, scene.cycles.max_bounces))
#raise Exception("TEST")
bpy.ops.object.bake(type='DIFFUSE')
save_baked_texture(image, _folder)
print("Object " + ob.name + " baked to texture " + blender_tex.name)
baked_obs.append(ob.name)
bpy.ops.object.mode_set(mode='OBJECT')
ob.active_material_index = orig_index
ob.data.uv_textures[orig_uv].active = True
ob.data.uv_textures[orig_uv].active_render = True
# If there is more than one material, restore the per-face material assignment
if len(ob.data.materials) > 1:
restore_mat_assignments(ob, orig_polys)
ob.select = False
ob["is_baked"] = True
ob["thug_last_bake_res"] = img_res
ob["thug_last_bake_type"] = ob.thug_lightmap_type
# Done!!
# Once we have finished baking everything, we then duplicate the materials and assign
# the lightmap texture to them - should be faster than doing it during the baking step
print("Baking complete. Setting up lightmapped materials...")
for obname in baked_obs:
ob = bpy.data.objects.get(obname)
if not ob:
raise Exception("Unable to find baked object {}".format(obname))
for mat in ob.data.materials:
mat.use_nodes = False
for mat_slot in ob.material_slots:
if group_name != '':
group_mat_name = '{}_{}'.format(mat_slot.material.name, group_name)
mat_slot.material = get_material(group_mat_name, mat_slot.material)
else:
mat_slot.material = mat_slot.material.copy()
mat_slot.material.thug_material_props.ugplus_matslot_lightmap.tex_image = maybe_get_image(lightmap_name_x)
mat_slot.material.thug_material_props.ugplus_matslot_lightmap2.tex_image = maybe_get_image(lightmap_name_y)
mat_slot.material.thug_material_props.ugplus_matslot_lightmap3.tex_image = maybe_get_image(lightmap_name_z)
# Also add the image to the legacy material system
if not mat_slot.material.texture_slots.get(blender_tex.name):
slot = mat_slot.material.texture_slots.add()
else:
slot = mat_slot.material.texture_slots.get(blender_tex.name)
slot.texture = blender_tex
slot.uv_layer = str('Lightmap')
slot.blend_type = 'MULTIPLY'
print("Processed object: {}".format(obname))
print("COMPLETE! Thank you for your patience!")
# Switch back to the original engine, if it wasn't Cycles
if previous_engine != scene.render.engine:
scene.render.engine = previous_engine
# Toggle use_nodes on the whole scene materials, if desired (depending on the engine we are on)
if previous_engine == 'BLENDER_RENDER':
for mat in bpy.data.materials:
mat.use_nodes = False
elif previous_engine == 'CYCLES':
for mat in bpy.data.materials:
mat.use_nodes = True
#----------------------------------------------------------------------------------
#- Bakes lightmaps to an object group, rather than individually
#- objects are merged, unwrapped, baked, then separated
#----------------------------------------------------------------------------------
def bake_to_group(objects, group_name, context):
bake_group = bpy.data.groups.get(group_name)
if not bake_group:
raise Exception('Group {} not found.'.format(group_name))
# Remove existing merged object, if it exists
ob_merged_old = bpy.data.objects.get(group_name + "_tempMerged")
if ob_merged_old is not None:
bpy.data.objects.remove(ob)
#----------------------------------------------------------------------------------
#- Bakes light/shadow maps for UG+/UG Classic's PBR shaders
#----------------------------------------------------------------------------------
def bake_ugplus_lightmaps(meshes, context):
scene = context.scene
# De-select any objects currently selected
if context.selected_objects:
for ob in context.selected_objects:
ob.select = False
is_cycles = True
previous_engine = 'CYCLES'
if scene.render.engine != 'CYCLES':
previous_engine = scene.render.engine
scene.render.engine = 'CYCLES'
# If the user saved but didn't pack images, the filler image will be black
# so we should get rid of it to ensure the bake result is always correct
if bpy.data.images.get("_tmp_flat"):
bpy.data.images["_tmp_flat"].user_clear()
bpy.data.images.remove(bpy.data.images.get("_tmp_flat"))
# Create destination folder for the baked textures
_lightmap_folder = bpy.path.basename(bpy.context.blend_data.filepath)[:-6] # = Name of blend file
_folder = bpy.path.abspath("//Tx_Lightmap_PBR/{}".format(_lightmap_folder))
os.makedirs(_folder, 0o777, True)
setup_cycles_scene(scene.thug_lightmap_uglymode)
total_meshes = len(meshes)
mesh_num = 0
baked_obs = []
rebake_existing_pass = False
dont_change_resolution = True
for ob in meshes:
mesh_num += 1
print("****************************************")
print("BAKING LIGHTING FOR OBJECT #" + str(mesh_num) + " OF " + str(total_meshes) + ": " + ob.name)
print("****************************************")
if "is_baked" in ob and ob["is_baked"] == True:
print("Object has been previously baked.")
if ob.thug_export_scene == False:
print("Object {} not marked for export to scene, skipping bake!".format(ob.name))
continue
if not ob.data.uv_layers:
print("Object {} has no UV maps. Cannot bake lighting!".format(ob.name))
continue
if not ob.data.materials:
print("Object {} has no materials. Cannot bake lighting!".format(ob.name))
continue
# Set it to active and go into edit mode
scene.objects.active = ob
ob.select = True
# Set the desired resolution, both for the UV map and the lightmap texture
img_res = 128
bake_margin = 1.0
lightmap_name = 'PM_{}_{}'.format(scene.thug_bake_slot, ob.name)
shadowmap_name = 'LM_{}_{}'.format(scene.thug_bake_slot, ob.name)
legacy_name = 'LM_{}'.format(ob.name)
lightmap_img = maybe_get_image(lightmap_name)
shadowmap_img = maybe_get_image(shadowmap_name)
legacy_img = maybe_get_image(legacy_name)
if ob.thug_lightmap_resolution:
img_res = int(ob.thug_lightmap_resolution)
print("Object lightmap resolution is: {}x{}".format(img_res, img_res))
if scene.thug_lightmap_scale:
img_res = int(img_res * float(scene.thug_lightmap_scale))
if img_res < 16:
img_res = 16
print("Resolution after scene scale is: {}x{}".format(img_res, img_res))
if dont_change_resolution and "thug_last_bake_res" in ob:
if ob["thug_last_bake_res"] > 0:
print("Re-baking with same resolution as previously used: {}".format(ob["thug_last_bake_res"]))
img_res = ob["thug_last_bake_res"]
# Blender's UV margins seem to scale with resolution, so we need to make them smaller
# as the UV resolution increases
uv_padding = 0.05
if img_res > 2048:
bake_margin = 0.025
uv_padding = 0.002
elif img_res > 1024:
bake_margin = 0.1
uv_padding = 0.005
elif img_res > 512:
bake_margin = 0.25
uv_padding = 0.01
elif img_res > 64:
uv_padding = 0.01
# Grab original UV map, so any diffuse/normal textures are mapped correctly
orig_uv = ob.data.uv_layers[0].name
# Also grab the original mesh data so we can remap the material assignments
# - if we have more than one material assigned to our object
if len(ob.data.materials) > 1:
orig_polys = [0] * len(ob.data.polygons)
for f in ob.data.polygons:
orig_polys[f.index] = f.material_index
uvs_are_new = False
bpy.ops.object.mode_set(mode='OBJECT')
# Recreate the UV map if it's a different resolution than we want now
if dont_change_resolution == False:
if ("thug_last_bake_res" in ob and ob["thug_last_bake_res"] != img_res) \
or ("thug_last_bake_type" in ob and ob["thug_last_bake_type"] != ob.thug_lightmap_type) \
or ("thug_last_bake_res" not in ob or "thug_last_bake_type" not in ob)\
or scene.thug_bake_force_remake == True:
print("Removing existing images/UV maps.")
if ob.data.uv_layers.get('Lightmap'):
ob.data.uv_textures.remove(ob.data.uv_textures['Lightmap'])
if lightmap_img:
lightmap_img.source = 'GENERATED'
if shadowmap_img:
shadowmap_img.source = 'GENERATED'
# Create the Lightmap UV layer
if not ob.data.uv_layers.get('Lightmap'):
uvs_are_new = True
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.mesh.uv_texture_add({"object": ob})
ob.data.uv_layers[len(ob.data.uv_layers)-1].name = 'Lightmap'
ob.data.uv_textures['Lightmap'].active = True
bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='SELECT')
# Unwrap the mesh based on the type specified on the object properties!
if ob.thug_lightmap_type == 'Lightmap':
bpy.ops.uv.lightmap_pack(
PREF_CONTEXT='ALL_FACES', PREF_PACK_IN_ONE=True, PREF_NEW_UVLAYER=False,
PREF_APPLY_IMAGE=False, PREF_IMG_PX_SIZE=img_res,
PREF_BOX_DIV=48, PREF_MARGIN_DIV=bake_margin)
elif ob.thug_lightmap_type == 'Smart':
bpy.ops.uv.smart_project()
else:
raise Exception("Unknown lightmap type specified on object {}".format(ob.name))
else:
ob.data.uv_textures['Lightmap'].active = True
bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
if uvs_are_new and scene.thug_bake_pad_uvs == True:
# Argh, Blender's UV projection sometimes creates seams on the edges of the image!
# Add some padding by scaling the whole thing down a little bit
scale_uvs(ob.data.uv_layers['Lightmap'], mathutils.Vector((1.0-uv_padding, 1.0-uv_padding)))
#-----------------------------------------------------------------------------------------
# Multi-pass bake: render multiple bake textures, then flatten then into a single image
# First, bake each pass to a separate image...