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
CH45c: footwear is a hard piece, and garments layer by where they lie
shinyobjectz3a646fa4bbb7
diff --git a/docs/character.feature b/docs/character.featureindex 0c7ed6ac..fb55eb48 100644--- a/docs/character.feature+++ b/docs/character.feature@@ -302,7 +302,8 @@ Feature: The character SDK as one system: SOMA bodies, Kimodo motion, generated# end standing; the seed kept is the one whose upper body moves most (a do line fails by standing through# it: one seed of three stood still through "scratch the head"), and the kept ten all do what they say# (seed 1 alone 7 of 10, seed 2 8, seed 3 7). Film: sheet3d out/do-eval-v1.mp4, posted for the user's look- # (i-show-mwj21c0d-1). Open: that look; the user's word on shipping the downloads (Kimodo under NVIDIA's+ # (i-show-mwj21c0d-1). The user's look, 11-16: "All ten read right". Open: the user's word on shipping the+ # downloads (i-show-mwj24i8o-2: Kimodo under NVIDIA's# Open Model License; Meta Llama 3 under its Community License, fetched from mlx-community's ungated 8-bit# copy; the adapters MIT); Kimodo's own post-processing (its C++ foot-skate clean-up) is not ported.Given the eval's lines passdiff --git a/docs/manual/reference/cli/clothes.md b/docs/manual/reference/cli/clothes.mdindex bae082b3..8182b6c9 100644--- a/docs/manual/reference/cli/clothes.md+++ b/docs/manual/reference/cli/clothes.md@@ -12,7 +12,7 @@ Clothes for SOMA's body from words: make sews a garment from a sewing pattern (G## Usage```sh-raea clothes [make NAME ["WHAT IT IS"] [--plain] [--set PATH=VALUE,...] [--colour #RRGGBB] | settings | cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] | wear OUT_DIR GARMENT... [--body DIR] [--head HEAD_DIR]] (clothes for SOMA's body from words: make sews a garment: a sewing pattern (GarmentCode, MIT) from the words, or the plain base with --plain, its settings changed by --set PATH=VALUE (settings lists them and what each may be), cut to SOMA's measurements, draped by raea's own cloth and baked, as assets/clothes/NAME.json and its .glb, in --colour or the palette's next; the first make sets up GarmentCode and its Python in raea's models folder; 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), --over a garment already made as the one under it; 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); --head HEAD_DIR the head that joins it (head.json), whose skin the body's is graded to at the collar; 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)+raea clothes [make NAME ["WHAT IT IS"] [--plain] [--set PATH=VALUE,...] [--colour #RRGGBB] | settings | cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] [--hard [--sole MM] [--sole-colour #RRGGBB] [--panels #RRGGBB,...]] | wear OUT_DIR GARMENT... [--body DIR] [--head HEAD_DIR]] (clothes for SOMA's body from words: make sews a garment: a sewing pattern (GarmentCode, MIT) from the words, or the plain base with --plain, its settings changed by --set PATH=VALUE (settings lists them and what each may be), cut to SOMA's measurements, draped by raea's own cloth and baked, as assets/clothes/NAME.json and its .glb, in --colour or the palette's next; the first make sets up GarmentCode and its Python in raea's models folder; 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), --over a garment already made as the one under it; 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); --head HEAD_DIR the head that joins it (head.json), whose skin the body's is graded to at the collar; 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)```Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.@@ -23,11 +23,15 @@ Headless: it needs nothing running and opens no window. Takes any number of argu| --- | --- | --- || `--body` | `DIR` | With `wear`: dress this SOMA body folder (body.glb, skeleton.json) instead of SOMA's own, such as a headless body that a generated head joins at the collar. || `--colour` | `#RRGGBB` | The garment's one colour. With `make` it is optional: one is picked from the name unless said. |+| `--hard` | – | With `cover`: footwear, made as a hard piece. Each foot gets its own shape: a rounded last around the foot, so the toes and the foot's small forms go under it. Underneath is a flat sole, and the top over the leg is left open as the collar. It is skinned to the foot like the skin it covers, and it does not swing. || `--head` | `HEAD_DIR` | With `wear`: the head folder (head.json, head.glb) that joins a headless body at the collar. The body's skin takes the head's neck colour and is graded to the head's own skin just under the collar, so no step of colour shows at the join. || `--over` | `UNDER` | With `cover`: lay it over one garment made by `cover`, a layer's thickness off it. |+| `--panels` | `#RRGGBB,...` | With `cover --hard`: the colours of up to three panels, in this order: a toe cap, a heel, and a band along each side. || `--parts` | `PART` | With `cover`: the body's parts the garment covers, comma-separated; a limb takes a share, how far along it from its top (`foreArm:0.5` is the half nearest the elbow). || `--plain` | – | With `make`: start from the plain base (a short-sleeved top) instead of a pattern guessed from words. The default when no words are given. || `--set` | `PATH=VALUE,...` | With `make`: change settings of the garment's pattern by path, comma-separated (`sleeve.length=0.9,meta.bottom=Pants`). A choice must be one of its options and a number within its range; `raea clothes settings` lists them. |+| `--sole` | `MM` | With `cover --hard`: the sole's thickness in millimetres (10 unless said, at most 60). Most of it is painted up the side; the bottom sits at most 8 mm below the bare foot, so the person does not sink into the floor. |+| `--sole-colour` | `#RRGGBB` | With `cover --hard`: the sole's colour (an off-white unless said). || `--stand` | `MM` | With `cover`: how far the cloth stands off the skin, in millimetres (6 unless said). |<!-- generated:end -->diff --git a/engine/cli/src/cli.rs b/engine/cli/src/cli.rsindex e29d0e48..db2f68b8 100644--- a/engine/cli/src/cli.rs+++ b/engine/cli/src/cli.rs@@ -135,7 +135,7 @@ pub fn run(args: &[String]) -> R<String> {let 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, sewn or laid on the skin (docs/character.feature CH45c): engine/cli/src/clothes.ts, wardrobe.ts and sewn.ts- let usage = format!("{usage}\n raea clothes [make NAME [\"WHAT IT IS\"] [--plain] [--set PATH=VALUE,...] [--colour #RRGGBB] | settings | cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] | wear OUT_DIR GARMENT... [--body DIR] [--head HEAD_DIR]] (clothes for SOMA's body from words: make sews a garment: a sewing pattern (GarmentCode, MIT) from the words, or the plain base with --plain, its settings changed by --set PATH=VALUE (settings lists them and what each may be), cut to SOMA's measurements, draped by raea's own cloth and baked, as assets/clothes/NAME.json and its .glb, in --colour or the palette's next; the first make sets up GarmentCode and its Python in raea's models folder; 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), --over a garment already made as the one under it; 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); --head HEAD_DIR the head that joins it (head.json), whose skin the body's is graded to at the collar; 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)");+ let usage = format!("{usage}\n raea clothes [make NAME [\"WHAT IT IS\"] [--plain] [--set PATH=VALUE,...] [--colour #RRGGBB] | settings | cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] [--hard [--sole MM] [--sole-colour #RRGGBB] [--panels #RRGGBB,...]] | wear OUT_DIR GARMENT... [--body DIR] [--head HEAD_DIR]] (clothes for SOMA's body from words: make sews a garment: a sewing pattern (GarmentCode, MIT) from the words, or the plain base with --plain, its settings changed by --set PATH=VALUE (settings lists them and what each may be), cut to SOMA's measurements, draped by raea's own cloth and baked, as assets/clothes/NAME.json and its .glb, in --colour or the palette's next; the first make sets up GarmentCode and its Python in raea's models folder; 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), --over a garment already made as the one under it; 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); --head HEAD_DIR the head that joins it (head.json), whose skin the body's is graded to at the collar; 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)");// body motion made on this Mac by Kimodo on MLX (docs/character.feature CH15c): apps/tools/src/motion.rslet usage = format!("{usage}\n {} ({})", tools::motion::USAGE, tools::motion::ABOUT);// a workspace's files and specs (docs/projects.feature), listed under render's usage like librarydiff --git a/engine/cli/src/clothes.ts b/engine/cli/src/clothes.tsindex dd66b8e0..ae5a1d78 100644--- a/engine/cli/src/clothes.ts+++ b/engine/cli/src/clothes.ts@@ -12,7 +12,7 @@ export const PARTS = ["chest", "foot", "foreArm", "hand", "head", "hips", "neck"export const CLOTHES_USAGE = `raea clothes (the project's garments: assets/clothes/NAME.json, their files in assets/clothes/NAME/)raea clothes make NAME ["WHAT IT IS"] [--plain] [--set PATH=VALUE,...] [--colour #RRGGBB] (a sewn garment: its pattern from the words, or from the plain base with --plain or no words; each PATH=VALUE changes one setting)raea clothes settings (a sewn garment's settings: each path, its value in the plain base, what it may be)-raea clothes cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] (by procedure on the skin: ${PARTS.join(", ")}; a limb's share is how far along it from its top, foreArm:0.5)+raea clothes cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] [--hard [--sole MM] [--sole-colour #RRGGBB] [--panels #RRGGBB,...]] (by procedure on the skin; --hard: footwear, on a last round the foot with a sole under it: ${PARTS.join(", ")}; a limb's share is how far along it from the end that joins the rest: upperArm,foreArm:0.5 from the elbow, foot,shin:0.4 from the ankle)raea clothes wear OUT_DIR GARMENT... [--body DIR] [--head HEAD_DIR] (GARMENT: a garment's name or its .json, innermost first; DIR: a SOMA body folder, SOMA's own unless said; HEAD_DIR: the head that joins a headless body, whose skin is graded to it at the collar)`;@@ -20,8 +20,10 @@ const flagOf = (args: string[], name: string) => {const i = args.indexOf(name);return i >= 0 ? args[i + 1] : undefined;};+/** the flags that take no value */+const BARE = new Set(["--plain", "--hard"]);/** 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 plain = (args: string[]) => args.filter((a, i) => !a.startsWith("--") && (!args[i - 1]?.startsWith("--") || BARE.has(args[i - 1])));const NAME = /^[a-z0-9][a-z0-9_-]*$/i;export function clothesVerb(ask: Ask, args: string[]): string {@@ -60,7 +62,14 @@ export function clothesVerb(ask: Ask, args: string[]): string {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;+ // a hard piece (footwear): its own shape on a last round the foot, a sole under it, panels in their colours+ const hard = rest.includes("--hard"), sole = flagOf(rest, "--sole"), soleColour = flagOf(rest, "--sole-colour"), panels = flagOf(rest, "--panels");+ if (!hard && (sole ?? soleColour ?? panels) !== undefined) throw new Error("--sole, --sole-colour and --panels are a hard piece's: add --hard");+ if (sole !== undefined && !(Number(sole) >= 0 && Number(sole) <= 60)) throw new Error("--sole takes the sole's thickness in millimetres (0 to 60)");+ for (const c of [soleColour, ...(panels?.split(",") ?? [])]) if (c !== undefined && !/^#?[0-9a-f]{6}$/i.test(c.trim())) throw new Error(`${c}: a colour is #RRGGBB`);+ const hex = (c: string) => (c.trim().startsWith("#") ? c.trim() : `#${c.trim()}`);+ return q("cover", { name, parts: parts.replace(/\s+/g, ""), colour: colour.startsWith("#") ? colour : `#${colour}`, stand: mm / 1000, over,+ ...(hard ? { hard: { sole: sole === undefined ? undefined : Number(sole), soleColour: soleColour && hex(soleColour), panels: panels?.split(",").map(hex) } } : {}) }).said;}case "wear": {const [out, ...garments] = plain(rest);diff --git a/engine/cli/src/wardrobe.ts b/engine/cli/src/wardrobe.tsindex 568089d8..e32b0dfc 100644--- a/engine/cli/src/wardrobe.ts+++ b/engine/cli/src/wardrobe.ts@@ -79,13 +79,14 @@ function list(cwd: string) {return { garments: garments.map((g) => (g.kind === "sewn" ? { name: g.name, layer: g.layer, sewn: g.made ?? "" } : { name: g.name, layer: g.layer, vertices: g.vertices.length, over: g.over })) };}-function cover(raea: string, cwd: string, env: Env, a: { name: string; parts: string; colour: string; stand: number; over?: string }): Said {+function cover(raea: string, cwd: string, env: Env, a: { name: string; parts: string; colour: string; stand: number; over?: string; hard?: { sole?: number; soleColour?: string; panels?: 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] : [])]);+ const hard = a.hard ? ["--hard", ...(a.hard.sole !== undefined ? ["--sole", String(a.hard.sole)] : []), ...(a.hard.soleColour ? ["--sole-colour", a.hard.soleColour] : []), ...(a.hard.panels?.length ? ["--panels", a.hard.panels.join(",")] : [])] : [];+ 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] : []), ...hard]);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" };}diff --git a/tools/clothes/garment.py b/tools/clothes/garment.pyindex 1f3bf5d8..59beebb0 100644--- a/tools/clothes/garment.py+++ b/tools/clothes/garment.py@@ -4,7 +4,7 @@# colour there. (Sewn garments are tools/garments; garments measured from drawn pictures were taken out on 11-15.)## 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: the skin of the parts named (each limb as far along as its share), in one colour, so+# a garment by procedure: the skin of the parts named (each limb as far along as its share, from the end that joins the rest), 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@@ -15,6 +15,14 @@ from mathutils import Vector, kdtreefrom mathutils.bvhtree import BVHTreeargs = sys.argv[sys.argv.index("--") + 1:]+# a hard piece (cover --hard [--sole MM] [--sole-colour #RRGGBB] [--panels #RRGGBB,...]): footwear, which keeps its own+# shape instead of the skin's (see make_hard)+FLAGS = {}+for k_ in ("--sole", "--sole-colour", "--panels"):+ if k_ in args:+ i_ = args.index(k_); FLAGS[k_] = args[i_ + 1]; del args[i_:i_ + 2]+if "--hard" in args:+ args.remove("--hard"); FLAGS["--hard"] = Truemode, body_glb, rig_usd = args[:3]OFF, THICK = 0.004, 0.003 # least stand-off, a layer's own thickness (metres)@@ -70,6 +78,128 @@ def export(obj, path, also=()):bpy.ops.export_scene.gltf(**kw)+def make_hard(g, covered, stand_v):+ """A hard piece (footwear) as its own mesh, not the skin's: each foot's covered skin, stood off as the garment says,+ closed in its convex hull (the toes and the foot's small forms go under it: a cover laid on the skin kept them, so+ shoes read as bare feet, chars/teal's sneakers and chars/wren's boots, 11-16), remeshed even (the foot's own+ triangles bunch at the toes, and a sole's line across them came out in stripes), its top over the leg opened as+ the collar, its corners rounded. Under it a sole, flat and set out, in its own colour up the side; a toe cap, a heel+ and a band in the panels' colours. Skinned like the skin it covers (the nearest covered vertices' weights)."""+ hard, sole = g["hard"], g["hard"]["sole_m"]+ arm = next(o for o in bpy.data.objects if o.type == "ARMATURE")+ J = {b_.name: np.array(arm.matrix_world @ b_.head_local) for b_ in arm.data.bones}+ sk = bmesh.new(); sk.from_mesh(skin.data); sk.transform(W); skin_bvh = BVHTree.FromBMesh(sk); sk.free()+ base = tuple(float(x) for x in np.mean(g["colour_srgb"], axis=0))+ groups = [{gg.group: gg.weight for gg in v.groups} for v in me.vertices]+ out = bmesh.new(); uv = out.loops.layers.uv.new("UVMap"); pal = [base]; wts = []+ for side in ("Left", "Right"):+ foot, toe = J.get(side + "Foot"), J.get(side + "ToeBase")+ if foot is None or toe is None:+ continue+ other = J.get(("Right" if side == "Left" else "Left") + "Foot")+ idx = np.where(covered & (np.linalg.norm(co - foot, axis=1) < (np.linalg.norm(co - other, axis=1) if other is not None else 9)))[0]+ if len(idx) < 8:+ continue+ P = co[idx] + no[idx] * stand_v[idx, None]+ hb = bmesh.new()+ for p_ in P:+ hb.verts.new(Vector(p_))+ bmesh.ops.convex_hull(hb, input=list(hb.verts), use_existing_faces=False)+ bmesh.ops.delete(hb, geom=[v for v in hb.verts if not v.link_faces], context="VERTS")+ bmesh.ops.recalc_face_normals(hb, faces=list(hb.faces))+ tm = bpy.data.meshes.new("hull"); hb.to_mesh(tm); hb.free()+ to = bpy.data.objects.new("hull", tm); bpy.context.scene.collection.objects.link(to)+ rm = to.modifiers.new("even", "REMESH"); rm.mode = "VOXEL"; rm.voxel_size = 0.004+ em = bpy.data.meshes.new_from_object(to.evaluated_get(bpy.context.evaluated_depsgraph_get()))+ bpy.data.objects.remove(to); bpy.data.meshes.remove(tm)+ bm = bmesh.new(); bm.from_mesh(em); bpy.data.meshes.remove(em)+ bmesh.ops.triangulate(bm, faces=list(bm.faces))+ # the collar: the hull's top over the leg (faces facing up whose nearest skin is not covered) left open+ kd = kdtree.KDTree(n)+ for i in range(n):+ kd.insert(Vector(co[i]), i)+ kd.balance()+ bm.normal_update()+ cap = [f for f in bm.faces if f.normal.z > 0.2 and not covered[kd.find(f.calc_center_median())[1]]]+ bmesh.ops.delete(bm, geom=cap, context="FACES")+ bmesh.ops.delete(bm, geom=[v for v in bm.verts if not v.link_faces], context="VERTS")+ held = {v for v in bm.verts if v.is_boundary}+ for it in range(40): # its corners rounded (Taubin: no shrinking)+ lam = 0.5 if it % 2 == 0 else -0.53+ nxt = {v: v.co + (sum((e.other_vert(v).co for e in v.link_edges), Vector()) / len(v.link_edges) - v.co) * lam+ for v in bm.verts if v not in held and v.link_edges}+ for v, c in nxt.items():+ v.co = c+ for v in bm.verts: # never nearer the skin than 2 mm+ q, nq, _, _ = skin_bvh.find_nearest(v.co)+ if q is not None and (v.co - q).dot(nq) < 0.002:+ v.co = v.co + nq * (0.002 - (v.co - q).dot(nq))+ # the sole: the bottom laid flat a little below the bare foot (a thick sole all below it would sink the+ # person into the floor), set out a few millimetres, its colour a sole's thickness up the side+ z0 = float(np.percentile(co[idx, 2], 1))+ zb = z0 - min(sole, 0.008)+ ax = toe - foot; ax[2] = 0; ax /= np.linalg.norm(ax) + 1e-9+ mid = co[idx, :2].mean(0)+ for v in bm.verts:+ if v.co.z < zb + 0.006:+ v.co.z = zb+ if v.co.z < zb + 0.8 * sole:+ o_ = np.array(v.co[:2]) - mid; o_ /= np.linalg.norm(o_) + 1e-9+ v.co.x += o_[0] * 0.003; v.co.y += o_[1] * 0.003+ along = lambda p_: float((np.array(p_[:2]) - foot[:2]) @ ax[:2])+ al = [along(v.co) for v in bm.verts]; a0, a1 = min(al), max(al)+ tip = max(bm.verts, key=lambda v: along(v.co) - abs(v.co.z - (zb + sole + 0.02))).co.copy()+ heel = min(bm.verts, key=lambda v: along(v.co) + abs(v.co.z - (zb + sole + 0.03))).co.copy()+ pn = hard["panels_srgb"]+ cols = {}+ for f in bm.faces:+ c_ = f.calc_center_median(); h = c_.z - zb; t = (along(c_) - a0) / max(a1 - a0, 1e-6)+ if h < sole:+ cols[f] = hard["sole_srgb"]+ elif pn and (c_ - tip).length < 0.055:+ cols[f] = pn[0] # the toe cap+ elif len(pn) > 1 and (c_ - heel).length < 0.05:+ cols[f] = pn[1] # the heel+ elif len(pn) > 2 and 0.3 < t < 0.72 and abs(h - (sole + 0.012 + 0.05 * (t - 0.3))) < 0.009:+ cols[f] = pn[2] # a band along the side, rising to the heel+ # into the one mesh, with each vertex's weights: its nearest covered skin's, by inverse distance+ ck = kdtree.KDTree(len(idx))+ for k_, i in enumerate(idx):+ ck.insert(Vector(co[i]), int(i))+ ck.balance()+ vmap = {}+ for v in bm.verts:+ nv = out.verts.new(v.co); vmap[v] = nv+ near = ck.find_n(v.co, 4); w = {}+ for _, i, d in near:+ for gi, gw in groups[i].items():+ w[gi] = w.get(gi, 0.0) + gw / max(d, 1e-4)+ tot = sum(w.values()) or 1.0+ wts.append({gi: x / tot for gi, x in w.items()})+ out.verts.ensure_lookup_table()+ for f in bm.faces:+ nf = out.faces.new([vmap[v] for v in f.verts])+ c = tuple(cols.get(f, base))+ if c not in pal:+ pal.append(c)+ for l in nf.loops:+ l[uv].uv = ((pal.index(c) + 0.5) / 16, 0.5)+ bm.free()+ out.transform(W.inverted())+ mesh = bpy.data.meshes.new(g["name"]); out.to_mesh(mesh); out.free()+ for p_ in mesh.polygons:+ p_.use_smooth = True+ obj = bpy.data.objects.new(g["name"], mesh); bpy.context.scene.collection.objects.link(obj)+ obj.parent = skin.parent; obj.matrix_parent_inverse = skin.matrix_parent_inverse.copy(); obj.matrix_basis = skin.matrix_basis.copy()+ vg = [obj.vertex_groups.new(name=x.name) for x in skin.vertex_groups]+ for vi, w in enumerate(wts):+ for gi, x in w.items():+ if x > 1e-3:+ vg[gi].add([vi], x, "REPLACE")+ md = obj.modifiers.new("Armature", "ARMATURE"); md.object = arm+ return obj, pal++def wear(out_dir, garments):os.makedirs(out_dir, exist_ok=True)under = np.zeros(n, bool)@@ -78,37 +208,46 @@ def wear(out_dir, garments):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()+ if g.get("hard"):+ piece, pal = make_hard(g, covered, stand[cid])+ else:+ piece, pal = skin.copy(), None+ piece.data = skin.data.copy(); bpy.context.scene.collection.objects.link(piece)+ if pal is None: # (cut from the skin, stood off it)+ 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 colourif "views" in g["source"]:sys.exit(f"clothes: {g['name']} was measured from drawn pictures, which raea no longer wears: sew it (raea clothes make) or lay it on the skin (raea clothes cover)")tex, lo, hi = np.tile(np.mean(g["colour_srgb"], axis=0).astype(np.float32), (4, 4, 1)), np.zeros(2), np.ones(2)+ if pal: # (its colours: a palette of 16 cells, make_hard's)+ tex = np.ones((4, 64, 3), np.float32)+ for k, c in enumerate(pal[:16]):+ tex[:, k * 4:(k + 1) * 4] = cuvl = piece.data.uv_layers[0].datafor 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))@@ -160,7 +299,7 @@ def part_of(name):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+ says ("foreArm:0.5", the half nearest the elbow; "foot,shin:0.4", the shin's lower 40%), in one colour, standing off the skin by stand_m (and off thelayer beneath by a layer's thickness)."""want = {}for s in spec.split(","):@@ -168,6 +307,14 @@ def cover(out, spec, colour, stand_m, under=None):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++ # a limb partly covered is covered from the end that joins the rest of the garment: a sleeve's forearm from the+ # elbow (upperArm,foreArm:0.5), a sock's or a boot's shin from the ankle (foot,shin:0.4). Counted from the top+ # alone, chars/teal's socks covered his knees and left his ankles bare (11-16)+ below = {"thigh": "shin", "shin": "foot", "upperArm": "foreArm", "foreArm": "hand"}+ above = {"shin": "thigh", "thigh": "hips", "foreArm": "upperArm", "upperArm": "chest"}+ def from_below(p):+ return below.get(p) in want and above.get(p) not in wantarm = 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}@@ -182,7 +329,7 @@ def cover(out, spec, colour, stand_m, under=None):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]:+ if (t < 1.0 - want[p]) if from_below(p) else (t > want[p]):continuecovered[i] = Truefor _ in range(2): # the edge evened without wearing it away: a vertex changes only when two thirds of its neighbours differ@@ -201,6 +348,11 @@ def cover(out, spec, colour, stand_m, under=None):"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]}+ if FLAGS.get("--hard"):+ srgb = lambda h: [round(int(h.lstrip("#")[k:k + 2], 16) / 255, 4) for k in (0, 2, 4)]+ g["hard"] = {"sole_m": float(FLAGS.get("--sole", "10")) / 1000, "sole_srgb": srgb(FLAGS.get("--sole-colour", "#e8e2d4")),+ "panels_srgb": [srgb(h) for h in FLAGS["--panels"].split(",")] if FLAGS.get("--panels") else []}+ g["stray"] = [0.0] * len(ids) # (a hard piece does not swing)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")diff --git a/tools/garments/hide_under.py b/tools/garments/hide_under.pyindex 0c0ce1be..b5356688 100644--- a/tools/garments/hide_under.py+++ b/tools/garments/hide_under.py@@ -1,7 +1,12 @@-# The body with the skin wholly under cloth left out, so it can't poke through as it moves.+# The body with the skin wholly under cloth left out, so it can't poke through as it moves; and each garment with what+# lies wholly under the garments worn over it left out too (GARMENT.glb... innermost first, each rewritten in place):+# chars/teal's tee came through his open jacket in patches, both draped on the bare body (11-16); now the tee shows+# only where the jacket leaves it uncovered, its open front and below its hem.# raea blender run hide_under.py BODY.glb OUT.glb GARMENT.glb...# A body vertex is under cloth when a ray out along its normal meets a garment within REACH (6 cm); a face goes when-# its vertices and all their neighbours are under cloth (the edge of the cut stays, so no gap shows at a hem).+# its vertices and all their neighbours are under cloth (the edge of the cut stays, so no gap shows at a hem). A+# garment's vertex is under the garments outside it when a ray either way along its normal meets one within REACH+# (cloth's normals are not all outward); NO_LAYERS=1 leaves garments whole.import bpy, bmesh, sys, osfrom mathutils import Vectorfrom mathutils.bvhtree import BVHTree@@ -9,6 +14,7 @@ from mathutils.bvhtree import BVHTreea = sys.argv[sys.argv.index("--") + 1:]body_glb, out, garments = a[0], a[1], a[2:]REACH = float(os.environ.get("REACH", "0.06"))+CLOSE, LATERAL = 0.03, 0.002 # a garment under another: within 3 cm, straight under its facebpy.ops.wm.read_factory_settings(use_empty=True)bpy.ops.import_scene.gltf(filepath=body_glb)skin = max((o for o in bpy.data.objects if o.type == "MESH"), key=lambda o: len(o.data.vertices))@@ -39,3 +45,55 @@ for o in bpy.data.objects:o.select_set(o in keep and o.type in ("MESH", "ARMATURE"))bpy.ops.export_scene.gltf(filepath=out, export_format="GLB", use_selection=True, export_animations=False, export_yup=True, export_skins=True)print(f"hide_under: {len(gone)} of {total} faces under cloth left out: {out}")+++# the garments, each under the ones worn over it (innermost first: the last has nothing over it)+def load_mesh(path):+ before = set(bpy.data.objects); bpy.ops.import_scene.gltf(filepath=path)+ return [o for o in set(bpy.data.objects) - before]+++if os.environ.get("NO_LAYERS") != "1":+ for k, gpath in enumerate(garments[:-1]):+ bpy.ops.wm.read_factory_settings(use_empty=True)+ mine = load_mesh(gpath)+ cloth = max((o for o in mine if o.type == "MESH"), key=lambda o: len(o.data.vertices))+ ob = bmesh.new()+ for opath in garments[k + 1:]:+ for o in load_mesh(opath):+ if o.type == "MESH":+ t = bmesh.new(); t.from_object(o, bpy.context.evaluated_depsgraph_get()); t.transform(o.matrix_world)+ m = bpy.data.meshes.new("t"); t.to_mesh(m); t.free(); ob.from_mesh(m)+ bpy.data.objects.remove(o)+ elif o.type != "ARMATURE":+ bpy.data.objects.remove(o)+ tree = BVHTree.FromBMesh(ob)+ W = cloth.matrix_world; N = W.to_3x3()+ bm = bmesh.new(); bm.from_mesh(cloth.data); bm.verts.ensure_lookup_table()+ under = [False] * len(bm.verts)+ for v in bm.verts:+ p = W @ v.co; nrm = (N @ v.normal).normalized()+ # met along its normal, or lying close (within CLOSE) under or over a garment over it: layered cloth all+ # but touches, and at a shoulder the normal points up past a sleeve beside it (11-16: 3,129 of chars/teal's+ # tee's vertices within 2 cm of his jacket, 1,667 met along their normals). Under or over its face, not+ # past its edge: the nearest point on it is straight across (off to the side by under LATERAL), where past+ # an open front, a hem or a cuff it is the edge, off to the side. (A distance from the edges kept a band of+ # tee along the jacket's open front that came through it in white flecks, at 8 mm as at 1.5 cm)+ hit = any(tree.ray_cast(p + d * nrm * 0.0005, d * nrm, REACH)[0] is not None for d in (1, -1))+ if not hit:+ q, nq, _, _ = tree.find_nearest(p, CLOSE)+ if q is not None:+ off = p - q+ hit = (off - off.dot(nq) * nq).length < LATERAL+ under[v.index] = hit+ # (a face under the garment over it goes when its own corners are under: kept to the skin's rule, all their+ # neighbours too, a ring of tee was left round each hidden patch and came through the jacket in specks)+ gone = [f for f in bm.faces if all(under[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(cloth.data); bm.free()+ for o in bpy.data.objects:+ o.select_set(o in mine and o.type in ("MESH", "ARMATURE"))+ bpy.ops.export_scene.gltf(filepath=gpath, export_format="GLB", use_selection=True, export_animations=False, export_yup=True, export_skins=True)+ print(f"hide_under: {os.path.basename(gpath)}: {len(gone)} of {total} faces under the garments over it left out")diff --git a/tools/garments/outfit.py b/tools/garments/outfit.pynew file mode 100644index 00000000..c1582481--- /dev/null+++ b/tools/garments/outfit.py@@ -0,0 +1,200 @@+# An outfit from words: the clothes in a character's description ("a long mustard-yellow oilskin coat to the knee,+# worn open, over a navy cable-knit jumper with a roll neck; dark brown wool trousers; black rubber boots to+# mid-calf") as the garments `raea clothes` makes, innermost first, each with how it is made.+#+# python3 outfit.py "WORDS" [--prefix NAME] -> JSON on stdout: {"garments": [...], "unread": [...]}+#+# Each garment is {"name", "kind", "words", "colour" (#rrggbb), "layer", "verb"} and, by its verb:+# make sewn from a pattern (CH47a): "set" holds the settings (paths as `raea clothes settings` lists them), on+# GarmentCode's plain base. The words model (CH48c) is not asked: measured, it is a first guess ("straight+# trousers" came out culottes, a turtleneck brought trousers along), so a garment named here is cut from+# the settings its words call for, and the words are kept with it+# cover laid on the skin by procedure (`raea clothes cover`): "parts" (a limb's share is how far down it from its+# top) and "stand" (mm off the skin). Footwear and socks: a shoe is not sewn+# A clause with no garment word this knows is returned in "unread", never guessed.+#+# What words do: the garment's noun picks its kind (the table below); a colour before the noun (a "with ..." clause+# is the garment's trim and does not colour it) picks its colour; length words ("to the knee", "long", "cropped",+# "to mid-calf", "ankle") and neck words ("roll neck", "crew-neck", "v-neck", "hood") change its settings. "X over+# Y" is two garments, Y under X; "worn open" is noted on the garment (GarmentCode cuts no open front: the outer+# top gets a deep V neck to its hem, the nearest the patterns come).+import json, re, sys++COLOURS = { # sRGB; a compound ("olive-green", "mustard-yellow") is looked up whole first+ "white": "#f0efea", "cream": "#ece3cf", "ivory": "#eee8d6", "black": "#1d1d20", "grey": "#85868a", "gray": "#85868a",+ "silver": "#b8b9bd", "charcoal": "#3b3c40", "navy": "#1f2a46", "blue": "#2f5ea8", "indigo": "#2a3352",+ "denim": "#3d5578", "teal": "#2a8a8a", "green": "#3f6b3a", "olive-green": "#5d6238", "olive": "#5d6238",+ "khaki": "#a99c6c", "mustard-yellow": "#cf9d22", "mustard": "#cf9d22", "yellow": "#e3c13a", "orange": "#e0702c",+ "red": "#b5322c", "burgundy": "#6d2230", "pink": "#e39aa8", "purple": "#5e3f86", "brown": "#6a4a30",+ "tan": "#b48f66", "beige": "#d6c3a2", "camel": "#bf9762", "rust": "#a5502a",+}+SHADES = {"dark": 0.6, "deep": 0.65, "light": 1.35, "pale": 1.45, "bright": 1.1}++# kind: (nouns, verb, layer, settings or cover). On SOMA, shirt.length 1.2 ends at the ribs (a crop top: the first+# tees, 11-16), 1.6 to 1.7 at the hip, 3.0 at the knee. Layer: 0 next to the skin (socks), 1 tops and bottoms, 2 footwear,+# 3 outer tops. A noun is matched whole, the longest first+KINDS = [+ ("socks", ["tube socks", "socks", "stockings"], "cover", 0, {"parts": "toes,foot,shin:0.35", "stand": 0.5}),+ ("tee", ["t-shirt", "tee", "tshirt", "vest top", "tank top"], "make", 1,+ ["meta.upper=FittedShirt", "sleeve.length=0.3", "shirt.length=1.65", "shirt.width=1.05"]),+ ("shirt", ["shirt", "blouse", "polo"], "make", 1, ["meta.upper=Shirt", "sleeve.length=1.05", "shirt.length=1.7"]),+ ("jumper", ["jumper", "sweater", "pullover", "sweatshirt", "hoodie", "cardigan"], "make", 1,+ # (no cuff band: GarmentCode's is a tube narrower than SOMA's forearm, which slid off and split the sleeve+ # open on chars/wren's jumper, as on CH48c's shirt)+ ["meta.upper=Shirt", "sleeve.length=1.05", "shirt.length=1.7", "shirt.width=1.1", "sleeve.end_width=0.65"]),+ ("trousers", ["trousers", "jeans", "pants", "chinos", "slacks", "joggers", "leggings"], "make", 1,+ ["meta.upper=none", "meta.bottom=Pants", "meta.wb=StraightWB", "pants.length=0.85", "pants.width=1.05"]),+ ("shorts", ["shorts"], "make", 1, ["meta.upper=none", "meta.bottom=Pants", "meta.wb=StraightWB", "pants.length=0.3", "pants.width=1.1"]),+ ("skirt", ["skirt"], "make", 1, ["meta.upper=none", "meta.bottom=PencilSkirt", "meta.wb=StraightWB", "pencil-skirt.length=0.5"]),+ ("boots", ["boots", "wellingtons", "wellies"], "cover", 2, {"parts": "toes,foot,shin:0.25", "stand": 4}),+ ("shoes", ["sneakers", "trainers", "shoes", "loafers", "brogues", "sandals"], "cover", 2, {"parts": "toes,foot", "stand": 5}),+ ("coat", ["coat", "overcoat", "raincoat", "parka", "mac", "trench"], "make", 3,+ ["meta.upper=Shirt", "sleeve.length=1.1", "shirt.length=2.6", "shirt.width=1.2", "shirt.flare=1.15", "sleeve.end_width=0.75"]),+ ("jacket", ["field jacket", "bomber jacket", "jacket", "blazer", "bomber", "overshirt", "anorak"], "make", 3,+ ["meta.upper=Shirt", "sleeve.length=1.1", "shirt.length=1.8", "shirt.width=1.2", "sleeve.end_width=0.7"]),+]+NOUNS = sorted(((n, k) for k in KINDS for n in k[1]), key=lambda x: -len(x[0]))+++def colour_of(text):+ """the first colour named, with a shade word before it ("dark indigo"), as #rrggbb; None if there is none"""+ t = text.lower()+ found = []+ for name in sorted(COLOURS, key=len, reverse=True):+ for m in re.finditer(r"(?<![a-z-])" + re.escape(name) + r"(?![a-z-])", t):+ if not any(a <= m.start() < b for a, b, _ in found):+ found.append((m.start(), m.end(), name))+ if not found:+ return None+ a, _, name = min(found)+ rgb = [int(COLOURS[name][i:i + 2], 16) for i in (1, 3, 5)]+ before = t[:a].split()[-1:] or [""]+ k = SHADES.get(before[0], 1.0)+ return "#" + "".join(f"{max(0, min(255, round(c * k))):02x}" for c in rgb)+++def garment(clause, prefix, used):+ """one garment from a clause naming one, or None"""+ low = clause.lower()+ hit = None+ for noun, k in NOUNS:+ m = re.search(r"(?<![a-z])" + re.escape(noun) + r"(?![a-z])", low)+ if m and (hit is None or m.start() < hit[0]):+ hit = (m.start(), noun, k)+ if hit is None:+ return None+ at, noun, (kind, _, verb, layer, spec) = hit+ body = low.split(" with ")[0] if " with " in low[:at + len(noun) + 1] or " with " not in low else low+ head = low[:at + len(noun)] # the colour is named before the noun+ col = colour_of(head) or colour_of(body) or "#8a8a8a"+ name = f"{prefix}-{kind}" if prefix else kind+ n = 2+ while name in used:+ name = f"{prefix}-{kind}{n}" if prefix else f"{kind}{n}"; n += 1+ used.add(name)+ g = {"name": name, "kind": kind, "words": clause.strip(), "colour": col, "layer": layer, "verb": verb}+ notes = []+ if verb == "make":+ s = dict(x.split("=", 1) for x in spec)+ if re.search(r"\bto the knee\b|knee-length|\blong\b", low) and kind in ("coat", "jacket", "shirt", "jumper"):+ s["shirt.length"] = "3.0" if kind == "coat" else "2.2"+ if re.search(r"\bcropped\b|\bshort\b", low) and kind in ("jacket", "jumper", "shirt", "tee"):+ s["shirt.length"] = "1.25"+ if kind == "jacket" and "bomber" in low:+ s["shirt.length"] = "1.5"+ if kind in ("trousers",) and re.search(r"\bslim\b|\bskinny\b", low):+ s["pants.width"] = "1.0"+ if kind in ("trousers",) and re.search(r"\bwide\b|\bbaggy\b|\bloose\b", low):+ s["pants.width"] = "1.35"+ if re.search(r"roll[- ]neck|turtle[- ]?neck|polo[- ]neck", low):+ # GarmentCode's Turtle collar falls in on itself in the drape (CH48c; chars/wren's jumper, 11-16): a high+ # round neck until the drape holds one up+ s["collar.f_collar"] = "CircleNeckHalf"; s["collar.fc_depth"] = "0.3"+ notes.append("roll neck made as a high round neck (a Turtle collar collapses in the drape)")+ if re.search(r"v[- ]neck", low):+ s["collar.f_collar"] = "VNeckHalf"+ if re.search(r"\bhood(ed|ie)?\b", low):+ s["collar.component.style"] = "Hood2Panels"+ if re.search(r"short[- ]sleeved?", low):+ s["sleeve.length"] = "0.3"+ if re.search(r"long[- ]sleeved?", low):+ s["sleeve.length"] = "1.05"+ if re.search(r"\b(worn )?open\b|\bunbuttoned\b|\bunzipped\b", low) and layer == 3:+ s["collar.f_collar"] = "VNeckHalf"; s["collar.fc_depth"] = "2"+ notes.append("worn open: a deep V to the hem (GarmentCode cuts no open front)")+ g["set"] = [f"{k}={v}" for k, v in s.items()]+ else:+ c = dict(spec)+ if kind == "boots":+ if re.search(r"\bankle\b", low):+ c["parts"] = "toes,foot,shin:0.15"+ elif re.search(r"mid[- ]calf", low):+ c["parts"] = "toes,foot,shin:0.5"+ elif re.search(r"\bknee\b", low):+ c["parts"] = "toes,foot,shin:0.95"+ if kind == "socks" and re.search(r"\btube\b|\bknee\b", low):+ c["parts"] = "toes,foot,shin:0.45"+ if kind in ("boots", "shoes"):+ # footwear is a hard piece (`raea clothes cover --hard`): its own shape on a last, a sole under it; a+ # chunky or platform sole is thicker, a boot's rubber or a sneaker's sole its own colour, and the panels+ # named ("with blue, yellow and red panels") a toe cap, a heel and a band in that order+ c["hard"] = True+ c["sole"] = 30 if re.search(r"\bchunky\b|\bplatform\b|\bthick[- ]soled\b", low) else 22 if kind == "shoes" and re.search(r"sneaker|trainer", low) else 12+ if re.search(r"sneaker|trainer", low):+ c["sole_colour"] = "#f4f1ea"+ elif re.search(r"rubber|welly|wellies|wellington", low):+ c["sole_colour"] = "#262422"+ pm = re.search(r"with ([a-z ,]+?) (?:panels|stripes|accents)", low)+ if pm:+ cs = [colour_of(w) for w in re.split(r",\s*|\s+and\s+", pm.group(1))]+ c["panels"] = [x for x in cs if x]+ g.update(c)+ trims = re.findall(r"with (.+)$", re.sub(r"\s+worn open$", "", clause.strip()), flags=re.I)+ made = r"roll[- ]neck|turtle[- ]?neck|polo[- ]neck|v[- ]neck|hood|crew[- ]neck"+ if trims and not re.fullmatch(r"(an? )?(" + made + r")", trims[0].strip().lower()) and not g.get("panels"):+ notes.append("trim not made yet: " + trims[0])+ if notes:+ g["notes"] = notes+ return g+++def outfit(text, prefix=""):+ # sentences, then clauses; "X over Y" is two garments+ clauses = []+ for part in re.split(r";|\.(?:\s|$)", text):+ part = part.strip()+ if not part:+ continue+ bits = re.split(r",?\s+(?:worn\s+(?:open\s+)?)?over\s+", part)+ if len(bits) == 2 and all(any(re.search(r"(?<![a-z])" + re.escape(n) + r"(?![a-z])", b.lower()) for n, _ in NOUNS) for b in bits):+ open_ = re.search(r"\bopen\b", part.lower()) is not None+ outer = bits[0] + (" worn open" if open_ and "open" not in bits[0].lower() else "")+ clauses += [bits[1], outer]+ else:+ clauses.append(part)+ used, out, unread = set(), [], []+ for c in clauses:+ # a clause naming several garments by commas ("dark jeans, brown boots") is split at its commas+ sub = [c]+ if sum(1 for n, _ in NOUNS if re.search(r"(?<![a-z])" + re.escape(n) + r"(?![a-z])", c.lower())) > 1 and " with " not in c.lower():+ sub = [s for s in re.split(r",\s*(?:and\s+)?|\s+and\s+", c) if s.strip()]+ for s in sub:+ g = garment(s, prefix, used)+ if g:+ out.append(g)+ elif s.strip():+ unread.append(s.strip())+ out.sort(key=lambda g: g["layer"])+ # footwear laid on the skin goes over socks laid on it (`raea clothes cover --over`)+ socks = [g["name"] for g in out if g["kind"] == "socks"]+ for g in out:+ if g["verb"] == "cover" and g["kind"] in ("boots", "shoes") and socks:+ g["over"] = socks[-1]+ return {"garments": out, "unread": unread}+++if __name__ == "__main__":+ a = sys.argv[1:]+ prefix = a[a.index("--prefix") + 1] if "--prefix" in a else ""+ words = [x for i, x in enumerate(a) if x != "--prefix" and (i == 0 or a[i - 1] != "--prefix")]+ print(json.dumps(outfit(" ".join(words), prefix), indent=1))