Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
CH45: raea clothes, garments for SOMA's body: make draws the mannequin's four views with an image model and measures them onto SOMA's template vertices (over garments already made, a procedure-made one drawn on the mannequin first); cover makes one by procedure with no picture; wear writes a dressed body folder; remeasure re-reads kept pictures. SOMA-X's body files are fetched once at a fixed commit by SHA-256; tools/clothes ships in a release. Measuring: hems evened, stand-off capped per part, shoulder tops and collar slopes covered, backdrop texels take the measured colour
shinyobjectz4110989ed46f
diff --git a/docs/character.feature b/docs/character.featureindex 4ddcdb1a..ab35f392 100644--- a/docs/character.feature+++ b/docs/character.feature@@ -484,6 +484,33 @@ Feature: The character SDK as one system: SOMA bodies, Kimodo motion, generated# yet a `raea` verb, and it makes no garment by hand or by procedure.Then a line of words becomes a garment file with its cost said+ @done+ Scenario: CH45b. `raea clothes`: garments from words, by procedure, and worn+ # 11-15. A shell verb (engine/cli/src/clothes.ts reads the words, wardrobe.ts does the work on the native raea;+ # the Blender scripts are tools/clothes, shipped with a release). The first use fetches SOMA-X's two body files+ # at a fixed commit, checked by SHA-256, into raea's models folder (soma/, with the Apache-2.0 licence), and makes+ # SOMA's body folder and the mannequin's four views there once (18 s on this Mac). `make NAME "words" [--over+ # A,B]` draws the four views at once (flux_2_pro, one picture a view) and measures them onto SOMA's template+ # vertices: assets/clothes/NAME.json, its pictures kept in assets/clothes/NAME/views as its source. Over a+ # garment made by procedure, or several at once, the mannequin is first drawn wearing them, and the layers beneath+ # are taken as one for the stand-off. `cover NAME --parts chest,torso,waist,upperArm:0.45 --colour #e8e4da` makes+ # one by procedure in the same file with no picture: the skin of the parts named (a limb as far along as its+ # share), with a one-ring hem allowance so garments on neighbouring parts overlap. `wear OUT_DIR A B C [--body+ # DIR]` writes a body folder (each garment's glb and picture, the body without the skin wholly under cloth, its+ # skeleton, joint stand-in and collar) and prints the composition's lines. `remeasure NAME` measures a garment+ # again from its kept pictures, for nothing. Run on an outfit: a t-shirt and shorts by procedure, a flannel+ # overshirt drawn over them for 20 cents in 35 seconds, all three worn on the headless body with the generated+ # head through the matched walk (sheet3d compositions/soma_wardrobe.tsx). Mended in the measuring on the way: each+ # garment's open edge is evened (it ran in a stair along the body's triangles; the body's own UV seams are left+ # where they are); a garment stands off each part no further than that part allows (a loose sleeve drawn hanging+ # below the arm had made a balloon of it); the top of a shoulder, and the slope by an open collar, is cloth when+ # there is cloth in front of it and behind it; a texel that the chosen view shows as backdrop or bare mannequin+ # takes the garment's measured colour (grey cuffs). Wrong still: the overshirt hangs to the hips in every+ # picture but wraps the hips when worn (a skin-offset garment can't hang free: CH44), the views disagree on+ # sleeve length (the back drew it to the elbow), and a sliver by the collar is still open. The verb makes one+ # garment a call; an outfit is several calls, innermost first.+ Then a garment is made by one command from words or by procedure, and an outfit is worn by one more+Scenario: CH45. From words to a wardrobeThen `raea` takes a description of an outfit, draws its layers and views, builds the garments, and writesthem beside the body, saying what each picture cost; the pictures are kept with the garment as its sourcediff --git a/engine/cli/conformance/clothes.test.ts b/engine/cli/conformance/clothes.test.tsnew file mode 100644index 00000000..0ca4e200--- /dev/null+++ b/engine/cli/conformance/clothes.test.ts@@ -0,0 +1,58 @@+// `raea clothes`: what the command sends the host for a garment made from words or garments put on a body (docs/+// character.feature CH45), and what it refuses before anything is drawn or paid for. The host (src/wardrobe.ts, which+// runs Blender and the image model) is faked: this is the command's side.+import { describe, expect, test } from "bun:test";+import { clothesVerb } from "../src/clothes.ts";++/** clothesVerb with a host that keeps each op it was asked and answers as the host does */+function run(args: string[], garments: { name: string; layer: number; vertices: number; over?: string }[] = []) {+ const ops: Record<string, unknown>[] = [];+ const ask = (op: string, b: Record<string, unknown>) => {+ expect(op).toBe("clothes");+ ops.push(b);+ return b.op === "list" ? { garments } : { said: `did ${b.op}\n` };+ };+ return { out: clothesVerb(ask, args), ops };+}++describe("raea clothes", () => {+ test("alone, it lists the project's garments, and says how to make one when there are none", () => {+ expect(run([]).out).toContain('raea clothes make NAME "what it is, as worn"');+ const { out } = run(["list"], [{ name: "tee-jeans", layer: 0, vertices: 11873 }, { name: "bomber", layer: 1, vertices: 6120, over: "tee-jeans" }]);+ expect(out).toBe("tee-jeans layer 0, 11873 of SOMA's vertices\nbomber layer 1, 6120 of SOMA's vertices, over tee-jeans\n");+ });++ test("make sends the name, the words, the layer under it and the most a picture may cost", () => {+ const { ops } = run(["make", "bomber", "an olive bomber jacket, zipped", "--over", "tee-jeans", "--max-cents", "8"]);+ expect(ops).toEqual([{ op: "make", name: "bomber", words: "an olive bomber jacket, zipped", over: "tee-jeans", cents: 8 }]);+ expect(run(["make", "tee", "a white tee"]).ops[0]).toMatchObject({ over: undefined, cents: 10 });+ });++ test("cover sends the parts, the colour and the stand-off in metres, for a garment with no picture", () => {+ const { ops } = run(["cover", "shorts", "--parts", "hips, thigh:0.5", "--colour", "1f2a44", "--stand", "8", "--over", "pants"]);+ expect(ops).toEqual([{ op: "cover", name: "shorts", parts: "hips,thigh:0.5", colour: "#1f2a44", stand: 0.008, over: "pants" }]);+ expect(run(["cover", "tee", "--parts", "chest,torso,waist,upperArm:0.4", "--colour", "#ffffff"]).ops[0]).toMatchObject({ stand: 0.006, over: undefined });+ });++ test("wear sends the folder, the garments innermost first and the body", () => {+ const { ops } = run(["wear", "assets/characters/dressed", "tee-jeans", "bomber", "--body", "assets/characters/soma-headless"]);+ expect(ops).toEqual([{ op: "wear", out: "assets/characters/dressed", garments: ["tee-jeans", "bomber"], body: "assets/characters/soma-headless" }]);+ });++ test("what doesn't fit is said before anything is drawn", () => {+ const refused = (args: string[], says: string) => expect(() => run(args)).toThrow(says);+ refused(["make", "tee"], 'raea clothes make NAME "WHAT IT IS, AS WORN"');+ refused(["make", "tee", "a white tee", "and more"], 'raea clothes make NAME "WHAT IT IS, AS WORN"');+ refused(["make", "../tee", "a white tee"], "a garment's name is letters, digits, - and _");+ refused(["make", "tee", "a white tee", "--over", "a b"], "--over a b: name garments already made");+ expect(run(["make", "jacket", "a denim jacket", "--over", "tee,shorts"]).ops[0]).toMatchObject({ over: "tee,shorts" });+ refused(["make", "tee", "a white tee", "--max-cents", "0"], "--max-cents takes the most one picture may cost");+ refused(["cover", "tee", "--parts", "chest"], "raea clothes cover NAME --parts");+ refused(["cover", "tee", "--parts", "belly", "--colour", "#ffffff"], "--parts: no part belly");+ refused(["cover", "tee", "--parts", "shin:1.5", "--colour", "#ffffff"], "a share is how far along the limb");+ refused(["cover", "tee", "--parts", "chest", "--colour", "white"], "--colour white: a colour is #RRGGBB");+ refused(["cover", "tee", "--parts", "chest", "--colour", "#ffffff", "--stand", "200"], "--stand takes how far the cloth stands off");+ refused(["wear", "out"], "raea clothes wear OUT_DIR GARMENT...");+ refused(["dress"], "raea clothes make NAME");+ });+});diff --git a/engine/cli/src/cli.rs b/engine/cli/src/cli.rsindex f0c14ae0..9af1e515 100644--- a/engine/cli/src/cli.rs+++ b/engine/cli/src/cli.rs@@ -134,6 +134,8 @@ pub fn run(args: &[String]) -> R<String> {// `raea library` (engine/cli/src/library.ts) and `raea show` (show.ts: in the raea app, not Preview, Shane 11-09), under render's usagelet usage = format!("{usage}\n raea library [new NAME [--cloud] | add LIBRARY PATH | files LIBRARY | tag SHA TAGS | status | scan ...] | raea library search \"WORDS\" [--library LIBRARY] [--kind KIND] [--limit N] [--sound] (the person's libraries in the raea app: folders and drives indexed on this machine, searched by meaning; a folder an agent adds waits for the person's yes)");let usage = format!("{usage}\n raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), or questions, all of them one item, each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)");+ // clothes for SOMA's body from words (docs/character.feature CH45): engine/cli/src/clothes.ts and wardrobe.ts+ let usage = format!("{usage}\n raea clothes [make NAME \"WHAT IT IS, AS WORN\" [--over UNDER[,UNDER...]] [--max-cents N] | remeasure NAME | cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] | wear OUT_DIR GARMENT... [--body DIR]] (clothes for SOMA's body from words: make has an image model (flux_2_pro, one picture a view, at most N cents each, 10 unless said) dress SOMA's grey mannequin from the front, back, left and right, then measures the pictures onto SOMA's own vertices as assets/clothes/NAME.json, its pictures in assets/clothes/NAME/; --over draws it over garments already made (innermost first), as the next layer, a garment made by procedure drawn on the mannequin first; remeasure measures a garment again from its kept pictures (after raea's measuring changed), nothing drawn or paid for; cover makes one by procedure in the same file, no picture: the skin of the parts named (hips, waist, torso, chest, neck, head, upperArm, foreArm, hand, thigh, shin, foot, toes; a limb's SHARE is how far along it from its top), in one colour, MM off the skin (6 unless said); wear puts garments on a body, innermost first (each GARMENT a name or its .json): OUT_DIR/NAME.glb each, with OUT_DIR/body.glb the body without the skin wholly under cloth; --body DIR another SOMA body folder (a headless one for a head part); alone, the project's garments. The first use fetches SOMA's body (NVlabs/SOMA-X, Apache-2.0) into raea's models folder and needs Blender: raea setup blender)");// a workspace's files and specs (docs/projects.feature), listed under render's usage like librarylet usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|plan|controller] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, plan.ts, controllers/ID.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects and controllers under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; split and join keep its history)\n raea controller ls [--json] | raea controller get PATH [--json] | raea controller set PATH VALUE [--project] [--by NAME] | raea controller write FILE.ts [--by NAME] | raea controller rm ID [--by NAME] (the workspace's controllers, controllers/ID.ts; PATH is controller.group.field; every change a commit)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\n raea next [DIR] (the two or three useful next steps for the project, from its brief, compositions, renders and checks)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}\n {}\n {}\n {}", skill::USAGE, tools::blender::USAGE, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE);let (export_game, capcut, scene, physics, splat) = (raea_app_game::USAGE, raea_app_capcut::USAGE, export::SCENE_USAGE, motion::physics::USAGE, tools::splat::USAGE);diff --git a/engine/cli/src/clothes.ts b/engine/cli/src/clothes.tsnew file mode 100644index 00000000..1e58ffdd--- /dev/null+++ b/engine/cli/src/clothes.ts@@ -0,0 +1,74 @@+// `raea clothes`: clothes for SOMA's body from words (raea docs/character.feature CH40 to CH45). make has an image+// model dress the mannequin's four views, one view a call, and measures the pictures onto SOMA's template vertices+// (a garment rides any SOMA body); wear puts garments on a body, innermost first. The work is the host's (op+// "clothes": engine/cli/src/wardrobe.ts on the native raea); this file reads the words and says what was done.++type Ask = (op: string, args: Record<string, unknown>) => any;++/** the body's parts a garment made by procedure covers (tools/clothes/garment.py's PARTS) */+export const PARTS = ["chest", "foot", "foreArm", "hand", "head", "hips", "neck", "shin", "thigh", "toes", "torso", "upperArm", "waist"];++export const CLOTHES_USAGE = `raea clothes (the project's garments: assets/clothes/NAME.json, their pictures in assets/clothes/NAME/)+raea clothes make NAME "WHAT IT IS, AS WORN" [--over UNDER[,UNDER...]] [--max-cents N] (drawn over the garments named; N: the most one picture may cost, 10 unless said)+raea clothes remeasure NAME (measured again from its kept pictures, after raea's measuring changed: nothing drawn or paid for)+raea clothes cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] (by procedure, no picture: ${PARTS.join(", ")}; a limb's share is how far along it from its top, foreArm:0.5)+raea clothes wear OUT_DIR GARMENT... [--body DIR] (GARMENT: a garment's name or its .json, innermost first; DIR: a SOMA body folder, SOMA's own unless said)+`;++const flagOf = (args: string[], name: string) => {+ const i = args.indexOf(name);+ return i >= 0 ? args[i + 1] : undefined;+};+/** the words that aren't flags or a flag's value */+const plain = (args: string[]) => args.filter((a, i) => !a.startsWith("--") && !args[i - 1]?.startsWith("--"));+const NAME = /^[a-z0-9][a-z0-9_-]*$/i;++export function clothesVerb(ask: Ask, args: string[]): string {+ const q = (op: string, a: Record<string, unknown> = {}) => ask("clothes", { op, ...a });+ const [sub, ...rest] = args;+ switch (sub) {+ case undefined:+ case "list": {+ const gs: { name: string; layer: number; vertices: number; over?: string }[] = q("list").garments;+ if (!gs.length) return 'No garments yet. raea clothes make NAME "what it is, as worn" makes one.\n';+ return gs.map((g) => `${g.name} layer ${g.layer}, ${g.vertices} of SOMA's vertices${g.over ? `, over ${g.over}` : ""}`).join("\n") + "\n";+ }+ case "make": {+ const [name, words, ...more] = plain(rest);+ if (!name || !words || more.length) throw new Error(`raea clothes make NAME "WHAT IT IS, AS WORN" [--over UNDER] [--max-cents N]\n${CLOTHES_USAGE}`);+ if (!NAME.test(name)) throw new Error(`${name}: a garment's name is letters, digits, - and _ (it names its file)`);+ const over = flagOf(rest, "--over"), cents = Number(flagOf(rest, "--max-cents") ?? 10);+ if (over !== undefined && !over.split(",").every((o) => NAME.test(o))) throw new Error(`--over ${over}: name garments already made, innermost first, with commas between (raea clothes lists them)`);+ if (!(cents > 0)) throw new Error("--max-cents takes the most one picture may cost, in cents");+ return q("make", { name, words, over, cents }).said;+ }+ case "remeasure": {+ const [name, ...more] = plain(rest);+ if (!name || more.length) throw new Error(`raea clothes remeasure NAME (measured again from its kept pictures; nothing is drawn or paid for)\n${CLOTHES_USAGE}`);+ if (!NAME.test(name)) throw new Error(`${name}: a garment's name is letters, digits, - and _ (it names its file)`);+ return q("remeasure", { name }).said;+ }+ case "cover": {+ const [name, ...more] = plain(rest);+ const parts = flagOf(rest, "--parts"), colour = flagOf(rest, "--colour"), over = flagOf(rest, "--over"), mm = Number(flagOf(rest, "--stand") ?? 6);+ if (!name || more.length || !parts || !colour) throw new Error(`raea clothes cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER]\n${CLOTHES_USAGE}`);+ if (!NAME.test(name)) throw new Error(`${name}: a garment's name is letters, digits, - and _ (it names its file)`);+ for (const p of parts.split(",")) {+ const [part, share] = p.trim().split(":");+ if (!PARTS.includes(part)) throw new Error(`--parts: no part ${part}; the parts are ${PARTS.join(", ")}`);+ if (share !== undefined && !(Number(share) > 0 && Number(share) <= 1)) throw new Error(`--parts ${p}: a share is how far along the limb, above 0 and at most 1`);+ }+ if (!/^#?[0-9a-f]{6}$/i.test(colour)) throw new Error(`--colour ${colour}: a colour is #RRGGBB`);+ if (!(mm > 0 && mm <= 80)) throw new Error("--stand takes how far the cloth stands off the skin, in millimetres (above 0, at most 80)");+ if (over !== undefined && !NAME.test(over)) throw new Error(`--over ${over}: name a garment already made (raea clothes lists them)`);+ return q("cover", { name, parts: parts.replace(/\s+/g, ""), colour: colour.startsWith("#") ? colour : `#${colour}`, stand: mm / 1000, over }).said;+ }+ case "wear": {+ const [out, ...garments] = plain(rest);+ if (!out || !garments.length) throw new Error(`raea clothes wear OUT_DIR GARMENT... [--body DIR]\n${CLOTHES_USAGE}`);+ return q("wear", { out, garments, body: flagOf(rest, "--body") }).said;+ }+ default:+ throw new Error(CLOTHES_USAGE);+ }+}diff --git a/engine/cli/src/index.ts b/engine/cli/src/index.tsindex c8e1b914..18615bdf 100644--- a/engine/cli/src/index.ts+++ b/engine/cli/src/index.ts@@ -25,6 +25,8 @@ const out = (stdout: string, exitCode = 0, stderr = "") => ({ stdout, stderr, eximport { libraryVerb } from "./library";// `raea show` (show.ts): what a session shows the person, in the raea appimport { showVerb } from "./show";+// `raea clothes` (clothes.ts): garments for SOMA's body from words+import { clothesVerb } from "./clothes";function flag(args: string[], name: string): string | undefined {const i = args.indexOf(name);@@ -263,6 +265,8 @@ export function raeaHandler(host?: Host, engine?: Engine) {return out(libraryVerb(ask, args.slice(1), (globalThis as { process?: { env: Record<string, string | undefined> } }).process?.env ?? {}));case "show":return out(showVerb(ask, args.slice(1), c.cwd, (globalThis as { process?: { env: Record<string, string | undefined> } }).process?.env ?? {}));+ case "clothes":+ return out(clothesVerb(ask, args.slice(1)));default:return await native();}diff --git a/engine/cli/src/native.ts b/engine/cli/src/native.tsindex ab536b58..578c291f 100644--- a/engine/cli/src/native.ts+++ b/engine/cli/src/native.ts@@ -11,6 +11,7 @@ import { brandKit } from "./brand";import { readSite, stylesOf } from "./scrape";import { wordsOf } from "./heard";import { harness, library, show, task } from "./app";+import { clothesHost } from "./wardrobe";import { raeaHandler, type Engine, type Host } from "./index";const [raea, ...args] = process.argv.slice(2);@@ -388,6 +389,8 @@ const host: Host = (op, a) => {return library(a);case "show":return show(a);+ case "clothes":+ return clothesHost(raea, cwd, process.env, a);case "harness":return harness();case "task":diff --git a/engine/cli/src/verbs.rs b/engine/cli/src/verbs.rsindex d073a123..13050d68 100644--- a/engine/cli/src/verbs.rs+++ b/engine/cli/src/verbs.rs@@ -96,7 +96,7 @@ pub fn mezz(args: &[String]) -> R<String> {/// The agent shell's own verbs (engine/cli/src/index.ts) this binary runs; the rest come one by one (docs/agent-surfaces.md)-pub const SHELL: &[&str] = &["init", "cut", "frame", "component", "part", "brand", "library", "show"];+pub const SHELL: &[&str] = &["init", "cut", "frame", "component", "part", "brand", "library", "show", "clothes"];/// One of SHELL's verbs: @raea/cli's handler, run by engine/cli/src/native.ts on raea's JavaScriptCore with Node's core, so the/// verb's one source is its TypeScript. native.ts answers the host's ops it needs, and runs this binary for the engine's verbs.diff --git a/engine/cli/src/wardrobe.ts b/engine/cli/src/wardrobe.tsnew file mode 100644index 00000000..02e9415f--- /dev/null+++ b/engine/cli/src/wardrobe.ts@@ -0,0 +1,224 @@+// The host's side of `raea clothes` (clothes.ts) on the native raea. SOMA-X's two body files are fetched once at a+// fixed commit (NVlabs/SOMA-X, Apache-2.0, checked by their SHA-256 and kept with the licence in raea's models+// folder, soma/), SOMA's body and the mannequin's views are made from them once by Blender (tools/clothes/body.py,+// mannequin.py), each view is dressed by `raea gen image`, and garments are measured and worn by+// tools/clothes/garment.py. A project's garments are assets/clothes/NAME.json, with their pictures in+// assets/clothes/NAME/.+import { spawnSync } from "node:child_process";+import { createHash } from "node:crypto";+import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";+import { basename, dirname, isAbsolute, join, relative } from "node:path";++type Env = Record<string, string | undefined>;+type Said = { said: string };++const COMMIT = "01ab5b5c0876058bd27d34b1607d74b2e55e0cf4";+const SOMA_X: Record<string, string> = {+ "SOMA_template_rig.usda": "a952cb7bdf4ccd801e355d53122d395b985b69d0d9181439edad5081bb171856",+ "SOMA_neutral.npz": "5829af4a5333abdba5ad449360b868faacee99d395971e62f35c0e7169432b63",+};+const VIEWS = ["front", "back", "left", "right"];+// what every picture must keep, so it lies over the mannequin pixel for pixel and the measure can read it+const KEEP =+ "Keep EXACTLY the pose, the proportions, the place of every limb and finger, the size in the frame and the camera view. Where no clothing covers it the mannequin stays featureless dark grey. Flat, even, unlit colour: no cast shadows, no highlights, plain light grey #C8C8C8 background, no text.";+const seen = (v: string) =>+ v === "front"+ ? "seen from the FRONT"+ : v === "back"+ ? "seen from BEHIND: we see its back, the back of its head and its heels, and only the back of each garment (no front opening, zip or buttons)"+ : `seen exactly from its ${v} side, in profile`;++/** raea's models folder (raea_io_home::models): ~/.local/share/raea-models, %LOCALAPPDATA%\raea\models on Windows */+const modelsDir = (env: Env) => (process.platform === "win32" && env.LOCALAPPDATA ? join(env.LOCALAPPDATA, "raea", "models") : join(env.HOME ?? "", ".local/share/raea-models"));++/** A script of tools/clothes: in RAEA_HOME, beside a release's bin/raea (share/raea/tools), or in the tree a built raea is in */+function tool(raea: string, env: Env, file: string): string {+ const bin = dirname(realpathSync(raea));+ const found = [env.RAEA_HOME && join(env.RAEA_HOME, "tools/clothes", file), join(bin, "../share/raea/tools/clothes", file), join(bin, "../../tools/clothes", file)].find((p) => p && existsSync(p));+ if (!found) throw new Error(`no tools/clothes/${file} beside ${bin} (a release keeps it in share/raea/tools/clothes)`);+ return found;+}++/** A tools/clothes script in a windowless Blender (`raea blender run`); the lines it says for raea ("clothes: ...") */+function blender(raea: string, env: Env, file: string, args: string[]): string[] {+ const r = spawnSync(raea, ["blender", "run", tool(raea, env, file), ...args], { encoding: "utf8", maxBuffer: 256 << 20 });+ const all = `${r.stdout ?? ""}${r.stderr ?? ""}`;+ if (r.status !== 0) throw new Error(`tools/clothes/${file} failed in Blender:\n${all.trim().split("\n").slice(-12).join("\n")}`);+ return all.split("\n").filter((l) => l.startsWith("clothes: ")).map((l) => l.slice(9));+}++/** SOMA-X's body files and licence in raea's models folder, fetched the first time and checked by their SHA-256 */+function somaX(dir: string): { rig: string; shapes: string } {+ mkdirSync(dir, { recursive: true });+ const get = (url: string, to: string) => {+ const r = spawnSync("curl", ["-fsSL", "--retry", "2", "-o", to, url], { encoding: "utf8" });+ if (r.status !== 0) throw new Error(`couldn't fetch SOMA's body from ${url}: ${(r.stderr ?? "").trim()}`);+ };+ for (const [file, sha] of Object.entries(SOMA_X)) {+ const to = join(dir, file);+ if (existsSync(to)) continue;+ get(`https://media.githubusercontent.com/media/NVlabs/SOMA-X/${COMMIT}/assets/${file}`, `${to}.part`);+ const got = createHash("sha256").update(readFileSync(`${to}.part`)).digest("hex");+ if (got !== sha) {+ rmSync(`${to}.part`, { force: true });+ throw new Error(`SOMA-X's ${file} came back changed (SHA-256 ${got}, not ${sha}); nothing was kept`);+ }+ renameSync(`${to}.part`, to);+ }+ if (!existsSync(join(dir, "LICENSE"))) get(`https://raw.githubusercontent.com/NVlabs/SOMA-X/${COMMIT}/LICENSE`, join(dir, "LICENSE"));+ return { rig: join(dir, "SOMA_template_rig.usda"), shapes: join(dir, "SOMA_neutral.npz") };+}++/** SOMA's body (soma/body: body.glb, skeleton.json) and the mannequin's four views (soma/mannequin), made once */+function soma(raea: string, env: Env): { rig: string; body: string; mannequin: string; made: string[] } {+ const dir = join(modelsDir(env), "soma"), x = somaX(dir), made: string[] = [];+ const body = join(dir, "body"), mannequin = join(dir, "mannequin");+ if (!["body.glb", "skeleton.json", "joint.glb"].every((f) => existsSync(join(body, f)))) made.push(...blender(raea, env, "body.py", [x.rig, x.shapes, body]));+ if (!VIEWS.every((v) => existsSync(join(mannequin, `mannequin_${v}.png`)))) made.push(...blender(raea, env, "mannequin.py", [join(body, "body.glb"), mannequin]));+ return { rig: x.rig, body, mannequin, made };+}++type Garment = { name: string; layer: number; vertices: number[]; stand: number[]; over?: string; topology?: string; source?: { views?: string } };+const readGarment = (file: string) => JSON.parse(readFileSync(file, "utf8")) as Garment;++/** a garment and what it is over, innermost first */+function chainOf(clothes: string, name: string, depth = 0): string[] {+ const file = join(clothes, `${name}.json`);+ if (!existsSync(file)) throw new Error(`no garment ${name} (assets/clothes/${name}.json): raea clothes lists the ones made`);+ // (over several at once: "tee+shorts")+ const g = readGarment(file), under = g.over && depth < 8 ? g.over.split("+").flatMap((o) => chainOf(clothes, o, depth + 1)) : [];+ return [...new Set(under.filter((n) => n !== name)), name];+}++/** What a new garment is drawn over: the pictures to draw on and measure against, and the layer beneath as one+ * garment file. One garment drawn from pictures is its own pictures; a garment made by procedure (no pictures), or+ * several at once, is drawn: the mannequin wearing them, innermost first, by Blender. */+function beneath(raea: string, env: Env, s: { rig: string; body: string }, clothes: string, own: string, over: string[]): { views: string; file: string; said: string[] } {+ const one = over.length === 1 ? readGarment(join(clothes, `${over[0]}.json`)) : undefined;+ if (one?.source?.views && existsSync(join(clothes, over[0], "views", "front.jpg"))) return { views: join(clothes, over[0], "views"), file: join(clothes, `${over[0]}.json`), said: [] };+ const names = [...new Set(over.flatMap((n) => chainOf(clothes, n)))], files = names.map((n) => join(clothes, `${n}.json`));+ const worn = join(own, "under"), views = join(own, "under", "views");+ blender(raea, env, "garment.py", ["wear", join(s.body, "body.glb"), s.rig, worn, ...files]);+ blender(raea, env, "mannequin.py", [join(worn, "body.glb"), views, "1024", ...names.map((n) => join(worn, `${n}.glb`))]);+ // the layers beneath as one: every vertex any of them covers, at the farthest any stands off+ const gs = files.map(readGarment), stand = new Map<number, number>();+ for (const g of gs) g.vertices.forEach((v, k) => stand.set(v, Math.max(stand.get(v) ?? 0, g.stand[k])));+ const ids = [...stand.keys()].sort((x, y) => x - y), file = join(worn, "beneath.json");+ writeFileSync(file, JSON.stringify({ name: over.join("+"), layer: Math.max(...gs.map((g) => g.layer)), vertices: ids, stand: ids.map((v) => stand.get(v)) }));+ return { views, file, said: [`drew the mannequin wearing ${names.join(", ")} to draw over (${views})`] };+}++function list(cwd: string) {+ const dir = join(cwd, "assets/clothes");+ const files = existsSync(dir) ? readdirSync(dir).filter((f) => f.endsWith(".json")).sort() : [];+ const garments = files.map((f) => readGarment(join(dir, f))).filter((g) => g.topology?.startsWith("SOMA"));+ return { garments: garments.map((g) => ({ name: g.name, layer: g.layer, vertices: g.vertices.length, over: g.over })) };+}++/** what one picture cost: the gen log's last "cents" (its total; the ones before are its steps') */+const centsOf = (log: string) => Number([...readFileSync(log, "utf8").matchAll(/"cents":\s*(\d+(?:\.\d+)?)/g)].pop()?.[1] ?? 0);++/** The four views dressed by the image model at once, each its own call (a sheet of views, or a second picture to+ * follow, loses the registration), kept as OWN/views/VIEW.jpg; what they cost, in cents */+function draw(raea: string, cwd: string, own: string, sources: (v: string) => string, layered: boolean, words: string, cents: number): number {+ const views = join(own, "views");+ mkdirSync(views, { recursive: true });+ const jobs = VIEWS.flatMap((v) => {+ const src = sources(v);+ if (!existsSync(src)) throw new Error(`${src}: the ${v} view to draw on is missing`);+ const prompt = layered+ ? `This dressed mannequin is ${seen(v)}. Add exactly one thing and keep everything else pixel for pixel: ${words}, worn over what it already wears. ${KEEP}`+ : `This grey mannequin is ${seen(v)}. Turn it into the same mannequin, still ${seen(v)}, wearing ${words}; only the surface changes where clothing covers it. ${KEEP}`;+ rmSync(join(own, `gen_${v}`), { recursive: true, force: true });+ return [prompt, src, join(own, `gen_${v}`), String(cents)];+ });+ const run = 'r=$1; shift; while [ $# -gt 0 ]; do ( "$r" gen image "$1" --model flux_2_pro --image "$2" --aspect 1:1 -o "$3" --max-cents "$4" > "$3.log" 2>&1 ) & shift 4; done; wait';+ spawnSync("bash", ["-c", run, "clothes", raea, ...jobs], { encoding: "utf8" });+ let spent = 0;+ for (const v of VIEWS) {+ const dir = join(own, `gen_${v}`), pic = existsSync(dir) ? readdirSync(dir).find((f) => /^out\.(jpe?g|png|webp)$/.test(f)) : undefined;+ if (!pic) throw new Error(`no picture for the ${v} view: ${relative(cwd, `${dir}.log`)} says why`);+ copyFileSync(join(dir, pic), join(views, `${v}.jpg`));+ spent += centsOf(`${dir}.log`);+ }+ return spent;+}++/** make draws and measures; again (remeasure) measures the pictures already kept, drawing nothing */+function make(raea: string, cwd: string, env: Env, a: { name: string; words?: string; over?: string; cents?: number; again?: boolean }): Said {+ const clothes = join(cwd, "assets/clothes"), own = join(clothes, a.name), views = join(own, "views"), file = join(clothes, `${a.name}.json`);+ let over = a.over ? a.over.split(",") : [];+ if (a.again) {+ if (!existsSync(file)) throw new Error(`no garment ${a.name} (assets/clothes/${a.name}.json): raea clothes lists the ones made`);+ const g = readGarment(file);+ if (!g.source?.views || !VIEWS.every((v) => existsSync(join(views, `${v}.jpg`)))) throw new Error(`${a.name} has no pictures to measure (${relative(cwd, views)}): one made by procedure is made again with raea clothes cover`);+ over = g.over ? g.over.split("+") : [];+ }+ for (const o of over) if (!existsSync(join(clothes, `${o}.json`))) throw new Error(`no garment ${o} (assets/clothes/${o}.json): raea clothes lists the ones made`);+ if (over.includes(a.name)) throw new Error("a garment can't be drawn over itself");+ const s = soma(raea, env);+ mkdirSync(own, { recursive: true });+ const under = over.length ? beneath(raea, env, s, clothes, own, over) : undefined;+ const cents = a.again ? 0 : draw(raea, cwd, own, (v) => (under ? join(under.views, `${v}.jpg`) : join(s.mannequin, `mannequin_${v}.png`)), !!under, a.words ?? "", a.cents ?? 10);+ const said = blender(raea, env, "garment.py", ["measure", join(s.body, "body.glb"), s.rig, views, file, ...(under ? [under.file, under.views] : [])]);+ if (!existsSync(file)) throw new Error(`the pictures didn't measure into a garment (${relative(cwd, views)})`);+ const worn = [...new Set(over.flatMap((o) => chainOf(clothes, o))), a.name].join(" ");+ return {+ said: [+ ...s.made,+ ...(under?.said ?? []),+ a.again ? `${a.name}: measured again from its four pictures (${relative(cwd, views)}), nothing drawn` : `${a.name}: four pictures, ${cents} cents (${relative(cwd, views)})`,+ ...said,+ `${relative(cwd, file)}. raea clothes wear assets/characters/NAME ${worn} puts it on SOMA's body; look at its pictures before you do.`,+ ].join("\n") + "\n",+ };+}++function cover(raea: string, cwd: string, env: Env, a: { name: string; parts: string; colour: string; stand: number; over?: string }): Said {+ const clothes = join(cwd, "assets/clothes"), file = join(clothes, `${a.name}.json`), under = a.over ? join(clothes, `${a.over}.json`) : undefined;+ if (under && !existsSync(under)) throw new Error(`no garment ${a.over} (assets/clothes/${a.over}.json): raea clothes lists the ones made`);+ if (a.over === a.name) throw new Error("a garment can't be laid over itself");+ const s = soma(raea, env);+ mkdirSync(clothes, { recursive: true });+ const said = blender(raea, env, "garment.py", ["cover", join(s.body, "body.glb"), s.rig, file, a.parts, a.colour, String(a.stand), ...(under ? [under] : [])]);+ if (!existsSync(file)) throw new Error("no garment was written");+ return { said: [...s.made, ...said, `${relative(cwd, file)}. raea clothes wear assets/characters/NAME ${a.over ? `${a.over} ` : ""}${a.name} puts it on SOMA's body.`].join("\n") + "\n" };+}++function wear(raea: string, cwd: string, env: Env, a: { out: string; garments: string[]; body?: string }): Said {+ const at = (p: string) => (isAbsolute(p) ? p : join(cwd, p));+ const files = a.garments.map((g) => (g.endsWith(".json") ? at(g) : join(cwd, "assets/clothes", `${g}.json`)));+ for (const f of files) if (!existsSync(f)) throw new Error(`no garment ${relative(cwd, f)}: raea clothes lists the ones made`);+ // innermost first: a garment drawn over another goes after it+ const layers = files.map((f) => readGarment(f).layer);+ if (layers.some((l, k) => k > 0 && l < layers[k - 1])) throw new Error(`put the garments innermost first (their layers are ${layers.join(", ")})`);+ const s = soma(raea, env), body = a.body ? at(a.body) : s.body, out = at(a.out);+ if (!existsSync(join(body, "body.glb"))) throw new Error(`${a.body}: not a body folder (no body.glb)`);+ mkdirSync(out, { recursive: true });+ const said = blender(raea, env, "garment.py", ["wear", join(body, "body.glb"), s.rig, out, ...files]);+ // the dressed body is a body folder of its own: its skeleton, its joints' stand-in and a headless body's collar+ for (const f of ["skeleton.json", "joint.glb", "collar.json"]) if (existsSync(join(body, f))) copyFileSync(join(body, f), join(out, f));+ const served = relative(join(cwd, "assets"), out);+ const use = served.startsWith("..")+ ? ""+ : `\nIn a composition: registerBody(skeleton, staticFile("${served}")), then <Character body=... parts={[${files.map((f) => `{ src: staticFile("${served}/${basename(f, ".json")}.glb") }`).join(", ")}]} />`;+ return { said: [...s.made, ...said].join("\n") + use + "\n" };+}++/** host op "clothes": list, make, remeasure, cover or wear */+export function clothesHost(raea: string, cwd: string, env: Env, a: Record<string, unknown>): unknown {+ switch (a.op) {+ case "list":+ return list(cwd);+ case "make":+ return make(raea, cwd, env, a as Parameters<typeof make>[3]);+ case "remeasure":+ return make(raea, cwd, env, { name: String(a.name), again: true });+ case "cover":+ return cover(raea, cwd, env, a as Parameters<typeof cover>[3]);+ case "wear":+ return wear(raea, cwd, env, a as Parameters<typeof wear>[3]);+ default:+ throw new Error(`raea clothes: no step ${String(a.op)}`);+ }+}diff --git a/tools/clothes/body.py b/tools/clothes/body.pynew file mode 100644index 00000000..361177e1--- /dev/null+++ b/tools/clothes/body.py@@ -0,0 +1,211 @@+# SOMA's template body (NVlabs/SOMA-X, Apache-2.0) as a raea body folder: body.glb skinned to flat joints under+# SOMA's names (the engine places each joint itself), and skeleton.json (rig "soma": the 78 named joints first,+# then the 32 twist joints as helpers; metres, Y up, facing +Z; skin samples per part). `raea clothes` makes the+# machine's copy once (in raea's models folder, soma/body) from SOMA-X's files beside it.+# raea blender run tools/clothes/body.py SOMA_template_rig.usda SOMA_neutral.npz OUT_DIR+import sys, os, json, random+import bpy, numpy as np+from mathutils import Matrix, Vector++usd, npz, out = sys.argv[sys.argv.index("--") + 1:][:3]+os.makedirs(out, exist_ok=True)+bpy.ops.wm.read_factory_settings(use_empty=True)+bpy.ops.wm.usd_import(filepath=usd)+src = next(o for o in bpy.data.objects if o.type == "ARMATURE")+keep = [o for o in bpy.data.objects if o.type == "MESH" and not o.name.endswith(("_lo", "_xlo")) and o.name != "c_fullBody_hi"]+for o in [o for o in bpy.data.objects if o.type == "MESH" and o not in keep]:+ bpy.data.objects.remove(o)++W = src.matrix_world+bones = [b for b in src.data.bones if b.name != "Root"] # parents first; SOMA's Root is a fixed frame at the floor, not a joint+# the body's joints first (what a clip turns: raea's clips hold the first joints of a skeleton), then the head's+# ends, eyes, jaw and the fingers, then the twist joints+BODY = ["Hips", "Spine1", "Spine2", "Chest", "Neck1", "Neck2", "Head"] + [s + n for s in ("Left", "Right") for n in ("Shoulder", "Arm", "ForeArm", "Hand")] \+ + [s + n for s in ("Left", "Right") for n in ("Leg", "Shin", "Foot", "ToeBase")]+named = [b for b in bones if "Twist" not in b.name]+named = [next(b for b in named if b.name == n) for n in BODY] + [b for b in named if b.name not in BODY]+order = named + [b for b in bones if "Twist" in b.name]+idx = {b.name: i for i, b in enumerate(order)}+head = {b.name: W @ b.head_local for b in bones} # Blender world, metres+++def R(v): # Blender's world (Z up, facing -Y) to raea's (Y up, facing +Z)+ return [round(v[0], 5), round(v[2], 5), round(-v[1], 5)]+++def tail_of(b):+ kids = [c for c in b.children if "Twist" not in c.name]+ if "Twist" in b.name: # a twist joint ends at the next one along its segment, or at the segment's end+ sib = sorted([c for c in b.parent.children if "Twist" in c.name], key=lambda c: c.name)+ k = sib.index(b)+ if k + 1 < len(sib):+ return head[sib[k + 1].name]+ far = [c for c in b.parent.children if "Twist" not in c.name]+ return head[far[0].name] if far else head[b.name] + Vector((0, 0, 0.02))+ if kids:+ # a trunk joint ends at the next joint up; a hand at its middle finger+ pick = next((c for c in kids if c.name.endswith(("Spine1", "Spine2", "Chest", "Neck1", "Neck2", "Head", "HeadEnd", "Middle1"))), kids[0])+ return head[pick.name]+ d = head[b.name] - head[b.parent.name] if b.parent and b.parent.name in head else Vector((0, 0, 0.03))+ return head[b.name] + d.normalized() * 0.02+++joints = [{"name": b.name, "parent": idx[b.parent.name] if b.parent and b.parent.name in idx else -1, "head": R(head[b.name]), "tail": R(tail_of(b)), **({"helper": True} if "Twist" in b.name else {})} for b in order]++# the flat rig: every joint a short bone pointing up, none a child of another+arm_data = bpy.data.armatures.new("soma")+rig = bpy.data.objects.new("soma", arm_data)+bpy.context.scene.collection.objects.link(rig)+bpy.context.view_layer.objects.active = rig+bpy.ops.object.mode_set(mode="EDIT")+for b in order:+ e = arm_data.edit_bones.new(b.name)+ e.head = head[b.name]; e.tail = head[b.name] + Vector((0, 0, 0.02)); e.roll = 0+bpy.ops.object.mode_set(mode="OBJECT")++# SHAPE="k:sigmas,k:sigmas": the body moved along SOMA's own shape model (SOMA_neutral.npz: component k by so many+# of its standard deviations; centimetres, Y up), for a person of another build. The joints stay where the+# template has them (SOMA's own layer moves them with the shape; that is not read here), so keep the change small.+SHAPE = [(int(a), float(b)) for a, b in (kv.split(":") for kv in os.environ.get("SHAPE", "").split(",") if kv)]+skin = None+for o in keep:+ me = o.data+ me.transform(o.matrix_world)+ if SHAPE and o.name.startswith("c_skin") and len(me.vertices) == 18056:+ zz = np.load(npz)+ d = sum(c * float(np.sqrt(zz["eigenvalues"][k])) * zz["shapedirs"][k].reshape(-1, 3) for k, c in SHAPE) / 100.0+ for v, dv in zip(me.vertices, d):+ v.co += Vector((float(dv[0]), float(-dv[2]), float(dv[1])))+ print("shaped", SHAPE, "largest move mm", round(float(np.linalg.norm(d, axis=1).max()) * 1000, 1))+ o.parent = None+ o.matrix_world = Matrix.Identity(4)+ for m in list(o.modifiers):+ o.modifiers.remove(m)+ o.modifiers.new("rig", "ARMATURE").object = rig+ o.parent = rig+ for p in me.polygons:+ p.use_smooth = True+ if o.name.startswith("c_skin"):+ skin = o++# CUT=height (metres): the body without its own head, for a head delivered as a part (docs/character.feature CH20):+# the skin is cut level at that height through the neck, and the eyes go. SKIN="r,g,b" (sRGB) is the skin's colour.+CUT = float(os.environ.get("CUT", "0")) or None+if CUT:+ import bmesh+ for o in [o for o in keep if o is not skin]:+ bpy.data.objects.remove(o)+ keep = [skin]+ bm = bmesh.new(); bm.from_mesh(skin.data)+ # a level plane through the neck: the skin is cut along it (new vertices on the plane, their weights between+ # their edge's ends), and everything above goes+ bmesh.ops.bisect_plane(bm, geom=bm.verts[:] + bm.edges[:] + bm.faces[:], plane_co=(0, 0, CUT), plane_no=(0, 0, 1), clear_outer=True, dist=1e-5)+ bm.to_mesh(skin.data); bm.free()+ print("cut at", CUT, "verts left", len(skin.data.vertices))+tone = [float(x) ** 2.2 for x in os.environ.get("SKIN", "0.81,0.80,0.79").split(",")]+mat = bpy.data.materials.new("skin"); mat.use_nodes = True+b = next(n for n in mat.node_tree.nodes if n.type == "BSDF_PRINCIPLED")+b.inputs["Base Color"].default_value = (*tone, 1); b.inputs["Roughness"].default_value = 0.6+eye = bpy.data.materials.new("eye"); eye.use_nodes = True+next(n for n in eye.node_tree.nodes if n.type == "BSDF_PRINCIPLED").inputs["Base Color"].default_value = (0.05, 0.05, 0.06, 1)+for o in keep:+ o.data.materials.clear(); o.data.materials.append(mat if o is skin else eye)++# skin samples, by the part the vertex mostly follows+PART = {"Hips": "hips", "Spine1": "waist", "Spine2": "torso", "Chest": "chest", "Neck1": "neck", "Neck2": "neck", "Head": "head", "Jaw": "head",+ "Shoulder": "chest", "Arm": "upperArm", "ForeArm": "foreArm", "Hand": "palm", "Leg": "thigh", "Shin": "shin", "Foot": "foot", "ToeBase": "toes"}+COUNT = {"hips": 120, "torso": 120, "chest": 120, "waist": 94, "head": 80, "palm": 80, "neck": 30}+++def part_of(name):+ side = "L" if name.startswith("Left") else "R" if name.startswith("Right") else ""+ n = name[len("Left"):] if side == "L" else name[len("Right"):] if side == "R" else name+ if "Twist" in n:+ n = n[:n.index("Twist")]+ if n.startswith("Hand") and n != "Hand": # a finger: HandIndex1 is in the palm, 2 to 4 are its three phalanges+ f = n[4:]+ finger = next(x for x in ("Thumb", "Index", "Middle", "Ring", "Pinky") if f.startswith(x))+ k = f[len(finger):]+ if finger == "Thumb":+ return (f"thumb{k}" if k in ("1", "2", "3") else "thumb3"), side+ return ("palm" if k == "1" else f"{finger.lower()}{min(int(k) - 1, 3)}" if k.isdigit() else f"{finger.lower()}3"), side+ return PART.get(n, "chest"), side+++gname = {g.index: g.name for g in skin.vertex_groups}+by_part = {}+for v in skin.data.vertices:+ ws = sorted(((g.weight, gname[g.group]) for g in v.groups if gname[g.group] in idx), reverse=True)[:3]+ if not ws:+ continue+ tot = sum(w for w, _ in ws)+ part, side = part_of(ws[0][1])+ j0 = ws[0][1]+ by_part.setdefault((part, side), []).append({"part": part, "side": side, "j": [idx[n] for _, n in ws], "w": [round(w / tot, 4) for w, _ in ws],+ "o": R(v.co - head[j0]), "n": R(v.normal)})+random.seed(7)+surface = []+for (part, side), vs in sorted(by_part.items()):+ n = COUNT.get(part, 30 if side else 60)+ if side and part in COUNT:+ n //= 2+ surface += random.sample(vs, min(n, len(vs)))++from pxr import Usd, UsdSkel+stage = Usd.Stage.Open(usd)+sk = next(UsdSkel.Skeleton(p) for p in stage.Traverse() if p.IsA(UsdSkel.Skeleton))+jn = [str(j).split("/")[-1] for j in sk.GetJointsAttr().Get()]+bind = {}+for n, m in zip(jn, sk.GetBindTransformsAttr().Get()):+ u, _, vt = np.linalg.svd(np.array(m).reshape(4, 4).T[:3, :3]); bind[n] = u @ vt+z = np.load(npz)+tp = dict(zip([str(x) for x in z["t_pose_world__v0.2.0__joint_names"]], z["t_pose_world__v0.2.0"].astype(float)))+tpose = {}+for n in idx:+ if n in tp:+ q = Matrix((tp[n] @ bind[n].T).tolist()).to_quaternion()+ tpose[n] = [round(q.x, 6), round(q.y, 6), round(q.z, 6), round(q.w, 6)]+zs = [v.co.z for v in skin.data.vertices]+eyes = (head["LeftEye"] + head["RightEye"]) / 2+skel = {"name": "soma", "rig": "soma", "body": {"source": "NVlabs/SOMA-X assets/SOMA_template_rig.usda, Apache-2.0"}, "height": round(max(zs) - min(zs), 4),+ "joints": joints, "landmarks": {"eyes": R(eyes), "sitDrop": 0.09}, "captured": len(BODY), "tpose": tpose, "surface": surface}+json.dump(skel, open(os.path.join(out, "skeleton.json"), "w"), separators=(",", ":"))+if CUT:+ # the open edge the cut left, in order round the neck, for the head's mesh to end on: each vertex's place, normal+ # and the joints that carry it+ import bmesh+ bm = bmesh.new(); bm.from_mesh(skin.data); bm.verts.ensure_lookup_table()+ edge = [e for e in bm.edges if e.is_boundary and all(abs(v.co.z - CUT) < 1e-4 for v in e.verts)]+ nxt = {}+ for e in edge:+ a_, b_ = e.verts+ nxt.setdefault(a_.index, []).append(b_.index); nxt.setdefault(b_.index, []).append(a_.index)+ ring = [edge[0].verts[0].index]+ while True:+ more = [v for v in nxt[ring[-1]] if v not in ring]+ if not more:+ break+ ring.append(more[0])+ gname2 = {g.index: g.name for g in skin.vertex_groups}+ def carried(i):+ ws = sorted(((g.weight, gname2[g.group]) for g in skin.data.vertices[i].groups if g.weight > 1e-4), reverse=True)[:4]+ t = sum(w for w, _ in ws)+ return {n: round(w / t, 4) for w, n in ws}+ json.dump({"units": "metres, Y up, +Z ahead", "cut": CUT, "closed": len(ring) == len(nxt),+ "ring": [{"at": R(bm.verts[i].co), "normal": R(bm.verts[i].normal), "weights": carried(i)} for i in ring]},+ open(os.path.join(out, "collar.json"), "w"), indent=1)+ print("collar ring", len(ring), "of", len(nxt), "edge vertices")+ bm.free()+print("clothes: SOMA's body, joints", len(joints), "named", len(named), "samples", len(surface), "height", skel["height"], "floor", round(min(zs), 4))++for o in bpy.data.objects:+ o.select_set(o is rig or o in keep)+bpy.data.objects.remove(src)+bpy.ops.export_scene.gltf(filepath=os.path.join(out, "body.glb"), export_format="GLB", use_selection=True, export_animations=False, export_yup=True, export_skins=True)+# joint.glb: the small stand-in <Character> puts at each joint for the skin's bones to follow (a body folder has one)+for o in bpy.data.objects:+ o.select_set(False)+bpy.ops.mesh.primitive_cube_add(size=0.01)+bpy.context.active_object.select_set(True)+bpy.ops.export_scene.gltf(filepath=os.path.join(out, "joint.glb"), export_format="GLB", use_selection=True, export_animations=False, export_yup=True)+print("saved", os.path.join(out, "body.glb"))diff --git a/tools/clothes/garment.py b/tools/clothes/garment.pynew file mode 100644index 00000000..01f7fa24--- /dev/null+++ b/tools/clothes/garment.py@@ -0,0 +1,479 @@+# Clothes for SOMA's body from pictures of the dressed mannequin (raea docs/character.feature CH40 to CH45), the+# measuring and wearing behind `raea clothes make` and `raea clothes wear`. A garment is data on SOMA's own+# vertices, by their numbers in SOMA's template (so it rides any SOMA body): which are covered, how far the cloth+# stands off each, and its colour there.+#+# measure: raea blender run tools/clothes/garment.py measure BODY.glb RIG.usda VIEWS_DIR OUT.json [UNDER.json UNDER_VIEWS_DIR]+# VIEWS_DIR/{front,back,left,right}.jpg: the mannequin's views (tools/clothes/mannequin.py), each dressed by an+# image model on its own, so each lies over its mannequin pixel for pixel. Each vertex of the skin is looked up+# in the views that face it and see it; where the picture shows cloth it is covered and takes the colour. With+# UNDER (the layer beneath and the pictures it was measured from), the garment is only where the picture changed+# from the layer beneath, and it stands off at least that layer's distance plus its own thickness.+# cover: raea blender run tools/clothes/garment.py cover BODY.glb RIG.usda OUT.json PART[:SHARE],... #RRGGBB STAND_M [UNDER.json]+# a garment by procedure in the same format, with no picture: the skin of the parts named (each limb as far+# along as its share), in one colour, so far off the skin (and a layer's thickness off UNDER).+# wear: raea blender run tools/clothes/garment.py wear BODY.glb RIG.usda OUT_DIR GARMENT.json... (innermost first)+# writes OUT_DIR/<name>.glb for each garment (the covered skin pushed out, with the body's own weights) and+# OUT_DIR/body.glb, the body with the skin that is wholly under cloth left out.+import sys, os, json+import bpy, bmesh, numpy as np+from mathutils import Vector, kdtree+from mathutils.bvhtree import BVHTree++args = sys.argv[sys.argv.index("--") + 1:]+mode, body_glb, rig_usd = args[:3]+OFF, THICK, MID = 0.004, 0.003, 0.9 # least stand-off, a layer's own thickness, the views' centre height (metres)+++def canon():+ """SOMA's template vertices at rest, Blender's frame, metres: the numbers a garment is kept by"""+ bpy.ops.wm.read_factory_settings(use_empty=True)+ bpy.ops.wm.usd_import(filepath=rig_usd)+ o = next(o for o in bpy.data.objects if o.type == "MESH" and o.name.startswith("c_skin_mid"))+ return np.array([o.matrix_world @ v.co for v in o.data.vertices])+++def load_body():+ bpy.ops.wm.read_factory_settings(use_empty=True)+ bpy.ops.import_scene.gltf(filepath=body_glb)+ for o in [o for o in bpy.data.objects if o.type == "MESH" and not any(m.type == "ARMATURE" for m in o.modifiers)]:+ bpy.data.objects.remove(o)+ return max((o for o in bpy.data.objects if o.type == "MESH"), key=lambda o: len(o.data.vertices))+++C = canon()+tree = kdtree.KDTree(len(C))+for i, p in enumerate(C):+ tree.insert(Vector(p), i)+tree.balance()+# each of the body's vertices: its number in the template, found by its rest place. A body of another shape has+# its vertices elsewhere, so NEUTRAL names the template-shaped body it was built beside (same export, same order).+neutral = os.environ.get("NEUTRAL")+if neutral:+ keep_path, body_glb = body_glb, neutral+ ref = load_body()+ cid = np.array([tree.find(ref.matrix_world @ v.co)[1] for v in ref.data.vertices])+ body_glb = keep_path+skin = load_body()+me, W = skin.data, skin.matrix_world+co = np.array([W @ v.co for v in me.vertices]); no = np.array([(W.to_3x3() @ v.normal).normalized() for v in me.vertices])+n = len(co)+if neutral:+ assert len(cid) == n, f"the shaped body has {n} vertices, its neutral twin {len(cid)}"+else:+ cid = np.array([tree.find(Vector(p))[1] for p in co])+bmw = bmesh.new(); bmw.from_mesh(me); bmw.transform(W); bvh = BVHTree.FromBMesh(bmw); bmw.verts.ensure_lookup_table()+ring = [[e.other_vert(v).index for e in v.link_edges] for v in bmw.verts]+bmw.free()++VIEWS = { # the way to the camera, a point's place in the picture (u right, v down, 0 to 1), the picture's right in the world+ "front": ((0, -1, 0), lambda p: (0.5 + p[0] / 2, 0.5 - (p[2] - MID) / 2), (1, 0, 0)),+ "back": ((0, 1, 0), lambda p: (0.5 - p[0] / 2, 0.5 - (p[2] - MID) / 2), (-1, 0, 0)),+ "left": ((1, 0, 0), lambda p: (0.5 + p[1] / 2, 0.5 - (p[2] - MID) / 2), (0, 1, 0)),+ "right": ((-1, 0, 0), lambda p: (0.5 - p[1] / 2, 0.5 - (p[2] - MID) / 2), (0, -1, 0)),+}+++def pixels(d, name):+ img = bpy.data.images.load(os.path.join(d, f"{name}.jpg"))+ w, h = img.size+ return np.array(img.pixels[:], dtype=np.float32).reshape(h, w, 4)[::-1, :, :3]+++def at(px, u, v):+ h, w = px.shape[:2]+ return px[min(h - 1, max(0, int(v * h))), min(w - 1, max(0, int(u * w)))]+++def measure(views_dir, out, under=None, under_views=None):+ weight = np.zeros(n); cloth = np.zeros(n); colour = np.zeros((n, 3)); PIX = {}+ for name, (toward, place, _) in VIEWS.items():+ px = PIX[name] = pixels(views_dir, name)+ below = pixels(under_views, name) if under_views else None+ t = Vector(toward)+ for i in range(n):+ facing = float(no[i] @ np.array(toward))+ if facing < 0.35:+ continue+ p = Vector(co[i])+ if bvh.ray_cast(p + t * 0.002 + Vector(no[i]) * 0.001, t)[0] is not None:+ continue # the body itself is between this point and the camera+ u, v = place(p)+ c = at(px, u, v); k = facing * facing+ weight[i] += k+ sat = float(c.max() - c.min()) / max(float(c.max()), 1e-3)+ bare = 0.17 < float(c.mean()) < 0.45 and sat < 0.12 # the mannequin's dark grey (black cloth is darker still)+ new = below is None or float(np.abs(c - at(below, u, v)).max()) > 0.08 # the picture changed here+ # (tried 11-15 and taken back: over a layer, counting any changed pixel as cloth whatever its shade. The+ # mannequin's own shade differs a little between two pictures, and the jacket then covered the hands)+ if not bare and new:+ cloth[i] += k; colour[i] += k * c+ seen = weight > 0+ covered = seen & (cloth > 0.5 * weight)+ colour[covered] /= cloth[covered][:, None]+ for _ in range(14): # a vertex no view saw takes its neighbours' answer+ for i in np.nonzero(~seen)[0]:+ near = [j for j in ring[i] if seen[j]]+ if near:+ covered[i] = sum(covered[j] for j in near) * 2 > len(near)+ cs = [colour[j] for j in near if covered[j]]+ if covered[i] and cs:+ colour[i] = np.mean(cs, axis=0)+ seen[i] = True+ for _ in range(3): # a bare vertex ringed by cloth is cloth+ for i in [i for i in range(n) if not covered[i] and ring[i] and sum(covered[j] for j in ring[i]) * 3 >= len(ring[i]) * 2]:+ cs = [colour[j] for j in ring[i] if covered[j]]+ covered[i] = True; colour[i] = np.mean(cs, axis=0)+ left = set(np.nonzero(covered)[0].tolist())+ while left: # and a small island of cloth is not+ stack, isle = [left.pop()], []+ while stack:+ i = stack.pop(); isle.append(i)+ for j in ring[i]:+ if j in left:+ left.remove(j); stack.append(j)+ if len(isle) < 150:+ covered[isle] = False+ # a small bare patch walled in by cloth is cloth: the tops of the shoulders, which no level view faces+ bare = set(np.nonzero(~covered)[0].tolist())+ while bare:+ stack, patch = [bare.pop()], []+ while stack:+ i = stack.pop(); patch.append(i)+ for j in ring[i]:+ if j in bare:+ bare.remove(j); stack.append(j)+ if len(patch) < 400:+ edge = [j for i in patch for j in ring[i] if covered[j]]+ if edge:+ c = np.mean(colour[edge], axis=0)+ covered[patch] = True; colour[patch] = c+ # and a bare vertex that faces up (which no level view sees squarely) among mostly covered skin is covered: the+ # tops of the shoulders under a jacket, whose gap runs into the collar and so is walled in by nothing+ for _ in range(4):+ add = []+ for i in np.nonzero(~covered & (no[:, 2] > 0.5))[0]:+ near, edge = {int(i)}, [int(i)]+ for _d in range(3):+ edge = [j for k in edge for j in ring[k] if j not in near]+ near.update(edge)+ near.discard(int(i))+ if near and sum(covered[j] for j in near) * 2 >= len(near):+ add.append(i)+ for i in add:+ cs = [colour[j] for j in ring[i] if covered[j]]+ covered[i] = True+ if cs:+ colour[i] = np.mean(cs, axis=0)+ if not add:+ break+ # and one that faces upward with cloth both in front of it and behind it, within 7 cm: the top of a shoulder+ # between a shirt's front and its back, which the bare neck beside it outvoted above, and the slope by the collar,+ # where the front view sees the layer beneath through an open collar (11-15, the overshirt's pale yokes); the neck+ # faces sideways and has no cloth in front of it+ for _ in range(3):+ held = np.nonzero(covered)[0]+ if not len(held):+ break+ kd = kdtree.KDTree(len(held))+ for k, i in enumerate(held):+ kd.insert(Vector(co[i]), k)+ kd.balance()+ add = []+ for i in np.nonzero(~covered & (no[:, 2] > 0.3))[0]:+ ys = [co[held[k]][1] - co[i][1] for _, k, _ in kd.find_range(Vector(co[i]), 0.07)]+ if any(y < -0.01 for y in ys) and any(y > 0.01 for y in ys):+ add.append(i)+ for i in add:+ cs = [colour[j] for j in ring[i] if covered[j]]+ covered[i] = True+ if cs:+ colour[i] = np.mean(cs, axis=0)+ if not add:+ break+ # the stand-off: read where a view sees a covered vertex on the body's outline, outward along its normal in the+ # picture until the backdrop, then spread over the garment+ floor = np.full(n, OFF)+ if under:+ u_stand = np.zeros(len(C)); u_stand[under["vertices"]] = under["stand"]+ floor = np.maximum(OFF, u_stand[cid] + THICK)+ stand = np.full(n, np.nan)+ for name, (toward, place, right) in VIEWS.items():+ px = PIX[name]; h, w = px.shape[:2]+ back = np.median(np.concatenate([px[:24, :24].reshape(-1, 3), px[:24, -24:].reshape(-1, 3)]), axis=0)+ ur, vd = np.array(right, float), np.array((0, 0, -1), float)+ for i in np.nonzero(covered)[0]:+ if abs(float(no[i] @ np.array(toward))) > 0.3:+ continue+ d = np.array([no[i] @ ur, no[i] @ vd]); L = np.hypot(*d)+ if L < 0.8:+ continue+ d /= L+ u0, v0 = place(Vector(co[i]))+ for k in range(1, 70):+ x, y = int(u0 * w + d[0] * k), int(v0 * h + d[1] * k)+ if not (0 <= x < w and 0 <= y < h):+ break+ if float(np.abs(px[y, x] - back).max()) < 0.07:+ r = k * 2.0 / w+ stand[i] = r if np.isnan(stand[i]) else min(stand[i], r)+ break+ known = ~np.isnan(stand)+ val = np.where(known, np.clip(stand, floor, 0.08), floor)+ for _ in range(60):+ nxt = val.copy()+ for i in np.nonzero(covered & ~known)[0]:+ nb = [j for j in ring[i] if covered[j]]+ if nb:+ nxt[i] = sum(val[j] for j in nb) / len(nb)+ val = nxt+ for _ in range(4):+ nxt = val.copy()+ for i in np.nonzero(covered)[0]:+ nb = [j for j in ring[i] if covered[j]]+ if nb:+ nxt[i] = 0.5 * val[i] + 0.5 * sum(val[j] for j in nb) / len(nb)+ val = np.maximum(nxt, floor)+ # and no further off than its part allows: a loose sleeve is drawn hanging below the arm in the mannequin's pose,+ # and that depth, read at the outline and laid all round the arm, made a balloon of it (11-15)+ gname = {g.index: g.name for g in skin.vertex_groups}+ cap = np.array([STAND_CAP.get(part_of(gname[max(v.groups, key=lambda g: g.weight).group])[0], 0.08) if v.groups else 0.08 for v in me.vertices])+ val = np.maximum(np.minimum(val, cap), floor)+ # by the template's numbers: a template vertex is covered if any of the body's copies of it is+ ids = sorted(set(int(c) for c in cid[covered]))+ where = {c: k for k, c in enumerate(ids)}+ s_sum = np.zeros(len(ids)); c_sum = np.zeros((len(ids), 3)); cnt = np.zeros(len(ids))+ for i in np.nonzero(covered)[0]:+ k = where[int(cid[i])]; s_sum[k] += val[i]; c_sum[k] += colour[i]; cnt[k] += 1+ g = {"name": os.path.splitext(os.path.basename(out))[0], "topology": "SOMA template, c_skin_mid, 18056 vertices", "units": "metres", "layer": (under["layer"] + 1) if under else 0,+ **({"over": under["name"]} if under else {}),+ # (the views by their path from the garment's file, so a project's garments move with it)+ "source": {"views": os.path.relpath(os.path.abspath(views_dir), os.path.dirname(os.path.abspath(out))), "how": "raea clothes make (tools/clothes/garment.py measure)"},+ "vertices": ids, "stand": [round(float(x), 5) for x in s_sum / cnt], "colour_srgb": [[round(float(x), 4) for x in c] for c in c_sum / cnt[:, None]],+ # how far the cloth may stray from its skinned place: nothing where it is snug, more the further it stands off+ "stray": [round(float(max(0.0, x - 0.012) * 0.6), 5) for x in s_sum / cnt]}+ json.dump(g, open(out, "w"), separators=(",", ":"))+ q = np.percentile(val[covered], [10, 50, 90]) * 1000+ print(f"clothes: {g['name']}: layer {g['layer']}, {len(ids)} of {len(C)} template vertices covered; stand-off mm at 10, 50, 90 per cent: {q[0]:.1f}, {q[1]:.1f}, {q[2]:.1f}; outline readings {int(known.sum())}")+++def export(obj, path, also=()):+ for o in bpy.data.objects:+ o.select_set(o is obj or o in also or o.type == "ARMATURE")+ kw = dict(filepath=path, export_format="GLB", use_selection=True, export_animations=False, export_yup=True, export_skins=True)+ try:+ bpy.ops.export_scene.gltf(**kw, export_vertex_color="ACTIVE", export_all_vertex_colors=False)+ except TypeError:+ bpy.ops.export_scene.gltf(**kw)+++def seen_by():+ """per view: which of the body's vertices it sees (facing it, nothing of the body between)"""+ out = {}+ for name, (toward, _, _) in VIEWS.items():+ t = Vector(toward); f = no @ np.array(toward)+ out[name] = np.array([f[i] > 0.2 and bvh.ray_cast(Vector(co[i]) + t * 0.002 + Vector(no[i]) * 0.001, t)[0] is None for i in range(n)])+ return out+++def bake(mesh, covered, views_dir, vcol, size=2048):+ """The garment's colour as a picture in the body's first UV set (spread to fill the picture): each texel of a+ covered triangle is a point of the body, looked up in the view that faces it most among those that see it. Where+ that view only grazes it, or shows backdrop or the bare mannequin there (a shoulder's top, a cuff past the drawn+ sleeve), the texel takes the garment's measured colour at its corners (vcol, per body vertex) instead."""+ uvl = mesh.uv_layers[0].data+ mesh.calc_loop_triangles()+ tris = [t for t in mesh.loop_triangles if all(covered[v] for v in t.vertices)]+ uv = np.array([[uvl[l].uv[:] for l in t.loops] for t in tris], float)+ lo, hi = uv.reshape(-1, 2).min(0), uv.reshape(-1, 2).max(0)+ uv = (uv - lo) / np.maximum(hi - lo, 1e-9)+ vid = np.array([t.vertices[:] for t in tris])+ PIX = {name: pixels(views_dir, name) for name in VIEWS}+ BACK = {name: np.median(np.concatenate([p[:24, :24].reshape(-1, 3), p[:24, -24:].reshape(-1, 3)]), axis=0) for name, p in PIX.items()}+ vis = seen_by()+ img = np.zeros((size, size, 3), np.float32); got = np.zeros((size, size), bool)+ names = list(VIEWS)+ toward = np.array([VIEWS[k][0] for k in names], float)+ for k in range(len(tris)):+ a, b, c = uv[k] * (size - 1)+ x0, x1 = int(np.floor(min(a[0], b[0], c[0]))), int(np.ceil(max(a[0], b[0], c[0])))+ y0, y1 = int(np.floor(min(a[1], b[1], c[1]))), int(np.ceil(max(a[1], b[1], c[1])))+ gx, gy = np.meshgrid(np.arange(x0, x1 + 1), np.arange(y0, y1 + 1))+ den = (b[1] - c[1]) * (a[0] - c[0]) + (c[0] - b[0]) * (a[1] - c[1])+ if abs(den) < 1e-9:+ continue+ w0 = ((b[1] - c[1]) * (gx - c[0]) + (c[0] - b[0]) * (gy - c[1])) / den+ w1 = ((c[1] - a[1]) * (gx - c[0]) + (a[0] - c[0]) * (gy - c[1])) / den+ w2 = 1 - w0 - w1+ inside = (w0 >= -0.02) & (w1 >= -0.02) & (w2 >= -0.02)+ if not inside.any():+ continue+ v = vid[k]; fn = no[v].mean(0); fn /= max(np.linalg.norm(fn), 1e-9)+ # the view: the one this triangle faces most, of those that see all its corners (else any it faces)+ score = toward @ fn+ ok = np.array([vis[nm][v].all() for nm in names])+ pick = int(np.argmax(np.where(ok, score, score - 2)))+ place = VIEWS[names[pick]][1]; px = PIX[names[pick]]; h, w = px.shape[:2]+ P = w0[inside][:, None] * co[v[0]] + w1[inside][:, None] * co[v[1]] + w2[inside][:, None] * co[v[2]]+ u, vv = place(P.T)+ col = px[np.clip((vv * h).astype(int), 0, h - 1), np.clip((u * w).astype(int), 0, w - 1)]+ mean, sat = col.mean(1), (col.max(1) - col.min(1)) / np.maximum(col.max(1), 1e-3)+ off = (np.abs(col - BACK[names[pick]]).max(1) < 0.07) | ((mean > 0.17) & (mean < 0.45) & (sat < 0.12)) | (score[pick] < 0.35)+ if off.any():+ mine = w0[inside][:, None] * vcol[v[0]] + w1[inside][:, None] * vcol[v[1]] + w2[inside][:, None] * vcol[v[2]]+ col = np.where(off[:, None], mine, col)+ img[gy[inside], gx[inside]] = col; got[gy[inside], gx[inside]] = True+ # (tried and taken out, 11-15: moving each other view's colours onto the front's by the front's main colours;+ # pale denim on the back was taken for the shirt's white and turned white. The views' colours still differ.)+ for _ in range(6): # spread past each island's edge, so a filtered lookup doesn't pull in black+ nb = np.zeros_like(img); cnt = np.zeros(got.shape, np.float32)+ for dy, dx in ((0, 1), (0, -1), (1, 0), (-1, 0)):+ nb += np.roll(np.roll(img * got[..., None], dy, 0), dx, 1); cnt += np.roll(np.roll(got, dy, 0), dx, 1)+ fill = ~got & (cnt > 0)+ img[fill] = nb[fill] / cnt[fill][:, None]; got |= fill+ return img, lo, hi+++def wear(out_dir, garments):+ os.makedirs(out_dir, exist_ok=True)+ under = np.zeros(n, bool)+ for path in garments:+ g = json.load(open(path))+ stand = np.zeros(len(C)); col = np.zeros((len(C), 3)); has = np.zeros(len(C), bool)+ has[g["vertices"]] = True; stand[g["vertices"]] = g["stand"]; col[g["vertices"]] = g["colour_srgb"]+ covered = has[cid]+ piece = skin.copy(); piece.data = skin.data.copy(); bpy.context.scene.collection.objects.link(piece)+ bm = bmesh.new(); bm.from_mesh(piece.data); bm.verts.ensure_lookup_table()+ # the body's own open edges (its UV seams, where glTF splits a vertex in two): kept where they are below+ seam = bm.verts.layers.int.new("seam")+ for v in bm.verts:+ v[seam] = int(v.is_boundary)+ layer = bm.loops.layers.color.new("cloth")+ for f in bm.faces:+ for l in f.loops:+ l[layer] = (*[float(x) ** 2.2 for x in col[cid[l.vert.index]]], 1.0)+ for v in bm.verts:+ v.co += v.normal * float(stand[cid[v.index]])+ bmesh.ops.delete(bm, geom=[f for f in bm.faces if not all(covered[v.index] for v in f.verts)], context="FACES")+ bmesh.ops.delete(bm, geom=[v for v in bm.verts if not v.link_faces], context="VERTS")+ # the hem: a garment's open edge runs along the body's triangles, a stair of them; each edge vertex is drawn+ # toward the middle of its two neighbours along the edge, a few times, which evens the stair into a line+ edge = [v for v in bm.verts if v.is_boundary and not v[seam]]+ for _ in range(4):+ to = {}+ for v in edge:+ nb = [e.other_vert(v) for e in v.link_edges if e.is_boundary and not e.other_vert(v)[seam]]+ if len(nb) == 2:+ to[v] = v.co * 0.5 + (nb[0].co + nb[1].co) * 0.25+ for v, c in to.items():+ v.co = c+ bm.to_mesh(piece.data); bm.free()+ # its colour: a picture in the body's UVs, baked from the views it was measured from (the garment's own UVs+ # are the body's, spread to fill that picture); a garment made by procedure has no views and is its one colour+ if "views" in g["source"]:+ tex, lo, hi = bake(skin.data, covered, os.path.join(os.path.dirname(os.path.abspath(path)), g["source"]["views"]), col[cid])+ else:+ tex, lo, hi = np.tile(np.mean(g["colour_srgb"], axis=0).astype(np.float32), (4, 4, 1)), np.zeros(2), np.ones(2)+ uvl = piece.data.uv_layers[0].data+ for l in uvl:+ l.uv = ((l.uv[0] - lo[0]) / max(hi[0] - lo[0], 1e-9), (l.uv[1] - lo[1]) / max(hi[1] - lo[1], 1e-9))+ im = bpy.data.images.new(g["name"], tex.shape[1], tex.shape[0], alpha=False)+ im.pixels = np.concatenate([tex, np.ones((*tex.shape[:2], 1), np.float32)], axis=2).reshape(-1) # (rows bottom up, as v runs)+ im.filepath_raw = os.path.join(out_dir, g["name"] + ".png"); im.file_format = "PNG"; im.save()+ mat = bpy.data.materials.new(g["name"]); mat.use_nodes = True+ bsdf = next(x for x in mat.node_tree.nodes if x.type == "BSDF_PRINCIPLED")+ a = mat.node_tree.nodes.new("ShaderNodeTexImage"); a.image = im+ mat.node_tree.links.new(a.outputs["Color"], bsdf.inputs["Base Color"]); bsdf.inputs["Roughness"].default_value = 0.85+ piece.data.materials.clear(); piece.data.materials.append(mat)+ export(piece, os.path.join(out_dir, g["name"] + ".glb"))+ bpy.data.objects.remove(piece)+ under |= covered+ print(f"clothes: wore {g['name']} over {int(covered.sum())} of the body's vertices: {os.path.join(out_dir, g['name'] + '.glb')}")+ # the skin wholly under cloth is left out: a vertex covered, with every neighbour covered too+ deep = under & np.array([all(under[j] for j in ring[i]) for i in range(n)])+ bm = bmesh.new(); bm.from_mesh(skin.data); bm.verts.ensure_lookup_table()+ gone = [f for f in bm.faces if all(deep[v.index] for v in f.verts)]+ total = len(bm.faces)+ bmesh.ops.delete(bm, geom=gone, context="FACES")+ bmesh.ops.delete(bm, geom=[v for v in bm.verts if not v.link_faces], context="VERTS")+ bm.to_mesh(skin.data); bm.free()+ # with the body's other parts (a whole SOMA's eyes; a headless body has none)+ export(skin, os.path.join(out_dir, "body.glb"), [o for o in bpy.data.objects if o.type == "MESH" and o is not skin])+ print(f"clothes: the body without the skin wholly under cloth ({len(gone)} of {total} faces left out): {os.path.join(out_dir, 'body.glb')}")+++# the most a garment measured from pictures stands off each part (metres; the trunk 8 cm)+STAND_CAP = {"upperArm": 0.03, "foreArm": 0.025, "hand": 0.01, "thigh": 0.04, "shin": 0.035, "foot": 0.015, "toes": 0.01, "neck": 0.03, "head": 0.03}+LIMB = {"Arm": ("upperArm", "ForeArm"), "ForeArm": ("foreArm", "Hand"), "Leg": ("thigh", "Shin"), "Shin": ("shin", "Foot"), "Foot": ("foot", "ToeBase")}+TRUNK = {"Hips": "hips", "Spine1": "waist", "Spine2": "torso", "Chest": "chest", "Shoulder": "chest", "Neck1": "neck", "Neck2": "neck", "ToeBase": "toes", "ToeEnd": "toes"}+PARTS = sorted(set(TRUNK.values()) | {v[0] for v in LIMB.values()} | {"hand", "head"})+++def part_of(name):+ """a joint's part (hips, waist, torso, chest, neck, head, upperArm, foreArm, hand, thigh, shin, foot, toes) and,+ for a limb, the joint it starts at and the one it ends at"""+ side = "Left" if name.startswith("Left") else "Right" if name.startswith("Right") else ""+ j = name[len(side):]+ if "Twist" in j: # a twist joint is its limb's+ j = j[:j.index("Twist")]+ if j.startswith("Hand"):+ return "hand", None+ if j in LIMB:+ return LIMB[j][0], (side + j, side + LIMB[j][1])+ return TRUNK.get(j, "head"), None+++def cover(out, spec, colour, stand_m, under=None):+ """A garment by procedure, with no picture: the skin of the parts named, each limb as far along as its share+ says ("foreArm:0.5", the half nearest the elbow), in one colour, standing off the skin by stand_m (and off the+ layer beneath by a layer's thickness)."""+ want = {}+ for s in spec.split(","):+ p, _, share = s.strip().partition(":")+ if p not in PARTS:+ raise SystemExit(f"clothes: no part {p!r}; the parts are {', '.join(PARTS)}")+ want[p] = float(share) if share else 1.0+ arm = next(o for o in bpy.data.objects if o.type == "ARMATURE")+ head = {b.name: np.array(arm.matrix_world @ b.head_local) for b in arm.data.bones}+ gname = {g.index: g.name for g in skin.vertex_groups}+ covered = np.zeros(n, bool)+ for i, v in enumerate(me.vertices):+ if not v.groups:+ continue+ top = gname[max(v.groups, key=lambda g: g.weight).group]+ p, limb = part_of(top)+ if p not in want:+ continue+ if limb and want[p] < 1.0 and limb[0] in head and limb[1] in head:+ a, b = head[limb[0]], head[limb[1]]+ t = float((co[i] - a) @ (b - a)) / max(float((b - a) @ (b - a)), 1e-9)+ if t > want[p]:+ continue+ covered[i] = True+ for _ in range(2): # the edge evened without wearing it away: a vertex changes only when two thirds of its neighbours differ+ k = np.array([sum(covered[j] for j in ring[i]) / max(len(ring[i]), 1) for i in range(n)])+ covered = np.where(k > 2 / 3, True, np.where(k < 1 / 3, False, covered))+ # a hem allowance: one ring past the parts' edge, so garments on neighbouring parts overlap instead of leaving a gap+ covered = covered | np.array([any(covered[j] for j in ring[i]) for i in range(n)])+ rgb = [int(colour.lstrip("#")[k:k + 2], 16) / 255 for k in (0, 2, 4)]+ ids = sorted(set(int(c) for c in cid[covered]))+ stand = np.full(len(ids), max(stand_m, OFF))+ if under:+ u = np.zeros(len(C)); u[under["vertices"]] = under["stand"]+ stand = np.maximum(stand, u[ids] + THICK)+ g = {"name": os.path.splitext(os.path.basename(out))[0], "topology": "SOMA template, c_skin_mid, 18056 vertices", "units": "metres", "layer": (under["layer"] + 1) if under else 0,+ **({"over": under["name"]} if under else {}),+ "source": {"how": "raea clothes cover (tools/clothes/garment.py cover)", "parts": spec, "colour": colour},+ "vertices": ids, "stand": [round(float(x), 5) for x in stand], "colour_srgb": [[round(x, 4) for x in rgb]] * len(ids),+ "stray": [round(float(max(0.0, x - 0.012) * 0.6), 5) for x in stand]}+ json.dump(g, open(out, "w"), separators=(",", ":"))+ print(f"clothes: {g['name']}: layer {g['layer']}, {len(ids)} of {len(C)} template vertices covered ({spec}), {colour}, {stand.min() * 1000:.1f} to {stand.max() * 1000:.1f} mm off what is under it")+++if mode == "measure":+ views_dir, out = args[3], args[4]+ measure(views_dir, out, json.load(open(args[5])) if len(args) > 5 else None, args[6] if len(args) > 6 else None)+elif mode == "cover":+ cover(args[3], args[4], args[5], float(args[6]), json.load(open(args[7])) if len(args) > 7 else None)+else:+ wear(args[3], args[4:])diff --git a/tools/clothes/mannequin.py b/tools/clothes/mannequin.pynew file mode 100644index 00000000..8cd0f0c8--- /dev/null+++ b/tools/clothes/mannequin.py@@ -0,0 +1,50 @@+# The mannequin clothes are drawn on (raea docs/character.feature CH40): SOMA's body at rest, flat dark grey on+# mid grey, without perspective, from the front, the back, its left and its right, the four views in one picture so+# an image model dresses all of them as one garment. The cameras are written beside it, so what is drawn can be laid+# back on the body. `raea clothes` makes the machine's views once, in raea's models folder (soma/mannequin).+# raea blender run tools/clothes/mannequin.py BODY.glb OUT_DIR [SIZE] [PIECE.glb...]+# With PIECEs (a dressed body's garments, `raea clothes wear`), the mannequin is drawn wearing them in their own+# colours, and the views are OUT_DIR/{front,back,left,right}.jpg: what a garment made by procedure looks like, for+# one drawn over it.+import sys, os, json, math+import bpy+from mathutils import Vector, Matrix++a = sys.argv[sys.argv.index("--") + 1:]+src, out, size, pieces = a[0], a[1], int(a[2]) if len(a) > 2 else 1024, a[3:]+os.makedirs(out, exist_ok=True)+bpy.ops.wm.read_factory_settings(use_empty=True)+bpy.ops.import_scene.gltf(filepath=src)+for o in [o for o in bpy.data.objects if o.type == "MESH" and not any(m.type == "ARMATURE" for m in o.modifiers)]:+ bpy.data.objects.remove(o)+for o in bpy.data.objects: # the body's own parts in the mannequin's grey (workbench draws a material's viewport colour)+ if o.type == "MESH":+ for m in o.data.materials:+ m.diffuse_color = (0.22, 0.22, 0.22, 1)+for p in pieces:+ bpy.ops.import_scene.gltf(filepath=p)+sc = bpy.context.scene+sc.render.engine = "BLENDER_WORKBENCH"+sh = sc.display.shading+sh.light = "STUDIO"; sh.color_type = "TEXTURE" if pieces else "SINGLE"; sh.single_color = (0.22, 0.22, 0.22); sh.show_cavity = True; sh.cavity_type = "BOTH"; sh.show_shadows = False+sc.world = bpy.data.worlds.new("w"); sc.world.color = (0.578, 0.578, 0.578)+sc.render.film_transparent = False+sc.view_settings.view_transform = "Standard"+sc.render.resolution_x = sc.render.resolution_y = size+cam_d = bpy.data.cameras.new("c"); cam_d.type = "ORTHO"; cam_d.ortho_scale = 2.0+cam = bpy.data.objects.new("c", cam_d); sc.collection.objects.link(cam); sc.camera = cam+MID = 0.9 # metres up: the frame is 2 m tall, the floor 10 cm above its bottom+views = {"front": (0, -4), "back": (0, 4), "left": (4, 0), "right": (-4, 0)} # the body faces -Y in Blender; +X is its left+cams = {}+for name, (x, y) in views.items():+ cam.location = (x, y, MID)+ cam.rotation_euler = (Vector((0, 0, MID)) - cam.location).to_track_quat("-Z", "Y").to_euler()+ if pieces:+ sc.render.image_settings.file_format = "JPEG"; sc.render.image_settings.quality = 95+ sc.render.filepath = os.path.join(out, f"{name}.jpg" if pieces else f"mannequin_{name}.png")+ bpy.ops.render.render(write_still=True)+ # raea's frame: y up, +z ahead, x its left+ cams[name] = {"from": [x, MID, -y], "at": [0, MID, 0], "height_m": 2.0}+if not pieces:+ json.dump({"units": "metres, Y up, +Z ahead", "orthographic": True, "size": size, "views": cams}, open(os.path.join(out, "mannequin.cam.json"), "w"), indent=1)+print("clothes: the mannequin's four views", out)diff --git a/tools/release.sh b/tools/release.shindex 61acdbe1..c59516f4 100755--- a/tools/release.sh+++ b/tools/release.sh@@ -159,7 +159,7 @@ done# (@raea/ui, the page's DOM every render goes through, isn't an @raea/<name> path, so it's named here)git archive "$ref" sdk/tsconfig.base.json sdk/ui/src sdk/ui/package.json sdk/ui/bevy sdk/raea/src sdk/raea/library sdk/raea/package.json sdk/react/js/src sdk/react/js/lite sdk/react/js/shims sdk/react/js/package.json sdk/react/js/tsconfig.json sdk/shell/src \"${pkgs[@]}" \- tools/tokensynth tools/sao tools/goo tools/splat tools/matchmove tools/ensure.sh sdk/guides/craft docs/sdk-coverage.md engine/cli/template/theme.css ':(glob)engine/cli/src/*.ts' \+ tools/tokensynth tools/sao tools/goo tools/splat tools/matchmove tools/clothes tools/ensure.sh sdk/guides/craft docs/sdk-coverage.md engine/cli/template/theme.css ':(glob)engine/cli/src/*.ts' \| tar -x -C "$stage/share/raea"# a folder copied as it is here (links kept, as rsync -a; tar, since Git's bash on Windows has no rsync)copy() { mkdir -p "$2" && tar -C "$(dirname "$1")" --exclude .cache -cf - "$(basename "$1")" | tar -C "$2" -xf -; }