This is how I instantiated my mesh object and material:
mymesh = bpy.data.meshes.new(objname)
myobject = bpy.data.objects.new(objname, mymesh)
mymat = bpy.data.materials.get("Material")
if mymat is None:
mymat = bpy.data.materials.new(name="Material")
if myobject.data.materials:
# assign to 1st material slot
myobject.data.materials[0] = mymat
else:
# no slots
myobject.data.materials.append(mymat)
Here's how I set the color of the vertex colors:
if len(mymesh.vertex_colors) == 0:
mymesh.vertex_colors.new()
for f in mymesh.vertex_colors[0].data:
f.color = rgb # (0,0,0,1) for black
I can see the colors when I am in vertex paint mode, but when I am rendering the scene with Eevee or Cycles the colors don't show.
I can fix this by changing the base color of the material to equal Vertex Colors, using the UI, however how can I do this using python code?
Edit: Maybe the solution uses bpy.data.materials["Material"].node_tree.nodes["Principled BSDF"].inputs
?
I was looking to do something similar. I don't know if you are still working on it but here is the solution I found which seems to work on Blender 2.92.0.
To test the script:
import bpy
from random import *
# ---------- SET RANDOM COLORS TO VERTICES ----------
# Load vertex colors data
mesh = bpy.data.objects["Cube"].data
if not mesh.vertex_colors:
mesh.vertex_colors.new()
print("Object had no vertex colors, adding them")
# Assign random colors to vertices
for vCol in mesh.vertex_colors[0].data:
for i in range(len(vCol.color) - 1):
vCol.color[i] = random()
# ---------- LOAD AND LINK MATERIAL TO MESH ----------
# Load material
mymat = bpy.data.materials.get("mymat")
if mymat is None:
mymat = bpy.data.materials.new(name = "mymat")
mymat.use_nodes = True
# Link material to mesh
if mesh.materials:
mesh.materials[0] = mymat
else:
mesh.materials.append(mymat)
# ---------- MANAGE NODES OF SHADER EDITOR ----------
# Get node tree from the material
nodes = mymat.node_tree.nodes
principled_bsdf_node = nodes.get("Principled BSDF")
# Get Vertex Color Node, create it if it does not exist in the current node tree
vertex_color_node = None
if not "VERTEX_COLOR" in [node.type for node in nodes]:
vertex_color_node = nodes.new(type = "ShaderNodeVertexColor")
else:
vertex_color_node = nodes.get("Vertex Color")
# Set the vertex_color layer we created at the beginning as input
vertex_color_node.layer_name = "Col"
# Link Vertex Color Node "Color" output to Principled BSDF Node "Base Color" input
links = mymat.node_tree.links
link = links.new(vertex_color_node.outputs[0], principled_bsdf_node.inputs[0])
Here are some resources which helped me to do it:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.