@ikijs/mcp 0.21.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -982,7 +982,7 @@ function formatTurnReport(result) {
982
982
 
983
983
  // src/measure.ts
984
984
  import fs2 from "fs";
985
- import path5 from "path";
985
+ import path6 from "path";
986
986
 
987
987
  // src/measure-arms.ts
988
988
  import path4 from "path";
@@ -1150,6 +1150,860 @@ function jointWarnings(pose, arm, stats, a, armLayer, b) {
1150
1150
  return warnings;
1151
1151
  }
1152
1152
 
1153
+ // src/measure-lips.ts
1154
+ import path5 from "path";
1155
+ import {
1156
+ ALPHA_OPAQUE as ALPHA_OPAQUE4,
1157
+ LIP_INSIDE_ROLES,
1158
+ LIP_ROLES,
1159
+ LayerGeometryError as LayerGeometryError4,
1160
+ columnRuns as columnRuns2,
1161
+ createLayerSetMeasurer as createLayerSetMeasurer5,
1162
+ isLipInsideRole,
1163
+ mouthOpening as mouthOpening2
1164
+ } from "@ikijs/editor";
1165
+
1166
+ // src/compose-lips.ts
1167
+ import sharp2 from "sharp";
1168
+ import {
1169
+ ALPHA_OPAQUE as ALPHA_OPAQUE3,
1170
+ columnRuns,
1171
+ createLayerSetMeasurer as createLayerSetMeasurer4,
1172
+ mouthOpening,
1173
+ mouthRestShift
1174
+ } from "@ikijs/editor";
1175
+
1176
+ // src/trim.ts
1177
+ import { ALPHA_OPAQUE as ALPHA_OPAQUE2 } from "@ikijs/editor";
1178
+ var TRIM_THRESHOLD = 12;
1179
+ var STRAY_SPECK_FRACTION = 0.01;
1180
+ function luma(rgba, i) {
1181
+ return 0.299 * rgba[i] + 0.587 * rgba[i + 1] + 0.114 * rgba[i + 2];
1182
+ }
1183
+ function boxWithoutStraySpecks(rgba, W, H) {
1184
+ const n = W * H;
1185
+ let kept = 0;
1186
+ for (let p = 0; p < n; p++) if (rgba[p * 4 + 3] > TRIM_THRESHOLD) kept++;
1187
+ const visited = new Uint8Array(n);
1188
+ let stack = new Int32Array(1024);
1189
+ const drawing = [W, H, -1, -1];
1190
+ const strays = [W, H, -1, -1];
1191
+ let anyOpaque = false;
1192
+ for (let start = 0; start < n; start++) {
1193
+ if (visited[start] || rgba[start * 4 + 3] <= TRIM_THRESHOLD) continue;
1194
+ let setLeft = W;
1195
+ let setTop = H;
1196
+ let setRight = -1;
1197
+ let setBottom = -1;
1198
+ let size = 0;
1199
+ let opaque = false;
1200
+ let depth = 0;
1201
+ visited[start] = 1;
1202
+ stack[depth++] = start;
1203
+ while (depth > 0) {
1204
+ const p = stack[--depth];
1205
+ size++;
1206
+ if (rgba[p * 4 + 3] >= ALPHA_OPAQUE2) opaque = true;
1207
+ const px2 = p % W;
1208
+ const py = (p - px2) / W;
1209
+ setLeft = Math.min(setLeft, px2);
1210
+ setTop = Math.min(setTop, py);
1211
+ setRight = Math.max(setRight, px2);
1212
+ setBottom = Math.max(setBottom, py);
1213
+ for (let y = Math.max(0, py - 1); y <= Math.min(H - 1, py + 1); y++) {
1214
+ for (let x = Math.max(0, px2 - 1); x <= Math.min(W - 1, px2 + 1); x++) {
1215
+ const q = y * W + x;
1216
+ if (!visited[q] && rgba[q * 4 + 3] > TRIM_THRESHOLD) {
1217
+ visited[q] = 1;
1218
+ if (depth === stack.length) {
1219
+ const grown = new Int32Array(Math.min(n, stack.length * 2));
1220
+ grown.set(stack);
1221
+ stack = grown;
1222
+ }
1223
+ stack[depth++] = q;
1224
+ }
1225
+ }
1226
+ }
1227
+ }
1228
+ anyOpaque ||= opaque;
1229
+ const into = !opaque && size < kept * STRAY_SPECK_FRACTION ? strays : drawing;
1230
+ into[0] = Math.min(into[0], setLeft);
1231
+ into[1] = Math.min(into[1], setTop);
1232
+ into[2] = Math.max(into[2], setRight);
1233
+ into[3] = Math.max(into[3], setBottom);
1234
+ }
1235
+ if (!anyOpaque || strays[2] < 0) return null;
1236
+ const [left, top, right, bottom] = drawing;
1237
+ if (strays[0] >= left && strays[1] >= top && strays[2] <= right && strays[3] <= bottom)
1238
+ return null;
1239
+ return { left, top, width: right - left + 1, height: bottom - top + 1 };
1240
+ }
1241
+
1242
+ // src/compose-lips.ts
1243
+ var KEYED_SRC = "mouth_keyed.png";
1244
+ var INTERIOR_SRC = "mouth_interior.png";
1245
+ var KEY_CANDIDATE = 0.5;
1246
+ var KEY_FILL_DIST = 20;
1247
+ var KEY_REACH = 8;
1248
+ var KEY_COLLINEAR = 12;
1249
+ var KEY_MIN_SHARE = 0.05;
1250
+ var STRAY_KEY_FRACTION = 0.02;
1251
+ var MIN_OPENING_WIDTH = 0.3;
1252
+ var SECOND_HOLE_FRACTION = 0.05;
1253
+ var BAND_LUMA = 150;
1254
+ var BAND_CAP = 3;
1255
+ var CAVITY_LUMA = 100;
1256
+ var SKIN_MIN_R = 225;
1257
+ var SKIN_MIN_G = 160;
1258
+ var SKIN_MIN_B = 135;
1259
+ var TEETH_MIN_G = 215;
1260
+ var TEETH_MIN_B = 205;
1261
+ var isSkin = (r, g, b) => r > SKIN_MIN_R && g > SKIN_MIN_G && b > SKIN_MIN_B && !(g > TEETH_MIN_G && b > TEETH_MIN_B);
1262
+ function components2(mask, W, H) {
1263
+ const n = W * H;
1264
+ const label = new Int32Array(n).fill(-1);
1265
+ const stack = new Int32Array(n);
1266
+ const sizes = [];
1267
+ const boxes = [];
1268
+ for (let start = 0; start < n; start++) {
1269
+ if (!mask[start] || label[start] >= 0) continue;
1270
+ const id = sizes.length;
1271
+ const box = { x0: W, y0: H, x1: -1, y1: -1 };
1272
+ let size = 0;
1273
+ let depth = 0;
1274
+ label[start] = id;
1275
+ stack[depth++] = start;
1276
+ while (depth > 0) {
1277
+ const p = stack[--depth];
1278
+ size++;
1279
+ const px2 = p % W;
1280
+ const py = (p - px2) / W;
1281
+ box.x0 = Math.min(box.x0, px2);
1282
+ box.x1 = Math.max(box.x1, px2);
1283
+ box.y0 = Math.min(box.y0, py);
1284
+ box.y1 = Math.max(box.y1, py);
1285
+ for (let y = Math.max(0, py - 1); y <= Math.min(H - 1, py + 1); y++) {
1286
+ for (let x = Math.max(0, px2 - 1); x <= Math.min(W - 1, px2 + 1); x++) {
1287
+ if (x !== px2 && y !== py) continue;
1288
+ const q = y * W + x;
1289
+ if (mask[q] && label[q] < 0) {
1290
+ label[q] = id;
1291
+ stack[depth++] = q;
1292
+ }
1293
+ }
1294
+ }
1295
+ }
1296
+ sizes.push(size);
1297
+ boxes.push(box);
1298
+ }
1299
+ return { label, sizes, boxes };
1300
+ }
1301
+ var largest = (sizes) => sizes.reduce((best, s, i) => best < 0 || s > sizes[best] ? i : best, -1);
1302
+ function dilate2(mask, W, H, reach) {
1303
+ const rows = new Uint8Array(W * H);
1304
+ const prefix = new Int32Array(Math.max(W, H) + 1);
1305
+ for (let y = 0; y < H; y++) {
1306
+ for (let x = 0; x < W; x++) prefix[x + 1] = prefix[x] + mask[y * W + x];
1307
+ for (let x = 0; x < W; x++) {
1308
+ rows[y * W + x] = prefix[Math.min(W, x + reach + 1)] - prefix[Math.max(0, x - reach)] > 0 ? 1 : 0;
1309
+ }
1310
+ }
1311
+ const out = new Uint8Array(W * H);
1312
+ for (let x = 0; x < W; x++) {
1313
+ for (let y = 0; y < H; y++) prefix[y + 1] = prefix[y] + rows[y * W + x];
1314
+ for (let y = 0; y < H; y++) {
1315
+ out[y * W + x] = prefix[Math.min(H, y + reach + 1)] - prefix[Math.max(0, y - reach)] > 0 ? 1 : 0;
1316
+ }
1317
+ }
1318
+ return out;
1319
+ }
1320
+ function shareOf(rgba, i, j, g) {
1321
+ const dr = g[0] - rgba[j];
1322
+ const dg = g[1] - rgba[j + 1];
1323
+ const db = g[2] - rgba[j + 2];
1324
+ const t = ((rgba[i] - rgba[j]) * dr + (rgba[i + 1] - rgba[j + 1]) * dg + (rgba[i + 2] - rgba[j + 2]) * db) / (dr * dr + dg * dg + db * db);
1325
+ return Math.min(1, Math.max(0, t));
1326
+ }
1327
+ function keyGreen(rgba, W, H) {
1328
+ const n = W * H;
1329
+ const noGreen = new AutoRigInputError(
1330
+ `${KEYED_SRC}: no green opening (#00FF00) to key \u2014 regenerate it with the inside of the open mouth painted ONE flat pure green`
1331
+ );
1332
+ const hist = [
1333
+ new Uint32Array(256),
1334
+ new Uint32Array(256),
1335
+ new Uint32Array(256)
1336
+ ];
1337
+ let candidates = 0;
1338
+ for (let p = 0; p < n; p++) {
1339
+ const i = p * 4;
1340
+ if (rgba[i + 3] < ALPHA_OPAQUE3) continue;
1341
+ const excess = (rgba[i + 1] - Math.max(rgba[i], rgba[i + 2])) / 255;
1342
+ if (excess < KEY_CANDIDATE) continue;
1343
+ candidates++;
1344
+ for (let c = 0; c < 3; c++) hist[c][rgba[i + c]]++;
1345
+ }
1346
+ if (candidates === 0) throw noGreen;
1347
+ const median = (h) => {
1348
+ let seen = 0;
1349
+ for (let v = 0; v < 256; v++) {
1350
+ seen += h[v];
1351
+ if (seen * 2 >= candidates) return v;
1352
+ }
1353
+ return 255;
1354
+ };
1355
+ const G = [median(hist[0]), median(hist[1]), median(hist[2])];
1356
+ const out = Buffer.from(rgba);
1357
+ const fill = new Uint8Array(n);
1358
+ const ref = new Uint8Array(n);
1359
+ let fillCount = 0;
1360
+ for (let p = 0; p < n; p++) {
1361
+ const i = p * 4;
1362
+ if (rgba[i + 3] === 0) continue;
1363
+ const dr = rgba[i] - G[0];
1364
+ const dg = rgba[i + 1] - G[1];
1365
+ const db = rgba[i + 2] - G[2];
1366
+ const green = dr * dr + dg * dg + db * db <= KEY_FILL_DIST * KEY_FILL_DIST;
1367
+ if (rgba[i + 3] < ALPHA_OPAQUE3) {
1368
+ if (green) out[i + 3] = 0;
1369
+ } else if (green) {
1370
+ fill[p] = 1;
1371
+ fillCount++;
1372
+ } else {
1373
+ ref[p] = 1;
1374
+ }
1375
+ }
1376
+ if (fillCount === 0) throw noGreen;
1377
+ const reach = dilate2(fill, W, H, KEY_REACH);
1378
+ const collinear = KEY_COLLINEAR * KEY_COLLINEAR;
1379
+ for (let y = 0; y < H; y++) {
1380
+ for (let x = 0; x < W; x++) {
1381
+ const p = y * W + x;
1382
+ if (!reach[p] || fill[p] || out[p * 4 + 3] === 0) continue;
1383
+ const i = p * 4;
1384
+ let best = i;
1385
+ let bestD2 = (rgba[i] - G[0]) ** 2 + (rgba[i + 1] - G[1]) ** 2 + (rgba[i + 2] - G[2]) ** 2;
1386
+ const y1 = Math.min(H - 1, y + KEY_REACH);
1387
+ const x1 = Math.min(W - 1, x + KEY_REACH);
1388
+ for (let qy = Math.max(0, y - KEY_REACH); qy <= y1; qy++) {
1389
+ for (let qx = Math.max(0, x - KEY_REACH); qx <= x1; qx++) {
1390
+ const q = qy * W + qx;
1391
+ if (q === p || !ref[q]) continue;
1392
+ const j = q * 4;
1393
+ const d2 = (rgba[j] - G[0]) ** 2 + (rgba[j + 1] - G[1]) ** 2 + (rgba[j + 2] - G[2]) ** 2;
1394
+ if (d2 <= bestD2) continue;
1395
+ const t = shareOf(rgba, i, j, G);
1396
+ const er = rgba[i] - rgba[j] - t * (G[0] - rgba[j]);
1397
+ const eg = rgba[i + 1] - rgba[j + 1] - t * (G[1] - rgba[j + 1]);
1398
+ const eb = rgba[i + 2] - rgba[j + 2] - t * (G[2] - rgba[j + 2]);
1399
+ if (er * er + eg * eg + eb * eb > collinear) continue;
1400
+ bestD2 = d2;
1401
+ best = j;
1402
+ }
1403
+ }
1404
+ const k = shareOf(rgba, i, best, G);
1405
+ if (k < KEY_MIN_SHARE) continue;
1406
+ rgba.copy(out, i, best, best + 3);
1407
+ out[i + 3] = Math.round(rgba[i + 3] * (1 - k));
1408
+ }
1409
+ }
1410
+ for (let p = 0; p < n; p++) if (fill[p]) out[p * 4 + 3] = 0;
1411
+ const { sizes } = components2(fill, W, H);
1412
+ const main = largest(sizes);
1413
+ const strays = sizes.filter((_, i) => i !== main);
1414
+ const strayPx = strays.reduce((a, b) => a + b, 0);
1415
+ if (strayPx > STRAY_KEY_FRACTION * sizes[main]) {
1416
+ throw new AutoRigInputError(
1417
+ `${KEYED_SRC}: green outside the opening (${strayPx} px in ${strays.length} regions beside the opening's) \u2014 the key must be one flat region inside the outline; regenerate with no green elsewhere`
1418
+ );
1419
+ }
1420
+ return out;
1421
+ }
1422
+ var GROUND_TOLERANCE = 4;
1423
+ var GROUND_LIGHT = 200;
1424
+ var GROUND_MIN = 238;
1425
+ var GROUND_BORDER_SHARE = 0.65;
1426
+ function keyBorderWhite(rgba, W, H) {
1427
+ const border = [[], [], []];
1428
+ const edge = (p) => {
1429
+ for (let c = 0; c < 3; c++) border[c].push(rgba[p * 4 + c]);
1430
+ };
1431
+ for (let x = 0; x < W; x++) {
1432
+ edge(x);
1433
+ edge((H - 1) * W + x);
1434
+ }
1435
+ for (let y = 1; y < H - 1; y++) {
1436
+ edge(y * W);
1437
+ edge(y * W + W - 1);
1438
+ }
1439
+ const ground = border.map((v) => v.sort((a, b) => a - b)[v.length >> 1]);
1440
+ const light = ground.every((v) => v >= GROUND_LIGHT);
1441
+ if (light && ground.some((v) => v < GROUND_MIN)) {
1442
+ throw new AutoRigInputError(
1443
+ `${INTERIOR_SRC} came back opaque on a non-white ground \u2014 regenerate it with a transparent background. Billed.`
1444
+ );
1445
+ }
1446
+ if (!light) ground.fill(255);
1447
+ const out = Buffer.from(rgba);
1448
+ const seen = new Uint8Array(W * H);
1449
+ const stack = new Int32Array(W * H);
1450
+ let depth = 0;
1451
+ const seed = (p) => {
1452
+ if (seen[p]) return;
1453
+ for (let c = 0; c < 3; c++) {
1454
+ if (Math.abs(rgba[p * 4 + c] - ground[c]) > GROUND_TOLERANCE) return;
1455
+ }
1456
+ seen[p] = 1;
1457
+ stack[depth++] = p;
1458
+ };
1459
+ for (let x = 0; x < W; x++) {
1460
+ seed(x);
1461
+ seed((H - 1) * W + x);
1462
+ }
1463
+ for (let y = 0; y < H; y++) {
1464
+ seed(y * W);
1465
+ seed(y * W + W - 1);
1466
+ }
1467
+ if (light && depth < GROUND_BORDER_SHARE * border[0].length) {
1468
+ throw new AutoRigInputError(
1469
+ `${INTERIOR_SRC} came back opaque on a white ground too noisy or shaded to key cleanly \u2014 regenerate it with a transparent background. Billed.`
1470
+ );
1471
+ }
1472
+ while (depth > 0) {
1473
+ const p = stack[--depth];
1474
+ out[p * 4 + 3] = 0;
1475
+ const x = p % W;
1476
+ if (x > 0) seed(p - 1);
1477
+ if (x < W - 1) seed(p + 1);
1478
+ if (p >= W) seed(p - W);
1479
+ if (p < W * H - W) seed(p + W);
1480
+ }
1481
+ return out;
1482
+ }
1483
+ function drawingBox(rgba, W, H) {
1484
+ const speckless = boxWithoutStraySpecks(rgba, W, H);
1485
+ if (speckless !== null) {
1486
+ return {
1487
+ x: speckless.left,
1488
+ y: speckless.top,
1489
+ w: speckless.width,
1490
+ h: speckless.height
1491
+ };
1492
+ }
1493
+ let x0 = W;
1494
+ let y0 = H;
1495
+ let x1 = -1;
1496
+ let y1 = -1;
1497
+ for (let y = 0; y < H; y++) {
1498
+ for (let x = 0; x < W; x++) {
1499
+ if (rgba[(y * W + x) * 4 + 3] <= TRIM_THRESHOLD) continue;
1500
+ x0 = Math.min(x0, x);
1501
+ x1 = Math.max(x1, x);
1502
+ y0 = Math.min(y0, y);
1503
+ y1 = Math.max(y1, y);
1504
+ }
1505
+ }
1506
+ return x1 < 0 ? null : { x: x0, y: y0, w: x1 - x0 + 1, h: y1 - y0 + 1 };
1507
+ }
1508
+ async function prepInterior(rgba, W, H) {
1509
+ const empty = new AutoRigInputError(
1510
+ `${INTERIOR_SRC}: nothing but lips/skin after trimming \u2014 regenerate it with the cavity, the teeth and the tongue only, NO lips`
1511
+ );
1512
+ const first = drawingBox(rgba, W, H);
1513
+ if (first === null) throw empty;
1514
+ const cw = first.w;
1515
+ const ch = first.h;
1516
+ const crop = Buffer.alloc(cw * ch * 4);
1517
+ for (let y = 0; y < ch; y++) {
1518
+ const from2 = ((first.y + y) * W + first.x) * 4;
1519
+ rgba.copy(crop, y * cw * 4, from2, from2 + cw * 4);
1520
+ }
1521
+ const skin = new Uint8Array(cw * ch);
1522
+ for (let p = 0; p < cw * ch; p++) {
1523
+ const i = p * 4;
1524
+ if (crop[i + 3] > TRIM_THRESHOLD && isSkin(crop[i], crop[i + 1], crop[i + 2]))
1525
+ skin[p] = 1;
1526
+ }
1527
+ const { label, boxes } = components2(skin, cw, ch);
1528
+ const rim = boxes.map(
1529
+ (b) => b.x0 === 0 || b.y0 === 0 || b.x1 === cw - 1 || b.y1 === ch - 1
1530
+ );
1531
+ for (let p = 0; p < cw * ch; p++) {
1532
+ if (label[p] >= 0 && rim[label[p]]) crop[p * 4 + 3] = 0;
1533
+ }
1534
+ const box = drawingBox(crop, cw, ch);
1535
+ if (box === null) throw empty;
1536
+ const sum = [0, 0, 0];
1537
+ const all = [0, 0, 0];
1538
+ let dark = 0;
1539
+ let count = 0;
1540
+ for (let y = box.y; y < box.y + box.h; y++) {
1541
+ for (let x = box.x; x < box.x + box.w; x++) {
1542
+ const i = (y * cw + x) * 4;
1543
+ if (crop[i + 3] < ALPHA_OPAQUE3) continue;
1544
+ count++;
1545
+ for (let c = 0; c < 3; c++) all[c] += crop[i + c];
1546
+ if (luma(crop, i) < CAVITY_LUMA) {
1547
+ dark++;
1548
+ for (let c = 0; c < 3; c++) sum[c] += crop[i + c];
1549
+ }
1550
+ }
1551
+ }
1552
+ if (count === 0) throw empty;
1553
+ const [from, over] = dark > 0 ? [sum, dark] : [all, count];
1554
+ const cavity = from.map((v) => Math.round(v / over));
1555
+ return { png: await cropToBuffer(crop, cw, ch, box), cavity };
1556
+ }
1557
+ var rawOf = async (png) => sharp2(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1558
+ var encode = (rgba, w, h) => sharp2(rgba, { raw: { width: w, height: h, channels: 4 } }).png().toBuffer();
1559
+ function enclosedHole(frame, w, h) {
1560
+ const n = w * h;
1561
+ const alpha = (p) => frame[p * 4 + 3];
1562
+ const outside = new Uint8Array(n);
1563
+ const stack = new Int32Array(n);
1564
+ let depth = 0;
1565
+ const seed = (p) => {
1566
+ if (!outside[p] && alpha(p) < ALPHA_OPAQUE3) {
1567
+ outside[p] = 1;
1568
+ stack[depth++] = p;
1569
+ }
1570
+ };
1571
+ for (let x = 0; x < w; x++) {
1572
+ seed(x);
1573
+ seed((h - 1) * w + x);
1574
+ }
1575
+ for (let y = 0; y < h; y++) {
1576
+ seed(y * w);
1577
+ seed(y * w + w - 1);
1578
+ }
1579
+ while (depth > 0) {
1580
+ const p = stack[--depth];
1581
+ const x = p % w;
1582
+ if (x > 0) seed(p - 1);
1583
+ if (x < w - 1) seed(p + 1);
1584
+ if (p >= w) seed(p - w);
1585
+ if (p < n - w) seed(p + w);
1586
+ }
1587
+ const mask = new Uint8Array(n);
1588
+ for (let p = 0; p < n; p++) {
1589
+ if (alpha(p) < ALPHA_OPAQUE3 && !outside[p]) mask[p] = 1;
1590
+ }
1591
+ const { label, sizes, boxes } = components2(mask, w, h);
1592
+ const main = largest(sizes);
1593
+ if (main < 0) {
1594
+ throw new AutoRigInputError(
1595
+ `${KEYED_SRC}: the outline is not closed round the opening (the key reached the outside, or the line is broken or too thin at this size) \u2014 regenerate with ONE closed, bolder outline`
1596
+ );
1597
+ }
1598
+ const box = boxes[main];
1599
+ const holeW = box.x1 - box.x0 + 1;
1600
+ if (holeW < MIN_OPENING_WIDTH * w) {
1601
+ throw new AutoRigInputError(
1602
+ `${KEYED_SRC}: the opening is only ${holeW} px wide of the mouth's ${w} \u2014 too small to fold; regenerate with the mouth open wider, or, if its outline is broken (only a small pocket of the opening was enclosed), with ONE closed, bolder outline`
1603
+ );
1604
+ }
1605
+ const others = sizes.filter(
1606
+ (s, i) => i !== main && s >= SECOND_HOLE_FRACTION * sizes[main]
1607
+ );
1608
+ if (others.length > 0) {
1609
+ throw new AutoRigInputError(
1610
+ `${KEYED_SRC}: the opening is not one connected region (${others.length + 1} holes: teeth or tongue drawn into the green?) \u2014 regenerate with nothing drawn inside the green`
1611
+ );
1612
+ }
1613
+ return { label, main, box };
1614
+ }
1615
+ function measureLips(layers, w, h) {
1616
+ const measurer = createLayerSetMeasurer4({ width: w, height: h });
1617
+ return new Map(
1618
+ Object.entries(layers).map(([role, rgba]) => [
1619
+ role,
1620
+ measurer.add({ role, fileName: `${role}.png`, rgba })
1621
+ ])
1622
+ );
1623
+ }
1624
+ function assertFoldContract(layers, w, h) {
1625
+ const byRole = /* @__PURE__ */ new Map();
1626
+ for (const [role, layer] of measureLips(layers, w, h)) {
1627
+ if (layer === null && role === "lip_lower") {
1628
+ throw new AutoRigInputError(
1629
+ `${KEYED_SRC}: no lip_lower after the split \u2014 there is no skin under the opening; draw the lower lip under the outline`
1630
+ );
1631
+ }
1632
+ byRole.set(role, layer);
1633
+ }
1634
+ const opening = mouthOpening(byRole);
1635
+ const runs = columnRuns(byRole.get("mouth_inner"));
1636
+ for (let col = opening.x0; col <= opening.x1; col++) {
1637
+ const c = opening.at(col);
1638
+ const why = !runs.has(col) ? "has no interior run" : c.Tu > c.T ? `has a gap between the line and the interior (Tu ${c.Tu} > T ${c.T})` : c.T > c.lineTop || c.lineH <= 0 ? `has no line above the interior (T ${c.T}, line top ${c.lineTop})` : c.Bl < c.Bb ? `has a gap between the interior and the skin (Bl ${c.Bl} < Bb ${c.Bb})` : null;
1639
+ if (why !== null) throw new Error(`splitLipSet: column ${col} ${why}`);
1640
+ }
1641
+ return opening;
1642
+ }
1643
+ async function splitLipSet(keyedPng, w, h, interior) {
1644
+ const { data: frame, info } = await rawOf(keyedPng);
1645
+ if (info.width !== w || info.height !== h) {
1646
+ throw new Error(
1647
+ `splitLipSet: the frame is ${info.width}x${info.height}, not ${w}x${h}`
1648
+ );
1649
+ }
1650
+ const n = w * h;
1651
+ const alpha = (p) => frame[p * 4 + 3];
1652
+ const { label, main, box: hb } = enclosedHole(frame, w, h);
1653
+ const holeW = hb.x1 - hb.x0 + 1;
1654
+ const top = new Int32Array(w).fill(-1);
1655
+ const bot = new Int32Array(w).fill(-1);
1656
+ for (let y = 0; y < h; y++) {
1657
+ for (let x = hb.x0; x <= hb.x1; x++) {
1658
+ if (label[y * w + x] !== main) continue;
1659
+ if (top[x] < 0) top[x] = y;
1660
+ bot[x] = y + 1;
1661
+ }
1662
+ }
1663
+ const centre = Math.round((hb.x0 + hb.x1) / 2);
1664
+ let stroke = 0;
1665
+ while (top[centre] - 1 - stroke >= 0 && alpha((top[centre] - 1 - stroke) * w + centre) >= ALPHA_OPAQUE3)
1666
+ stroke++;
1667
+ const bandCap = BAND_CAP * Math.max(1, stroke);
1668
+ const skinRow = new Int32Array(w).fill(-1);
1669
+ const inM = new Uint8Array(n);
1670
+ for (let x = hb.x0; x <= hb.x1; x++) {
1671
+ let y = bot[x];
1672
+ while (y < h && y - bot[x] < bandCap && alpha(y * w + x) >= ALPHA_OPAQUE3 && luma(frame, (y * w + x) * 4) < BAND_LUMA)
1673
+ y++;
1674
+ for (let k = top[x]; k < y; k++) inM[k * w + x] = 1;
1675
+ let r = y;
1676
+ while (r < h && alpha(r * w + x) < ALPHA_OPAQUE3) r++;
1677
+ if (r < h) {
1678
+ skinRow[x] = r;
1679
+ inM[r * w + x] = 1;
1680
+ }
1681
+ }
1682
+ const grown = Uint8Array.from(inM);
1683
+ for (let y = 0; y < h; y++) {
1684
+ for (let x = 0; x < w; x++) {
1685
+ const p = y * w + x;
1686
+ if (inM[p] || alpha(p) < ALPHA_OPAQUE3) continue;
1687
+ if (top[x] >= 0 && y < top[x]) continue;
1688
+ if (x > 0 && inM[p - 1] || x < w - 1 && inM[p + 1]) grown[p] = 1;
1689
+ }
1690
+ }
1691
+ const wall = new Uint8Array(w);
1692
+ for (const x of [hb.x0 - 1, hb.x1 + 1]) {
1693
+ if (x < 0 || x >= w) continue;
1694
+ let first = 0;
1695
+ while (first < h && !(grown[first * w + x] && !inM[first * w + x])) first++;
1696
+ if (first > 0 && first < h && alpha((first - 1) * w + x) >= ALPHA_OPAQUE3)
1697
+ wall[x] = 1;
1698
+ }
1699
+ const gx = hb.x0 - 1;
1700
+ const gy = hb.y0 - 1;
1701
+ const gw = holeW + 2;
1702
+ const gh = hb.y1 - hb.y0 + 3;
1703
+ const { data: fitted } = await sharp2(interior.png).resize(gw, gh, { fit: "fill" }).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1704
+ const hole = (q) => label[q] === main;
1705
+ const upperHalf = (x, y) => 2 * y < top[x] + bot[x];
1706
+ const faintUpper = (p, x, y) => y < bot[x] && hole(p) && upperHalf(x, y);
1707
+ const besideHole = (p, x, y) => x > 0 && hole(p - 1) || x < w - 1 && hole(p + 1) || y > 0 && hole(p - w) || y < h - 1 && hole(p + w);
1708
+ const upper = Buffer.alloc(n * 4);
1709
+ const lower = Buffer.alloc(n * 4);
1710
+ const inner = Buffer.alloc(n * 4);
1711
+ const tongue = Buffer.alloc(n * 4);
1712
+ const teeth = Buffer.alloc(n * 4);
1713
+ const copy = (to, p) => frame.copy(to, p * 4, p * 4, p * 4 + 4);
1714
+ for (let y = 0; y < h; y++) {
1715
+ for (let x = 0; x < w; x++) {
1716
+ const p = y * w + x;
1717
+ const inOpening = top[x] >= 0;
1718
+ if ((!inOpening || y < top[x] || faintUpper(p, x, y)) && !(wall[x] && grown[p]))
1719
+ copy(upper, p);
1720
+ if (inOpening && skinRow[x] >= 0 && y >= skinRow[x]) copy(lower, p);
1721
+ if (!grown[p]) {
1722
+ const a = alpha(p);
1723
+ if (a >= ALPHA_OPAQUE3 && a < 255 && besideHole(p, x, y)) {
1724
+ inner.set(interior.cavity, p * 4);
1725
+ inner[p * 4 + 3] = 255 - a;
1726
+ }
1727
+ continue;
1728
+ }
1729
+ const out = [...interior.cavity];
1730
+ const ix = x - gx;
1731
+ const iy = y - gy;
1732
+ if (ix >= 0 && ix < gw && iy >= 0 && iy < gh) {
1733
+ const i = (iy * gw + ix) * 4;
1734
+ const a = fitted[i + 3] / 255;
1735
+ for (let c = 0; c < 3; c++) out[c] += (fitted[i + c] - out[c]) * a;
1736
+ }
1737
+ if ((inM[p] || wall[x]) && !faintUpper(p, x, y)) {
1738
+ const a = alpha(p) / 255;
1739
+ for (let c = 0; c < 3; c++) out[c] += (frame[p * 4 + c] - out[c]) * a;
1740
+ }
1741
+ inner[p * 4] = Math.round(out[0]);
1742
+ inner[p * 4 + 1] = Math.round(out[1]);
1743
+ inner[p * 4 + 2] = Math.round(out[2]);
1744
+ inner[p * 4 + 3] = 255;
1745
+ if (hole(p) && luma(inner, p * 4) >= CAVITY_LUMA) {
1746
+ const to = upperHalf(x, y) ? teeth : tongue;
1747
+ inner.copy(to, p * 4, p * 4, p * 4 + 4);
1748
+ inner.set(interior.cavity, p * 4);
1749
+ }
1750
+ }
1751
+ }
1752
+ const opening = assertFoldContract(
1753
+ { mouth_inner: inner, lip_lower: lower, lip_upper: upper },
1754
+ w,
1755
+ h
1756
+ );
1757
+ const [innerPng, lowerPng, upperPng, tonguePng, teethPng] = await Promise.all(
1758
+ [inner, lower, upper, tongue, teeth].map((b) => encode(b, w, h))
1759
+ );
1760
+ return {
1761
+ inner: innerPng,
1762
+ lower: lowerPng,
1763
+ upper: upperPng,
1764
+ tongue: tonguePng,
1765
+ teeth: teethPng,
1766
+ opening
1767
+ };
1768
+ }
1769
+ async function restShiftOf(layers, width, height) {
1770
+ const [mouth_inner, lip_lower, lip_upper] = await Promise.all(
1771
+ [layers.mouth_inner, layers.lip_lower, layers.lip_upper].map(
1772
+ async (png) => (await rawOf(png)).data
1773
+ )
1774
+ );
1775
+ const byRole = /* @__PURE__ */ new Map();
1776
+ for (const [role, layer] of measureLips(
1777
+ { mouth_inner, lip_lower, lip_upper },
1778
+ width,
1779
+ height
1780
+ )) {
1781
+ if (layer === null) {
1782
+ throw new AutoRigInputError(
1783
+ `layout.mouth_inner places the lip set so that ${role} falls off the canvas (nothing of it is left) \u2014 move it back on the canvas`
1784
+ );
1785
+ }
1786
+ byRole.set(role, layer);
1787
+ }
1788
+ return mouthRestShift(byRole);
1789
+ }
1790
+ async function closedLips(upper, lower, shift, left, top) {
1791
+ const shut = async (png, role) => {
1792
+ const { data, info } = await rawOf(png);
1793
+ const { width: w, height: h } = info;
1794
+ const out = Buffer.alloc(w * h * 4);
1795
+ for (let x = 0; x < w; x++) {
1796
+ const px2 = (row, c) => row < 0 || row >= h ? 0 : data[(row * w + x) * 4 + c];
1797
+ const landed = [];
1798
+ for (let row = 0; row < h; row++) {
1799
+ const dy = shift(role, left + x, top + row);
1800
+ if (dy !== void 0) landed.push([row, row + 0.5 - dy]);
1801
+ }
1802
+ if (landed.length > 1) {
1803
+ const [a, b] = landed;
1804
+ const [y, z2] = landed.slice(-2);
1805
+ landed.unshift([a[0] - 1, 2 * a[1] - b[1]]);
1806
+ landed.push([z2[0] + 1, 2 * z2[1] - y[1]]);
1807
+ }
1808
+ let i = 0;
1809
+ for (let to = 0; to < h; to++) {
1810
+ const centre = to + 0.5;
1811
+ while (i + 1 < landed.length && landed[i + 1][1] < centre) i++;
1812
+ if (i + 1 >= landed.length || landed[i][1] > centre) continue;
1813
+ const [r0, y0] = landed[i];
1814
+ const [r1, y1] = landed[i + 1];
1815
+ const t = (centre - y0) / (y1 - y0);
1816
+ const a0 = px2(r0, 3);
1817
+ const a1 = px2(r1, 3);
1818
+ const a = (1 - t) * a0 + t * a1;
1819
+ if (a === 0) continue;
1820
+ const o = (to * w + x) * 4;
1821
+ for (let c = 0; c < 3; c++)
1822
+ out[o + c] = Math.round(
1823
+ ((1 - t) * a0 * px2(r0, c) + t * a1 * px2(r1, c)) / a
1824
+ );
1825
+ out[o + 3] = Math.round(a);
1826
+ }
1827
+ }
1828
+ return encode(out, w, h);
1829
+ };
1830
+ const [u, l] = await Promise.all([
1831
+ shut(upper, "lip_upper"),
1832
+ shut(lower, "lip_lower")
1833
+ ]);
1834
+ return { upper: u, lower: l };
1835
+ }
1836
+
1837
+ // src/measure-lips.ts
1838
+ var isLipLayerRole = (role) => LIP_ROLES.includes(role) || isLipInsideRole(role);
1839
+ var MIN_OPENING_ROWS = 8;
1840
+ var MIN_LINE_ROWS = 2;
1841
+ var GREEN_EXCESS = 40;
1842
+ var INTERIOR_GAP_FRACTION = 0.05;
1843
+ var columns = (cols) => `${cols.length} column${cols.length === 1 ? "" : "s"} (first at x=${cols[0]})`;
1844
+ async function lipWarnings(absDir, layers) {
1845
+ const warnings = [];
1846
+ const present = LIP_ROLES.filter((role) => layers[role] !== void 0);
1847
+ const inside = LIP_INSIDE_ROLES.filter((role) => layers[role] !== void 0);
1848
+ if (present.length === 0) {
1849
+ if (inside.length > 0) {
1850
+ warnings.push(
1851
+ `${inside.join("/")}: a lip set's inside layer with no lip set \u2014 auto_rig_from_layers refuses it (it is cut from the interior and clipped to it). Recompose from mouth_keyed.png + mouth_interior.png, or remove it.`
1852
+ );
1853
+ }
1854
+ return { warnings };
1855
+ }
1856
+ const legacy = ["mouth", "mouth_open"].filter(
1857
+ (role) => layers[role] !== void 0
1858
+ );
1859
+ if (legacy.length > 0) {
1860
+ warnings.push(
1861
+ `${present.join("/")}: the lip set cannot be mixed with ${legacy.join("/")} \u2014 auto_rig_from_layers refuses it. Remove one route: compose again with only mouth_keyed.png + mouth_interior.png, or without them.`
1862
+ );
1863
+ }
1864
+ if (present.length < LIP_ROLES.length) {
1865
+ const missing = LIP_ROLES.filter((role) => layers[role] === void 0);
1866
+ warnings.push(
1867
+ `${present.join("/")}: partial lip set, missing ${missing.join("/")} \u2014 auto_rig_from_layers refuses it. Compose mouth_keyed.png + mouth_interior.png together, which cuts all three.`
1868
+ );
1869
+ return { warnings };
1870
+ }
1871
+ const { mouth_inner: inner, lip_upper: upper } = layers;
1872
+ for (const role of ["lip_lower", "lip_upper", ...inside]) {
1873
+ const stats = layers[role];
1874
+ if (stats.canvasW !== inner.canvasW || stats.canvasH !== inner.canvasH) {
1875
+ warnings.push(
1876
+ `${role}: its canvas ${stats.canvasW}x${stats.canvasH} differs from mouth_inner's ${inner.canvasW}x${inner.canvasH} \u2014 auto_rig_from_layers refuses layers of different sizes; recompose them together.`
1877
+ );
1878
+ return { warnings };
1879
+ }
1880
+ }
1881
+ const box = (m) => ({
1882
+ x0: m.bboxCx - m.w / 2,
1883
+ x1: m.bboxCx + m.w / 2,
1884
+ y0: m.bboxCy - m.h / 2,
1885
+ y1: m.bboxCy + m.h / 2
1886
+ });
1887
+ const cavity = box(inner);
1888
+ for (const role of inside) {
1889
+ const b = box(layers[role]);
1890
+ if (b.x0 < cavity.x0 || b.x1 > cavity.x1 || b.y0 < cavity.y0 || b.y1 > cavity.y1) {
1891
+ warnings.push(
1892
+ `${role}: its box leaves mouth_inner's \u2014 the cavity clips it away there. Recompose from mouth_keyed.png + mouth_interior.png (free).`
1893
+ );
1894
+ }
1895
+ }
1896
+ const measurer = createLayerSetMeasurer5({
1897
+ width: inner.canvasW,
1898
+ height: inner.canvasH
1899
+ });
1900
+ const set = /* @__PURE__ */ new Map();
1901
+ const green = [];
1902
+ for (const role of LIP_ROLES) {
1903
+ const fileName = `${role}.png`;
1904
+ const { rgba } = await decodePng(path5.join(absDir, fileName));
1905
+ set.set(role, measurer.add({ role, fileName, rgba }));
1906
+ for (let i = 0; i < rgba.length; i += 4) {
1907
+ if (rgba[i + 3] >= ALPHA_OPAQUE4 && rgba[i + 1] - Math.max(rgba[i], rgba[i + 2]) > GREEN_EXCESS) {
1908
+ green.push(role);
1909
+ break;
1910
+ }
1911
+ }
1912
+ }
1913
+ let opening;
1914
+ try {
1915
+ opening = mouthOpening2(set);
1916
+ } catch (err) {
1917
+ if (err instanceof LayerGeometryError4) {
1918
+ warnings.push(err.message);
1919
+ return { warnings };
1920
+ }
1921
+ throw err;
1922
+ }
1923
+ const innerRuns = columnRuns2(set.get("mouth_inner"));
1924
+ const noInterior = [];
1925
+ const gap = [];
1926
+ const noLine = [];
1927
+ const skinGap = [];
1928
+ let area = 0;
1929
+ let hollow = 0;
1930
+ for (let x = opening.x0; x <= opening.x1; x++) {
1931
+ const runs = innerRuns.get(x);
1932
+ if (runs === void 0) {
1933
+ noInterior.push(x);
1934
+ continue;
1935
+ }
1936
+ const span = runs[runs.length - 1][1] - runs[0][0];
1937
+ area += span;
1938
+ hollow += span - runs.reduce((n, r) => n + r[1] - r[0], 0);
1939
+ const c = opening.at(x);
1940
+ if (c.lineH <= 0) noLine.push(x);
1941
+ else if (c.Tu > c.T) gap.push(x);
1942
+ if (c.Bl < c.Bb) skinGap.push(x);
1943
+ }
1944
+ const recompose = (file, ask) => `Recompose from mouth_keyed.png + mouth_interior.png (free); if it persists, regenerate ${file} ${ask}. Billed.`;
1945
+ const regenKeyed = recompose(
1946
+ "mouth_keyed.png",
1947
+ "with a closed outline and solid lips under it"
1948
+ );
1949
+ if (noInterior.length > 0) {
1950
+ warnings.push(
1951
+ `mouth_inner: no interior in ${columns(noInterior)} of the opening \u2014 the fold has nothing to scale there. ${recompose("mouth_interior.png", "as one solid cavity")}`
1952
+ );
1953
+ }
1954
+ if (gap.length > 0) {
1955
+ warnings.push(
1956
+ `lip_upper: a gap between the line and the interior in ${columns(gap)} \u2014 the face shows through it at rest (the interior's top must reach the line's ink). ${regenKeyed}`
1957
+ );
1958
+ }
1959
+ if (noLine.length > 0) {
1960
+ warnings.push(
1961
+ `lip_upper: no line above the interior in ${columns(noLine)} \u2014 nothing closes the mouth there. ${regenKeyed}`
1962
+ );
1963
+ }
1964
+ if (skinGap.length > 0) {
1965
+ warnings.push(
1966
+ `lip_lower: a gap between the interior and the skin in ${columns(skinGap)} \u2014 the face shows through it once the mouth opens (the skin must reach the interior's bottom). ${regenKeyed}`
1967
+ );
1968
+ }
1969
+ const width = opening.x1 - opening.x0 + 1;
1970
+ const centre = opening.at(opening.centre);
1971
+ if (width < MIN_OPENING_WIDTH * upper.w) {
1972
+ warnings.push(
1973
+ `mouth_inner: the opening is ${width} px wide, ${Math.round(100 * width / upper.w)}% of lip_upper's ${upper.w} px (under ${Math.round(100 * MIN_OPENING_WIDTH)}%) \u2014 too narrow to fold; the slit stays a hairline. Regenerate mouth_keyed.png with the mouth open wider. Billed.`
1974
+ );
1975
+ }
1976
+ if (centre.H < MIN_OPENING_ROWS) {
1977
+ const w = Math.ceil(upper.w * MIN_OPENING_ROWS / centre.H);
1978
+ const retune = w <= inner.canvasW ? w : null;
1979
+ warnings.push(
1980
+ `mouth_inner: the opening is ${centre.H} px tall at its centre (under ${MIN_OPENING_ROWS}) \u2014 too small to fold; the slit stays shut until MouthOpen is nearly 1. ` + (retune === null ? "" : `If the mouth is smaller than the reference's, set layout.mouth_inner.w to ${retune} (free; the whole set scales with it, so scale layout.mouth_inner.h too if it is set). Otherwise `) + `${retune === null ? "R" : "r"}egenerate mouth_keyed.png with the mouth open taller. Billed.`
1981
+ );
1982
+ }
1983
+ if (opening.w < MIN_LINE_ROWS) {
1984
+ warnings.push(
1985
+ `lip_upper: the upper line is ${opening.w} px at the opening's centre (under ${MIN_LINE_ROWS}) \u2014 a hairline closes to nothing. Regenerate mouth_keyed.png with a bolder upper line, never thinner than the reference's mouth line. Billed.`
1986
+ );
1987
+ }
1988
+ if (green.length > 0) {
1989
+ warnings.push(
1990
+ `${green.join("/")}: opaque green left (key green, g exceeds r and b by over ${GREEN_EXCESS}) \u2014 it shows as a green fringe on the lips. Regenerate mouth_keyed.png with the green only inside the opening, or mouth_interior.png without green in it. Billed.`
1991
+ );
1992
+ }
1993
+ if (area > 0 && hollow > INTERIOR_GAP_FRACTION * area) {
1994
+ warnings.push(
1995
+ `mouth_inner: ${Math.round(100 * hollow / area)}% of the opening is transparent inside the interior's own span (over ${Math.round(100 * INTERIOR_GAP_FRACTION)}%) \u2014 the face shows through it. Regenerate mouth_interior.png as one solid cavity. Billed.`
1996
+ );
1997
+ }
1998
+ return {
1999
+ warnings,
2000
+ lips: {
2001
+ opening: { width, height: centre.H, line: opening.w },
2002
+ deadZone: centre.overlap / (centre.H + centre.overlap)
2003
+ }
2004
+ };
2005
+ }
2006
+
1153
2007
  // src/measure.ts
1154
2008
  var IRIS_RATIO_MIN = 0.45;
1155
2009
  var IRIS_RATIO_MAX = 0.72;
@@ -1278,8 +2132,8 @@ async function measureDir(absDir, noseSpeck) {
1278
2132
  const layers = {};
1279
2133
  const empty = [];
1280
2134
  for (const f of files) {
1281
- const role = path5.basename(f, ".png");
1282
- const m = await layerStats(path5.join(absDir, f));
2135
+ const role = path6.basename(f, ".png");
2136
+ const m = await layerStats(path6.join(absDir, f));
1283
2137
  if (!m) {
1284
2138
  empty.push(role);
1285
2139
  continue;
@@ -1288,6 +2142,7 @@ async function measureDir(absDir, noseSpeck) {
1288
2142
  }
1289
2143
  const warnings = [];
1290
2144
  for (const [role, m] of Object.entries(layers)) {
2145
+ if (isLipLayerRole(role)) continue;
1291
2146
  const edges = [
1292
2147
  ["top", m.edgeTop, m.w, m.marginTop],
1293
2148
  ["left", m.edgeLeft, m.h, m.marginLeft],
@@ -1317,7 +2172,7 @@ async function measureDir(absDir, noseSpeck) {
1317
2172
  }
1318
2173
  }
1319
2174
  for (const [role, m] of Object.entries(layers)) {
1320
- if (role === "body") continue;
2175
+ if (role === "body" || isLipLayerRole(role)) continue;
1321
2176
  if (m.flatCutRun > FLAT_CUT_MAX_FRAC * m.w && m.flatCutRun >= FLAT_CUT_MIN_PX) {
1322
2177
  warnings.push(
1323
2178
  `${role}: ${m.flatCutRun}px of straight flat edge at y=${m.flatCutY} (${pct(m.flatCutRun / m.w)} of its width) \u2014 the source art is cut through there. ` + (isArm(role) ? `It hides at rest and opens into a seam once the arm raises. ` : `It hides while the head faces front and opens into a seam on turn. `) + `Regenerate this part with the whole subject inside the frame.`
@@ -1326,6 +2181,8 @@ async function measureDir(absDir, noseSpeck) {
1326
2181
  }
1327
2182
  warnings.push(...await armWarnings(absDir, layers));
1328
2183
  warnings.push(...await forearmPoseWarnings(absDir, layers));
2184
+ const lip = await lipWarnings(absDir, layers);
2185
+ warnings.push(...lip.warnings);
1329
2186
  for (const side of ["L", "R"]) {
1330
2187
  const eye = layers[`eye_${side}`];
1331
2188
  const iris = layers[`iris_${side}`];
@@ -1354,8 +2211,8 @@ async function measureDir(absDir, noseSpeck) {
1354
2211
  }
1355
2212
  if (lash) {
1356
2213
  const { opaque, off } = await lashOffSclera(
1357
- path5.join(absDir, `eye_${side}.png`),
1358
- path5.join(absDir, `lash_${side}.png`)
2214
+ path6.join(absDir, `eye_${side}.png`),
2215
+ path6.join(absDir, `lash_${side}.png`)
1359
2216
  );
1360
2217
  const dTop = lash.marginTop - eye.marginTop;
1361
2218
  const faults = [
@@ -1381,7 +2238,7 @@ async function measureDir(absDir, noseSpeck) {
1381
2238
  if (noseSpeck !== void 0) {
1382
2239
  warnings.push(noseSpeckWarning(noseSpeck, "compose"));
1383
2240
  } else if (layers.nose !== void 0) {
1384
- const nose = await decodePng(path5.join(absDir, "nose.png"));
2241
+ const nose = await decodePng(path6.join(absDir, "nose.png"));
1385
2242
  const core = denseCoreOf(nose.rgba, nose.width, nose.height);
1386
2243
  if (core !== null) {
1387
2244
  const crop = detectAlphaBbox(nose.rgba, nose.width, nose.height);
@@ -1399,7 +2256,12 @@ async function measureDir(absDir, noseSpeck) {
1399
2256
  ]) {
1400
2257
  if (layers[role] === void 0) warnings.push(`${role}: missing \u2014 ${why}.`);
1401
2258
  }
1402
- return { layers, empty, warnings };
2259
+ return {
2260
+ layers,
2261
+ empty,
2262
+ warnings,
2263
+ ...lip.lips === void 0 ? {} : { lips: lip.lips }
2264
+ };
1403
2265
  }
1404
2266
  async function measureLayers(input) {
1405
2267
  try {
@@ -1433,6 +2295,13 @@ function formatMeasureReport(result) {
1433
2295
  `${role.padEnd(13)} ${`${m.w}x${m.h}`.padEnd(11)} ${`${m.bboxCx.toFixed(0)},${m.bboxCy.toFixed(0)}`.padEnd(14)} ${`${m.massCx.toFixed(0)},${m.massCy.toFixed(0)}`.padEnd(13)} ${m.marginTop}/${m.marginBottom}/${m.marginLeft}/${m.marginRight}`
1434
2296
  );
1435
2297
  }
2298
+ if (result.lips !== void 0) {
2299
+ const { opening, deadZone } = result.lips;
2300
+ lines.push(
2301
+ "",
2302
+ `lips: opening ${opening.width} px wide, ${opening.height} px tall at its centre under a ${opening.line} px line \u2014 no slit below MouthOpen ${deadZone.toFixed(2)}`
2303
+ );
2304
+ }
1436
2305
  lines.push("", "# checks", "");
1437
2306
  if (result.warnings.length === 0) {
1438
2307
  lines.push("all geometry checks passed");
@@ -1444,23 +2313,27 @@ function formatMeasureReport(result) {
1444
2313
 
1445
2314
  // src/compose.ts
1446
2315
  import fs3 from "fs";
1447
- import path6 from "path";
1448
- import sharp3 from "sharp";
1449
- import { ALPHA_OPAQUE as ALPHA_OPAQUE2, detectAlphaBbox as scanAlphaBbox2 } from "@ikijs/editor";
2316
+ import path7 from "path";
2317
+ import sharp4 from "sharp";
2318
+ import {
2319
+ ALPHA_OPAQUE as ALPHA_OPAQUE5,
2320
+ isLipInsideRole as isLipInsideRole2,
2321
+ detectAlphaBbox as scanAlphaBbox2
2322
+ } from "@ikijs/editor";
1450
2323
 
1451
2324
  // src/compose-arms.ts
1452
- import sharp2 from "sharp";
2325
+ import sharp3 from "sharp";
1453
2326
  import {
1454
- LayerGeometryError as LayerGeometryError4,
2327
+ LayerGeometryError as LayerGeometryError5,
1455
2328
  armGeometry as armGeometry3,
1456
- createLayerSetMeasurer as createLayerSetMeasurer4,
2329
+ createLayerSetMeasurer as createLayerSetMeasurer6,
1457
2330
  forearmPoseGeometry as forearmPoseGeometry2
1458
2331
  } from "@ikijs/editor";
1459
2332
  var ARM_WIDTH = 0.4;
1460
2333
  var SHOULDER_DROP = 0.12;
1461
2334
  async function armPlacement(role, cfg, part, body) {
1462
- const { data } = await sharp2(part.buf).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1463
- const layer = createLayerSetMeasurer4({ width: part.w, height: part.h }).add({
2335
+ const { data } = await sharp3(part.buf).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2336
+ const layer = createLayerSetMeasurer6({ width: part.w, height: part.h }).add({
1464
2337
  role,
1465
2338
  fileName: "arm.png",
1466
2339
  rgba: data
@@ -1474,7 +2347,7 @@ async function armPlacement(role, cfg, part, body) {
1474
2347
  try {
1475
2348
  g = armGeometry3(layer, role === "arm_R" ? Infinity : -Infinity);
1476
2349
  } catch (err) {
1477
- if (err instanceof LayerGeometryError4) {
2350
+ if (err instanceof LayerGeometryError5) {
1478
2351
  throw new AutoRigInputError(`layout.${role}: ${err.message}`);
1479
2352
  }
1480
2353
  throw err;
@@ -1500,8 +2373,8 @@ async function armPlacement(role, cfg, part, body) {
1500
2373
  };
1501
2374
  }
1502
2375
  async function poseGeometryOf(role, png, size, when) {
1503
- const { data } = await sharp2(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1504
- const layer = createLayerSetMeasurer4({
2376
+ const { data } = await sharp3(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2377
+ const layer = createLayerSetMeasurer6({
1505
2378
  width: size.w,
1506
2379
  height: size.h
1507
2380
  }).add({ role, fileName: "forearm_pose.png", rgba: data });
@@ -1540,8 +2413,6 @@ var IRIS_W = 50;
1540
2413
  var EYEWHITE_SRC = "eyewhite.png";
1541
2414
  var EYE_LASH_LUMA = 120;
1542
2415
  var LASH_KEEP_FRACTION = 0.5;
1543
- var TRIM_THRESHOLD = 12;
1544
- var STRAY_SPECK_FRACTION = 0.01;
1545
2416
  var NOSE_TIP_AT = 0.66;
1546
2417
  var DEFAULT_LAYOUT = {
1547
2418
  // Back hair and body sit behind the face. Both are OPTIONAL: a parts dir
@@ -1592,6 +2463,19 @@ var DEFAULT_LAYOUT = {
1592
2463
  w: 76,
1593
2464
  optional: true
1594
2465
  },
2466
+ // The lip set's ONE frame, mouth_open's place: the keyed mouth is split into
2467
+ // mouth_inner / lip_lower / lip_upper, the interior's light paint into
2468
+ // mouth_tongue / mouth_teeth, and all of them land here, so a retune moves
2469
+ // them together. The other four have no key of their own (LIP_FRAME).
2470
+ // OPTIONAL and opt-in: with mouth_keyed.png + mouth_interior.png it stands
2471
+ // in for mouth and mouth_open.
2472
+ mouth_inner: {
2473
+ src: KEYED_SRC,
2474
+ cx: 550,
2475
+ cy: 596,
2476
+ w: 76,
2477
+ optional: true
2478
+ },
1595
2479
  // eye_* (sclera) and lash_* share the eyewhite's cropped frame via noTrim (so
1596
2480
  // they are NOT re-bboxed independently): the upper lash stays anchored ABOVE
1597
2481
  // the sclera center, so on blink it folds DOWN over the eye like the sample
@@ -1638,6 +2522,11 @@ var ORDER = [
1638
2522
  "nose",
1639
2523
  "mouth",
1640
2524
  "mouth_open",
2525
+ "mouth_inner",
2526
+ "mouth_tongue",
2527
+ "mouth_teeth",
2528
+ "lip_lower",
2529
+ "lip_upper",
1641
2530
  "eye_L",
1642
2531
  "eye_R",
1643
2532
  "iris_L",
@@ -1656,13 +2545,15 @@ var PART_FILES = [
1656
2545
  ...new Set(
1657
2546
  Object.values(DEFAULT_LAYOUT).map((cfg) => cfg.src).filter((src) => !src.startsWith("eyewhite_"))
1658
2547
  ),
1659
- EYEWHITE_SRC
2548
+ EYEWHITE_SRC,
2549
+ INTERIOR_SRC
1660
2550
  ];
1661
2551
  var FACE_FEATURES = [
1662
2552
  "blush_L",
1663
2553
  "blush_R",
1664
2554
  "mouth",
1665
2555
  "mouth_open",
2556
+ "mouth_inner",
1666
2557
  "eye_L",
1667
2558
  "eye_R",
1668
2559
  "iris_L",
@@ -1766,14 +2657,14 @@ function keyWhiteToAlpha(rgba) {
1766
2657
  return keyed;
1767
2658
  }
1768
2659
  async function coreAndBoundsOf(png) {
1769
- const { data, info } = await sharp3(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2660
+ const { data, info } = await sharp4(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1770
2661
  return {
1771
2662
  core: denseCoreOf(data, info.width, info.height),
1772
2663
  bounds: { x: 0, y: 0, w: info.width, h: info.height }
1773
2664
  };
1774
2665
  }
1775
2666
  async function hasCoverage(png) {
1776
- const { data, info } = await sharp3(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2667
+ const { data, info } = await sharp4(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1777
2668
  return scanAlphaBbox2(data, info.width, info.height) !== null;
1778
2669
  }
1779
2670
  async function noseSizingOf(png) {
@@ -1794,24 +2685,24 @@ async function noseSizingOf(png) {
1794
2685
  async function trimmedPart(role, cfg, partsDir, inMemory, flipSource) {
1795
2686
  let img;
1796
2687
  if (inMemory !== void 0) {
1797
- img = sharp3(inMemory);
2688
+ img = sharp4(inMemory);
1798
2689
  } else {
1799
- const srcPath = path6.join(partsDir, cfg.src);
2690
+ const srcPath = path7.join(partsDir, cfg.src);
1800
2691
  if (!fs3.existsSync(srcPath)) {
1801
2692
  if (cfg.optional) return null;
1802
2693
  throw new AutoRigInputError(
1803
- `missing part source for role "${role}": ${srcPath}`
2694
+ `missing part source for role "${role}": ${srcPath}` + (role === "mouth" ? " \u2014 draw mouth.png (with mouth_open.png), or the lip set's mouth_keyed.png + mouth_interior.png" : "")
1804
2695
  );
1805
2696
  }
1806
2697
  const png = await decodePng(srcPath);
1807
- img = sharp3(png.hasAlpha ? png.rgba : keyWhiteToAlpha(png.rgba), {
2698
+ img = sharp4(png.hasAlpha ? png.rgba : keyWhiteToAlpha(png.rgba), {
1808
2699
  raw: { width: png.width, height: png.height, channels: 4 }
1809
2700
  });
1810
2701
  }
1811
2702
  if (!cfg.noTrim) {
1812
2703
  const kept = await img.trim({ threshold: TRIM_THRESHOLD }).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1813
2704
  const { width: keptW, height: keptH } = kept.info;
1814
- img = sharp3(kept.data, {
2705
+ img = sharp4(kept.data, {
1815
2706
  raw: { width: keptW, height: keptH, channels: 4 }
1816
2707
  });
1817
2708
  const box = boxWithoutStraySpecks(kept.data, keptW, keptH);
@@ -1837,7 +2728,7 @@ async function sizedPart(role, cfg, trimmed, canvas) {
1837
2728
  `layout.${role}.${field}: resized part ${width}x${height} exceeds the ${canvasName(canvas)} canvas`
1838
2729
  );
1839
2730
  }
1840
- const resized = await sharp3(trimmed.data).resize(cfg.h === void 0 ? { width } : { width, height, fit: "fill" }).png().toBuffer({ resolveWithObject: true });
2731
+ const resized = await sharp4(trimmed.data).resize(cfg.h === void 0 ? { width } : { width, height, fit: "fill" }).png().toBuffer({ resolveWithObject: true });
1841
2732
  return {
1842
2733
  buf: resized.data,
1843
2734
  w: resized.info.width,
@@ -1862,7 +2753,7 @@ function placement(role, cfg, w, h, canvas) {
1862
2753
  assertOnCanvas(`layout.${role}.cx/cy`, w, h, left, top, canvas);
1863
2754
  return { left, top };
1864
2755
  }
1865
- function nosePlacement(layout, box, w, h, canvas) {
2756
+ function nosePlacement(layout, mouthKey, box, w, h, canvas) {
1866
2757
  const { cx, cy } = layout.nose;
1867
2758
  const left = Math.round(cx - (box.x + box.w / 2));
1868
2759
  let top;
@@ -1871,12 +2762,12 @@ function nosePlacement(layout, box, w, h, canvas) {
1871
2762
  } else {
1872
2763
  const eyeRow = (layout.eye_L.cy + layout.eye_R.cy) / 2;
1873
2764
  const tipRow = Math.round(
1874
- eyeRow + NOSE_TIP_AT * (layout.mouth.cy - eyeRow)
2765
+ eyeRow + NOSE_TIP_AT * (layout[mouthKey].cy - eyeRow)
1875
2766
  );
1876
2767
  top = tipRow - (box.y + box.h - 1);
1877
2768
  }
1878
2769
  assertOnCanvas(
1879
- cy !== void 0 ? "layout.nose.cx/cy" : "layout.nose.cx/cy (cy unset: its tip row comes from layout.eye_L/eye_R/mouth.cy)",
2770
+ cy !== void 0 ? "layout.nose.cx/cy" : `layout.nose.cx/cy (cy unset: its tip row comes from layout.eye_L/eye_R/${mouthKey}.cy)`,
1880
2771
  w,
1881
2772
  h,
1882
2773
  left,
@@ -1886,7 +2777,7 @@ function nosePlacement(layout, box, w, h, canvas) {
1886
2777
  return { left, top };
1887
2778
  }
1888
2779
  function blankCanvas(canvas) {
1889
- return sharp3({
2780
+ return sharp4({
1890
2781
  create: {
1891
2782
  width: canvas.width,
1892
2783
  height: canvas.height,
@@ -1895,74 +2786,13 @@ function blankCanvas(canvas) {
1895
2786
  }
1896
2787
  });
1897
2788
  }
1898
- function luma(rgba, i) {
1899
- return 0.299 * rgba[i] + 0.587 * rgba[i + 1] + 0.114 * rgba[i + 2];
1900
- }
1901
- function boxWithoutStraySpecks(rgba, W, H) {
1902
- const n = W * H;
1903
- let kept = 0;
1904
- for (let p = 0; p < n; p++) if (rgba[p * 4 + 3] > TRIM_THRESHOLD) kept++;
1905
- const visited = new Uint8Array(n);
1906
- let stack = new Int32Array(1024);
1907
- const drawing = [W, H, -1, -1];
1908
- const strays = [W, H, -1, -1];
1909
- let anyOpaque = false;
1910
- for (let start = 0; start < n; start++) {
1911
- if (visited[start] || rgba[start * 4 + 3] <= TRIM_THRESHOLD) continue;
1912
- let setLeft = W;
1913
- let setTop = H;
1914
- let setRight = -1;
1915
- let setBottom = -1;
1916
- let size = 0;
1917
- let opaque = false;
1918
- let depth = 0;
1919
- visited[start] = 1;
1920
- stack[depth++] = start;
1921
- while (depth > 0) {
1922
- const p = stack[--depth];
1923
- size++;
1924
- if (rgba[p * 4 + 3] >= ALPHA_OPAQUE2) opaque = true;
1925
- const px2 = p % W;
1926
- const py = (p - px2) / W;
1927
- setLeft = Math.min(setLeft, px2);
1928
- setTop = Math.min(setTop, py);
1929
- setRight = Math.max(setRight, px2);
1930
- setBottom = Math.max(setBottom, py);
1931
- for (let y = Math.max(0, py - 1); y <= Math.min(H - 1, py + 1); y++) {
1932
- for (let x = Math.max(0, px2 - 1); x <= Math.min(W - 1, px2 + 1); x++) {
1933
- const q = y * W + x;
1934
- if (!visited[q] && rgba[q * 4 + 3] > TRIM_THRESHOLD) {
1935
- visited[q] = 1;
1936
- if (depth === stack.length) {
1937
- const grown = new Int32Array(Math.min(n, stack.length * 2));
1938
- grown.set(stack);
1939
- stack = grown;
1940
- }
1941
- stack[depth++] = q;
1942
- }
1943
- }
1944
- }
1945
- }
1946
- anyOpaque ||= opaque;
1947
- const into = !opaque && size < kept * STRAY_SPECK_FRACTION ? strays : drawing;
1948
- into[0] = Math.min(into[0], setLeft);
1949
- into[1] = Math.min(into[1], setTop);
1950
- into[2] = Math.max(into[2], setRight);
1951
- into[3] = Math.max(into[3], setBottom);
1952
- }
1953
- if (!anyOpaque || strays[2] < 0) return null;
1954
- const [left, top, right, bottom] = drawing;
1955
- if (strays[0] >= left && strays[1] >= top && strays[2] <= right && strays[3] <= bottom)
1956
- return null;
1957
- return { left, top, width: right - left + 1, height: bottom - top + 1 };
1958
- }
1959
2789
  function detachedAboveWhite(rgba, W, H) {
1960
2790
  const n = W * H;
1961
2791
  const ink = new Uint8Array(n);
1962
2792
  for (let p = 0; p < n; p++) {
1963
2793
  const alpha = rgba[p * 4 + 3];
1964
2794
  if (alpha > 0 && luma(rgba, p * 4) >= EYE_LASH_LUMA)
1965
- ink[p] = alpha >= ALPHA_OPAQUE2 ? 2 : 1;
2795
+ ink[p] = alpha >= ALPHA_OPAQUE5 ? 2 : 1;
1966
2796
  }
1967
2797
  const label = new Int32Array(n).fill(-1);
1968
2798
  const stack = new Int32Array(n);
@@ -2042,7 +2872,7 @@ function detachedAboveWhite(rgba, W, H) {
2042
2872
  return detached;
2043
2873
  }
2044
2874
  async function prepEyeSplit(partsDir) {
2045
- const srcPath = path6.join(partsDir, EYEWHITE_SRC);
2875
+ const srcPath = path7.join(partsDir, EYEWHITE_SRC);
2046
2876
  if (!fs3.existsSync(srcPath)) {
2047
2877
  throw new AutoRigInputError(`missing eyewhite source: ${srcPath}`);
2048
2878
  }
@@ -2094,6 +2924,50 @@ async function prepEyeSplit(partsDir) {
2094
2924
  lashLower: lowerInk ? await cropToBuffer(lashLower, W, H, region) : null
2095
2925
  };
2096
2926
  }
2927
+ function hasTransparency(rgba) {
2928
+ for (let p = 3; p < rgba.length; p += 4) if (rgba[p] < 255) return true;
2929
+ return false;
2930
+ }
2931
+ async function prepLipSources(partsDir, mirrored) {
2932
+ const has = (name) => fs3.existsSync(path7.join(partsDir, name));
2933
+ const keyed = has(KEYED_SRC);
2934
+ const interior = has(INTERIOR_SRC);
2935
+ if (keyed && !interior) {
2936
+ throw new AutoRigInputError(
2937
+ `${KEYED_SRC} needs ${INTERIOR_SRC}: the composer fits the drawn interior into the keyed opening \u2014 draw it (billed)`
2938
+ );
2939
+ }
2940
+ if (interior && !keyed) {
2941
+ throw new AutoRigInputError(
2942
+ `${INTERIOR_SRC} needs ${KEYED_SRC}: the composer cuts the lip set from the keyed open mouth and fits the interior into its opening \u2014 draw it (billed)`
2943
+ );
2944
+ }
2945
+ if (!keyed) return void 0;
2946
+ const legacy = ["mouth.png", "mouth_open.png"].filter(has);
2947
+ if (legacy.length > 0) {
2948
+ throw new AutoRigInputError(
2949
+ `${KEYED_SRC}/${INTERIOR_SRC} cannot be composed beside mouth.png/mouth_open.png (the lip set replaces the mouth drawings, and auto_rig_from_layers refuses the mix) \u2014 remove ${legacy.join(" and ")}`
2950
+ );
2951
+ }
2952
+ const k = await decodePng(path7.join(partsDir, KEYED_SRC));
2953
+ const keyedRgba = keyGreen(
2954
+ hasTransparency(k.rgba) ? k.rgba : keyWhiteToAlpha(k.rgba),
2955
+ k.width,
2956
+ k.height
2957
+ );
2958
+ const i = await decodePng(path7.join(partsDir, INTERIOR_SRC));
2959
+ const prepared = await prepInterior(
2960
+ hasTransparency(i.rgba) ? i.rgba : keyBorderWhite(i.rgba, i.width, i.height),
2961
+ i.width,
2962
+ i.height
2963
+ );
2964
+ return {
2965
+ keyedPng: await sharp4(keyedRgba, {
2966
+ raw: { width: k.width, height: k.height, channels: 4 }
2967
+ }).png().toBuffer(),
2968
+ interior: mirrored.has(INTERIOR_SRC) ? { ...prepared, png: await sharp4(prepared.png).flop().png().toBuffer() } : prepared
2969
+ };
2970
+ }
2097
2971
  async function composeLayersFromParts(input) {
2098
2972
  try {
2099
2973
  const outDir = resolveOutputDir(input.outDir);
@@ -2117,10 +2991,58 @@ async function composeLayersFromParts(input) {
2117
2991
  if (split.lashLower !== null) {
2118
2992
  splitSources.set(LOWER_LASH_SRC, split.lashLower);
2119
2993
  }
2994
+ const lips = await prepLipSources(partsDir, mirrored);
2995
+ let lipSplit;
2120
2996
  const placed = [];
2121
2997
  const skipped = [];
2122
2998
  let noseSpeck;
2123
2999
  for (const role of ORDER) {
3000
+ if (lips !== void 0 && (role === "mouth" || role === "mouth_open")) {
3001
+ continue;
3002
+ }
3003
+ if (role === "mouth_inner") {
3004
+ if (lips === void 0) continue;
3005
+ const cfg2 = layout.mouth_inner;
3006
+ const part2 = await partBuffer(
3007
+ role,
3008
+ cfg2,
3009
+ partsDir,
3010
+ lips.keyedPng,
3011
+ mirrored.has(KEYED_SRC),
3012
+ canvas
3013
+ );
3014
+ const split2 = await splitLipSet(
3015
+ part2.buf,
3016
+ part2.w,
3017
+ part2.h,
3018
+ lips.interior
3019
+ );
3020
+ const { left: left2, top: top2 } = placement(role, cfg2, part2.w, part2.h, canvas);
3021
+ lipSplit = { split: split2, w: part2.w, h: part2.h, left: left2, top: top2 };
3022
+ placed.push({
3023
+ role,
3024
+ part: { buf: split2.inner, w: part2.w, h: part2.h },
3025
+ left: left2,
3026
+ top: top2
3027
+ });
3028
+ continue;
3029
+ }
3030
+ if (role === "mouth_tongue" || role === "mouth_teeth" || role === "lip_lower" || role === "lip_upper") {
3031
+ if (lipSplit === void 0) continue;
3032
+ const { split: split2, w, h, left: left2, top: top2 } = lipSplit;
3033
+ const buf = {
3034
+ mouth_tongue: split2.tongue,
3035
+ mouth_teeth: split2.teeth,
3036
+ lip_lower: split2.lower,
3037
+ lip_upper: split2.upper
3038
+ }[role];
3039
+ if (isLipInsideRole2(role) && !await hasCoverage(buf)) {
3040
+ skipped.push(role);
3041
+ continue;
3042
+ }
3043
+ placed.push({ role, part: { buf, w, h }, left: left2, top: top2 });
3044
+ continue;
3045
+ }
2124
3046
  const lower = role === "lash_lower_L" || role === "lash_lower_R";
2125
3047
  const key = lower ? LOWER_LASH[role] : role;
2126
3048
  if (lower && split.lashLower === null) {
@@ -2129,7 +3051,7 @@ async function composeLayersFromParts(input) {
2129
3051
  }
2130
3052
  if (key === "arm_L" || key === "arm_R") {
2131
3053
  const arm = layout[key];
2132
- if (!fs3.existsSync(path6.join(partsDir, arm.src))) continue;
3054
+ if (!fs3.existsSync(path7.join(partsDir, arm.src))) continue;
2133
3055
  const body = placed.find((p) => p.role === "body");
2134
3056
  if (body === void 0) {
2135
3057
  throw new AutoRigInputError(
@@ -2172,7 +3094,7 @@ async function composeLayersFromParts(input) {
2172
3094
  }
2173
3095
  if (key === "forearm_pose_L" || key === "forearm_pose_R") {
2174
3096
  const pose = layout[key];
2175
- if (!fs3.existsSync(path6.join(partsDir, pose.src))) continue;
3097
+ if (!fs3.existsSync(path7.join(partsDir, pose.src))) continue;
2176
3098
  const armRole = key === "forearm_pose_L" ? "arm_L" : "arm_R";
2177
3099
  const arm = placed.find((p) => p.role === armRole);
2178
3100
  if (arm?.elbow === void 0 || arm.elbowRun === void 0) {
@@ -2243,7 +3165,14 @@ async function composeLayersFromParts(input) {
2243
3165
  noseSpeck = part.nose?.speck;
2244
3166
  const { core, bounds } = await coreAndBoundsOf(part.buf);
2245
3167
  const box = part.nose?.whole ? bounds : core ?? bounds;
2246
- ({ left, top } = nosePlacement(layout, box, part.w, part.h, canvas));
3168
+ ({ left, top } = nosePlacement(
3169
+ layout,
3170
+ lips === void 0 ? "mouth" : "mouth_inner",
3171
+ box,
3172
+ part.w,
3173
+ part.h,
3174
+ canvas
3175
+ ));
2247
3176
  } else {
2248
3177
  ({ left, top } = placement(key, layout[key], part.w, part.h, canvas));
2249
3178
  }
@@ -2258,20 +3187,40 @@ async function composeLayersFromParts(input) {
2258
3187
  }
2259
3188
  placed.push({ role, part, left, top });
2260
3189
  }
3190
+ const built = /* @__PURE__ */ new Map();
3191
+ for (const { role, part, left, top } of placed) {
3192
+ built.set(
3193
+ role,
3194
+ await blankCanvas(canvas).composite([{ input: part.buf, left, top }]).png().toBuffer()
3195
+ );
3196
+ }
3197
+ const closed = lipSplit === void 0 ? void 0 : await closedLips(
3198
+ lipSplit.split.upper,
3199
+ lipSplit.split.lower,
3200
+ await restShiftOf(
3201
+ {
3202
+ mouth_inner: built.get("mouth_inner"),
3203
+ lip_lower: built.get("lip_lower"),
3204
+ lip_upper: built.get("lip_upper")
3205
+ },
3206
+ canvas.width,
3207
+ canvas.height
3208
+ ),
3209
+ lipSplit.left,
3210
+ lipSplit.top
3211
+ );
2261
3212
  for (const role of ORDER) {
2262
3213
  if (placed.some((p) => p.role === role)) continue;
2263
- fs3.rmSync(path6.join(outDir, `${role}.png`), { force: true });
3214
+ fs3.rmSync(path7.join(outDir, `${role}.png`), { force: true });
2264
3215
  }
2265
3216
  const posed = (role) => role === "forearm_pose_L" || role === "forearm_pose_R";
2266
3217
  if (!placed.some((p) => posed(p.role))) {
2267
- fs3.rmSync(path6.join(outDir, "preview-pose.png"), { force: true });
3218
+ fs3.rmSync(path7.join(outDir, "preview-pose.png"), { force: true });
2268
3219
  }
2269
3220
  const layers = [];
2270
- const preview = [];
2271
3221
  for (const { role, part, left, top } of placed) {
2272
- const layer = await blankCanvas(canvas).composite([{ input: part.buf, left, top }]).png().toBuffer();
2273
- const outPath = path6.join(outDir, `${role}.png`);
2274
- writeFileAtomic(outPath, layer);
3222
+ const outPath = path7.join(outDir, `${role}.png`);
3223
+ writeFileAtomic(outPath, built.get(role));
2275
3224
  layers.push({
2276
3225
  role,
2277
3226
  path: outPath,
@@ -2280,9 +3229,20 @@ async function composeLayersFromParts(input) {
2280
3229
  left,
2281
3230
  top
2282
3231
  });
2283
- if (!posed(role)) preview.push({ input: part.buf, left, top });
2284
3232
  }
2285
- const previewPng = await sharp3({
3233
+ const restInput = (role, buf) => {
3234
+ if (role === "mouth_inner" || isLipInsideRole2(role)) return null;
3235
+ if (closed === void 0) return buf;
3236
+ if (role === "lip_upper") return closed.upper;
3237
+ if (role === "lip_lower") return closed.lower;
3238
+ return buf;
3239
+ };
3240
+ const preview = [];
3241
+ for (const { role, part, left, top } of placed) {
3242
+ const input2 = restInput(role, part.buf);
3243
+ if (!posed(role) && input2 !== null) preview.push({ input: input2, left, top });
3244
+ }
3245
+ const previewPng = await sharp4({
2286
3246
  create: {
2287
3247
  width: canvas.width,
2288
3248
  height: canvas.height,
@@ -2290,7 +3250,7 @@ async function composeLayersFromParts(input) {
2290
3250
  background: { r: 245, g: 245, b: 248, alpha: 1 }
2291
3251
  }
2292
3252
  }).composite(preview).png().toBuffer();
2293
- const previewPath = path6.join(outDir, "preview.png");
3253
+ const previewPath = path7.join(outDir, "preview.png");
2294
3254
  writeFileAtomic(previewPath, previewPng);
2295
3255
  let previewPosePath;
2296
3256
  if (placed.some((p) => posed(p.role))) {
@@ -2300,17 +3260,18 @@ async function composeLayersFromParts(input) {
2300
3260
  (p) => p.role === (role === "arm_L" ? "forearm_pose_L" : "forearm_pose_R")
2301
3261
  );
2302
3262
  if (!armPosed) {
2303
- pose.push({ input: part.buf, left, top });
3263
+ const input2 = restInput(role, part.buf);
3264
+ if (input2 !== null) pose.push({ input: input2, left, top });
2304
3265
  continue;
2305
3266
  }
2306
3267
  const rows = Math.min(part.h, Math.max(1, Math.round(elbow.y - top)));
2307
3268
  pose.push({
2308
- input: await sharp3(part.buf).extract({ left: 0, top: 0, width: part.w, height: rows }).png().toBuffer(),
3269
+ input: await sharp4(part.buf).extract({ left: 0, top: 0, width: part.w, height: rows }).png().toBuffer(),
2309
3270
  left,
2310
3271
  top
2311
3272
  });
2312
3273
  }
2313
- const posePng = await sharp3({
3274
+ const posePng = await sharp4({
2314
3275
  create: {
2315
3276
  width: canvas.width,
2316
3277
  height: canvas.height,
@@ -2318,7 +3279,7 @@ async function composeLayersFromParts(input) {
2318
3279
  background: { r: 245, g: 245, b: 248, alpha: 1 }
2319
3280
  }
2320
3281
  }).composite(pose).png().toBuffer();
2321
- previewPosePath = path6.join(outDir, "preview-pose.png");
3282
+ previewPosePath = path7.join(outDir, "preview-pose.png");
2322
3283
  writeFileAtomic(previewPosePath, posePng);
2323
3284
  }
2324
3285
  return {
@@ -2341,7 +3302,7 @@ async function composeLayersFromParts(input) {
2341
3302
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2342
3303
  import { z } from "zod";
2343
3304
  function createIkiMcpServer() {
2344
- const server = new McpServer({ name: "iki", version: "0.21.0" });
3305
+ const server = new McpServer({ name: "iki", version: "0.23.0" });
2345
3306
  server.registerTool(
2346
3307
  "validate_iki",
2347
3308
  {
@@ -2406,7 +3367,7 @@ function createIkiMcpServer() {
2406
3367
  server.registerTool(
2407
3368
  "auto_rig_from_layers",
2408
3369
  {
2409
- description: "Auto-rigs role-named PNG layers (face, eye_L/eye_R and either mouth or the lip set (mouth_inner + lip_lower + lip_upper, a mouth that folds open instead of crossfading) required; iris_L/R, brow_L/R, hair_front, body, arm_L/arm_R, forearm_pose_L/forearm_pose_R, etc. optional; an arm needs the body, a pose forearm needs its arm, and a partial lip set or one mixed with mouth/mouth_open is refused) into a renderable .iki written to disk. Pass full-canvas PNG file paths; returns the output path + summary (the model is NOT inlined). Filenames map to roles unless `fileName` is given.",
3370
+ description: "Auto-rigs role-named PNG layers (face, eye_L/eye_R and either mouth or the lip set (mouth_inner + lip_lower + lip_upper, a mouth that folds open instead of crossfading) required; iris_L/R, brow_L/R, hair_front, body, arm_L/arm_R, forearm_pose_L/forearm_pose_R, mouth_tongue/mouth_teeth (only with the lip set: drawn under its lips and clipped to mouth_inner), etc. optional; an arm needs the body, a pose forearm needs its arm, and a partial lip set, one mixed with mouth/mouth_open, or mouth_tongue/mouth_teeth without it is refused) into a renderable .iki written to disk. Pass full-canvas PNG file paths; returns the output path + summary (the model is NOT inlined). Filenames map to roles unless `fileName` is given.",
2410
3371
  inputSchema: {
2411
3372
  layers: z.array(
2412
3373
  z.object({
@@ -2461,7 +3422,7 @@ function createIkiMcpServer() {
2461
3422
  server.registerTool(
2462
3423
  "compose_layers_from_parts",
2463
3424
  {
2464
- description: "Composes AI-generated part PNGs into canvas-aligned, role-named PNG layers on disk, ready for auto_rig_from_layers (the eyewhite split, alpha-trim/white-key, and placement pipeline the character-generation skill needs), with the same geometry report measure_layers returns standalone included inline. face, mouth, eyewhite, iris, brow, hair_front are required; hair_back, body, mouth_open, blush (one blush.png makes the blush_L/blush_R pair) and nose are optional \u2014 without a nose layer the head still turns on the rig's default profile, but it has no nose to lead the turn, and `auto_rig_from_layers` fits no turn to the art (`turnTargets` is inert, no `turn` report). One arm.png \u2014 the arm on the screen LEFT, drawn hanging with its shoulder at the top \u2014 makes both arms of a full body: arm_R takes it as drawn and arm_L mirrored. The arms are opt-in: without arm.png the compose is a bust's and `skipped` never lists them. arm.png needs body.png, and each arm is hung on the body's shoulder by default (see `layout`). One forearm_pose.png \u2014 the arm's forearm raised, on the screen LEFT, standing up from its elbow with the hand at the top \u2014 makes both pose forearms (forearm_pose_R as drawn, forearm_pose_L mirrored): each is scaled so its elbow end is as wide as its arm's elbow run and pinned on that arm's elbow (see `layout`), and it needs arm.png. With one, preview-pose.png shows the switch at 1 as the rig draws it (the hanging forearms hidden below the elbow, the pose forearms over everything) while preview.png stays the rest pose; without one it is removed. The inline report carries the full-body checks too: a body whose feet a tall canvas's bottom cuts off, an arm without a body, an arm whose shoulder cap does not reach under the torso's edge, and a pose forearm without its arm or off its arm's elbow in pivot, width or length. A nose whose dense core is a speck \u2014 under a quarter of its trimmed part's width or height, such as a lone nostril mark or highlight \u2014 is sized and placed whole, and the inline report warns of it. A light mark drawn detached above the eye white, such as a double-eyelid crease, is dropped from the sclera (the iris's clip); dark strokes there stay lash ink. The eyewhite's dark lower lid \u2014 its line and lashes \u2014 becomes lash_lower_L/lash_lower_R, drawn over the iris; a white with none writes none and lists them in `skipped`.",
3425
+ description: "Composes AI-generated part PNGs into canvas-aligned, role-named PNG layers on disk, ready for auto_rig_from_layers (the eyewhite split, alpha-trim/white-key, and placement pipeline the character-generation skill needs), with the same geometry report measure_layers returns standalone included inline. face, eyewhite, iris, brow, hair_front are required, with mouth.png \u2014 or the lip set's mouth_keyed.png (the open mouth, its inside painted flat #00FF00) + mouth_interior.png (the cavity, teeth and tongue alone), which the composer keys and splits into mouth_inner / lip_lower / lip_upper on one frame so auto_rig_from_layers folds the mouth open like the eyelid, the interior's light paint (luma 100 and over) written as mouth_tongue and mouth_teeth on the same frame, riding the opening's bottom and the upper line and clipped to the cavity (listed in `skipped` when the interior has none); the two routes cannot be mixed, one keyed file without the other is refused, and a key that fails (no green, green outside the opening, an outline not closed round it, more than one opening, no skin under the opening, an interior that is only lips, or one drawn opaque on a non-white or noisy ground) is refused naming the regeneration; with the lip set neither mouth nor mouth_open is written and preview.png shows the mouth closed, as the rig draws the rest pose. hair_back, body, mouth_open (legacy route only), blush (one blush.png makes the blush_L/blush_R pair) and nose are optional \u2014 without a nose layer the head still turns on the rig's default profile, but it has no nose to lead the turn, and `auto_rig_from_layers` fits no turn to the art (`turnTargets` is inert, no `turn` report). One arm.png \u2014 the arm on the screen LEFT, drawn hanging with its shoulder at the top \u2014 makes both arms of a full body: arm_R takes it as drawn and arm_L mirrored. The arms are opt-in: without arm.png the compose is a bust's and `skipped` never lists them. arm.png needs body.png, and each arm is hung on the body's shoulder by default (see `layout`). One forearm_pose.png \u2014 the arm's forearm raised, on the screen LEFT, standing up from its elbow with the hand at the top \u2014 makes both pose forearms (forearm_pose_R as drawn, forearm_pose_L mirrored): each is scaled so its elbow end is as wide as its arm's elbow run and pinned on that arm's elbow (see `layout`), and it needs arm.png. With one, preview-pose.png shows the switch at 1 as the rig draws it (the hanging forearms hidden below the elbow, the pose forearms over everything) while preview.png stays the rest pose; without one it is removed. The inline report carries the full-body checks too: a body whose feet a tall canvas's bottom cuts off, an arm without a body, an arm whose shoulder cap does not reach under the torso's edge, and a pose forearm without its arm or off its arm's elbow in pivot, width or length. A nose whose dense core is a speck \u2014 under a quarter of its trimmed part's width or height, such as a lone nostril mark or highlight \u2014 is sized and placed whole, and the inline report warns of it. A light mark drawn detached above the eye white, such as a double-eyelid crease, is dropped from the sclera (the iris's clip); dark strokes there stay lash ink. The eyewhite's dark lower lid \u2014 its line and lashes \u2014 becomes lash_lower_L/lash_lower_R, drawn over the iris; a white with none writes none and lists them in `skipped`.",
2465
3426
  inputSchema: {
2466
3427
  partsDir: z.string().describe(
2467
3428
  "Directory of the source part PNGs (resolved against cwd)."
@@ -2478,7 +3439,7 @@ function createIkiMcpServer() {
2478
3439
  h: z.number()
2479
3440
  }).partial()
2480
3441
  ).optional().describe(
2481
- "Per-role override merged over the built-in defaults, keyed by role \u2014 hair_back, body, arm_L, arm_R, face, blush_L, blush_R, nose, mouth, mouth_open, eye_L, eye_R, iris_L, iris_R, lash_L, lash_R, brow_L, brow_R, hair_front, forearm_pose_L, forearm_pose_R \u2014 e.g. `{ eye_L: { cx: 660 } }`. `w` is an integer in 1..1100 (the canvas width) and `h` in 1..canvasHeight; omit `h` to keep the part's own aspect, set it to stretch. The defaults of the face's features \u2014 blush, nose, mouth, mouth_open, eyes, irises, lashes, brows \u2014 are proportions of the face: an override of face.cx, face.cy or face.w carries them with it (scaled by the width; face.h stretches the face alone), while a feature's own override names canvas px. The nose is sized and placed by its dense core (its pixels at alpha >= 128, the drawing inside a soft nose's feather), not its whole part: `w`/`h` size the core, `cx` centres it, and a set `cy` centres its rows. A nose whose core is a speck \u2014 under a quarter of the trimmed part's width or height, such as a lone nostril mark or highlight \u2014 is sized and placed whole instead, and the report warns of it. Its `cy` defaults to unset, which lands the core's bottom row (the tip) 0.66 of the way from the eye row down to the mouth's, so the nose follows a retuned eye or mouth row. eye_L/lash_L and eye_R/lash_R are cut from one eyewhite into one frame, so each pair must land on the same frame \u2014 a pair set to land apart is rejected. lash_lower_L/lash_lower_R are cut from it too and have no key: they land on their eye's frame. arm_L/arm_R have no cx/cy/w defaults: an unset `w` is 0.4 of the placed body's width, and an unset `cx` or `cy` hangs the arm's shoulder pivot \u2014 the one auto_rig_from_layers turns it about \u2014 on the body box's shoulder corner on that axis: its left edge for arm_R, its right edge for arm_L, 0.12 of its height under its top. A set one centres the arm as for every other role. forearm_pose_L/forearm_pose_R have no cx/cy/w defaults either: an unset `w` scales the forearm so its elbow end (the shoulder rule run from its bottom) is as wide as the placed arm's elbow run, and an unset `cx` or `cy` pins that elbow end's pivot on the arm's elbow \u2014 the one auto_rig_from_layers hangs it from."
3442
+ "Per-role override merged over the built-in defaults, keyed by role \u2014 hair_back, body, arm_L, arm_R, face, blush_L, blush_R, nose, mouth, mouth_open, mouth_inner, eye_L, eye_R, iris_L, iris_R, lash_L, lash_R, brow_L, brow_R, hair_front, forearm_pose_L, forearm_pose_R \u2014 e.g. `{ eye_L: { cx: 660 } }`. `w` is an integer in 1..1100 (the canvas width) and `h` in 1..canvasHeight; omit `h` to keep the part's own aspect, set it to stretch. The defaults of the face's features \u2014 blush, nose, mouth, mouth_open, mouth_inner, eyes, irises, lashes, brows \u2014 are proportions of the face: an override of face.cx, face.cy or face.w carries them with it (scaled by the width; face.h stretches the face alone), while a feature's own override names canvas px. The nose is sized and placed by its dense core (its pixels at alpha >= 128, the drawing inside a soft nose's feather), not its whole part: `w`/`h` size the core, `cx` centres it, and a set `cy` centres its rows. A nose whose core is a speck \u2014 under a quarter of the trimmed part's width or height, such as a lone nostril mark or highlight \u2014 is sized and placed whole instead, and the report warns of it. Its `cy` defaults to unset, which lands the core's bottom row (the tip) 0.66 of the way from the eye row down to the mouth's, so the nose follows a retuned eye or mouth row. eye_L/lash_L and eye_R/lash_R are cut from one eyewhite into one frame, so each pair must land on the same frame \u2014 a pair set to land apart is rejected. lash_lower_L/lash_lower_R are cut from it too and have no key: they land on their eye's frame. mouth_inner is the lip set's one frame (mouth_open's place by default; lip_lower, lip_upper, mouth_tongue and mouth_teeth have no key and land on it, so a retune moves them together), and with the lip set the nose's tip rule reads layout.mouth_inner.cy. arm_L/arm_R have no cx/cy/w defaults: an unset `w` is 0.4 of the placed body's width, and an unset `cx` or `cy` hangs the arm's shoulder pivot \u2014 the one auto_rig_from_layers turns it about \u2014 on the body box's shoulder corner on that axis: its left edge for arm_R, its right edge for arm_L, 0.12 of its height under its top. A set one centres the arm as for every other role. forearm_pose_L/forearm_pose_R have no cx/cy/w defaults either: an unset `w` scales the forearm so its elbow end (the shoulder rule run from its bottom) is as wide as the placed arm's elbow run, and an unset `cx` or `cy` pins that elbow end's pivot on the arm's elbow \u2014 the one auto_rig_from_layers hangs it from."
2482
3443
  ),
2483
3444
  mirrorParts: z.array(z.string()).optional().describe(
2484
3445
  "Part files to flip left-right as they are read, e.g. `[\"eyewhite.png\"]`. The composer reads eyewhite.png as the eye on the screen LEFT (lash wing at the image's left end, lash-free tear duct at its right), brow.png as the brow on the screen RIGHT (thick head at the image's left end, tail at its right), blush.png as the blush on the screen LEFT (outer end, toward the face's edge, at the image's left end, inner end at its right), arm.png as the arm on the screen LEFT (the character's right, hanging, its shoulder at the image's top), and forearm_pose.png as the raised forearm on the screen LEFT (standing up from its elbow, the hand at the image's top, the thumb toward the body at the image's right); a part drawn the other way round is fixed here for free. It flips the source, so every role cut from it flips together and an eye's sclera and lash stay in one frame."
@@ -2509,7 +3470,7 @@ function createIkiMcpServer() {
2509
3470
  server.registerTool(
2510
3471
  "measure_layers",
2511
3472
  {
2512
- description: "Reports read-only geometry checks over an already-composed layers directory \u2014 the same checks compose_layers_from_parts returns inline (iris ratio/offset, eye aspect, cropped/cut edges, a nose whose dense core is a speck of its crop, missing optional roles, a body whose feet a tall canvas's bottom cuts off, an arm without a body, an arm whose shoulder cap does not reach under the torso's edge on its shoulder pivot's row, a pose forearm without its arm or whose elbow end is off its arm's elbow in pivot, width or length). Every preview*.png is skipped. Use to re-check a layers dir without recomposing. Its nose check reads the composed file against its crop, which is what auto_rig_from_layers acts on. Compose's inline report does the same unless the composer found the source part's core a speck, which it reports instead \u2014 so a speck that resampling erased from the layer shows there and not here.",
3473
+ description: "Reports read-only geometry checks over an already-composed layers directory \u2014 the same checks compose_layers_from_parts returns inline (iris ratio/offset, eye aspect, cropped/cut edges, a nose whose dense core is a speck of its crop, missing optional roles, a body whose feet a tall canvas's bottom cuts off, an arm without a body, an arm whose shoulder cap does not reach under the torso's edge on its shoulder pivot's row, a pose forearm without its arm or whose elbow end is off its arm's elbow in pivot, width or length, and the lip set: a partial one or one beside mouth/mouth_open, the fold's contract per column of the opening, an opening too narrow or short, a line too thin, green left, an interior with holes, and of mouth_tongue/mouth_teeth: one with no lip set, one on another canvas, one whose box leaves mouth_inner's \u2014 with the opening's size and the MouthOpen below which no slit shows). Every preview*.png is skipped. Use to re-check a layers dir without recomposing. Its nose check reads the composed file against its crop, which is what auto_rig_from_layers acts on. Compose's inline report does the same unless the composer found the source part's core a speck, which it reports instead \u2014 so a speck that resampling erased from the layer shows there and not here.",
2513
3474
  inputSchema: {
2514
3475
  layersDir: z.string().describe(
2515
3476
  "Directory of role-named layer PNGs (resolved against cwd)."
@@ -2586,4 +3547,4 @@ export {
2586
3547
  composeLayersFromParts,
2587
3548
  createIkiMcpServer
2588
3549
  };
2589
- //# sourceMappingURL=chunk-EKGWFKU2.mjs.map
3550
+ //# sourceMappingURL=chunk-YQECLFI4.mjs.map