FERRETGame engine over Babylon.js
Ferret

Clothes

@ferret/clothing dresses any skinned character the way clothes are made: garments are cut from flat patterns by a tailor's rules, sewn along their seams off the body into one closed cloth, put on the body and left to settle under their weight against the body and the garments under them. Then they get the body's skin weights, so they move with every animation, and textures made at the real scale of their threads, with the stitching drawn where the seams are. Nothing in the module knows a particular character: the patterns are drafted from the body's own measurements.

The rebuild "clothes made the way a tailor makes them" is described in plans/PLAN-CLOTHING-TAILOR.md. This page says what is built and checked by tests now, and marks what is still in progress. A line status: in progress below means that nothing is promised about the part beyond what the code does today.

The steps#

stepwhat it doesAPI
bodya skinned mesh in its bind pose: positions, triangles, skin, joint names and positionsbodyFromMesh(mesh) (Babylon), or build a ClothingBody
measuregirths (neck, chest, waist, seat, thigh, knee, calf, ankle, upper arm, wrist, head), heights, shoulder width, arm lengthmeasureBody(body); the figure (bust, underbust, apexes, proportions of a child): bodyFit (fit.ts)
drafta garment's panels, seams, supports, tacks (buttons), trims, cloth values, from the measurements and a style, cut by the rules belowblocks: trousers, jersey, jacket, cap, neckerchief, shirt, tshirt, waistcoat, coat, cloak, hoodie, skirt, shorts, breeches, dress, hat, beanie; gloves(body, style) and boots(body, style) build meshes on the hand and foot
sewthe pieces joined off the body in the tailor's order into one closed clothsewGarment(garment, options)
drapethe garment put on the body and settled; layers dressed inner to outerdrape(body, garments, { h, frames }) (the old way, see "Putting on")
weightsevery cloth vertex takes the skin of the body surface under it, smoothed along the clothtransferSkin(body, dressed)
hidden bodythe body triangles every garment covers well inside its edgeshiddenBody(body, dressed)
texturesthe panels packed in an atlas; the fabric's colour, relief and roughness at its thread scale; seams, hems, buttonholesbakeGarment(dressed, { fabrics })
trimsbuttons (horn, brass with an anchor), a cap's peak, riding the clothtrimsOf(dressed)
footwearlaced boots built on a last taken from the body's foot: sole, heel, upper, shaft, tongue, eyelets, lacesboots(body, style)
storean outfit dressed once is stored by the content of its inputoutfitKey, OutfitStore, dressCached
motionfree cloth simulated on the animated body, or baked per clipClothMotion, ClothMotionService, bakeClip

Patterns and the cutting rules#

