> ## Documentation Index
> Fetch the complete documentation index at: https://docs.lokutor.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Asset pipeline

> Modelling a game character that can speak: the 15 viseme blend shapes and what each looks like, expression shapes, a code-first Blender to glTF build, cel shading in Godot, and contact sheets that show every shape

A voice needs a mouth. This page is what to model, how to name it so that [Lokutor Lip Sync](https://docs.lokutor.com/sdks/godot/lip-sync.md) finds it, and a pipeline where a character is code: one command builds it, checks it, and another draws a sheet with every shape. The examples are Blender and Godot; the naming is the same for Unity.

If you already have a rig (Ready Player Me, VRoid, VRChat, or a face with the 52 ARKit shapes), you may have nothing to model: see [which are recognised](https://docs.lokutor.com/sdks/godot/lip-sync.md#set-it-up).

## The 15 visemes

One blend shape each, named `viseme_` and the name below, on every mesh that moves with the mouth (face, teeth, tongue). Upper and lower case do not matter.

| Blend shape | Sounds | What it looks like |
| :- | :- | :- |
| `viseme_sil` | Silence | The mouth at rest. Optional: the base mesh is already that. |
| `viseme_PP` | p, b, m | Lips pressed together, a little thicker. **They must touch.** |
| `viseme_FF` | f, v | Lower lip under the upper teeth. |
| `viseme_TH` | th | Barely open, the tongue tip between the teeth. |
| `viseme_DD` | t, d | Barely open, teeth showing, tongue up. |
| `viseme_kk` | k, g | Slightly open, the jaw a little down. |
| `viseme_CH` | ch, j, sh | Narrow and pushed forward, teeth together. |
| `viseme_SS` | s, z | Wide and nearly closed, both rows of teeth. |
| `viseme_nn` | n, l | Slightly open, tongue up behind the teeth. |
| `viseme_RR` | r | Narrow, a little round. |
| `viseme_aa` | a | Wide open, the jaw down. The biggest one. |
| `viseme_E` | e | Open and wide, about half of `aa`. |
| `viseme_I` | i | The widest, nearly closed, teeth showing. |
| `viseme_O` | o | Round and open, lips forward. |
| `viseme_U` | u | Small, round, the furthest forward. |

* **Model each at full strength.** Lip sync mixes neighbours, and short sounds never reach their full weight.
* **Push them.** On a cartoon, `aa` should look too big in a still and right in motion. `PP`, `FF`, `O` and `U` are the ones people read: make them unmistakable.
* **Let the jaw in.** Move the chin and cheeks with the open shapes, not only the lips.
* **At least 8 of them** are needed to be recognised as visemes. With fewer, or other names, write a mapping ([Godot](https://docs.lokutor.com/sdks/godot/lip-sync.md#your-own-names), [Unity](https://docs.lokutor.com/sdks/unity/lip-sync.md#your-own-names)).

The [visemes page](https://docs.lokutor.com/sdk/visemes.md#the-15-visemes) has the sounds of each in full.

## Expressions

Anything else on the mesh is yours. A set that covers most characters:

| | |
| :- | :- |
| Mouth | `smile` `grin` `laugh` `frown` `gasp` `grit` `pout` `smirk` `puff` |
| Eyes | `blink_l` `blink_r` `happy_eyes` `bored_eyes` `angry_eyes` `sad_eyes` `squint` `wide_eyes` |
| Brows | `brow_up_l` `brow_up_r` `brow_angry` `brow_sad` |
| Gaze | `look_l` `look_r` `look_u` `look_d` |

Keep mouth, eyes and brows in separate shapes, so that a mood can keep its brows while the mouth speaks ([layers](https://docs.lokutor.com/guides/game-characters.md#layers)).

## A face in numbers

Sculpting forty shapes by hand, for every character, and again when the head changes, is most of the work of a talking cast. The alternative for a cartoon: draw the face as a few flat layers (mouth, teeth, tongue, lips, eyes, lids, brows), each a **function of a few numbers**. A viseme is then a line of numbers, its blend shape is exact, every character of the cast has the same forty shapes, and a layer cannot poke through another because the order is built in.

This is the idea at its smallest: a mouth with the 15 visemes, checked and exported. A real face adds layers to it. (Blender 5 or newer.)

```python theme={null}
"""blender -b --factory-startup --python-exit-code 1 --python head.py -- head.glb"""
import sys

import bpy
import numpy as np

# The mouth in numbers: half width, how far it opens up and down, and how far the lips come forward (metres).
REST = dict(w=0.13, top=0.004, bot=0.004, pout=0.0)
VISEMES = {
    "sil": {}, "PP": dict(w=0.11, top=0.001, bot=0.001, pout=0.01), "FF": dict(top=0.02, bot=0.006), "TH": dict(top=0.02, bot=0.025),
    "DD": dict(top=0.022, bot=0.026), "kk": dict(top=0.02, bot=0.04), "CH": dict(w=0.085, top=0.03, bot=0.03, pout=0.03),
    "SS": dict(w=0.14, top=0.018, bot=0.018), "nn": dict(w=0.12, top=0.018, bot=0.022), "RR": dict(w=0.09, top=0.024, bot=0.03, pout=0.02),
    "aa": dict(top=0.035, bot=0.10), "E": dict(w=0.15, top=0.03, bot=0.055), "I": dict(w=0.16, top=0.025, bot=0.03),
    "O": dict(w=0.09, top=0.05, bot=0.065, pout=0.025), "U": dict(w=0.06, top=0.03, bot=0.035, pout=0.035)}
N = 32


def mouth(**numbers):
    """The points of the mouth: a centre and a ring, the same ones in the same order for every shape."""
    f = {**REST, **numbers}
    a = np.arange(N) * 2 * np.pi / N
    x, y = np.cos(a) * f["w"], np.sin(a)
    z = np.where(y > 0, y * f["top"], y * f["bot"])
    ring = np.stack([x, np.full(N, -0.5 - f["pout"]), z], axis=1)
    return np.concatenate([[[0.0, -0.49, 0.0]], ring])


def check(shapes):
    rest = mouth()
    for name, points in shapes.items():
        assert np.isfinite(points).all(), name + " has points that are not numbers"
        moved = np.linalg.norm(points - rest, axis=1).max()
        assert moved < 0.3, f"{name} moves a point {moved:.2f} m"
        assert name == "sil" or moved > 0.002, name + " moves nothing"
        top, bottom = points[1:N // 2 + 1, 2], points[N // 2 + 1:, 2]
        assert top.min() > -1e-9 and bottom.max() < 1e-9, name + ": the lips cross"


shapes = {v: mouth(**numbers) for v, numbers in VISEMES.items()}
check(shapes)
mesh = bpy.data.meshes.new("Face")
mesh.from_pydata(mouth().tolist(), [], [(0, 1 + i, 1 + (i + 1) % N) for i in range(N)])
face = bpy.data.objects.new("Face", mesh)
bpy.context.collection.objects.link(face)
ink = bpy.data.materials.new("face_mouth")
ink.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (0.25, 0.05, 0.1, 1.0)
mesh.materials.append(ink)
face.shape_key_add(name="Basis", from_mix=False)
for name, points in shapes.items():
    key = face.shape_key_add(name="viseme_" + name, from_mix=False)
    key.data.foreach_set("co", points.astype(np.float32).ravel())
bpy.data.objects.remove(bpy.data.objects["Cube"])
bpy.ops.export_scene.gltf(filepath=sys.argv[sys.argv.index("--") + 1], export_format="GLB", export_yup=True, export_morph=True,
    export_morph_normal=False, export_skins=True, export_animations=True, export_animation_mode="ACTIONS", export_apply=False)
```

```bash theme={null}
blender -b --factory-startup --python-exit-code 1 --python head.py -- assets/head.glb
```

* **The same points in the same order** for every shape: a blend shape is a displacement, so build them all with the same function.
* **The build fails** when a shape has broken points, moves too far, moves nothing, or crosses the lips. `--python-exit-code 1` turns a failed check into a failed command.
* **Export** as GLB with morph targets (`export_morph`) and skins. Morph normals are not needed for flat shading, and make the file bigger.
* **Name materials by what they are** (`face_mouth`, `face_white`, `skin`, `gold`): the game decides how each looks, so shading stays out of Blender.
* Save the `.blend` in a folder of its own with an empty `.gdignore` file, or Godot tries to import it.

## Body and clips

The same approach works for animation. Write poses as keys with an easing for each (in, out, overshoot, snap, hold) and let the code add what every clip needs:

* **Overlap**: the head a few hundredths of a second after the chest, the hands after the arms.
* **Arcs**: hands travel around the shoulder, with two-bone IK, never in straight lines.
* **Breathing** in a whole number of cycles, so loops have no seam.
* **30 frames per second**, and no baked secondary motion: springs in the game do belly, hat and cloth, so they also survive blending.

Clips never move the face: faces belong to moods and lip sync.

Write a small report next to the GLB (vertices, shapes, clips and whether each one loops). The game reads the loops from it, and a diff of it shows what a change did.

## Into the engine

In Godot, select the GLB, **Import** tab: **Ensure Tangents** off (flat materials have no UVs to make them from), **Generate LODs** and **Create Shadow Meshes** off for a face that is always close when it speaks, animation **FPS** 30. Give the mesh a larger `extra_cull_margin` when blend shapes or springs take it far from its box.

In Unity, FBX imports with **Import BlendShapes** on. GLB needs an importer package.

### Cel shading

Flat colours hide that there are no textures, and make mouth shapes readable from far away. One shader, one look per material name. The inside of the mouth, the teeth and the eyes are better not lit at all.

```glsl toon.gdshader theme={null}
shader_type spatial;
render_mode cull_disabled;

uniform vec4 colour : source_color = vec4(1.0);
uniform float edge : hint_range(0.0, 1.0) = 0.46;          // where light turns into shadow
uniform float softness : hint_range(0.001, 0.4) = 0.025;
uniform float flat_colour : hint_range(0.0, 1.0) = 0.0;    // 1 = not lit at all: eyes, teeth, the inside of the mouth

void fragment() {
    ALBEDO = colour.rgb;
    ROUGHNESS = 1.0;
    SPECULAR = 0.0;
    EMISSION = colour.rgb * flat_colour * 0.1;
}

void light() {
    float lit = dot(NORMAL, LIGHT) * 0.5 + 0.5;
    float band = smoothstep(edge - softness, edge + softness, lit * ATTENUATION);
    DIFFUSE_LIGHT += mix(band, 1.0, flat_colour) * LIGHT_COLOR / PI;
}
```

```gdscript toon.gd theme={null}
class_name ToonLook
## Gives every material of a model the toon shader, with its own colour. Rules go by the material's name.

const SHADER := preload("res://toon.gdshader")

static func apply(model: Node) -> void:
    for mesh: MeshInstance3D in model.find_children("*", "MeshInstance3D", true, false):
        for i in mesh.mesh.get_surface_count():
            var old := mesh.get_active_material(i)
            var m := ShaderMaterial.new()
            m.shader = SHADER
            if old is BaseMaterial3D:
                m.set_shader_parameter("colour", old.albedo_color)
            if old and old.resource_name.begins_with("face_"):
                m.set_shader_parameter("flat_colour", 1.0)
            mesh.set_surface_override_material(i, m)
```

## Contact sheets

Nobody finds a broken `viseme_CH` by playing. Draw every shape, with the game's own shading, after every build, and look at the sheet:

```gdscript sheet.gd theme={null}
extends SceneTree
## Contact sheet of the visemes, in the game's own shading.
##   godot --path . --script res://sheet.gd -- res://assets/head.glb sheet.png

const SIZE := 256
const COLUMNS := 5

func _initialize() -> void:
    _run()

func _run() -> void:
    var args := OS.get_cmdline_user_args()
    var model: Node3D = (load(args[0]) as PackedScene).instantiate()
    ToonLook.apply(model)
    var view := SubViewport.new()
    view.size = Vector2i(SIZE, SIZE)
    view.own_world_3d = true
    view.render_target_update_mode = SubViewport.UPDATE_ALWAYS
    root.add_child(view)
    view.add_child(model)
    var sun := DirectionalLight3D.new()
    sun.rotation_degrees = Vector3(-40, 30, 0)
    view.add_child(sun)
    var face: MeshInstance3D = model.find_children("*", "MeshInstance3D", true, false)[0]
    var box := face.get_aabb()
    var camera := Camera3D.new()
    view.add_child(camera)
    camera.position = box.get_center() + Vector3(0, 0, box.size.length() * 1.1)

    # What LokutorLipSync makes of the face.
    await process_frame
    var lips := LokutorLipSync.new()
    lips.faces = [face]
    root.add_child(lips)
    print("rig: ", LokutorLipSync.Rig.keys()[lips.rig()])

    var shapes: Array = []
    for i in face.get_blend_shape_count():
        if str(face.mesh.get_blend_shape_name(i)).begins_with("viseme_"):
            shapes.append(i)
    var rows := ceili(shapes.size() / float(COLUMNS))
    var sheet := Image.create(SIZE * COLUMNS, SIZE * rows, false, Image.FORMAT_RGBA8)
    for n in shapes.size():
        for i in shapes:
            face.set_blend_shape_value(i, 1.0 if i == shapes[n] else 0.0)
        for frame in 3:
            await RenderingServer.frame_post_draw
        var shot := view.get_texture().get_image()
        shot.convert(Image.FORMAT_RGBA8)
        sheet.blit_rect(shot, Rect2i(0, 0, SIZE, SIZE), Vector2i(n % COLUMNS, n / COLUMNS) * SIZE)
    sheet.save_png(args[1])
    quit()
```

```bash theme={null}
godot --headless --path . --import
godot --path . --script res://sheet.gd -- res://assets/head.glb sheet.png
```

It also prints what lip sync makes of the face: `VISEMES` is what you want. It draws, so it needs a window: the second command does not work with `--headless`.

What to look for:

* `PP` closed, with no gap and no crossing.
* `aa`, `O` and `U` different at a glance, in the size they will have on screen.
* Teeth inside the lips in `E`, `I` and `SS`; no tongue through them.
* Nothing moving that should not: ears, hat, collar.
* The same sheet for expressions, then one of your usual moods at 30% of their mouth with each viseme on top: that is what players will see.

Then the last check, with sound: say a line full of *p*, *b* and *m* ("Poppy baked my mum a big brown pie") and watch the lips touch on each.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.