-
Notifications
You must be signed in to change notification settings - Fork 25
/
generate.py
1855 lines (1593 loc) · 63.5 KB
/
generate.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
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
import os
import bpy
from .. import conf
from .. import util
# -----------------------------------------------------------------------------
# Material prep and generation functions (no registration)
# -----------------------------------------------------------------------------
def update_mcprep_texturepack_path(self, context):
"""Triggered if the scene-level resource pack path is updated."""
bpy.ops.mcprep.reload_items()
bpy.ops.mcprep.reload_materials()
conf.material_sync_cache = None
def get_mc_canonical_name(name):
"""Convert a material name to standard MC name.
Returns:
canonical name, or fallback to generalized name (never returns None)
form (mc, jmc, or mineways)
"""
general_name = util.nameGeneralize(name)
if not conf.json_data:
res = util.load_mcprep_json()
if not res:
return general_name, None
# Special case to allow material names, e.g. in meshswap, to end in .emit
# while still mapping to canonical names, to pick up features like animated
# textures. Cross check that name isn't exactly .emit to avoid None return.
if ".emit" in general_name and general_name != ".emit":
general_name = general_name.replace(".emit", "")
if ("blocks" not in conf.json_data
or "block_mapping_mc" not in conf.json_data["blocks"]
or "block_mapping_jmc" not in conf.json_data["blocks"]
or "block_mapping_mineways" not in conf.json_data["blocks"]):
conf.log("Missing key values in json")
return general_name, None
if general_name in conf.json_data["blocks"]["block_mapping_mc"]:
canon = conf.json_data["blocks"]["block_mapping_mc"][general_name]
form = "mc"
elif general_name in conf.json_data["blocks"]["block_mapping_jmc"]:
canon = conf.json_data["blocks"]["block_mapping_jmc"][general_name]
form = "jmc2obj"
elif general_name in conf.json_data["blocks"]["block_mapping_mineways"]:
canon = conf.json_data["blocks"]["block_mapping_mineways"][general_name]
form = "mineways"
elif general_name.lower() in conf.json_data["blocks"]["block_mapping_jmc"]:
canon = conf.json_data["blocks"]["block_mapping_jmc"][general_name.lower()]
form = "jmc2obj"
elif general_name.lower() in conf.json_data["blocks"]["block_mapping_mineways"]:
canon = conf.json_data["blocks"]["block_mapping_mineways"][general_name.lower()]
form = "mineways"
else:
conf.log("Canonical name not matched: " + general_name, True)
canon = general_name
form = None
if canon is None or canon == '':
conf.log("Error: Encountered None canon value with " + str(general_name))
canon = general_name
return canon, form
def find_from_texturepack(blockname, resource_folder=None):
"""Given a blockname (and resource folder), find image filepath.
Finds textures following any pack which should have this structure, and
the input folder or default resource folder could target at any of the
following sublevels above the <subfolder> level.
//pack_name/assets/minecraft/textures/<subfolder>/<blockname.png>
"""
if not resource_folder:
# default to internal pack
resource_folder = bpy.path.abspath(bpy.context.scene.mcprep_texturepack_path)
if not os.path.isdir(resource_folder):
conf.log("Error, resource folder does not exist")
return
elif os.path.isdir(os.path.join(resource_folder,"textures")):
resource_folder = os.path.join(resource_folder,"textures")
elif os.path.isdir(os.path.join(resource_folder,"minecraft","textures")):
resource_folder = os.path.join(resource_folder,"minecraft","textures")
elif os.path.isdir(os.path.join(resource_folder,"assets","minecraft","textures")):
resource_folder = os.path.join(resource_folder,"assets","minecraft","textures")
# if conf.vv:print("\tFinal resource folder/subfolder checking:",resource_folder)
search_paths = [resource_folder,
os.path.join(resource_folder,"blocks"),
os.path.join(resource_folder,"block"),
os.path.join(resource_folder,"items"),
os.path.join(resource_folder,"item"),
os.path.join(resource_folder,"entity"),
os.path.join(resource_folder,"models"),
os.path.join(resource_folder,"model"),
]
res = None
# first see if subpath included is found, prioritize use of that
extensions = [".png",".jpg",".jpeg"]
if "/" in blockname:
newpath = blockname.replace("/", os.path.sep)
for ext in extensions:
if os.path.isfile(os.path.join(resource_folder,newpath+ext)):
res = os.path.join(resource_folder,newpath+ext)
return res
newpath = os.path.basename(blockname) # case where goes into other subpaths
for ext in extensions:
if os.path.isfile(os.path.join(resource_folder,newpath+ext)):
res = os.path.join(resource_folder,newpath+ext)
return res
# fallback (more common case), wide-search for
for path in search_paths:
if not os.path.isdir(path):
continue
for ext in extensions:
check_path = os.path.join(path, blockname+ext)
if os.path.isfile(check_path):
res = os.path.join(path, blockname+ext)
return res
# Mineways fallback
for suffix in ["-Alpha", "-RGB", "-RGBA"]:
if blockname.endswith(suffix):
res = os.path.join(resource_folder,"mineways_assets",
"mineways"+suffix+".png")
if os.path.isfile(res):
return res
return res
def detect_form(materials):
"""Function which, given the input materials, guesses the exporter form.
Useful for pre-determining elibibility of a function and also for tracking
reporting to give sense of how common which exporter is used.
"""
jmc2obj = 0
mc = 0
mineways = 0
for mat in materials:
if not mat:
continue
name = util.nameGeneralize(mat.name)
_, form = get_mc_canonical_name(name)
if form == "jmc2obj":
jmc2obj+=1
elif form == "mineways":
mineways+=1
else:
mc+=1
only_mineways = False
# more logic, e.g. count
if mineways==0 and jmc2obj==0:
res = None # unknown
elif mineways>0 and jmc2obj==0:
res = "mineways"
elif jmc2obj>0 and mineways==0:
res = "jmc2obj"
elif jmc2obj < mineways:
res = "mineways"
elif jmc2obj > mineways:
res = "jmc2obj"
else:
res = None # unknown
return res # one of jmc2obj, mineways, or None
def checklist(matName, listName):
"""Helper to expand single wildcard within generalized material names"""
if not conf.json_data:
conf.log("No json_data for checklist to call from!")
if not "blocks" in conf.json_data or not listName in conf.json_data["blocks"]:
conf.log("conf.json_data is missing blocks or listName "+str(listName))
return False
if matName in conf.json_data["blocks"][listName]:
return True
for name in conf.json_data["blocks"][listName]:
if not '*' in name:
continue
x = name.split('*')
if x[0] != '' and x[0] in matName:
return True
elif x[1] != '' and x[1] in matName:
return True
return False
def matprep_internal(mat, passes, use_reflections, only_solid):
"""Update existing internal materials with improved settings.
Will not necessarily properly convert cycles materials into internal."""
if not conf.json_data:
res = util.load_mcprep_json()
image_diff = passes["diffuse"]
image_norm = passes["diffuse"]
image_spec = passes["diffuse"]
image_disp = None # not used
newName = mat.name+'_tex'
texList = mat.texture_slots.values()
try:
bpy.data.textures[texList[0].name].name = newName
except:
conf.log('\twarning: material '
+mat.name+' has no texture slot. skipping...')
return
# disable all but first slot, ensure first slot enabled
mat.use_textures[0] = True
diff_layer = 0
spec_layer = None
norm_layer = None
disp_layer = None
saturate_layer = None
first_unused = None
for index in range(1,len(texList)):
if not mat.texture_slots[index] or not mat.texture_slots[index].texture:
mat.use_textures[index] = False
if not first_unused:
first_unused = index
elif "MCPREP_diffuse" in mat.texture_slots[index].texture:
diff_layer = index
mat.use_textures[index] = True
elif "MCPREP_specular" in mat.texture_slots[index].texture:
spec_layer = index
mat.use_textures[index] = True
elif "MCPREP_normal" in mat.texture_slots[index].texture:
norm_layer = index
mat.use_textures[index] = True
elif "SATURATE" in mat.texture_slots[index].texture:
saturate_layer = index
mat.use_textures[index] = True
else:
mat.use_textures[index] = False
if mat.texture_slots[diff_layer].texture.type != "IMAGE":
conf.log("No diffuse-detected texture, skipping material: "+mat.name)
return 1
# strip out the .00#
canon, _ = get_mc_canonical_name(util.nameGeneralize(mat.name))
mat.use_nodes = False
mat.use_transparent_shadows = True #all materials receive trans
mat.specular_intensity = 0
mat.texture_slots[diff_layer].texture.use_interpolation = False
mat.texture_slots[diff_layer].texture.filter_type = 'BOX'
mat.texture_slots[diff_layer].texture.filter_size = 0
mat.texture_slots[diff_layer].use_map_color_diffuse = True
mat.texture_slots[diff_layer].diffuse_color_factor = 1
if only_solid is False and not checklist(canon, "solid"): # alpha default on
bpy.data.textures[newName].use_alpha = True
mat.texture_slots[diff_layer].use_map_alpha = True
mat.use_transparency = True
mat.alpha = 0
mat.texture_slots[diff_layer].alpha_factor = 1
for index in [spec_layer, norm_layer, disp_layer]:
if index:
mat.texture_slots[index].use_map_alpha = False
if use_reflections and checklist(canon, "reflective"):
mat.alpha = 0
mat.raytrace_mirror.use = True
mat.raytrace_mirror.reflect_factor = 0.15
else:
mat.raytrace_mirror.use = False
mat.alpha = 0
if checklist(canon, "emit") or "emit" in mat.name.lower():
mat.emit = 1
else:
mat.emit = 0
# cycle through and see if the layer exists to enable/disable blend
if not checklist(canon, "desaturated"):
pass
else:
diff_img = mat.texture_slots[diff_layer].texture.image
is_grayscale = is_image_grayscale(diff_img)
# TODO: code is duplicative to below, consolidate later
if mat.name+"_saturate" in bpy.data.textures:
new_tex = bpy.data.textures[mat.name+"_saturate"]
else:
new_tex = bpy.data.textures.new(name=mat.name+"_saturate", type="BLEND")
if not saturate_layer:
if not first_unused:
first_unused = len(mat.texture_slots)-1 # force reuse last at worst
sl = mat.texture_slots.create(first_unused)
else:
sl = mat.texture_slots[saturate_layer]
sl.texture = new_tex
sl.texture["SATURATE"] = True
sl.use_map_normal = False
sl.use_map_color_diffuse = True
sl.use_map_specular = False
sl.use_map_alpha = False
sl.blend_type = 'MULTIPLY' # changed from OVERLAY
sl.use = bool(is_grayscale) # turns off if not grayscale (or None)
new_tex.use_color_ramp = True
for _ in range(len(new_tex.color_ramp.elements)-1):
new_tex.color_ramp.elements.remove(new_tex.color_ramp.elements[0])
desat_color = conf.json_data['blocks']['desaturated'][canon]
if len(desat_color) < len(new_tex.color_ramp.elements[0].color):
desat_color.append(1.0)
new_tex.color_ramp.elements[0].color = desat_color
return 0
def matprep_cycles(mat, passes, use_reflections, use_principled, only_solid, pack_format):
"""Determine how to prep or generate the cycles materials.
Args:
mat: the existing material
passes: dictionary struc of all found pass names
use_reflections: whether to turn reflections on
use_principled: if available and cycles, use principled node
saturate: if a desaturated texture (by canonical resource), add color
format: which format of PBR, string ("Specular" or "SEUS")
Returns:
int: 0 only if successful, otherwise None or other
"""
if util.bv28():
# ensure nodes are enabled esp. after importing from BI scenes
mat.use_nodes = True
matGen = util.nameGeneralize(mat.name)
canon, form = get_mc_canonical_name(matGen)
use_emission = checklist(canon, "emit") or "emit" in mat.name.lower()
# Choose between principled or not, and tells the generator which PBR format to use
# TODO: Update different options for water before enabling this
# if use_reflections and checklist(canon, "water"):
# res = matgen_special_water(mat, passes)
# if use_reflections and checklist(canon, "glass"):
# res = matgen_special_glass(mat, passes)
if use_principled and hasattr(bpy.types, 'ShaderNodeBsdfPrincipled'):
res = matgen_cycles_principled(mat, passes, use_reflections, use_emission, only_solid, pack_format)
else:
res = matgen_cycles_original(mat, passes, use_reflections, use_emission, only_solid, pack_format)
return res
def set_texture_pack(material, folder, use_extra_passes):
"""Replace existing material's image with texture pack's.
Run through and check for each if counterpart material exists, then
run the swap (and auto load e.g. normals and specs if avail.)
"""
mc_name, _ = get_mc_canonical_name(material.name)
image = find_from_texturepack(mc_name, folder)
if image is None:
return 0
image_data = util.loadTexture(image)
engine = bpy.context.scene.render.engine
if engine == 'CYCLES' or engine == 'BLENDER_EEVEE':
status = set_cycles_texture(image_data, material, True)
elif engine == 'BLENDER_RENDER' or engine == 'BLENDER_GAME':
status = set_internal_texture(image_data, material, use_extra_passes)
return 1
def assert_textures_on_materials(image, materials):
"""Called for any texture changing, e.g. skin, input a list of material and
an already loaded image datablock."""
# TODO: Add option to search for or ignore/remove extra maps (normal, etc)
engine = bpy.context.scene.render.engine
count = 0
if engine == 'BLENDER_RENDER' or engine == 'BLENDER_GAME':
for mat in materials:
status = set_internal_texture(image, mat)
if status: count+=1
elif engine == 'CYCLES' or engine == 'BLENDER_EEVEE':
for mat in materials:
status = set_cycles_texture(image, mat)
if status: count+=1
return count
def set_cycles_texture(image, material, extra_passes=False):
"""
Used by skin swap and assiging missing textures or tex swapping.
Args:
image: already loaded image datablock
material: existing material datablock
extra_passes: whether to include or hard exclude non diffuse passes
"""
conf.log("Setting cycles texture for img: {} mat: {}".format(image.name, material.name))
if material.node_tree is None:
return False
# check if there is more data to see pass types
img_sets = {}
if extra_passes:
img_sets = find_additional_passes(image.filepath)
changed=False
is_grayscale = False
canon, _ = get_mc_canonical_name(util.nameGeneralize(material.name))
if checklist(canon, "desaturated"):
is_grayscale = is_image_grayscale(image)
for node in material.node_tree.nodes:
if node.type == "MIX_RGB" and "SATURATE" in node:
node.mute = not is_grayscale
node.hide = not is_grayscale
conf.log(" mix_rgb to saturate texture")
# if node.type != "TEX_IMAGE": continue
# check to see nodes and their respective pre-named field,
# saved as an attribute on the node
if "MCPREP_diffuse" in node:
node.image = image
node.mute = False
node.hide = False
elif "MCPREP_normal" in node and node.type == 'TEX_IMAGE':
if "normal" in img_sets:
new_img = util.loadTexture(img_sets["normal"])
node.image = new_img
util.apply_colorspace(node, 'Non-Color')
node.mute = False
node.hide = False
else:
node.mute = True
node.hide = True
# remove the link between normal map and principled shader
# normal_map = node.outputs[0].links[0].to_node
# principled = ...
elif "MCPREP_specular" in node and node.type == 'TEX_IMAGE':
if "specular" in img_sets:
new_img = util.loadTexture(img_sets["specular"])
node.image = new_img
node.mute = False
node.hide = False
util.apply_colorspace(node, 'Non-Color')
else:
node.mute = True
node.hide = True
elif node.type == "TEX_IMAGE":
# assume all unlabeled texture nodes should be the diffuse pass
node["MCPREP_diffuse"] = True # annotate node for future reference
node.image = image
node.mute = False
node.hide = False
else:
continue
changed = True
return changed
def set_internal_texture(image, material, extra_passes=False):
"""Set texture for internal engine. Input is image datablock."""
# TODO: when going through layers, see if enabled already for normal /
# spec or not and enabled/disable accordingly (e.g. if was resource
# with normal, now is not)
# check if there is more data to see pass types
canon, _ = get_mc_canonical_name(util.nameGeneralize(material.name))
is_grayscale = False
if checklist(canon, "desaturated"):
is_grayscale = is_image_grayscale(image)
img_sets = {}
if extra_passes:
img_sets = find_additional_passes(image.filepath)
if is_grayscale is True:
img_sets["saturate"] = True
base = None
tex = None
# set primary diffuse color as the first image found
for i,sl in enumerate(material.texture_slots):
if sl==None or sl.texture==None or sl.texture.type!='IMAGE':
continue
sl.texture.image = image
sl.use = True
tex = sl.texture
base=i
sl.use_map_normal = False
sl.use_map_color_diffuse = True
sl.use_map_specular = False
sl.blend_type = 'MIX'
break
# if no textures found, assert adding this one as the first
if tex is None:
conf.log("Found no textures, asserting texture onto material")
name = material.name+"_tex"
if name not in bpy.data.textures:
tex = bpy.data.textures.new(name=name,type="IMAGE")
else:
tex = bpy.data.textures[name]
tex.image = image
if material.texture_slots[0] == None:
material.texture_slots.create(0)
material.texture_slots[0].texture = tex
material.texture_slots[0].texture["MCPREP_diffuse"] = True
material.texture_slots[0].use = True
base = 0
# go through and turn off any previous passes not in img_sets
for i,sl in enumerate(material.texture_slots):
if i==base:
continue # skip primary texture set
if "normal" in img_sets and img_sets["normal"]: # pop item each time
if tex and tex.name+"_n" in bpy.data.textures:
new_tex = bpy.data.textures[tex.name+"_n"]
else:
new_tex = bpy.data.textures.new(name=tex.name+"_n",type="IMAGE")
print(sl)
if not sl:
sl = material.texture_slots.create(i)
f = img_sets.pop("normal")
new_img = util.loadTexture(f)
new_tex.image = new_img
sl.texture = new_tex
sl.texture["MCPREP_normal"] = True
sl.use_map_normal = True
sl.normal_factor = 0.1
sl.use_map_color_diffuse = False
sl.use_map_specular = False
sl.use_map_alpha = False
sl.blend_type = 'MIX'
sl.use = True
elif "spec" in img_sets and img_sets["spec"]:
if tex and tex.name+"_s" in bpy.data.textures:
new_tex = bpy.data.textures[tex.name+"_s"]
else:
new_tex = bpy.data.textures.new(name=tex.name+"_s",type="IMAGE")
if not sl:
sl = material.texture_slots.create(i)
f = img_sets.pop("specular")
new_img = util.loadTexture(f)
new_img.use_alpha = False # would mess up material
new_tex.image = new_img
sl.texture = new_tex
sl.texture["MCPREP_specular"] = True
sl.use_map_normal = False
sl.use_map_color_diffuse = False
sl.use_map_specular = True
sl.use_map_alpha = False
sl.blend_type = 'MIX'
sl.use = True
elif "saturate" in img_sets:
img_sets.pop("saturate")
print("Running saturate")
if not checklist(canon, "desaturated"):
continue
if tex and tex.name+"_saturate" in bpy.data.textures:
new_tex = bpy.data.textures[tex.name+"_saturate"]
else:
new_tex = bpy.data.textures.new(name=tex.name+"_saturate", type="BLEND")
if not sl:
sl = material.texture_slots.create(i)
sl.texture = new_tex
sl.texture["SATURATE"] = True
sl.use_map_normal = False
sl.use_map_color_diffuse = True
sl.use_map_specular = False
sl.use_map_alpha = False
sl.blend_type = 'OVERLAY'
sl.use = True
new_tex.use_color_ramp = True
for _ in range(len(new_tex.color_ramp.elements)-1):
new_tex.color_ramp.elements.remove(new_tex.color_ramp.elements[0])
desat_color = conf.json_data['blocks']['desaturated'][canon]
if len(desat_color) < len(new_tex.color_ramp.elements[0].color):
desat_color.append(1.0)
new_tex.color_ramp.elements[0].color = desat_color
return True
def get_node_for_pass(material, pass_name):
"""Assumes cycles material, returns texture node for given pass in mat."""
if pass_name not in ["diffuse", "specular", "normal", "displace"]:
return None
if not material.node_tree:
return None
return_node = None
for node in material.node_tree.nodes:
if node.type != "TEX_IMAGE":
continue
elif "MCPREP_diffuse" in node and pass_name == "diffuse":
return_node = node
elif "MCPREP_normal" in node and pass_name == "normal":
return_node = node
elif "MCPREP_specular" in node and pass_name == "specular":
return_node = node
elif "MCPREP_displace" in node and pass_name == "displace":
return_node = node
else:
if not return_node:
return_node = node
return return_node
def get_texlayer_for_pass(material, pass_name):
"""Assumes BI material, returns texture layer for given pass in mat."""
if pass_name not in ["diffuse", "specular", "normal", "displace"]:
return None
if not hasattr(material, "texture_slots"):
return None
for sl in material.texture_slots:
if not (sl and sl.use and sl.texture!=None
and hasattr(sl.texture, "image")
and sl.texture.image!=None): continue
if sl.use_map_color_diffuse and pass_name == "diffuse":
return sl.texture
elif sl.use_map_normal and pass_name == "normal":
return sl.texture
elif sl.use_map_specular and pass_name == "specular":
return sl.texture
elif sl.use_map_displacement and pass_name == "displace":
return sl.texture
def get_textures(material):
"""Extract the image datablocks for a given material (prefer cycles).
Returns {"diffuse":texture.image, "normal":node.image "spec":None, ...}
"""
image_block = None
passes = {"diffuse":None, "specular":None, "normal":None,
"displace":None}
if not material:
return passes
# first try cycles materials, fall back to internal if not present
if material.use_nodes == True:
for node in material.node_tree.nodes:
if node.type != "TEX_IMAGE":
continue
elif "MCPREP_diffuse" in node:
passes["diffuse"] = node.image
elif "MCPREP_normal" in node:
passes["normal"] = node.image
elif "MCPREP_specular" in node:
passes["specular"] = node.image
else:
if not passes["diffuse"]:
passes["diffuse"] = node.image
# look through internal, unless already found main diffuse pass
# TODO: Consider checking more explicitly checking based on selected engine
if hasattr(material, "texture_slots") and not passes["diffuse"]:
for sl in material.texture_slots:
if not (sl and sl.use and sl.texture!=None
and hasattr(sl.texture, "image")
and sl.texture.image!=None): continue
if sl.use_map_color_diffuse and passes["diffuse"] is None:
passes["diffuse"] = sl.texture.image
elif sl.use_map_normal and passes["normal"] is None:
passes["normal"] = sl.texture.image
elif sl.use_map_specular and passes["specular"] is None:
passes["specular"] = sl.texture.image
elif sl.use_map_displacement and passes["displace"] is None:
passes["displace"] = sl.texture.image
return passes
def find_additional_passes(image_file):
"""Find relevant passes like normal and spec in same folder as image."""
abs_img_file = bpy.path.abspath(image_file)
conf.log("\tFind additional passes for: "+image_file, vv_only=True)
if not os.path.isfile(abs_img_file):
return {}
img_dir = os.path.dirname(abs_img_file)
img_base = os.path.basename(abs_img_file)
base_name = os.path.splitext(img_base)[0] # remove extension
# valid extentsions and ending names for pass types
exts = [".png",".jpg",".jpeg",".tiff"]
normal = [" n","_n","-n"," normal","_norm","_nrm"," normals"]
spec = [" s","_s","-s"," specular","_spec"]
disp = [" d","_d","-d"," displace","_disp"," bump"," b","_b","-b"]
res = {"diffuse":image_file}
# find lowercase base name matching with valid extentions
filtered_files = []
for f in os.listdir(img_dir):
if not f.lower().startswith(base_name.lower()):
continue
if not os.path.isfile(os.path.join(img_dir,f)):
continue
if os.path.splitext(f)[-1].lower() not in exts:
continue
filtered_files.append(f)
# now do narrow matching based on each extention name type
for filtered in filtered_files:
this_base = os.path.splitext(filtered)[0]
for npass in normal:
if this_base.lower() == (base_name+npass).lower():
res["normal"]=os.path.join(img_dir, filtered)
for spass in spec:
if this_base.lower() == (base_name+spass).lower():
res["specular"]=os.path.join(img_dir, filtered)
for dpass in disp:
if this_base.lower() == (base_name+dpass).lower():
res["displace"]=os.path.join(img_dir, filtered)
return res
def replace_missing_texture(image):
"""If image missing from image datablock, replace from texture pack.
Image block name could be the diffuse or any other pass of material, and
should handle accordingly
"""
if image is None:
return False
if image.source == 'SEQUENCE' and os.path.isfile(bpy.path.abspath(image.filepath)):
# technically the next statement should prevail, but this filecheck
# addresses animated textures who show up without any size/pixel data
# just after a reload (even though functional)
return False
if image.size[0] != 0 and image.size[1] != 0:
# Non zero means currently loaded, but could be lost on reload
if image.packed_file:
# only assume safe if packed...
return False
elif os.path.isfile(bpy.path.abspath(image.filepath)):
# ... or the filepath is present.
return False
conf.log("Missing datablock detected: "+image.name)
name = image.name
if len(name)>4 and name[-4] == ".":
name = name[:-4] # cuts off e.g. .png
elif len(name)>5 and name[-5] == ".":
name = name[:-5] # cuts off e.g. .jpeg
canon, _ = get_mc_canonical_name(name)
# TODO: detect for pass structure like normal and still look for right pass
image_path = find_from_texturepack(canon)
if not image_path:
return False
image.filepath = image_path
# image.reload() # not needed?
# pack?
return True # updated image block
def is_image_grayscale(image):
"""Returns true if image data is all grayscale, false otherwise"""
def rgb_to_saturation(r, g, b):
"""Converter 0-1 rgb values back to 0-1 saturation value"""
mx = max(r, g, b)
if mx == 0:
return 0
mn = min(r, g, b)
df = mx-mn
return (df/mx)
if not image:
return None
conf.log("Checking image for grayscale "+image.name, vv_only=True)
if 'grayscale' in image: # cache
return image['grayscale']
if not image.pixels:
conf.log("Not an image / no pixels", vv_only=True)
return None
# setup sampling to limit number of processed pixels
max_samples = 1000
pxl_count = len(image.pixels)/image.channels
interval = int(pxl_count/max_samples) if pxl_count>max_samples else 1
# Pixel by pixel saturation checks, with some wiggle room thresholds
thresh = 0.1 # treat saturated if any more than 10%
# max pixels above thresh to return as saturated,
# 15% is chosen as ~double the % of "yellow" pixels in vanilla jungle leaves
max_thresh = 0.15*pxl_count
# running count to check against
pixels_saturated = 0
# check all pixels until
for ind in range(int(pxl_count))[::interval]:
ind = ind*image.channels # could be rgb or rgba
if image.channels > 3 and image.pixels[ind+3] == 0:
continue # skip alpha pixels during check
if rgb_to_saturation(image.pixels[ind],
image.pixels[ind+1],
image.pixels[ind+2]) > thresh:
pixels_saturated += 1
if pixels_saturated >= max_thresh:
image['grayscale'] = False
conf.log("Image not grayscale: "+image.name, vv_only=True)
return False
image['grayscale'] = True # set cache
conf.log("Image is grayscale: "+image.name, vv_only=True)
return True
def set_saturation_material(mat):
"""Update material to be saturated or not"""
if not mat:
return
canon, _ = get_mc_canonical_name(mat.name)
if not checklist(canon, "desaturated"):
conf.log("debug: not eligible for saturation", vv_only=True)
return
conf.log("Running set_saturation on "+mat.name, vv_only=True)
diff_pass = get_node_for_pass(mat, "diffuse")
if not diff_pass:
return
diff_img = diff_pass.image
if not diff_img:
conf.log("debug: No diffuse", vv_only=True)
return
#conf.log(["Detected image?? ", canon, diff_img, diff_img.filepath, diff_img.size[0]])
saturate = is_image_grayscale(diff_img)
desat_color = conf.json_data['blocks']['desaturated'][canon]
engine = bpy.context.scene.render.engine
if engine == 'BLENDER_RENDER' or engine == 'BLENDER_GAME':
# get the saturation textureslot, or create
sat_slot_ind = None
first_unused = None
for index in range(len(mat.texture_slots)):
slot = mat.texture_slots[index]
if not slot or not slot.texture:
if not first_unused:
first_unused = index
continue
elif "SATURATE" not in slot.texture:
continue
sat_slot_ind = index
break
if not sat_slot_ind:
return
mat.use_textures[sat_slot_ind] = bool(saturate)
elif engine == 'CYCLES' or engine == 'BLENDER_EEVEE':
sat_node = None
for node in mat.node_tree.nodes:
if "SATURATE" not in node:
continue
sat_node = node
break
if not sat_node:
return # requires regenerating material to add back
if len(desat_color)==3:
desat_color += [1] # add in alpha
sat_node.inputs[2].default_value = desat_color
sat_node.mute = not bool(saturate)
sat_node.hide = not bool(saturate)
# -----------------------------------------------------------------------------
# Generating node groups
# -----------------------------------------------------------------------------
def copy_texture_animation_pass_settings(mat):
"""Get any animation settings for passes."""
# Pre-copy any animated node settings before clearing nodes
animated_data = {}
if not mat.use_nodes:
return {}
for node in mat.node_tree.nodes:
if node.type != "TEX_IMAGE":
continue
if not node.image:
continue
if not node.image.source == 'SEQUENCE':
continue
if "MCPREP_diffuse" in node:
passname = "diffuse"
elif "MCPREP_normal" in node:
passname = "normal"
elif "MCPREP_specular" in node:
passname = "specular"
elif "MCPREP_displace" in node:
passname = "displace"
else:
if not animated_data.get("diffuse"):
passname = "diffuse"
animated_data[passname] = {
"frame_duration": node.image_user.frame_duration,
"frame_start": node.image_user.frame_start,
"frame_offset": node.image_user.frame_offset
}
return animated_data
def apply_texture_animation_pass_settings(mat, animated_data):
"""Apply animated texture settings for all given passes of dict."""
if not mat.use_nodes:
return {}
node_diff = get_node_for_pass(mat, "diffuse")
node_normal = get_node_for_pass(mat, "normal")
node_specular = get_node_for_pass(mat, "specular")
node_displace = get_node_for_pass(mat, "displace")
for itm in animated_data:
if itm == "diffuse" and node_diff:
anim_node = node_diff
elif itm == "normal" and node_normal:
anim_node = node_normal
elif itm == "specular" and node_specular:
anim_node = node_specular
elif itm == "displace" and node_displace:
anim_node = node_displace
else:
continue
anim_node.image_user.frame_duration = animated_data[itm]["frame_duration"]
anim_node.image_user.frame_start = animated_data[itm]["frame_start"]
anim_node.image_user.frame_offset = animated_data[itm]["frame_offset"]
anim_node.image_user.use_auto_refresh = True
anim_node.image_user.use_cyclic = True
def texgen_specular(mat, passes, nodeInputs, use_reflections):
matGen = util.nameGeneralize(mat.name)
canon, form = get_mc_canonical_name(matGen)
# Define links and nodes
nodes = mat.node_tree.nodes
links = mat.node_tree.links
# Define the diffuse, normal, and specular nodes
image_diff = passes["diffuse"]
image_norm = passes["normal"]
image_spec = passes["specular"]
# Creates the neccecary nodes
nodeTexDiff = nodes.new("ShaderNodeTexImage")
nodeTexNorm = nodes.new("ShaderNodeTexImage")
nodeTexSpec = nodes.new("ShaderNodeTexImage")
nodeSpecInv = nodes.new("ShaderNodeInvert")