-
Notifications
You must be signed in to change notification settings - Fork 4
/
latk_mtl.py
558 lines (507 loc) · 18.9 KB
/
latk_mtl.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
# MATERIALS / RENDERING
import bpy
from . latk import *
from . latk_tools import *
def cleanUvs(target=None, limit=1):
if not target:
target = s()
for obj in target:
try:
uvs = obj.data.uv_textures
while (len(uvs) > limit):
uvs.remove(uvs[len(uvs)-1])
except:
pass
def createMaterial(target=None, name="NewMaterial", unique=True):
if not target:
target = s()
if (unique == False):
mat = bpy.data.materials.new(name=name)
for obj in target:
try:
if (len(obj.data.materials) < 1):
if (unique==True):
mat = bpy.data.materials.new(name=name)
obj.data.materials.append(mat)
except:
pass
def deleteMaterial(target=None):
if not target:
target = s()
for obj in target:
try:
setActiveObject(obj)
bpy.ops.object.material_slot_remove()
except:
pass
# http://blender.stackexchange.com/questions/17738/how-to-uv-unwrap-object-with-python
def planarUvProject():
'''
for area in bpy.context.screen.areas:
if area.type == 'VIEW_3D':
for region in area.regions:
if region.type == 'WINDOW':
override = {'area': area, 'region': region, 'edit_object': bpy.context.edit_object}
bpy.ops.uv.smart_project(override)
'''
# https://blender.stackexchange.com/questions/103195/smart-uv-unwrap-multiple-objects
bpy.ops.object.editmode_toggle() #entering edit mode
bpy.ops.mesh.select_all(action='SELECT') #select all objects elements
bpy.ops.uv.smart_project() #the actual unwrapping operation
bpy.ops.object.editmode_toggle() #exiting edit mode
def colorVertexCyclesMat(obj, vertName="Cd"):
# http://blender.stackexchange.com/questions/6084/use-python-to-add-multiple-colors-to-a-nurbs-curve
# http://blender.stackexchange.com/questions/5668/add-nodes-to-material-with-python
# this will fail if you don't have Cycles Render enabled
mesh = obj.data
#~
obj.active_material = bpy.data.materials.new('material')
obj.active_material.use_vertex_color_paint = True
#~
obj.active_material.use_nodes = True
nodes = obj.active_material.node_tree.nodes
material_output = nodes.get('Diffuse BSDF')
nodeAttr = nodes.new("ShaderNodeAttribute")
nodeAttr.attribute_name = vertName
obj.active_material.node_tree.links.new(material_output.inputs[0], nodeAttr.outputs[0])
def colorVertexAlt(obj, vert, color=[1,0,0]):
mesh = obj.data
scn = bpy.context.scene
# check if our mesh already has Vertex Colors, and if not add some... (first we need to make sure it's the active object)
scn.objects.active = obj
obj.select = True
if len(mesh.vertex_colors) == 0:
bpy.ops.mesh.vertex_color_add()
i=0
for poly in mesh.polygons:
for vert_side in poly.loop_indices:
global_vert_num = poly.vertices[vert_side-min(poly.loop_indices)]
if vert == global_vert_num:
mesh.vertex_colors[0].data[i].color = color
i += 1
def getVertexColor(mesh=None, vert=0):
if not mesh:
mesh = ss().data
if (len(mesh.vertex_colors)) == 0:
return None
i=0
for poly in mesh.polygons:
for vert_side in poly.loop_indices:
if (vert == poly.vertices[vert_side-min(poly.loop_indices)]):
return mesh.vertex_colors[0].data[i].color
i += 1
return None
# TODO fix
def getBmeshVCol(mesh=None, vert=0):
if not mesh:
mesh = getBmesh()
color_layer = mesh.loops.layers.color[0]
for face in mesh.faces:
for loop in face.loops:
if (vert == loop.index):
return loop[color_layer]
return None
# TODO fix
def getBmeshVCols(mesh=None):
returns = []
if not mesh:
mesh = getBmesh()
color_layer = mesh.loops.layers.color[0]
for i, vert in enumerate(mesh.verts):
returns.append(getBmeshVCol(mesh, i))
return returns
def colorVertices(obj, color=(1,0,0), makeMaterial=False, colorName="rgba"):
# start in object mode
mesh = obj.data
#~
if not mesh.vertex_colors:
mesh.vertex_colors.new(name=colorName)
#~
color_layer = mesh.vertex_colors.active
#~
i = 0
for poly in mesh.polygons:
for idx in poly.loop_indices:
try:
color_layer.data[i].color = (color[0], color[1], color[2], 1) # future-proofing 2.79a
except:
color_layer.data[i].color = color # 2.79 and earlier
i += 1
#~
if (makeMaterial==True):
colorVertexCyclesMat(obj)
def togglePoints(strokes=None):
palette = getActivePalette()
for mtl in palette:
bpy.data.materials[mtl.name].grease_pencil.show_fill = False
bpy.data.materials[mtl.name].grease_pencil.mode = "DOTS"
'''
layer = getActiveLayer()
if not strokes:
strokes = getSelectedStrokes()
if not strokes:
strokes = getAllStrokes()
#~
for stroke in strokes:
stroke.color.use_volumetric_strokes = True
layer.line_change = 1
'''
def createMtlPalette(numPlaces=5, numReps = 1):
palette = None
removeUnusedMtl()
for h in range(0, numReps):
palette = []
# 1-3. Creating palette of all materials
for mtl in bpy.data.materials:
foundNewMtl = True
for palMtl in palette:
if (compareTuple(getDiffuseColor(mtl), getDiffuseColor(palMtl), numPlaces=numPlaces)==True):
foundNewMtl = False
break
if (foundNewMtl==True):
palette.append(mtl)
for i, mtl in enumerate(palette):
mtl.name = "Palette_" + str(i+1)
# 2-3. Matching palette colors for all objects
for obj in bpy.context.scene.objects:
try:
for i, mtl in enumerate(obj.data.materials):
for palMtl in palette:
if (compareTuple(getDiffuseColor(mtl), getDiffuseColor(palMtl), numPlaces=numPlaces)==True):
obj.data.materials[i] = palMtl
except:
pass
# 3-3. Removing unused materials
removeUnusedMtl()
#~
print ("Created palette of " + str(len(palette)) + " materials.")
return palette
def removeUnusedMtl():
# http://blender.stackexchange.com/questions/5300/how-can-i-remove-all-unused-materials-from-a-file/35637#35637
for mtl in bpy.data.materials:
if not mtl.users:
bpy.data.materials.remove(mtl)
# https://blender.stackexchange.com/questions/5668/add-nodes-to-material-with-python
def texAllMtl(filePath="D://Asset Collections//Images//Element maps 2K//Plaster_maps//plaster_wall_distressed_04_normal.jpg", strength=1.0, colorData=False):
for mtl in bpy.data.materials:
mtl.use_nodes = True
nodes = mtl.node_tree.nodes
links = mtl.node_tree.links
#~
shaderNode = nodes["Diffuse BSDF"]
texNode = None
mapNode = None
try:
texNode = nodes["Image Texture"]
except:
texNode = nodes.new("ShaderNodeTexImage")
try:
mapNode = nodes["Normal Map"]
except:
mapNode = nodes.new("ShaderNodeNormalMap")
#~
links.new(texNode.outputs[0], mapNode.inputs[1])
links.new(mapNode.outputs[0], shaderNode.inputs[2])
#~
texNode.image = bpy.data.images.load(filePath)
if (colorData==True):
texNode.color_space = "COLOR"
else:
texNode.color_space = "NONE"
mapNode.inputs[0].default_value = strength
#~
mapNode.location = [shaderNode.location.x - 250, shaderNode.location.y]
texNode.location = [mapNode.location.x - 250, shaderNode.location.y]
# TODO handle multiple materials on one mesh
def searchMtl(color=None, name="latk"):
returns = []
if not color:
color = getActiveColor().color
curves = matchName(name)
for curve in curves:
if (compareTuple(curve.data.materials[0].diffuse_color, color)):
returns.append(curve)
return returns
# TODO handle multiple materials on one mesh
def changeMtl(color=(1,1,0), searchColor=None, name="latk"):
if not searchColor:
searchColor = getActiveColor().color
curves = searchMtl(color=searchColor, name=name)
print("changed: " + str(curves))
for curve in curves:
curve.data.materials[0].diffuse_color = color
def consolidateMtl():
palette = getActivePalette()
for color in palette.colors:
matchMat = None
for obj in bpy.context.scene.objects:
try:
for i, mat in enumerate(obj.data.materials):
if (compareTuple((color.color[0],color.color[1],color.color[2]), getDiffuseColor(mat)) == True):
if (matchMat == None):
matchMat = mat
else:
obj.data.materials[i] = matchMat
except:
pass
# old version, can't handle multiple materials on one mesh
def consolidateMtlAlt(name="latk"):
palette = getActivePalette()
for color in palette.colors:
curves = searchMtl(color=color.color, name=name)
for i in range(1, len(curves)):
curves[i].data.materials[0] = curves[0].data.materials[0]
def getActiveMtl(obj=None):
if not obj:
obj = ss()
if len(obj.data.materials) > 0:
return obj.data.materials[obj.active_material_index]
else:
return None
def getMtlColor(mtl=None, node="principled"):
if not mtl:
mtl = getActiveMtl()
color = None
if (node.lower() == "emission"):
color = mtl.node_tree.nodes["Emission"].inputs["Color"].default_value
elif (node.lower() == "diffuse"):
color = mtl.node_tree.nodes["Diffuse BSDF"].inputs["Color"].default_value
elif (node.lower() == "gltf"):
color = mtl.node_tree.nodes["Group"].inputs["BaseColor"].default_value
else:
color = mtl.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value
return (color[0], color[1], color[2], color[3])
# assumes that we're starting with diffuse shader, the default
def setMtlShader(shader="diffuse", mtl=None):
# https://blender.stackexchange.com/questions/23436/control-cycles-material-nodes-and-material-properties-in-python
if not mtl:
mtl = getActiveMtl()
col = getUnknownColor(mtl)
if not col:
return None
#~
# https://blender.stackexchange.com/questions/33189/python-script-attribute-error-while-using-node-editor
# clear all nodes to start clean
mtl.use_nodes = True
nodes = mtl.node_tree.nodes
for node in nodes:
nodes.remove(node)
#~
destNode = None
#~
# https://docs.blender.org/api/blender_python_api_2_78_0/bpy.types.html
# create emission node
if (shader.lower()=="emission"):
destNode = nodes.new(type="ShaderNodeEmission")
destNode.inputs[0].default_value = (col[0], col[1], col[2], 1) # RGBA
#destNode.inputs[1].default_value = 5.0 # strength
elif (shader.lower()=="principled"):
destNode = nodes.new(type="ShaderNodeBsdfPrincipled")
destNode.inputs["Base Color"].default_value = (col[0], col[1], col[2], 1) # RGBA
destNode.inputs["Subsurface Color"].default_value = (col[0], col[1], col[2], 1) # RGBA
elif (shader.lower()=="gltf"):
group = bpy.data.node_groups["glTF Metallic Roughness"]
destNode = mtl.node_tree.nodes.new("ShaderNodeGroup")
destNode.node_tree = group
destNode.inputs["BaseColor"].default_value = (col[0], col[1], col[2], 1) # RGBA
destNode.inputs["BaseColorFactor"].default_value = (col[0], col[1], col[2], 1) # RGBA
destNode.inputs["MetallicRoughness"].default_value = (col[0], col[1], col[2], 1) # RGBA
destNode.inputs["MetallicFactor"].default_value = 0.5
destNode.inputs["RoughnessFactor"].default_value = 0.5
else:
destNode = nodes.new(type="ShaderNodeBsdfDiffuse")
destNode.inputs[0].default_value = (col[0], col[1], col[2], 1) # RGBA
#~
destNode.location = 0,0
#~
# create output node
node_output = nodes.new(type="ShaderNodeOutputMaterial")
node_output.location = 400,0
#~
# link nodes
links = mtl.node_tree.links
link = links.new(destNode.outputs[0], node_output.inputs[0])
#~
return mtl
def setAllMtlShader(shader="principled"):
for mtl in bpy.data.materials:
setMtlShader(shader, mtl)
def getDiffuseColor(mtl=None):
if not mtl:
mtl = getActiveMtl()
col = getMtlColor("diffuse", mtl)
if (col==None):
col = mtl.diffuse_color
return col
def getEmissionColor(mtl=None):
if not mtl:
mtl = getActiveMtl()
return getMtlColor("emission", mtl)
def getPrincipledColor(mtl=None):
if not mtl:
mtl = getActiveMtl()
return getMtlColor("principled", mtl)
def getGltfColor(mtl=None):
if not mtl:
mtl = getActiveMtl()
return getMtlColor("gltf", mtl)
def getUnknownColor(mtl=None):
if not mtl:
mtl = getActiveMtl()
col = None
if (col == None):
col = getEmissionColor(mtl)
if (col == None):
col = getPrincipledColor(mtl)
if (col == None):
col = getGltfColor(mtl)
if (col == None):
col = getDiffuseColor(mtl)
return col
def getColorExplorer(obj=None, vert=0, images=None):
if not obj:
obj = ss()
mesh = obj.data
col = None
if (len(images) > 0):
uv_first = mesh.uv_layers.active.data[vert].uv
pixel = getPixelFromUvArray(images[obj.active_material.node_tree.nodes["Image Texture"].image.name], uv_first[0], uv_first[1])
return (pixel[0], pixel[1], pixel[2])
else:
i=0
for poly in mesh.polygons:
for vert_side in poly.loop_indices:
if (vert == poly.vertices[vert_side-min(poly.loop_indices)]):
return mesh.vertex_colors[0].data[i].color
i += 1
col = getMtlColor(mesh.materials[0])
if not col:
return (1, 1, 1)
else:
return col
# is this obsolete now that all materials are linked by color value?
def makeEmissionMtl():
mtl = getActiveMtl()
color = getEmissionColor()
for obj in bpy.context.scene.objects:
try:
for j in range(0, len(obj.data.materials)):
destColor = getDiffuseColor(obj.data.materials[j])
if (compareTuple(destColor, color) == True):
obj.data.materials[j] = mtl
except:
pass
#~ ~ ~ ~ ~ ~ ~ ~
# pixel / uv methods
#~ ~ ~ ~ ~ ~ ~ ~
# http://blender.stackexchange.com/questions/49341/how-to-get-the-uv-corresponding-to-a-vertex-via-the-python-api
# https://blenderartists.org/forum/archive/index.php/t-195230.html
# https://developer.blender.org/T28211
# http://blenderscripting.blogspot.ca/2012/08/adjusting-image-pixels-walkthrough.html
# https://www.blender.org/forum/viewtopic.php?t=25804
# https://docs.blender.org/api/blender_python_api_2_63_2/bmesh.html
# http://blender.stackexchange.com/questions/1311/how-can-i-get-vertex-positions-from-a-mesh
# TODO is this for bmesh only?
def uv_from_vert_first(uv_layer, v):
for l in v.link_loops:
uv_data = l[uv_layer]
return uv_data.uv
return None
def uv_from_vert_average(uv_layer, v):
uv_average = Vector((0.0, 0.0))
total = 0.0
for loop in v.link_loops:
uv_average += loop[uv_layer].uv
total += 1.0
#~
if total != 0.0:
return uv_average * (1.0 / total)
else:
return None
# Example using the functions above
'''
def testUvs():
obj = bpy.context.scene.objects.active #edit_object
me = obj.data
bm = bmesh.new()
bm.from_mesh(me) #from_edit_mesh(me)
#~
images = getUvImages()
#~
uv_layer = bm.loops.layers.uv.active
#~
for v in bm.verts:
uv_first = uv_from_vert_first(uv_layer, v)
uv_average = uv_from_vert_average(uv_layer, v)
print("Vertex: %r, uv_first=%r, uv_average=%r" % (v, uv_first, uv_average))
#~
pixel = getPixelFromUvArray(images[obj.active_material.texture_slots[0].texture.image.name], uv_first[0], uv_first[1])
print("Pixel: " + str(pixel))
'''
def getUvImages(obj=None):
if not obj:
obj = ss()
uv_images = {}
#~
#for uv_tex in obdata.uv_textures.active.data:
#for tex in obj.active_material.texture_slots:
for tex in obj.material_slots:
try:
uv_tex = tex.texture
if (uv_tex.image and
uv_tex.image.name not in uv_images and
uv_tex.image.pixels):
uv_images[uv_tex.image.name] = (
uv_tex.image.size[0],
uv_tex.image.size[1],
uv_tex.image.pixels[:]
# Accessing pixels directly is far too slow.
# Copied to new array for massive performance-gain.
)
except:
pass
if (len(uv_images) < 1):
try:
uv_tex = obj.active_material.node_tree.nodes["Image Texture"]
if (uv_tex.image and
uv_tex.image.name not in uv_images and
uv_tex.image.pixels):
uv_images[uv_tex.image.name] = (
uv_tex.image.size[0],
uv_tex.image.size[1],
uv_tex.image.pixels[:]
# Accessing pixels directly is far too slow.
# Copied to new array for massive performance-gain.
)
except:
pass
#~
return uv_images
def getPixelFromImage(img, xPos, yPos):
imgWidth = int(img.size[0])
r = img.pixels[4 * (xPos + imgWidth * yPos) + 0]
g = img.pixels[4 * (xPos + imgWidth * yPos) + 1]
b = img.pixels[4 * (xPos + imgWidth * yPos) + 2]
a = img.pixels[4 * (xPos + imgWidth * yPos) + 3]
return [r, g, b, a]
def getPixelFromUv(img, u, v):
imgWidth = int(img.size[0])
imgHeight = int(img.size[1])
pixel_x = int(u * imgWidth)
pixel_y = int(v * imgHeight)
return getPixelFromImage(img, pixel_x, pixel_y)
# *** these methods are much faster but don't work in all contexts
def getPixelFromImageArray(img, xPos, yPos):
imgWidth = int(img[0]) #img.size[0]
#r = img.pixels[4 * (xPos + imgWidth * yPos) + 0]
r = img[2][4 * (xPos + imgWidth * yPos) + 0]
g = img[2][4 * (xPos + imgWidth * yPos) + 1]
b = img[2][4 * (xPos + imgWidth * yPos) + 2]
a = img[2][4 * (xPos + imgWidth * yPos) + 3]
return [r, g, b, a]
def getPixelFromUvArray(img, u, v):
imgWidth = int(img[0]) #img.size[0]
imgHeight = int(img[1]) #img.size[1]
pixel_x = int(u * imgWidth)
pixel_y = int(v * imgHeight)
return getPixelFromImageArray(img, pixel_x, pixel_y)