-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblockbuild.py
1543 lines (1247 loc) · 59.3 KB
/
blockbuild.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
# 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.
#
# Contributors:
# Originally authored by Acro
# Modified by Phil B
import bpy
from mathutils import *
import os, sys
import sysutil
DEBUG_BBUV = False
DEBUG_SHADER = False
#create class for the other functions? BlockBuilder.
#NICEIF: SpaceView3D.grid_subdivisions = 16 (so they're MC pixel-based)
TERRAIN_TEXTURE_ATLAS_NAME = 'textures_0.png' # based on the filename used by Minecraft (was terrain.png)
TEXTURE_ATLAS_UNITS = 32 # Number of textures x & y in the texture atlas (was 16)
TEXTURE_ATLAS_PIXELS_PER_UNIT = 16
TEXTURE_ATLAS_PIXELS = 512 # Pixel w & h of the texture atlas (TEXTURE_ATLAS_UNITS*TEXTURE_ATLAS_PIXELS_PER_UNIT) (was 256)
def getTextureAtlasU(faceTexId):
return faceTexId % TEXTURE_ATLAS_UNITS
def getTextureAtlasV(faceTexId):
return int(faceTexId / TEXTURE_ATLAS_UNITS) #int division.
def getUVUnit():
#The normalised size of a tx tile within the texture image.
return 1/TEXTURE_ATLAS_UNITS
def isBMesh():
majorver = bpy.app.version[0] * 100 + bpy.app.version[1]
return majorver > 262
#return int(bpy.app.build_revision) > 43451
#class BlockBuilder:
# """Defines methods for creating whole-block Minecraft blocks with correct texturing - just needs minecraft path."""
def construct(blockID, basename, diffuseRGB, cubeTexFaces, extraData, constructType="box", shapeParams=None, cycParams=None):
# find block function/constructor that matches the construct type.
#if it's a simple cube...
#stairs
#onehigh
#torch
block = None
if constructType == 'box':
block = createMCBlock(basename, diffuseRGB, cubeTexFaces, cycParams) #extra data
elif constructType == 'onehigh':
block = createInsetMCBlock(basename, diffuseRGB, cubeTexFaces, [0,15,0], cycParams)
elif constructType == '00track':
block = createTrack(basename, diffuseRGB, cubeTexFaces, extraData, cycParams)
#elif constructType == 'hash': #or crop? Is it the same? crops, etc.
elif constructType == 'cross':
block = createXBlock(basename, diffuseRGB, cubeTexFaces, extraData, cycParams)
elif constructType == 'stair':
block = createStairBlock(basename, diffuseRGB, cubeTexFaces, extraData, cycParams)
elif constructType == 'fence':
block = createFenceBlock(basename, diffuseRGB, cubeTexFaces, shapeParams, cycParams) # for this, shape params will be NESW flags.
elif constructType == 'inset': #make an inset box (requires shapeParams)
block = createInsetMCBlock(basename, diffuseRGB, cubeTexFaces, shapeParams, cycParams) #shapeprms must be a 3-list
else:
block = createMCBlock(basename, diffuseRGB, cubeTexFaces, cycParams) #extra data # soon to be removed as a catch-all!
return block
def getMCTex():
tname = 'mcTexBlocks'
if tname in bpy.data.textures:
return bpy.data.textures[tname]
print("creating fresh new minecraft terrain texture")
texNew = bpy.data.textures.new(tname, 'IMAGE')
texNew.image = getMCImg()
# FIXME
#texNew.image.use_premultiply = True
texNew.image.alpha_mode = 'PREMUL'
texNew.use_alpha = True
texNew.use_preview_alpha = True
texNew.use_interpolation = False
texNew.filter_type = 'BOX' #no AA - nice minecraft pixels!
def getMCImg():
MCPATH = sysutil.getMCPath()
osdir = os.getcwd() #original os folder before jumping to temp.
if TERRAIN_TEXTURE_ATLAS_NAME in bpy.data.images:
return bpy.data.images[TERRAIN_TEXTURE_ATLAS_NAME]
else:
img = None
temppath = os.path.sep.join([MCPATH, TERRAIN_TEXTURE_ATLAS_NAME])
print("Mineblend loading terrain: "+temppath)
if os.path.exists(temppath):
img = bpy.data.images.load(temppath)
else:
# generate a placeholder image for the texture if terrain.png doesn't exist (rather than failing)
print("no terrain texture found... creating empty")
img = bpy.data.images.new(TERRAIN_TEXTURE_ATLAS_NAME, 1024, 1024, True, False)
img.source = 'FILE'
os.chdir(osdir)
return img
def getCyclesMCImg():
#Ideally, we want a very large version of terrain.png to hack around
#cycles' inability to give us control of Alpha in 2.61
#However, for now it just gives a separate instance of the normal one that
#will need to be scaled up manually (ie replace this image to fix all transparent noodles)
#todo: proper interpolation via nodes
if 'hiResTerrain.png' not in bpy.data.images:
im1 = None
if TERRAIN_TEXTURE_ATLAS_NAME not in bpy.data.images:
im1 = getMCImg()
else:
im1 = bpy.data.images[TERRAIN_TEXTURE_ATLAS_NAME]
#Create second version/instance of it.
im2 = im1.copy()
im2.name = 'hiResTerrain.png'
#scale that up / modify... somehow? Add no-interpolation nodes
return bpy.data.images['hiResTerrain.png']
def createBMeshBlockCubeUVs(blockname, me, matrl, faceIndices): #assume me is a cube mesh. RETURNS **NAME** of the uv layer created.
"""Uses faceIndices, a list of per-face MC texture indices, to unwrap
the cube's faces onto their correct places on terrain.png.
Face order for faceIndices is [Bottom,Top,Right,Front,Left,Back]"""
#print("Creating bmesh uvs for: %s" % blockname)
if faceIndices is None:
print("Warning: no face texture for %s" % blockname)
return
__listtype = type([])
if type(faceIndices) != __listtype:
if (type(faceIndices) == type(0)):
faceIndices = [faceIndices]*6
print("Applying singular value to all 6 faces")
else:
print("setting material and uvs for %s: non-numerical face list" % blockname)
print(faceIndices)
raise IndexError("improper face assignment data!")
if matrl.name not in me.materials:
me.materials.append(matrl)
uname = blockname + 'UVs'
if uname in me.uv_textures:
blockUVLayer = me.uv_textures[uname]
else:
blockUVLayer = me.uv_textures.new(name=uname)
#blockUVLoop = me.uv_loop_layers[-1] #works prior to 2.63??
blockUVLoop = me.uv_layers.active
uvData = blockUVLoop.data
#bmesh face indices - a mapping to the new cube order
#faceIndices face order is [Bottom,Top,Right,Front,Left,Back]
#BMESH loop face order is [left,back,right,front,bottom,top] (for default cube)
if DEBUG_BBUV:
print("createBMeshBlockCubeUVs "+blockname+" attempting to get faces: "+str(faceIndices))
bmfi = [faceIndices[4], faceIndices[5], faceIndices[2], faceIndices[3], faceIndices[0], faceIndices[1]]
#get the loop, and iterate it based on the me.polygons face info. yay!
#The order is a bit off from what might be expected, though...
#And the uv order goes uv2 <-- uv1
# | ^
# v |
# uv3 --> uv4
# It's anticlockwise from top right.
#the 4 always-the-same offsets from the uv tile to get its corners
#(anticlockwise from top right).
#TODO: get image dimension to automagically work with hi-res texture packs.
uvUnit = getUVUnit()
#16px is 1/16th of the a 256x256 terrain.png. etc.
#calculation of the tile location will get the top left corner, via "* 16".
# these are the default face uvs, ie topright, topleft, botleft, botright.
uvcorners = [(uvUnit, 0.0), (0.0,0.0), (0.0, -uvUnit), (uvUnit,-uvUnit)]
#uvUnit is subtracted, as Y(v) counts up from image bottom, but I count 0 from top
#top is rotated from default
uvcornersTop = [(uvUnit,-uvUnit), (uvUnit, 0.0), (0.0,0.0), (0.0, -uvUnit)] # 4,1,2,3
#bottom is rotated and flipped from default
uvcornersBot = [(0.0, -uvUnit), (0.0,0.0), (uvUnit, 0.0), (uvUnit,-uvUnit)] # 3,2,1,4
#we have to assign each UV in sequence of the 'loop' for the whole mesh: 24 for a cube.
xim = getMCImg()
meshtexfaces = blockUVLayer.data.values()
matrl.game_settings.alpha_blend = 'CLIP'
matrl.game_settings.use_backface_culling = False
faceNo = 0 #or enumerate me.polygons?
#face order is: [left,back,right,front,bottom,top]
for pface in me.polygons:
face = meshtexfaces[faceNo]
face.image = xim
faceTexId = bmfi[faceNo]
# FIXME - old 16x16 (256x256px) texture map
##calculate the face location on the uvmap
#mcTexU = faceTexId % 16
#mcTexV = int(faceTexId / 16) #int division.
##multiply by square size to get U1,V1 (topleft):
#u1 = (mcTexU * 16.0) / 256.0 # or >> 4 (div by imagesize to get as fraction)
#v1 = (mcTexV * 16.0) / 256.0 # ..
# New 25x19 (512x512px) texture map
mcTexU = getTextureAtlasU(faceTexId)
mcTexV = getTextureAtlasV(faceTexId)
u1 = (mcTexU * TEXTURE_ATLAS_PIXELS_PER_UNIT) / TEXTURE_ATLAS_PIXELS
v1 = (mcTexV * TEXTURE_ATLAS_PIXELS_PER_UNIT) / TEXTURE_ATLAS_PIXELS
v1 = 1.0 - v1 #y goes low to high #DEBUG print("That means u1,v1 is %f,%f" % (u1,v1))
##DEBUG
if DEBUG_BBUV:
print("mcTexU,mcTexV "+str(mcTexU)+", "+str(mcTexV)+" - u1, v1 %d,%d" % (u1,v1))
#print("minecraft chunk texture x,y within image: %d,%d" % (mcTexU, mcTexV))
#if DEBUG_BBUV:
# print("createBMeshBlockCubeUVs "+blockname+" u1, v1: %d,%d" % (u1, v1))
loopPolyStart = pface.loop_start #where its verts start in the loop. Yay!
#if loop total's not 4, need to work with ngons or tris or do more complex stuff.
loopPolyCount = pface.loop_total
loopPolyEnd = loopPolyStart + loopPolyCount
corners = uvcorners
if faceNo == 5: #top face
corners = uvcornersTop
elif faceNo == 4: #bottom face
corners = uvcornersBot
uvx = 0
for uvc in range(loopPolyStart, loopPolyEnd):
offset = corners[uvx] # 0..3
mcUV = Vector((u1+offset[0], v1+offset[1]))
#apply the calculated face uv + vert offset to the current loop element
if DEBUG_BBUV:
print("offset "+str(offset)+", mvUV "+str(mcUV))
uvData[uvc].uv = mcUV
uvx += 1
faceNo += 1
me.tessface_uv_textures.data.update() #a guess. does this actually help? YES! Without it all the world's grey and textureless!
return "".join([blockname, 'UVs'])
def createBlockCubeUVs(blockname, me, matrl, faceIndices): #assume me is a cube mesh. RETURNS **NAME** of the uv layer created.
#Use faceIndices, a list of per-face MC texture square indices, to unwrap
#the cube's faces to correct places on terrain.png
if faceIndices is None:
print("Warning: no face texture for %s" % blockname)
return
#Face order is [Bottom,Top,Right,Front,Left,Back]
__listtype = type([])
if type(faceIndices) != __listtype:
if (type(faceIndices) == type(0)):
faceIndices = [faceIndices]*6
print("Applying singular value to all 6 faces")
else:
print("setting material and uvs for %s: non-numerical face list" % blockname)
print(faceIndices)
raise IndexError("improper face assignment data!")
if matrl.name not in me.materials:
me.materials.append(matrl)
uname = blockname + 'UVs'
blockUVLayer = me.uv_textures.new(uname) #assuming it's not so assigned already, ofc.
xim = getMCImg()
meshtexfaces = blockUVLayer.data.values()
#Legacy compatibility feature: before 2.60, the alpha clipping is set not
#via the 'game_settings' but in the material...
bver = bpy.app.version[0] + bpy.app.version[1] / 100.0 #eg 2.59
if bver >= 2.6:
matrl.game_settings.alpha_blend = 'CLIP'
matrl.game_settings.use_backface_culling = False
for fnum, fid in enumerate(faceIndices):
face = meshtexfaces[fnum]
face.image = xim
if bver < 2.6:
face.blend_type = 'ALPHA'
#use_image
#Pick UV square off the 2D texture surface based on its Minecraft texture 'index'
#eg 160 for lapis, 49 for glass, etc.
mcTexU = getTextureAtlasU(fid)
mcTexV = getTextureAtlasV(fid)
#multiply by square size to get U1,V1:
u1 = (mcTexU * TEXTURE_ATLAS_PIXELS_PER_UNIT) / TEXTURE_ATLAS_PIXELS # or >> 4 (div by imagesize to get as fraction)
v1 = (mcTexV * TEXTURE_ATLAS_PIXELS_PER_UNIT) / TEXTURE_ATLAS_PIXELS # ..
v1 = 1.0 - v1 #y goes low to high for some reason.
#DEBUG print("That means u1,v1 is %f,%f" % (u1,v1))
#16px will be 1/16th of the image.
#The image is 256px wide and tall.
uvUnit = getUVUnit()
mcUV1 = Vector((u1,v1))
mcUV2 = Vector((u1+uvUnit,v1))
mcUV3 = Vector((u1+uvUnit,v1-uvUnit)) #subtract uvunit for y
mcUV4 = Vector((u1, v1-uvUnit))
#DEBUG
if DEBUG_BBUV:
print("createBlockCubeUVs Creating UVs for face with values: %f,%f to %f,%f" % (u1,v1,mcUV3[0], mcUV3[1]))
#We assume the cube faces are always the same order.
#So, face 0 is the bottom.
if fnum == 1: # top
face.uv1 = mcUV2
face.uv2 = mcUV1
face.uv3 = mcUV4
face.uv4 = mcUV3
elif fnum == 5: #back
face.uv1 = mcUV1
face.uv2 = mcUV4
face.uv3 = mcUV3
face.uv4 = mcUV2
else: #bottom (0) and all the other sides..
face.uv1 = mcUV3
face.uv2 = mcUV2
face.uv3 = mcUV1
face.uv4 = mcUV4
return "".join([blockname, 'UVs'])
#References for UV stuff:
#http://www.blender.org/forum/viewtopic.php?t=15989&view=previous&sid=186e965799143f26f332f259edd004f4
#newUVs = cubeMesh.uv_textures.new('lapisUVs')
#newUVs.data.values() -> list... readonly?
#contains one item per face...
#each item is a bpy_struct MeshTextureFace
#each has LOADS of options
# .uv1 is a 2D Vector(u,v)
#they go:
# uv1 --> uv2
# |
# V
# uv4 <-- uv3
#
# .. I think
## For comments/explanation, see above.
def createInsetUVs(blockname, me, matrl, faceIndices, insets):
"""Returns name of UV layer created."""
__listtype = type([])
if type(faceIndices) != __listtype:
if (type(faceIndices) == type(0)):
faceIndices = [faceIndices]*6
print("Applying singular value to all 6 faces")
else:
print("setting material and uvs for %s: non-numerical face list" % blockname)
print(faceIndices)
raise IndexError("improper face assignment data!")
#faceindices: array of minecraft material indices into the terrain.png.
#Face order is [Bottom,Top,Right,Front,Left,Back]
uname = blockname + 'UVs'
blockUVLayer = me.uv_textures.new(uname)
xim = getMCImg()
#ADD THE MATERIAL! ...but why not earlier than this? uv layer add first?
if matrl.name not in me.materials:
me.materials.append(matrl)
meshtexfaces = blockUVLayer.data.values()
bver = bpy.app.version[0] + bpy.app.version[1] / 100.0 #eg 2.59
if bver >= 2.6:
matrl.game_settings.alpha_blend = 'CLIP'
matrl.game_settings.use_backface_culling = False
#Insets are [bottom,top,sides]
uvUnit = getUVUnit()
uvPixl = uvUnit / TEXTURE_ATLAS_UNITS
iB = insets[0] * uvPixl
iT = insets[1] * uvPixl
iS = insets[2] * uvPixl
for fnum, fid in enumerate(faceIndices):
face = meshtexfaces[fnum]
face.image = xim
if bver < 2.6:
face.blend_type = 'ALPHA'
#Pick UV square off the 2D texture surface based on its Minecraft index
#eg 160 for lapis, 49 for glass... etc, makes for x,y:
mcTexU = getTextureAtlasU(fid)
mcTexV = getTextureAtlasV(fid)
#DEBUG print("MC chunk tex x,y in image: %d,%d" % (mcTexU, mcTexV))
#multiply by square size to get U1,V1:
u1 = (mcTexU * TEXTURE_ATLAS_PIXELS_PER_UNIT) / TEXTURE_ATLAS_PIXELS # or >> 4 (div by imagesize to get as fraction)
v1 = (mcTexV * TEXTURE_ATLAS_PIXELS_PER_UNIT) / TEXTURE_ATLAS_PIXELS
v1 = 1.0 - v1 #y goes low to high for some reason. (er...)
#DEBUG print("That means u1,v1 is %f,%f" % (u1,v1))
#16px will be 1/16th of the image.
#The image is 256px wide and tall.
mcUV1 = Vector((u1,v1))
mcUV2 = Vector((u1+uvUnit,v1))
mcUV3 = Vector((u1+uvUnit,v1-uvUnit)) #subtract uvunit for y
mcUV4 = Vector((u1, v1-uvUnit))
#DEBUG print("Creating UVs for face with values: %f,%f to %f,%f" % (u1,v1,mcUV3[0], mcUV3[1]))
#can we assume the cube faces are always the same order? It seems so, yes.
#So, face 0 is the bottom.
if fnum == 0: #bottom
face.uv1 = mcUV3
face.uv2 = mcUV2
face.uv3 = mcUV1
face.uv4 = mcUV4
face.uv3 = Vector((face.uv3[0]+iS, face.uv3[1]-iS))
face.uv2 = Vector((face.uv2[0]-iS, face.uv2[1]-iS))
face.uv1 = Vector((face.uv1[0]-iS, face.uv1[1]+iS))
face.uv4 = Vector((face.uv4[0]+iS, face.uv4[1]+iS))
elif fnum == 1: # top
face.uv1 = mcUV2
face.uv2 = mcUV1
face.uv3 = mcUV4
face.uv4 = mcUV3
#do insets! OMG, they really ARE anticlockwise. ffs.
#why wasn't it right the very, very first time?!
## Nope. This is messed up. The error is endemic and spread
#through all uv application in this script.
#vertex ordering isn't the problem, script references have
#confused the entire issue.
# uv1(2)-> uv2 (1)
# |
# V
# uv4(3) <-- uv3(4)
face.uv2 = Vector((face.uv2[0]+iS, face.uv2[1]-iS))
face.uv1 = Vector((face.uv1[0]-iS, face.uv1[1]-iS))
face.uv4 = Vector((face.uv4[0]-iS, face.uv4[1]+iS))
face.uv3 = Vector((face.uv3[0]+iS, face.uv3[1]+iS))
elif fnum == 5: #back
face.uv1 = mcUV1
face.uv2 = mcUV4
face.uv3 = mcUV3
face.uv4 = mcUV2
face.uv1 = Vector((face.uv1[0]+iS, face.uv1[1]-iT))
face.uv4 = Vector((face.uv4[0]-iS, face.uv4[1]-iT))
face.uv3 = Vector((face.uv3[0]-iS, face.uv3[1]+iB))
face.uv2 = Vector((face.uv2[0]+iS, face.uv2[1]+iB))
else: #all the other sides..
face.uv1 = mcUV3
face.uv2 = mcUV2
face.uv3 = mcUV1
face.uv4 = mcUV4
face.uv3 = Vector((face.uv3[0]+iS, face.uv3[1]-iT))
face.uv2 = Vector((face.uv2[0]-iS, face.uv2[1]-iT))
face.uv1 = Vector((face.uv1[0]-iS, face.uv1[1]+iB))
face.uv4 = Vector((face.uv4[0]+iS, face.uv4[1]+iB))
return "".join([blockname, 'UVs'])
def createBMeshInsetUVs(blockname, me, matrl, faceIndices, insets):
"""Uses faceIndices, a list of per-face MC texture indices, to unwrap
the cube's faces onto their correct places on terrain.png.
Uses 3 insets ([bottom,top,sides]) to indent UVs per-face.
Face order for faceIndices is [Bottom,Top,Right,Front,Left,Back]"""
#print("Creating bmesh uvs for: %s" % blockname)
if faceIndices is None:
print("Warning: no face texture for %s" % blockname)
return
__listtype = type([])
if type(faceIndices) != __listtype:
if (type(faceIndices) == type(0)):
faceIndices = [faceIndices]*6
print("Applying singular value to all 6 faces")
else:
print("setting material and uvs for %s: non-numerical face list" % blockname)
print(faceIndices)
raise IndexError("improper face assignment data!")
if matrl.name not in me.materials:
me.materials.append(matrl)
uname = blockname + 'UVs'
if uname in me.uv_textures:
blockUVLayer = me.uv_textures[uname]
else:
blockUVLayer = me.uv_textures.new(name=uname)
#blockUVLoop = me.uv_loop_layers[-1] #Works prior to 2.63! no it doesn't!!
blockUVLoop = me.uv_layers.active
uvData = blockUVLoop.data
bmfi = [faceIndices[4], faceIndices[5], faceIndices[2], faceIndices[3], faceIndices[0], faceIndices[1]]
uvUnit = getUVUnit()
#Insets are [bottom,top,sides]
uvPixl = uvUnit / TEXTURE_ATLAS_UNITS
iB = insets[0] * uvPixl #insetBottom
iT = insets[1] * uvPixl #insetTop
iS = insets[2] * uvPixl #insetSides
#Sorry. This array set is going to be dense, horrible, and impenetrable.
#For the simple version of this, see createBMeshUVs, not the insets one
#uvcorners is for sides. Xvalues affected by iS
uvcorners = [(uvUnit-iS, 0.0-iT), (0.0+iS,0.0-iT), (0.0+iS, -uvUnit+iB), (uvUnit-iS,-uvUnit+iB)]
uvcornersTop = [(uvUnit-iS,-uvUnit+iS), (uvUnit-iS, 0.0-iS), (0.0+iS,0.0-iS), (0.0+iS, -uvUnit+iS)] # 4,1,2,3
uvcornersBot = [(0.0+iS, -uvUnit+iS), (0.0+iS,0.0-iS), (uvUnit-iS, 0.0-iS), (uvUnit-iS,-uvUnit+iS)] # 3,2,1,4
xim = getMCImg()
meshtexfaces = blockUVLayer.data.values()
matrl.game_settings.alpha_blend = 'CLIP'
matrl.game_settings.use_backface_culling = False
faceNo = 0 #or enumerate me.polygons?
#face order is: [left,back,right,front,bottom,top]
for pface in me.polygons:
face = meshtexfaces[faceNo]
face.image = xim
faceTexId = bmfi[faceNo]
#calculate the face location on the uvmap
mcTexU = getTextureAtlasU(faceTexId)
mcTexV = getTextureAtlasV(faceTexId)
#DEBUG
if DEBUG_BBUV:
print("createBMeshInsetUVs minecraft chunk texture x,y within image: %d,%d" % (mcTexU, mcTexV))
#multiply by square size to get U1,V1 (topleft):
u1 = (mcTexU * TEXTURE_ATLAS_PIXELS_PER_UNIT) / TEXTURE_ATLAS_PIXELS # or >> 4 (div by imagesize to get as fraction)
v1 = (mcTexV * TEXTURE_ATLAS_PIXELS_PER_UNIT) / TEXTURE_ATLAS_PIXELS # ..
v1 = 1.0 - v1 #y goes low to high #DEBUG print("That means u1,v1 is %f,%f" % (u1,v1))
loopPolyStart = pface.loop_start #where its verts start in the loop. Yay!
#if loop total's not 4, need to work with ngons or tris or do more complex stuff.
loopPolyCount = pface.loop_total
loopPolyEnd = loopPolyStart + loopPolyCount
corners = uvcorners
if faceNo == 5: #top face
corners = uvcornersTop
elif faceNo == 4: #bottom face
corners = uvcornersBot
uvx = 0
for uvc in range(loopPolyStart, loopPolyEnd):
offset = corners[uvx] # 0..3
mcUV = Vector((u1+offset[0], v1+offset[1]))
#apply the calculated face uv + vert offset to the current loop element
uvData[uvc].uv = mcUV
uvx += 1
faceNo += 1
me.tessface_uv_textures.data.update() #Without this, all the world is grey and textureless!
return "".join([blockname, 'UVs'])
# Cycles materials. createNGmc* are for Node Groups and create*CyclesMat are the for the materials that use them.
#
# Aside from simplifying the individual material layouts, the reason for using Node Groups extensively is to allow for users to easily customize the overall look of their scene (i.e. rather than having to modify dozens of materials, some changes can have global effect by modifying a single Node Group, depending on the change desired)
MC_SHADER_TEX="mcShaderTex"
MC_SHADER_DIFFUSE="mcShaderDiffuse"
MC_SHADER_STENCIL="mcShaderStencil"
MC_SHADER_STENCIL_COLORED="mcShaderStencilColored"
MC_GROUP_TEX_OUTPUT="Color"
MC_GROUP_DIFFUSE_OUTPUT="BSDF"
MC_GROUP_STENCIL_OUTPUT="Shader"
MC_GROUP_STENCIL_COLORED_OUTPUT="Shader"
TYPE_NODE_GROUP_INPUT="NodeGroupInput"
TYPE_NODE_GROUP_OUTPUT="NodeGroupOutput"
TYPE_NODE_GROUP="ShaderNodeGroup"
BSDF_OUTPUT="BSDF"
FACTOR_INPUT="Fac"
def createNGmcTexture():
"""Node Group for texture. This is a simple texture atlas mapping"""
if DEBUG_SHADER:
print("createNGmcTexture")
ng = bpy.data.node_groups.new(MC_SHADER_TEX,"ShaderNodeTree")
ngo = ng.nodes.new(type=TYPE_NODE_GROUP_OUTPUT)
texCoord = ng.nodes.new(type="ShaderNodeTexCoord")
imageTex = ng.nodes.new(type="ShaderNodeTexImage")
imageTex.image = getMCImg()
imageTex.interpolation = "Closest"
ng.links.new(imageTex.inputs[0],texCoord.outputs[2]) # link the texCoord uv to the imageTex vector
ng.links.new(ngo.inputs[0],imageTex.outputs[0])
ng.links.new(ngo.inputs[1],imageTex.outputs[1])
texCoord.location = Vector((-200, 200))
imageTex.location = Vector((0, 200))
ngo.location = Vector((200, 200))
def setNodeGroup(node,ngName):
if DEBUG_SHADER:
print("setNodeGroup: "+ngName)
# FIXME - is there a better way to use a node group from within a node group?
node.name=ngName
node.label=ngName
node.node_tree=bpy.data.node_groups[ngName]
def createNGmcDiffuse():
"""Node Group for diffuse materials"""
if DEBUG_SHADER:
print("createNGmcDiffuse")
ng = bpy.data.node_groups.new(MC_SHADER_DIFFUSE,"ShaderNodeTree")
ngo = ng.nodes.new(type=TYPE_NODE_GROUP_OUTPUT)
tex = ng.nodes.new(type=TYPE_NODE_GROUP)
setNodeGroup(tex,MC_SHADER_TEX)
diffuse = ng.nodes.new(type="ShaderNodeBsdfDiffuse")
ng.links.new(diffuse.inputs[0],tex.outputs[0]) # link the texCoord uv to the imageTex vector
ng.links.new(ngo.inputs[0],diffuse.outputs[0])
ng.links.new(ngo.inputs[1],tex.outputs[1]) # For stained glass etc
tex.location = Vector((0, 0))
diffuse.location = Vector((200, 200))
ngo.location = Vector((400, 0))
#def createNGmcStencil(): # FIXME - how to handle alternate node data flows? (i.e. loopback / inner node group issue)
# ng = bpy.data.node_groups.new(MC_SHADER_STENCIL,"ShaderNodeTree")
# ngo = ng.nodes.new(type="NodeGroupOutput")
# ngi = ng.nodes.new(type="NodeGroupInput")
# diffNode = ng.nodes.new(type="ShaderNodeGroup")
# setNodeGroup(diffNode,MC_SHADER_DIFFUSE)
#
# links = ng.links
#
# rgbtobwNode = ng.nodes.new(type="ShaderNodeRGBToBW")
# gtNode = ng.nodes.new(type="ShaderNodeMath")
# gtNode.name = "AlphaBlackGT"
# gtNode.operation = 'GREATER_THAN'
# gtNode.inputs[0].default_value = 0.001
#
# transpNode = ng.nodes.new(type="ShaderNodeBsdfTransparent")
# mixNode = ng.nodes.new(type="ShaderNodeMixShader")
#
# ngi.location = Vector((-200,0))
# diffNode.location = Vector((0,0))
# rgbtobwNode.location = Vector((200,200))
# gtNode.location = Vector((400,200))
# transpNode.location = Vector((400,-200))
# mixNode.location = Vector((600,0))
# ngo.location = Vector((800,0))
#
# links.new(input=diffNode.outputs[MC_GROUP_DIFFUSE_OUTPUT], output=rgbtobwNode.inputs['Color'])
# links.new(input=rgbtobwNode.outputs['Val'], output=gtNode.inputs[1])
# links.new(input=gtNode.outputs['Value'], output=mixNode.inputs['Fac'])
#
# #links.new(input=diffNode.outputs[MC_GROUP_DIFFUSE_OUTPUT], output=diff2Node.inputs['Color'])
# #links.new(input=diff2Node.outputs['BSDF'], output=mixNode.inputs[1])
#
# # leave the options open
# #links.new(input=diffNode.outputs['BSDF'], output=mixNode.inputs[1])
#
# links.new(input=transpNode.outputs['BSDF'], output=mixNode.inputs[2])
#
# links.new(input=ngi.outputs[0], output=mixNode.inputs[1])
#
# #links.new(input=mixNode.outputs['Shader'], output=ngo.inputs['Surface'])
# links.new(input=mixNode.outputs['Shader'], output=ngo.inputs[0])
# links.new(input=diffNode.outputs['BSDF'], output=ngo.inputs[1])
def createNGmcStencil():
"""Node Group for stencil materials (i.e. colored textures with alpha)"""
if DEBUG_SHADER:
print("createNGmcStencil")
ng = bpy.data.node_groups.new(MC_SHADER_STENCIL,"ShaderNodeTree")
ngo = ng.nodes.new(type=TYPE_NODE_GROUP_OUTPUT)
ngi = ng.nodes.new(type=TYPE_NODE_GROUP_INPUT)
inNode = ng.nodes.new(type=TYPE_NODE_GROUP)
setNodeGroup(inNode,MC_SHADER_TEX)
links = ng.links
diffNode = ng.nodes.new(type="ShaderNodeBsdfDiffuse")
rgbtobwNode = ng.nodes.new(type="ShaderNodeRGBToBW")
gtNode = ng.nodes.new(type="ShaderNodeMath")
gtNode.name = "AlphaBlackGT"
gtNode.operation = 'GREATER_THAN'
gtNode.inputs[0].default_value = 0.001
transpNode = ng.nodes.new(type="ShaderNodeBsdfTransparent")
mixNode = ng.nodes.new(type="ShaderNodeMixShader")
ngi.location = Vector((-200,0))
inNode.location = Vector((0,0))
rgbtobwNode.location = Vector((200,200))
diffNode.location = Vector((200,0))
gtNode.location = Vector((400,200))
transpNode.location = Vector((400,-200))
mixNode.location = Vector((600,0))
ngo.location = Vector((800,0))
links.new(input=inNode.outputs[MC_GROUP_TEX_OUTPUT], output=rgbtobwNode.inputs['Color'])
links.new(input=rgbtobwNode.outputs['Val'], output=gtNode.inputs[1])
links.new(input=gtNode.outputs['Value'], output=mixNode.inputs[FACTOR_INPUT])
# leave the options open
links.new(input=inNode.outputs[MC_GROUP_TEX_OUTPUT], output=diffNode.inputs['Color'])
links.new(input=diffNode.outputs[BSDF_OUTPUT], output=mixNode.inputs[1])
links.new(input=transpNode.outputs[BSDF_OUTPUT], output=mixNode.inputs[2])
links.new(input=mixNode.outputs['Shader'], output=ngo.inputs[0])
def createNGmcStencilColored():
"""Node Group for colored stencil materials (i.e. grey scale texture with alpha that needs to be colored)"""
if DEBUG_SHADER:
print("createNGmcStencilColored")
ng = bpy.data.node_groups.new(MC_SHADER_STENCIL_COLORED,"ShaderNodeTree")
ngo = ng.nodes.new(type=TYPE_NODE_GROUP_OUTPUT)
ngi = ng.nodes.new(type=TYPE_NODE_GROUP_INPUT)
texNode = ng.nodes.new(type=TYPE_NODE_GROUP)
setNodeGroup(texNode,MC_SHADER_TEX)
links = ng.links
rgbtobwNode = ng.nodes.new(type="ShaderNodeRGBToBW")
gtNode = ng.nodes.new(type="ShaderNodeMath")
gtNode.name = "AlphaBlackGT"
gtNode.operation = 'GREATER_THAN'
gtNode.inputs[0].default_value = 0.001
transpNode = ng.nodes.new(type="ShaderNodeBsdfTransparent")
alphaMixNode = ng.nodes.new(type="ShaderNodeMixShader")
ngi.location = Vector((-200,0))
texNode.location = Vector((0,0))
rgbtobwNode.location = Vector((200,200))
gtNode.location = Vector((400,200))
transpNode.location = Vector((400,-200))
alphaMixNode.location = Vector((600,0))
ngo.location = Vector((800,0))
links.new(input=texNode.outputs[MC_GROUP_TEX_OUTPUT], output=rgbtobwNode.inputs['Color'])
links.new(input=rgbtobwNode.outputs['Val'], output=gtNode.inputs[1])
links.new(input=gtNode.outputs['Value'], output=alphaMixNode.inputs[FACTOR_INPUT])
links.new(input=transpNode.outputs[BSDF_OUTPUT], output=alphaMixNode.inputs[2])
links.new(input=alphaMixNode.outputs['Shader'], output=ngo.inputs[0])
## 'colored' specific portion of material
colorMixNode = ng.nodes.new(type="ShaderNodeMixRGB")
#colorMixNode.inputs[1].name="Dark color"
#colorMixNode.inputs[2].name="Light color"
colorDiffNode = ng.nodes.new(type="ShaderNodeBsdfDiffuse")
colorMixNode.location = Vector((0,400))
colorDiffNode.location = Vector((200,400))
links.new(input=rgbtobwNode.outputs['Val'], output=colorMixNode.inputs[FACTOR_INPUT])
# FIXME - material will not render correctly when names are set (i.e. even though the viewport looks fine, the rgb color mix needs to be re-added and links re-established for successful (i.e. non-black) render.)
#colorMixNode.inputs[1].name="Dark color"
#colorMixNode.inputs[2].name="Light color"
#links.new(input=ngi.outputs[0], output=colorMixNode.inputs["Dark color"])
#links.new(input=ngi.outputs[1], output=colorMixNode.inputs["Light color"])
links.new(input=ngi.outputs[0], output=colorMixNode.inputs[1])
links.new(input=ngi.outputs[1], output=colorMixNode.inputs[2])
links.new(input=colorMixNode.outputs["Color"], output=colorDiffNode.inputs["Color"])
links.new(input=colorDiffNode.outputs[BSDF_OUTPUT], output=alphaMixNode.inputs[1])
ngi.outputs[1].name="Dark color"
ngi.outputs[2].name="Light color"
def createNodeGroups():
"""Create node groups if they don't already exist"""
if DEBUG_SHADER:
print("createNodeGroups")
existsNode = bpy.data.node_groups.get(MC_SHADER_DIFFUSE)
if existsNode==None:
createNGmcTexture()
createNGmcDiffuse()
createNGmcStencil()
createNGmcStencilColored()
def removeExistingDiffuseNode(ntree):
olddif = ntree.nodes['Diffuse BSDF']
ntree.nodes.remove(olddif)
def createDiffuseCyclesMat(mat):
"""Create a basic textured, diffuse material that uses existing UV mapping into texture atlas"""
if DEBUG_SHADER:
print("createDiffuseCyclesMat")
#compatibility with Blender 2.5x:
if not hasattr(bpy.context.scene, 'cycles'):
print("No cycles support... skipping")
return
#Switch render engine to Cycles. Yippee ki-yay!
if bpy.context.scene.render.engine != 'CYCLES':
bpy.context.scene.render.engine = 'CYCLES'
mat.use_nodes = True
#maybe check number of nodes - there should be 2.
ntree = mat.node_tree
mcdif = ntree.nodes.new(type=TYPE_NODE_GROUP)
setNodeGroup(mcdif,MC_SHADER_DIFFUSE)
removeExistingDiffuseNode(ntree)
matOutNode = ntree.nodes['Material Output']
ntree.links.new(input=mcdif.outputs[MC_GROUP_DIFFUSE_OUTPUT], output=matOutNode.inputs['Surface'])
mcdif.location = Vector((0,0))
matOutNode.location = Vector((200,0))
def createEmissionCyclesMat(mat, emitAmt):
"""Emissive materials such as lava, glowstone, etc"""
if DEBUG_SHADER:
print("createEmissionCyclesMat")
if bpy.context.scene.render.engine != 'CYCLES':
bpy.context.scene.render.engine = 'CYCLES'
mat.use_nodes = True
ntree = mat.node_tree #there will now be 4 nodes in there, one of them being the diffuse shader.
removeExistingDiffuseNode(ntree)
diffNode = ntree.nodes.new(type=TYPE_NODE_GROUP)
setNodeGroup(diffNode,MC_SHADER_TEX)
matNode = ntree.nodes['Material Output']
emitNode = ntree.nodes.new(type='ShaderNodeEmission')
nodes = ntree.nodes
links = ntree.links
diffNode.location = Vector((0,0))
emitNode.location = Vector((200,0))
matNode.location = Vector((400,0))
#change links: delete the old links and add new ones.
emitNode.inputs['Strength'].default_value = float(emitAmt) #set this from the EMIT value of data passed in.
bsdfDiffSockOut = diffNode.outputs[MC_GROUP_TEX_OUTPUT]
emitSockOut = emitNode.outputs[0]
for nl in links:
print("link "+str(nl))
if nl.to_socket == matNode:
links.remove(nl)
links.new(input=diffNode.outputs[0], output=emitNode.inputs[0])
links.new(input=emitNode.outputs[0], output=matNode.inputs['Surface'])
def createStencilCyclesMat(mat):
"""Stencil materials such as flowers"""
if DEBUG_SHADER:
print("createStencilCyclesMat")
#Ensure Cycles is in use
if bpy.context.scene.render.engine != 'CYCLES':
bpy.context.scene.render.engine = 'CYCLES'
mat.use_nodes = True
ntree = mat.node_tree
nodes = ntree.nodes
links = ntree.links
inNode = ntree.nodes.new(type=TYPE_NODE_GROUP)
setNodeGroup(inNode,MC_SHADER_TEX)
diffNode = nodes["Diffuse BSDF"] # reuse the one that already exists
matNode = nodes['Material Output']
rgbtobwNode = ntree.nodes.new(type="ShaderNodeRGBToBW")
gtNode = ntree.nodes.new(type="ShaderNodeMath")
gtNode.name = "AlphaBlackGT"
gtNode.operation = 'GREATER_THAN'
gtNode.inputs[0].default_value = 0.001
transpNode = ntree.nodes.new(type="ShaderNodeBsdfTransparent")
mixNode = ntree.nodes.new(type="ShaderNodeMixShader")
inNode.location = Vector((0,0))
diffNode.location = Vector((200,0))
rgbtobwNode.location = Vector((200,200))
gtNode.location = Vector((400,200))
transpNode.location = Vector((400,-200))
mixNode.location = Vector((600,0))
matNode.location = Vector((800,0))
for nl in links:
if nl.to_socket == matNode:
links.remove(nl)
links.new(input=inNode.outputs[MC_GROUP_TEX_OUTPUT], output=rgbtobwNode.inputs['Color'])
links.new(input=rgbtobwNode.outputs['Val'], output=gtNode.inputs[1])
links.new(input=gtNode.outputs['Value'], output=mixNode.inputs[FACTOR_INPUT])
links.new(input=inNode.outputs[MC_GROUP_TEX_OUTPUT], output=diffNode.inputs["Color"])
links.new(input=diffNode.outputs[BSDF_OUTPUT], output=mixNode.inputs[1])
links.new(input=transpNode.outputs[BSDF_OUTPUT], output=mixNode.inputs[2])
links.new(input=mixNode.outputs['Shader'], output=matNode.inputs['Surface'])
def createLeafCyclesMat(mat):
"""Colored stencil materials such as leaves"""
if DEBUG_SHADER:
print("createLeafCyclesMat")
"""Very similar to the transparent (glass) material but different enough to need its own"""
#Ensure Cycles is in use
if bpy.context.scene.render.engine != 'CYCLES':
bpy.context.scene.render.engine = 'CYCLES'
mat.use_nodes = True
ntree = mat.node_tree #there will now be 4 nodes in there, one of them being the diffuse shader.
removeExistingDiffuseNode(ntree)
nodes = ntree.nodes
links = ntree.links
stencilNode = ntree.nodes.new(type=TYPE_NODE_GROUP)
setNodeGroup(stencilNode,MC_SHADER_STENCIL_COLORED)
matNode = nodes['Material Output']
darkColorNode = ntree.nodes.new(type="ShaderNodeRGB")
darkColorNode.outputs[0].default_value = (0.01, 0.0185002, 0.0137021, 1)
lightColorNode = ntree.nodes.new(type="ShaderNodeRGB")
lightColorNode.outputs[0].default_value = (0.098, 0.238398, 0.135633, 1)
darkColorNode.location = Vector((0, 200))
lightColorNode.location = Vector((0, 0))
stencilNode.location = Vector((400,0))
matNode.location = Vector((600,0))
links.new(input=darkColorNode.outputs['Color'], output=stencilNode.inputs[0])
links.new(input=lightColorNode.outputs['Color'], output=stencilNode.inputs[1])
links.new(input=stencilNode.outputs['Shader'], output=matNode.inputs['Surface'])
def createLeafCyclesMatOld(mat):
"""Very similar to the transparent (glass) material but different enough to need its own"""
if DEBUG_SHADER:
print("createLeafCyclesMat")
#Ensure Cycles is in use
if bpy.context.scene.render.engine != 'CYCLES':
bpy.context.scene.render.engine = 'CYCLES'
mat.use_nodes = True
ntree = mat.node_tree #there will now be 4 nodes in there, one of them being the diffuse shader.
nodes = ntree.nodes
links = ntree.links
removeExistingDiffuseNode(ntree)
diffNode = ntree.nodes.new(type=TYPE_NODE_GROUP)
setNodeGroup(diffNode,MC_SHADER_TEX)
matNode = nodes['Material Output']
rgbtobwNode = ntree.nodes.new(type="ShaderNodeRGBToBW")
gtNode = ntree.nodes.new(type="ShaderNodeMath")
gtNode.name = "AlphaBlackGT"
gtNode.operation = 'GREATER_THAN'
gtNode.inputs[0].default_value = 0.001
transpNode = ntree.nodes.new(type="ShaderNodeBsdfTransparent")
mixNode = ntree.nodes.new(type="ShaderNodeMixShader")
diffNode.location = Vector((0,0))
rgbtobwNode.location = Vector((200,200))
gtNode.location = Vector((400,200))
transpNode.location = Vector((400,-200))
mixNode.location = Vector((600,0))
matNode.location = Vector((800,0))
for nl in links:
if nl.to_socket == matNode:
links.remove(nl)