UV Layers and Mesh Attributes
Trigger
Use this skill when the user:
- Creates or edits UVs from a script (
mesh.uv_layers,bm.loops.layers.uv,calc_uvs=True) - Builds a second UV channel for baked lighting, or runs
uv.lightmap_pack/uv.smart_projecton it - Computes tangents for a normal-mapped game asset (
calc_tangents,bitangent_sign) - Writes vertex colors (
color_attributes, the deprecatedvertex_colors) - Authors shape keys or reads a blended shape
- Caps skin weights at four influences per vertex for a game engine
- Reports a textured mesh that renders as one flat color, a UV op that wrecked channel 0, a crash or garbage values after
calc_tangents, or weights that sum short of one
High-level shape
Every one of these lives in the mesh's CustomData. Three rules cover most bugs: create the layer before anything that fills it, address layers by name, and re-fetch a layer by name after any call that can reallocate CustomData.
pythonimport bmesh import bpy me = bpy.data.meshes.new("Panel") bm = bmesh.new() try: bm.loops.layers.uv.new("UVMap") # first: calc_uvs only fills an existing layer bmesh.ops.create_grid(bm, x_segments=4, y_segments=4, size=1.0, calc_uvs=True) bm.to_mesh(me) finally: bm.free() me.uv_layers.new(name="UVLight") # a second channel does NOT become active assert me.uv_layers.active.name == "UVMap" assert me.uv_layers["UVMap"].active_render me.calc_tangents(uvmap="UVMap") # reallocates loop CustomData uv = me.uv_layers["UVMap"].data # so re-fetch by name after it co = [0.0] * (len(me.loops) * 2) uv.foreach_get("uv", co) assert len(me.loops) == 64 and min(co) >= -1e-6 and max(co) <= 1.0 + 1e-6 col = me.color_attributes.new("Tint", 'FLOAT_COLOR', 'CORNER') assert len(col.data) == len(me.loops) # CORNER is per loop, not per vertex
UV layers
mesh.uv_layers.new(name="UVMap")on a Mesh,bm.loops.layers.uv.new("UVMap")on a BMesh. Look layers up withmesh.uv_layers["UVMap"], never by index or "the first one".calc_uvs=Trueis a silent no-op without a layer.bmesh.ops.create_grid(and the other primitive ops) only fill a UV layer that already exists on the BMesh. With none, the flag does nothing,to_meshleavesmesh.uv_layersempty, and an Image Texture samples texel (0, 0) everywhere: the mesh renders one flat color. Create the layer first, or assign UVs yourself.- Bulk-read and write UVs with
uv_layer.data.foreach_get("uv", flat)/foreach_set, sizedlen(mesh.loops) * 2. UVs are per loop (face corner), not per vertex.
A second (lightmap) channel
Engines bake lighting into UV1. Two flags decide which channel a tool touches:
| Flag | Meaning |
|---|---|
uv_layer.active (mesh.uv_layers.active) | the layer edit-mode UV operators read and write |
uv_layer.active_render | the layer the renderer and exporters treat as the primary UV |
uv_layers.new()does not move either flag. The first layer keeps both, so an unwrap or pack after addingUVLightruns on channel 0 and destroys it (measured drift 2.068 inlightmap-uv-channel). Setmesh.uv_layers.active = mesh.uv_layers["UVLight"]before the UV op.- Edit-mode UV operators clear both flags. Re-assert them afterwards:
activeon the channel you edit,active_renderonUVMap. bpy.ops.uv.lightmap_packexits OK while packing nothing when its context is wrong; check the result (bounds in[0, 1], non-overlap), not the return value.
Handle lifetime: re-fetch by name
A MeshUVLoopLayer, attribute or color-attribute object is a view into CustomData. Calls that reallocate CustomData leave held views dangling:
mesh.calc_tangents(),VertexGroup.add(), adding or removing modifiers or layers, edit-mode UV operators- On 4.5 LTS a held UV handle read after
calc_tangentsreturns tangent floats instead of UVs: exit 0, silently wrong (measured intriangulate-tangents). Iterating a helduv_layer.dataafter edit-mode UV ops segfaulted 4.5.11 headless (5 of 5 runs). On 5.1 and 5.2 the same stale read survives by memory-layout luck, which hides the bug.
Fetch the layer by name again after each such call, as the block above does.
Tangents
mesh.calc_tangents(uvmap="UVMap")fillsloop.tangentandloop.bitangent_sign; the bitangent isbitangent_sign * normal.cross(tangent).- It needs triangles and quads. One n-gon anywhere aborts the whole call: triangulate first, or build caps as triangle fans.
- Tangents follow the UVs, so planar UVs on a curved wall collapse the tangent onto the normal. Unwrap the wall instead.
- mikktspace output is identical on 4.5.11, 5.1.2 and 5.2.1; a difference between versions points at a stale handle, not the math.
Color attributes
- Use
mesh.color_attributes.new(name, type, domain).mesh.vertex_colorsis the deprecated alias. - The domain sets the length:
'CORNER'is per loop (len(mesh.loops)),'POINT'is per vertex. Per-vertex data written to aCORNERattribute must be expanded across each vertex's corners. - A material only shows it through a Shader Attribute node (
attribute_type='GEOMETRY',attribute_nameset) wired into Base Color. Without that node the mesh stays gray even when the data is right.
Shape keys
obj.shape_key_add(name="Basis", from_mix=False)first, then the target key. Write the target withkey_blocks["Tall"].data.foreach_set("co", flat).- A shape key does not rewrite
mesh.vertices: those stay at Basis. Read the blended shape from the evaluated mesh (obj.evaluated_get(depsgraph).to_mesh(), thento_mesh_clear()), where each vertex isbasis + value * (key - basis).
Skin weights: four influences
- Engines cap skinning at four bone influences per vertex. Enforce it on the data API rather than
bpy.ops.object.vertex_group_limit_total: readv.groups, keep the four heaviest,VertexGroup.remove([v.index])the rest, then renormalize the survivors to sum to one. Dropping without renormalizing shrinks the mesh toward the origin under load. - The weights on the mesh (
v.groups) are the contract, not the weights you meant to write: read them back to check. - The vertex-group API is the same on 4.5 LTS and 5.2.
Common AI mistakes
- Trusting
calc_uvs=Trueon a BMesh with no UV layer. - Adding
UVLightand unwrapping without movingactive, or forgetting that edit-mode UV ops clearedactive_render. - Holding
uv = mesh.uv_layers.active.dataacrosscalc_tangents()or other reallocating calls. - Calling
calc_tangentson a mesh with an n-gon. - Sizing
CORNERcolor data by vertex count, or never adding the Attribute node. - Reading shape-key results from
mesh.vertices. - Removing extra skin influences without renormalizing.
See also
mesh-editing-and-bmesh: bmesh ownership,foreach_get/foreach_set, evaluated meshesdepsgraph-and-evaluated-data: theto_mesh/to_mesh_clearlifetimeengine-export-presets: exporting UV1, tangents and weights to Unity, Godot and Unreal
Runnable examples
Each example runs headless, asserts the contract, and exits non-zero when it breaks. Run one with blender --background --python <script> --; pass a falsifier flag to watch the check fail.
color-attribute-wheel: The modern color-attributes API — mesh.color_attributes.new() on the CORNER domain. Falsify:--point-domain(exit 6).lightmap-uv-channel: A market cart carrying the two-channel UV contract for baked lighting: UV0 untouched, UVLight packed with no overlaps and a respected margin. Falsify:--overlap-islands(exit 7).shape-key-blend: A relative Tall shape key that turns a squat ceramic jar into a trumpet vase. Falsify:--zero-blend(exit 5).triangulate-tangents: A machined buckler verifying the tangent-space contract a game engine's normal mapping depends on. Falsify:--zero-uv(exit 4).uv-layer-grid: The UV-layer authoring hazard — bmesh.ops.create_grid(..., calc_uvs=True) is a silent no-op unless a UV layer already exists; without one an Image Texture samples texel (0,0) everywhere. Falsify:--precreate-on-hazard(exit 3).vertex-weight-limit: A rigged industrial robot arm pruned to the game-engine cap of four bone influences per vertex, through the data API. Falsify:--skip-limit(exit 4).
References
- https://docs.blender.org/api/current/bpy.types.MeshUVLoopLayer.html
- https://docs.blender.org/api/current/bpy.types.Mesh.html#bpy.types.Mesh.calc_tangents
- https://docs.blender.org/api/current/bpy.types.AttributeGroupMesh.html
- https://docs.blender.org/api/current/bpy.types.ShapeKey.html
- https://docs.blender.org/api/current/bpy.types.VertexGroup.html