A Panel is a closed chain of named edges in metres (x across, y along the grain), with a place (the old wrapping, see below) and a grain: the angle in radians from the panel's y axis to the warp (0 for a body panel, pi/2 for a band cut lengthwise, pi/4 for a bias cut that drapes and stretches round a curve). A knit's grain is its wales. stiff on a panel is the bending multiplier of an interfaced piece. A Seam joins two edges (each may run reversed); hinge seams fold flat (a lapel turned back on its front, a collar's fall over its stand); stage orders the sewing. tacks hold a point of one panel over a point of another (buttons). over lists panels lying over panels of the same garment (a front buttoned over the other).

The blocks do not carry numbers tuned for an outfit. A block states what the garment is (its fitting, its sleeve, its kind of support) and the rules of blocks/ease.ts give the numbers (all exported from @ferret/clothing):

  • Ease by kind. ease(fitting, fit?) (fit.ts) gives the metres of girth over the body at the bust, waist and hip for a fitting: skin 0, close 0.03/0.02/0.03, fitted 0.06/0.04/0.05, comfortable 0.10/0.08/0.08, loose 0.16/0.14/0.12, oversized 0.26/0.26/0.20; a child's figure gets a little more (childness).
  • Ease by layer. A garment worn over others is cut over them: underThickness(under) is the radial thickness of everything under it (numbers in metres, or the garments, whose cloth.thickness is used); the girth it adds is layerGirth(t) = 2 pi t (1 + LAYER_BULK) (layers do not squeeze to nothing: a layer takes its thickness and half as much again). Every block takes under. No layer is corrected after the fact.
  • upperEases({ fitting, kind, fit?, t?, chest?, sleeve?, cloth?, sleeveless? }) gives the chest ease (the fitting's bust ease plus the layer girth, or the explicit chest), the upper-arm ease (4 cm of movement plus 0.6 of the chest ease), the ease at the sleeve end for a plain hem, a band cuff (0.06) and a rib cuff (0.05), the setting ease and the armhole drop.
  • Sleeve cap = armhole + setting ease. capCrown(armholeFront, armholeBack, ...) (parts/sleeves.ts) cuts the cap longer than the armhole it goes in by the setting ease: settingEase(sleeve, cloth) is 0 for a knit and for sleeves with no cap (raglan, drop, kimono, none), and for a set-in sleeve in a woven cloth 2.5 % for a light one, 3.5 % for a medium one, 5 % for a heavy woollen (by cloth.density below 0.3, below 0.5, 0.5 and above). The cap is eased in, as by steaming and a row of gathering stitches.
  • Armhole depth. armholeDrop(kind, thickness, sleeveless) is 0.04 m for a sleeveless garment, 0.02 m for a hung one, nothing for a fitted one, and 5 times the thickness of the layers under it.
  • Darts. darts(m, 'fitted' | 'semi' | 'shift' | 'none', { fit, easeBust, easeWaist, easeHip, region }) (fit.ts) makes the bust and waist darts from the figure (bodyFit: bust girth and height, apexes, underbust, bust-to-waist and hip-to-waist shaping); the dress, the skirt and the fitted upper garments take their darts from it.
  • Grain. Each panel carries its grain; a fabric's stretch and bending are taken along it (see "Fabric physics").
  • Interlining. INTERLINING (blocks/ease.ts) gives the bending factor of a stiffened piece: collar stand 4, collar fall 6, lapel 3, waistband 4, cuff 3, brim 250, band 2, flap 2, facing 2, crown 40.

Supports and stiff pieces#

Every block states Garment.support (Support): kind, pinned lines, stiff pieces and optional zones.

kindwhat holds itgarments
fittedthe whole surface rests on what is under itT-shirt, shirt, bodice, jersey, a close dress
hungthe shoulder line and the collar stand hold it, the closure holds the fronts, the rest fallscoat, jacket, cape, loose shirt
waistthe waistband holds it; hips and legs only stop itskirt, trousers, shorts, breeches
head, hand, foota hat on the head, a glove on the hand, a boot on the foothats, gloves, boots

kind is a HoldKind. supportKindFor(fitting) gives hung for loose and oversized and fitted otherwise. A PinnedLine names a panel and an edge and a role (shoulder, neck, collar, waist, closure, band, cuff, brim, hem). A StiffPiece names a panel (or a strip of depth metres along an edge, as a waistband cut in one with the trouser panels), the bend multiplier and what it is (collar stand, collar fall, lapel, waistband, cuff, brim, band, flap, facing, crown). zones give parts a different kind (a dress: the skirt hangs from the waist seam, the bodice rests). The helpers the blocks use: supportOf, upperPinned, waistSupport.

Fabric physics#

weave.ts: the physical cloth model per fabric, SI units, from Kawabata and FAST ranges (the file lists the sources and marks the rough entries). fabricPhysics(name) gives a FabricPhysics for a catalogue fabric (PHYSICS_FABRICS lists them: wool serge, tweed, flannel, melton, cotton shirting, denim, canvas, linen, silk, satin, velvet, jersey knit, rib knit, leather, felt, corduroy; an unknown name throws): mass per area, stretch (strain per N/m along the warp, the weft and the bias), shear stiffness, bending rigidity (warp and weft), friction (against skin and against cloth), thickness, air drag.

  • stretchAlong(p, theta): the tensile compliance along a direction at theta from the warp (exact at 0, 90 and 45 degrees).
  • triangleCompliances(p, grainDir, flat): for one flat triangle of the pattern, the XPBD compliance of each edge by its angle to the grain and the shear compliance: a woven cloth barely stretches along its threads and gives on the bias, a knit stretches across.
  • bendCompliance(p, interlining): the bending compliance with an interlining (none, fusible 3, canvas 8, stiff 25, or a factor); bendRigidityAt(c, theta) is the rigidity of a fold along an edge at theta to the warp; hingeStiffness(rigidity, l, a1, a2) is the dihedral stiffness of one hinge.

Sewing off the body#

sewGarment(garment, options) (sew.ts) joins the pieces of a garment into one closed cloth that has its own shape. No body is present: no collision, nothing shrunk, no seam closes round a limb. The pieces start laid out round the garment's own form (tubes along the axes the pattern names, girth from the pieces' own widths); the seams close stage by stage on the free cloth.

  • Order of the seams. seamRank(seam, transverse): a seam's own stage when it has one, else by what it is: darts, pleats, tucks and gathers first (-2), shoulders (-1), body seams (0), sleeves into armholes (1), collars, bands, cuffs, welts, facings, waistbands, necks (2), hinges (a collar's fall, a lapel's roll) last (3).
  • Welded nodes. After each stage the paired vertices of its closed seams become ONE node of the solver, so a corner where three or four pieces meet is one point that is never moved apart again; the cloth is then relaxed (relaxFrames, relaxPasses).
  • Supports. supportsOf(garment, extra) lists the lines where the garment is held: a list of SupportSpec in the garment's support when it has one; otherwise its hold edges, the shoulder seams and the collar panel's edges (the Support object of the blocks is not read by sewGarment yet). The result's supports are vertex lists by name and role; SewOptions.supports adds lines.
  • Result SewnGarment: positions, normals, flat (the UVs at the real scale), indices, panelOf, weld, groups, edgeVerts (vertices along each panel.edge), seams (SewnSeam: the paired vertices and the widest gap before the weld), supports, stages, stats (maxGapBeforeWeld, maxStretch, frames). Options: h, frames, substeps, passes, seamPasses, relaxFrames, relaxPasses, supports, onStage, log.

Putting on#

status: in progress, see plans/PLAN-CLOTHING-TAILOR.md

The sewn garment placed over the body (and the layers already on it) at its supports and let go under gravity with a real collision is the plan's step 5 (dress.ts, lane D); there is no such function in the package yet. The collision core (vertex against triangle, edge against edge, continuous, layer side, self-collision; collide.ts: CollisionWorld, SelfCollider, ContactSet) is being written and tested and is not yet what ClothSim uses.

Until then the only way to put garments on is the old one: drape(body, garments, { h, frames }) wraps the panels on tubes round the body, sews them on a shrunk ("thin") body and corrects the result with post passes. Old way, to be removed (plan step 6). The per-outfit switches it reads are collected in packages/clothing/OLD-SWITCHES.md and src/blocks/old-switches.ts; Garment.hold and Placement belong to it.

The outfit cache and the store#

An outfit dressed once on a body is stored and never dressed again for the same input (cache.ts, all exported). The store lives in the game (its own folder, later its own Ferret package); the engine and the library keep none. The module gives the generation and the record format; the tool is tools/clothing/store.mjs (see tools/clothing/README-store.md).

  • Key. outfitKey({ body, garments, fabrics, options }) is a SHA-256 (64 hex) over the body (mesh, skin, joints, rig hints), the drafted garments, the fabrics, the options and CLOTHING_CORE_VERSION. No time, no file dates; the order of object keys does not matter, any value change does; a function inside the input throws. bodyKey(body) is the body's part.
  • Rule of the core version. Every change that can change a dressed result (sim, drape, sew, collision in body.ts, transfer.ts, fabric.ts, trims.ts, footwear.ts, the record layout) bumps CLOTHING_CORE_VERSION in cache.ts by one, in the same commit. When unsure, bump.
  • Record. OutfitRecord in a .fout file (encodeOutfit, decodeOutfit; layout in OUTFIT_RECORD_FORMAT): per garment the positions, normals, uv, indices, skin, panel of each vertex, edge vertex lists, hems, baked textures, material; trims and boots meshes; hidden-body masks per LOD; baked cloth animation per clip and garment (setAnim, getAnim, listAnims); meta. Build the parts with garmentRecord(dressed, { skin, uv, texture }) and trimRecord(trim, garmentName, skin); sameOutfit(a, b) compares.
  • Store. OutfitStore(backend): get, put, has, list, drop, and the character map: assign(characterId, outfitId, key, fit), forCharacter(characterId, outfitId) giving { key, fit }, loadFor(...) (the entry and its record), assignments(), dangling(), unassign, addAnim. Ids are opaque strings; fit is plain JSON the maker chooses. Backends: MemoryBackend, FolderBackend(io), PackageBackend(packageSource) (read only, files under outfits/).
  • dressCached(body, garments, options, store, dress): a hit returns the record; a miss calls the dress(input) you give, stores and returns { key, record, hit }. Two calls for one key at once dress once; a read-only store that misses throws.
  • The tool node tools/clothing/store.mjs build <list.mjs> <dir> dresses what is not stored and writes the map; list <dir> shows records and the map (dangling entries exit 1); verify <list.mjs> <dir> checks that the stored keys match and that re-dressing gives the same bytes; pack <dir> <out.ferret> --id <id> [--folder] makes a package the game opens with new OutfitStore(new PackageBackend(await zipSource(bytesSource(bytes)))). list.mjs is the game's own file.

Cloth in motion#

motion.ts. A dressed garment can move with the animation in two ways, both made by the same ClothMotion.

Simulated while the game runs. new ClothMotion(garment, body, options): vertices at one place (the two sides of a seam) are one particle. Which part follows the skin rigidly and which is free is chosen by the support kind (SupportKind: fitted, hung, waist, free; taken from garment.support when it has one): fitted follows the skin everywhere; hung and waist hold the cloth within rigid metres (0.04, 0.03 for waist) of the supports along the cloth and let the rest fall, with a smooth band (0.08) between; the free band follows the bones of the nearest held particle (a skirt follows the waist, not the thigh it passes). An explicit driven list or supports (vertex indices) wins. Options: skin, density, stretch, bend (the garment's own cloth values are used otherwise), damping, gravity, thickness, friction, substeps (6), budget, maxStretch (1.1), reach (0.06), under (collider surfaces of the layers under: asCollider() of another ClothMotion), fadeTime (0.5 s). step(mats, dt) takes the skinning matrices (16 per joint) and returns the cloth; the body is collided as posed now. Levels of detail: setDetail(0 | 1 | 2): 0 skinned only (costs nothing), 1 simulated with half the substeps, 2 full; a change blends over fadeTime. cost() is links times substeps; setBudget(b) caps it (fewer substeps, 2 at least). Helpers: freeIndices(), maxStretchNow(), skinnedPositions(mats), reset().

In the world. ClothMotionService (name clothing-motion) moves the garments ClothingService has dressed on an entity each fixed step. Budget and distances set the detail: the nearest garments within near metres (12) of viewer() are simulated in full until the budget of free vertices (budget, 4000) is spent, those within far (30) at level 1, the rest are skinned only. Commands:

commandarguments
clothing.motion.start{entity, garments?, options?}: the entity must be dressed (clothing.dress first)
clothing.motion.stop{entity}: the garments stay skinned
clothing.motion.set{budget?, near?, far?, enabled?}
clothing.motion.statsper garment: free vertices, detail, substeps, the longest stretch, distance
clothing.motion.reset{entity?}: start the cloth over from the skinned pose

status: in progress, see plans/PLAN-CLOTHING-TAILOR.md. The collision the motion uses is today ClothSim's (a vertex against the nearest plane of the surface, with a thickness); it changes to the new collision core when that is in. The supports follow the bones through the skin weights.

Baked per clip. bakeClip(garment, body, clip, options) (bake.ts) runs the same simulation over an animation clip and stores the cloth of every frame; playing it back needs no simulation. clipPoseSource(body, clipJson, rest) makes the pose source from a clip of @ferret/animation. Options: fps (it must divide 60; default 30), motion (the MotionOptions), warmCycles (3) and warmHold (60), loopBlend (0.3 s: the start of a loop is blended into the continuation of its end so the loop closes), garmentName, clipName, onFrame. A BakedCloth stores only the vertices that are not rigid (active), each frame as the offset from the rest position in the bind pose, quantised to 16 bits with one scale (a skirt of 2000 free vertices over a 1 s walk at 30 fps is about 360 kB). sampleBakedCloth(baked, time, rest, out) gives the bind-pose positions at time (two frames blended; a loop wraps, a clip that does not loop holds its last frame): put them in the garment mesh's vertex buffer while the skeleton plays the same clip. serializeBakedCloth and parseBakedCloth give the bytes; the outfit record keeps them per clip (setAnim).

The regression set#

tools/clothing/regress (README there). Run it before and after every change of the clothing core; outputs go to D:\temp\clothing\regress\<tag>\<case>\. 17 cases: the five outfits of the Take 37 game and the gallery (tools/clothing/gallery.mjs) on four bodies in sets A, B, C.

node tools/clothing/regress/run.mjs <case|a,b,c|all> [--tag t] [--lod 1] [--full] [--no-render] [--no-walk] [--resume] [--cache]
node tools/clothing/regress/compare.mjs <tagA> <tagB> [--garments]
node tools/clothing/regress/sheet.mjs <tag>

Metrics per garment and per outfit (A pose): seamGapMm, clothInBody, skinThrough, layerThrough, spikes, hemRmsMm, hemP95Mm, foldsRmsMm, foldsP95Mm, foldsMaxMm, tris, verts, timeApproxS, dressS. Views: front, side, back, torso, torso back, waist, feet, neck, and three walk frames (phases 0.1, 0.4, 0.7). Acceptance with no per-outfit switch: widest seam gap under 10 mm; clothInBody + skinThrough + layerThrough = 0 in the A pose and in the walk frames; spikes = 0; even hems and cuffs; folds from the cut and the weight; the jacket over the shirt with lapels, collar and buttons in place; fabrics without a glossy grid. The metrics are the A pose; the walk frames are looked at by eye. One case takes 5-10 minutes of one core and 1-2 minutes of GPU renders: run one at a time, at low priority, on the RTX 3050 (the runner stops if the renderer string has none).

Any skeleton#

mapRig(jointNames, jointPositions, jointParents, hint?, map?) finds the bone roles (pelvis, spine, neck, head, clavicle, upper arm, forearm, hand, thigh, calf, foot, ball, per side) from the names of MetaHuman/UE, Mixamo and Character Creator, or from the shape of the skeleton when the names are unknown; map overrides by hand. Nothing else reads bone names.

Parts and descriptions#

The upper garments are assembled from parts (src/parts): sleeves (set-in, raglan, drop, kimono, short, none), collars (band, stand, shirt, notched, peaked, shawl, hood), closures (single, double, zip, pullover, wrap), pockets (patch, flap, welt, kangaroo), hems. describe(text | json) turns "a long single-breasted wool overcoat with notched lapels" into blocks, styles and fabrics (FABRICS: serge, tweed, flannel, melton, shirting, denim, canvas, linen, silk, velvet, knits, leather, felt, corduroy, satin). Women's and children's cuts use bodyFit and darts (fit.ts).

Commands#

commandarguments
clothing.blocksthe blocks by name
clothing.measure{entity, mesh?}: the measurements of the entity's skinned body
clothing.dress{entity, garments: [{block, style?}], fabrics, h?, frames?, hide?}: drape and put on
clothing.describe{text} or {json}: garments and fabrics ready for clothing.dress
clothing.catalogthe blocks with their style options
clothing.listdressed entities and their garments
clothing.undress{entity}: the garments off, the whole body shown again
clothing.motion.*start, stop, set, stats, reset: see "Cloth in motion"

Fabrics#

FabricSpec: weave (twill, plain, stockinette, rib, flannel, leather, felt), color (linear), heather mix, period (the thread or stitch size), depth (relief), roughness, wear, sheen (KHR_materials_sheen for wool), thread (stitching), and for knits a yoke pattern (ladder, moss, ridges) above a height on the listed panels, as on a fisherman's guernsey. This is the look of the cloth (the texture); how it hangs is the fabric physics above.

Costs#

Dressing is done once per character and outfit (seconds to minutes on a desktop CPU; the owner accepts 2-15 minutes at the game's build) and stored (see the store); at run time the garments are ordinary skinned meshes, and the cloth that moves freely is either simulated within the budget or played from the baked clips. The British merchant seaman of 1912 (tools/clothing/outfits.mjs, tools/humans/mh/character.mjs sailor): trousers, guernsey, kerchief, reefer jacket, cap, boots.

What usually goes wrong#

  • Cloth through a limb, a seam open by centimetres, a garment that slides off, ripples like crumpled paper: with the old drape these were met by per-outfit switches and post passes (seamIterations, hold, bend, layerPush, fair ...). Old way, to be removed (plan step 6); do not add a switch for an outfit: a fault is a fault of the cut (a wrong ease, a missing support), of the fabric values, or of the core, and is checked by the regression set.
  • A garment falls off in motion: no support holds it. Give the block's support the pinned lines (waistband, shoulder line) or pass supports/driven to ClothMotion.
  • Cloth too stiff or too floppy: check the fabric's physics (fabricPhysics) and the interlining of the stiff pieces before touching bend.
  • The stored outfit does not change after a code change: the key includes CLOTHING_CORE_VERSION; a change that alters the result must bump it.
  • A baked cloth does not close its loop: fps must divide 60, and the clip must be flagged loop; raise warmCycles or loopBlend.