Hi folks
I’m struggling with assigning a UV map on a mesh I generate with Python.
The mesh is fine but I can’t figure out how to apply the UVs.
Here’s my code. Should run without any prerequisites:
import bpy
import math
step = 2
# make mesh
vertices = []
edges = []
faces = []
uvs = []
for y in range(-90,91, step):
for x in range(0,360,step):
vx = math.sin(x/180*math.pi) * math.cos(y/180*math.pi)
vy = math.cos(x/180*math.pi) * math.cos(y/180*math.pi)
vz = math.sin(y/180*math.pi)
vertex = (vx, vy, vz)
vertices.append(vertex)
vu = 0.5 * (1 + math.sin(x/180*math.pi) * ((y+90)/180))
vv = 0.5 * (1 + math.cos(x/180*math.pi) * ((y+90)/180))
uv = (vu, vv)
uvs.append(uv)
ry = len(range(-90,91, step))
rx = len(range(0,360,step))
for y in range(ry+1):
for x in range(rx):
v1 = y * rx + (x) % rx
v2 = y * rx + (x+1) % rx
v3 = v2 + rx
v4 = v1 + rx
if v3 >= len(vertices):
break
face = (v1, v2, v3, v4)
faces.append(face)
new_mesh = bpy.data.meshes.new('new_mesh')
new_mesh.from_pydata(vertices, edges, faces)
new_mesh.update()
# make object from mesh
new_object = bpy.data.objects.new('new_object', new_mesh)
# make collection
new_collection = bpy.data.collections.new('new_collection')
bpy.context.scene.collection.children.link(new_collection)
# add object to scene collection
new_collection.objects.link(new_object)
new_uv = new_object.data.uv_layers.new(name='NewUV')
for loop in new_object.data.loops:
new_uv.data[loop.index].uv = uvs[loop.index]
Thank you very much!
Bastian