From 01e9605f1e3d9ffadf9f2427c1083f166b0e2ab7 Mon Sep 17 00:00:00 2001 From: CRT Date: Fri, 28 Aug 2026 12:03:50 +0000 Subject: [PATCH] Fork the kit into contemporary-props with a nineteen slot palette, a per-model check that needs no registry round trip, and the first model. --- contemporary-props/CATALOGUE.md | 294 ++++++ contemporary-props/LICENSE | 21 + contemporary-props/build.ts | 202 ++++ contemporary-props/check.ts | 122 +++ contemporary-props/meta.ts | 56 ++ .../models/ceramic-vase/model.ts | 123 +++ contemporary-props/models/core/geometry.ts | 870 ++++++++++++++++++ contemporary-props/models/core/index.ts | 31 + contemporary-props/models/core/kit.ts | 341 +++++++ contemporary-props/models/core/materials.ts | 351 +++++++ contemporary-props/models/core/occlusion.ts | 176 ++++ contemporary-props/models/core/parts.ts | 49 + contemporary-props/models/core/random.ts | 26 + contemporary-props/models/core/tint.ts | 52 ++ contemporary-props/models/core/tool.ts | 131 +++ contemporary-props/package.json | 36 + models.json | 4 + models.lock.json | 47 + scripts/raster.ts | 33 +- scripts/support.ts | 17 +- .../contemporary-props/core/geometry.ts | 870 ++++++++++++++++++ src/models/contemporary-props/core/index.ts | 31 + src/models/contemporary-props/core/kit.ts | 341 +++++++ .../contemporary-props/core/materials.ts | 351 +++++++ .../contemporary-props/core/occlusion.ts | 176 ++++ src/models/contemporary-props/core/parts.ts | 49 + src/models/contemporary-props/core/random.ts | 26 + src/models/contemporary-props/core/tint.ts | 52 ++ src/models/contemporary-props/core/tool.ts | 131 +++ tsconfig.json | 12 +- 30 files changed, 5005 insertions(+), 16 deletions(-) create mode 100644 contemporary-props/CATALOGUE.md create mode 100644 contemporary-props/LICENSE create mode 100644 contemporary-props/build.ts create mode 100644 contemporary-props/check.ts create mode 100644 contemporary-props/meta.ts create mode 100644 contemporary-props/models/ceramic-vase/model.ts create mode 100644 contemporary-props/models/core/geometry.ts create mode 100644 contemporary-props/models/core/index.ts create mode 100644 contemporary-props/models/core/kit.ts create mode 100644 contemporary-props/models/core/materials.ts create mode 100644 contemporary-props/models/core/occlusion.ts create mode 100644 contemporary-props/models/core/parts.ts create mode 100644 contemporary-props/models/core/random.ts create mode 100644 contemporary-props/models/core/tint.ts create mode 100644 contemporary-props/models/core/tool.ts create mode 100644 contemporary-props/package.json create mode 100644 src/models/contemporary-props/core/geometry.ts create mode 100644 src/models/contemporary-props/core/index.ts create mode 100644 src/models/contemporary-props/core/kit.ts create mode 100644 src/models/contemporary-props/core/materials.ts create mode 100644 src/models/contemporary-props/core/occlusion.ts create mode 100644 src/models/contemporary-props/core/parts.ts create mode 100644 src/models/contemporary-props/core/random.ts create mode 100644 src/models/contemporary-props/core/tint.ts create mode 100644 src/models/contemporary-props/core/tool.ts diff --git a/contemporary-props/CATALOGUE.md b/contemporary-props/CATALOGUE.md new file mode 100644 index 0000000..56d5d9e --- /dev/null +++ b/contemporary-props/CATALOGUE.md @@ -0,0 +1,294 @@ + + +# CONTEMPORARY-PROPS: THE CATALOGUE + +339 candidates in, 306 unique after merging cross-domain repeats. 100 in the core, 150 in the follow-on, 56 cut outright, 33 merged into another candidate's generator. + +--- + +## 1. THE CORE 100 + +Read top to bottom as the build order. Rows 1 to 32 exist to establish and prove the shared vocabulary (revolve profiles, extrusions and chamfers, linear and radial arrays, perforation), and each is cheap enough that a mistake in the helper is cheap to fix. Rows 33 to 69 compose that vocabulary into frames, carcasses and mechanisms, and are where the shared parts library (castor, hinge, drawer, door, louvre, slat) gets settled. Rows 70 to 100 are the expensive objects that should only be attempted once everything below them exists. + +| # | id | name | domain | complexity | action | why it earns a place | +|---|---|---|---|---|---|---| +| 1 | ceramic-vase | Ceramic Vase | decor | simple | | The revolve profile itself: one waist, shoulder and lip curve proves the lathe helper and the whole vessel family follows from it | +| 2 | coffee-mug | Coffee Mug | kitchen | simple | | Adds the swept handle attached to a lathed body, the second most reused join in the kit | +| 3 | wine-glass | Stemmed Wine Glass | kitchen | simple | | Proves wall thickness on a revolve and the glass slot before anything expensive depends on either | +| 4 | pepper-mill | Pepper Mill | kitchen | simple | cap twists on the body | Longest profile curve in the kit at the lowest cost; the flute grip is the first radial cut | +| 5 | stockpot | Lidded Stockpot | kitchen | simple | lid lifts off | Rolled rim, riveted lug and a separable lid, three details every metal vessel afterwards reuses | +| 6 | traffic-cone | Traffic Cone | street | simple | | The clearest outline in the whole set, and it is where vertex-colour banding on a revolve gets defined | +| 7 | street-bollard | Street Bollard | street | simple | | Same generator as the cone with a different profile, which is the cheapest possible proof that profiles are data | +| 8 | gas-cylinder | Gas Cylinder | tools | simple | valve handwheel turns | Shoulder taper plus foot ring plus caged guard: the first time a lathe carries an array | +| 9 | fire-extinguisher | Fire Extinguisher | tools | simple | lever squeezes against the guard | The valve head assembly is the first small-part cluster and the first squeeze lever | +| 10 | pedestal-basin | Pedestal Basin | living | simple | | Two lathes making an hourglass, and the first object where the ceramic slot has to look like ceramic | +| 11 | jersey-barrier | Concrete Traffic Barrier | street | simple | | One extruded polyline with end connectors; this is the extrusion helper's reference implementation | +| 12 | picnic-table | Picnic Table | street | simple | | Plank runs on a mirrored A-frame, the cheapest object that is entirely plank array plus mirrored frame | +| 13 | park-bench | Park Bench | street | medium | | Slat array between two cast side frames; establishes the slat-with-gap rule everything else copies | +| 14 | pavement-sign-board | A-frame Pavement Sign | retail | simple | folds flat about the top hinge | The first hinge with a real origin, on the simplest possible body | +| 15 | lectern | Lectern | office | simple | | Angled cap on a panelled shaft: the chamfer helper on a tall thin mass, and it absorbs the school lectern | +| 16 | bookcase | Open Bookcase | office | simple | | The shelf-in-carcass generator, needed before every cabinet in the list | +| 17 | pedestal-dining-table | Pedestal Dining Table | kitchen | medium | | Lathed column plus radial feet plus edge-chamfered top; the round-table family and the bistro table both live here | +| 18 | sit-stand-desk | Sit-Stand Desk | office | medium | setHeight drives the telescoping stages | The telescope helper, defined once on the object where it is most visible | +| 19 | wall-bars | Gym Wall Bars | school | simple | | Pure rung ladder, the reference for arrayLinear with end caps into a stile | +| 20 | heated-towel-rail | Heated Towel Rail | living | simple | | Same ladder, bowed rungs, different material and pitch; proves the array is genuinely reusable | +| 21 | bike-rack | Cycle Stand Rack | street | simple | | One swept hoop instanced along a rail, the reference for sweep-then-instance | +| 22 | clothes-hanger | Clothes Hanger | living | simple | | Bent profile sweep with a coiled hook, the smallest object with a helix in it | +| 23 | wine-rack | Wine Rack | kitchen | medium | | A lattice of cells in two axes, the first genuine grid rather than a row | +| 24 | venetian-blind | Venetian Blind | living | medium | tilt the slats, raise the stack | Dozens of identical curved slats on ladder cords, and a tilt that swings the whole read from solid to striped | +| 25 | wall-clock | Wall Clock | office | simple | setTime sweeps the hands | Tick ring plus hands, legible with no numerals; absorbs the classroom and decor clocks | +| 26 | cable-drum | Cable Drum | street | simple | rolls about its axle | Spoked flanges, battens and a helical winding, three repetitions in one small cheap object | +| 27 | panel-radiator | Panel Radiator | living | medium | thermostat head turns | The zigzag convector fin rank behind a pressed panel, and the first object that is only interesting from its top edge | +| 28 | mesh-waste-bin | Mesh Waste Bin | office | medium | | The perforation helper on a tapered drum, defined here so every bin, grille and louvre after it is free | +| 29 | colander | Perforated Colander | kitchen | medium | | Perforation mapped onto a curved shell rather than a straight one, which is the harder case | +| 30 | litter-bin | Litter Bin | street | medium | hood hinges up | Perforated drum under an overhanging hood, and the first object where a hinge carries real mass | +| 31 | temporary-fence-panel | Temporary Fence Panel | street | medium | panels hinge at the coupler | Welded mesh in a tube frame; thousands of identical bars is exactly the work generation should absorb | +| 32 | wheeled-waste-bin | Wheeled Waste Bin | street | medium | lid swings on the rear hinge, wheels spin | Tapered ribbed moulding, hinged lid and an axle; the first appearance of the wheel part | +| 33 | stacking-chair | Stacking Chair | office | medium | | The cantilever bent-tube frame, and the first object built to stack with copies of itself | +| 34 | dining-chair | Dining Chair | kitchen | medium | | Spindle back on tapered legs, the turned-leg seating archetype; absorbs the living-room chair | +| 35 | bar-stool | Bar Stool | kitchen | medium | seat swivels and rises on the column | Tall column with a foot ring; absorbs the lab stool, retail stool and living stool as parameter sets | +| 36 | dish-drying-rack | Dish Drying Rack | kitchen | medium | | Wire tine array over a drip tray, the reference for many-identical-rods with a formed frame | +| 37 | sack-truck | Sack Truck | tools | medium | | Tubular L with cross rungs and inboard wheels, the first frame whose whole read is a right angle | +| 38 | wheelbarrow | Wheelbarrow | tools | medium | tips forward on the wheel | The dished-sheet helper, needed for every tray, pan, bowl and shell after it | +| 39 | utility-trolley | Utility Trolley | office | medium | castors roll and swivel | The castor part with its own swivel origin, plus the tiered tray frame; absorbs the kitchen, clinical and tray trolleys | +| 40 | garment-rack | Garment Rack | living | medium | rolls, rail telescopes | Almost all negative space, so it tests whether the tube frame reads without mass; absorbs the retail rail trolley | +| 41 | mobile-whiteboard | Mobile Whiteboard | school | medium | flip the board in its yoke | A blank panel that stays legible because the H frame, pen tray and pivot carry it; absorbs the office version | +| 42 | shopping-trolley | Shopping Trolley | retail | involved | castors swivel, child-seat flap folds | Tapered mesh basket over a raked chassis, the hardest wire object and the payoff for rows 28 to 39 | +| 43 | filing-cabinet | Filing Cabinet | office | medium | openDrawer(index) | The drawer generator: carcass, runner, face, shadow gap, handle rail; nine later objects depend on it | +| 44 | locker-bank | Locker Bank | office | medium | openDoor(bay, tier) | The door grid plus the louvre slot; absorbs the school and gym locker banks | +| 45 | wardrobe | Wardrobe | living | medium | doors swing, revealing the rail | Cornice, plinth and a vertical split, and the first tall carcass whose open state changes the silhouette | +| 46 | shelving-rack | Steel Shelving Rack | office | medium | | Slotted angle uprights with punched slots and diagonal braces; absorbs the wire and domestic shelving units | +| 47 | gondola-shelving | Gondola Shelving Run | retail | involved | | Stepped shelf depths down a run of bays, the most recognisable retail outline and the best use of the bay loop | +| 48 | base-cabinet-run | Base Cabinet Run | kitchen | involved | any door opens, any drawer slides | The bay-pattern generator: door, drawer stack or open, under one continuous worktop and plinth | +| 49 | utility-cabinet | Pavement Utility Cabinet | street | medium | doors swing open | Louvre banks on a plinth with a rain-shed roof; absorbs the street telecom cabinet | +| 50 | parcel-locker-bank | Parcel Locker Bank | street | medium | individual doors swing open | A door grid with a mixed size distribution, which is the locker generator's harder case | +| 51 | upright-fridge | Upright Fridge Freezer | kitchen | involved | doors swing, freezer drawer slides | The monolith that survives on its door gap, recessed handle rail and toe plinth alone | +| 52 | microwave-oven | Countertop Microwave | kitchen | medium | door swings, turntable spins | Inset glazed door, perforated vent band and a recessed control column; the small-appliance carcass template | +| 53 | pedal-bin | Pedal Bin | kitchen | medium | pedal press raises the lid on its linkage | The four-bar linkage, defined on the object where it is most visible; absorbs the living and retail bins | +| 54 | stapler | Desktop Stapler | office | medium | press closes the lever onto the anvil | Sprung hinge with a travel limit, and an outline nameable at thumbnail size | +| 55 | scissors | Office Scissors | office | medium | setOpen rotates both halves | Two parts sharing one pivot in opposite directions, which no earlier object has needed | +| 56 | folding-step-stool | Folding Step Stool | office | medium | fold and unfold | The first object with two completely different silhouettes from one angle parameter | +| 57 | step-ladder | Step Ladder | tools | medium | folds flat about the top hinge | The A-frame with treads and a spreader, one of the most legible workshop outlines there is | +| 58 | bench-vice | Bench Vice | tools | medium | jaws close along the screw | The screw-and-slide prismatic joint plus jaw serration; absorbs the school vice | +| 59 | boom-barrier | Boom Barrier | street | medium | boom raises from horizontal to vertical | A single lever over a box, and the cleanest test that a 90 degree action changes the read entirely | +| 60 | folding-room-divider | Folding Room Divider | living | medium | fold the panels to any concertina angle | Alternating hinges on repeated panels, a plan-view silhouette nothing else has | +| 61 | patio-parasol | Patio Parasol | decor | medium | canopy opens and closes on the rib linkage | A radial mechanism where every rib and stretcher is driven by one parameter | +| 62 | fire-hydrant | Fire Hydrant | street | medium | outlet caps unscrew and swing on chains | Bonnet, bolted flanges and radial outlets: a stepped lathe stack that names itself at 50 metres | +| 63 | claw-hammer | Claw Hammer | tools | simple | | The most nameable outline in the domain and the reference for a lofted head on a waisted grip | +| 64 | hand-saw | Hand Saw | tools | medium | | The tooth-row helper, needed later by the tape dispenser, ratchets and the chainsaw | +| 65 | cordless-drill | Cordless Drill | tools | medium | chuck spins, jaws open | The pistol-plus-battery T, plus the three-jaw chuck as a small radial mechanism | +| 66 | drill-press | Bench Drill Press | tools | medium | feed lever turns, quill drops | A strictly vertical lathe stack with a swinging table; absorbs the school drill press | +| 67 | shop-vacuum | Shop Vacuum | tools | medium | latches release, head lifts off | Ribbed drum, domed head, side latches and a coiled ribbed hose, three loops in one body | +| 68 | workbench | Workbench | tools | medium | drawers slide out | Thick top, apron, braced legs, lower shelf and a pegboard back; absorbs the school pegboard bench | +| 69 | tripod-work-light | Tripod Work Light | tools | medium | mast telescopes, heads tilt on the yoke | Top-heavy on thin legs, and the first object combining telescope, tripod and a tilting yoke | +| 70 | mechanical-keyboard | Mechanical Keyboard | computing | involved | depress a key, flip the tilt feet | The key-grid generator built from a row and column table with per-row cap profiles; four later objects reuse it | +| 71 | scientific-calculator | Scientific Calculator | school | medium | pressKey depresses one cap | The key grid at a second scale with a sunken display, proving the generator is not keyboard-specific | +| 72 | widescreen-monitor | Widescreen Monitor | computing | medium | tilt and swivel the panel | Panel, neck and foot make a T that reads with a dead screen, which is the whole test | +| 73 | laptop-computer | Laptop Computer | computing | involved | open and close the lid | Two chamfered slabs on a hinge reusing the key grid, and the open wedge is unmistakable | +| 74 | wireless-router | Wireless Router | computing | simple | rotate each antenna | Three to six pivoting rods on a wedge, the highest silhouette return for the lowest geometry in the kit | +| 75 | case-fan | Case Fan | computing | simple | spin the rotor | The swept-blade helper on a radiused square frame, needed by four later objects | +| 76 | cpu-tower-cooler | CPU Tower Cooler | computing | medium | spin the clip-on fan | Dozens of thin fins pierced by heat pipes, the geometry hand modelling hates most | +| 77 | tower-pc-case | Tower PC Case | computing | involved | slide the side panel off, spin the intakes | A tall box saved by a perforated mesh front, a tinted window and visible fan mounts | +| 78 | server-rack-cabinet | Server Rack Cabinet | computing | involved | swing the front and rear doors | Two metres of punched rail repetition behind a mesh door, and the anchor for a whole scene type | +| 79 | desktop-printer | Desktop Printer | computing | involved | raise the scanner lid, slide the tray | A stepped tiered stack with two independent moving parts and a paper stack that uses the paper slot | +| 80 | vending-machine | Vending Machine | retail | involved | a coil rotates one turn, delivery flap swings | An interior grid of helical coils behind glass, the single best generated-geometry showcase in the set | +| 81 | task-lamp | Articulated Task Lamp | office | involved | setPose on three joints, setLit | The most pose-dependent silhouette in the kit, plus the coil spring; absorbs the living-room swing arm | +| 82 | tripod-floor-lamp | Tripod Floor Lamp | living | medium | switch the shade lining | A drum on three splayed legs, and where the emissive slot gets defined; absorbs the table lamp at low height | +| 83 | pendant-lamp | Pendant Lamp | living | simple | switch the bulb emissive | Occupies the upper air where nothing else in the kit sits, with an optional wire cage for repetition | +| 84 | ceiling-fan | Ceiling Fan | living | medium | spin the blades and coast to a stop | Radial blades on a downrod, a shape defined entirely by its array count | +| 85 | street-lamp | Street Lamp Column | street | medium | | Tapered column, swan-neck sweep and a shallow head, the skyline shape a street scene needs | +| 86 | electric-kettle | Electric Kettle | kitchen | medium | lid flips open, switch rocks | Lathed body with a spout, strap handle and a separate base, legible at any scale | +| 87 | pop-up-toaster | Pop Up Toaster | kitchen | medium | lever slides down and springs back | Slots cut through a rounded deck plus a lever in a track, a small body with real structure | +| 88 | sink-with-drainer | Sink Unit With Drainer | kitchen | medium | strainer plug lifts out | A pressed basin beside a fluted drainer board, a deck shape nothing else shares | +| 89 | mixer-tap | Kitchen Mixer Tap | kitchen | medium | lever tilts and swings, spout rotates | Pure lathe and sweep, and the chrome slot's reference object; absorbs the basin mixer | +| 90 | extractor-hood | Chimney Extractor Hood | kitchen | medium | | A lofted tapered canopy meeting a straight flue, readable even from behind | +| 91 | range-cooker | Freestanding Range Cooker | kitchen | involved | oven door drops open, knobs rotate | Grate bars, a knob row and a glazed door make the busiest legible front in the domain | +| 92 | close-coupled-toilet | Close Coupled Toilet | living | involved | lid and seat raise separately, flush lever | Everyone names it instantly, and the pan-to-rim sweep is the hardest blend the kit will attempt | +| 93 | task-chair | Swivel Task Chair | office | involved | swivel, setHeight, castors roll | The five-star base is the most recognisable office outline and it is pure radial repetition over the castor part | +| 94 | modular-sofa | Modular Sofa | living | involved | | The seat-count family, and the only place the kit learns to make a cushion mass read as soft while staying rigid | +| 95 | slatted-bed-frame | Slatted Bed Frame | living | medium | | The low rectangle plus headboard that every domestic scene needs, with the slat run doing the work | +| 96 | potted-snake-plant | Potted Snake Plant | decor | simple | | The only greenery in the core, and stiff twisted blades are the one plant form code genuinely builds well | +| 97 | espresso-machine | Espresso Machine | retail | involved | portafilter twists in, steam wands swing | Dense asymmetric cluster of small lathed parts; absorbs the kitchen version as a single-group preset | +| 98 | acoustic-guitar | Acoustic Guitar | decor | involved | tuning pegs turn | Three separate clean repetitions on one axis (frets, strings, tuners) under a top-tier outline | +| 99 | bus-shelter | Bus Shelter | street | involved | | A cantilevered roof over glazed bays, the largest thing in the kit that is still a thing rather than a building | +| 100 | traffic-signal | Traffic Signal | street | involved | cycle the lit aspect, swing the head | Hooded visors on stacked aspects with a mast arm, and the emissive slot's most demanding user | + +--- + +## 2. THE NEXT 150 + +**computing (19)** +`monitor-arm`, `laptop-riser-stand`, `graphics-card`, `motherboard`, `hard-disk-drive`, `single-board-computer`, `solderless-breadboard`, `open-frame-gpu-rig`, `rack-server-chassis`, `network-switch`, `rack-console-drawer`, `cable-ladder-tray`, `power-distribution-strip`, `cable-coil`, `desk-voip-phone`, `headset-stand`, `boom-arm-microphone`, `video-projector`, `desktop-3d-printer` + +**office (14)** +`meeting-table`, `drafting-table`, `desk-partition-screen`, `coat-stand`, `tambour-cabinet`, `pigeonhole-sorter`, `literature-rack`, `water-cooler`, `desk-globe`, `tripod-projector-screen`, `hole-punch`, `tape-dispenser`, `pen-pot`, `paper-shredder` + +**school (17)** +`lift-lid-school-desk`, `tiered-lecture-bench`, `library-book-trolley`, `lab-bench`, `fume-hood`, `bunsen-burner`, `retort-stand`, `compound-microscope`, `test-tube-rack`, `bench-centrifuge`, `eyewash-station`, `ball-and-stick-molecule`, `sewing-machine`, `artist-easel`, `basketball-goal`, `retractable-bleachers`, `abacus` + +**kitchen (15)** +`glazed-dresser`, `spice-rack`, `roll-top-bread-bin`, `utensil-rail`, `paper-towel-holder`, `knife-block`, `stand-mixer`, `blender`, `moka-pot`, `french-press`, `frying-pan`, `box-grater`, `balloon-whisk`, `cutlery-set`, `teapot` + +**living (14)** +`folding-chair`, `rocking-chair`, `tufted-ottoman`, `hanging-egg-chair`, `bunk-bed`, `baby-cot`, `chest-of-drawers`, `laundry-hamper`, `lava-lamp`, `clothes-airer`, `ironing-board`, `freestanding-bathtub`, `shower-cubicle`, `shower-riser-rail` + +**street (16)** +`road-sign-post`, `work-zone-barricade`, `utility-pole`, `bottle-bank`, `skip-container`, `ev-charging-post`, `parking-ticket-machine`, `mail-drop-box`, `drinking-fountain`, `tree-guard`, `street-clock`, `portable-toilet`, `mobile-light-tower`, `pop-up-canopy`, `sign-gantry`, `street-planter` + +**tools (17)** +`rolling-tool-chest`, `cantilever-toolbox`, `parts-bin-rack`, `socket-set-case`, `extension-ladder`, `sawhorse`, `rolling-scaffold-tower`, `adjustable-wrench`, `bolt-cutters`, `circular-saw`, `chainsaw`, `mitre-saw`, `bench-grinder`, `air-compressor`, `floor-jack`, `engine-hoist`, `jerry-can` + +**retail (19)** +`wire-shopping-basket`, `rotating-display-spinner`, `counter-display-case`, `upright-drinks-cooler`, `checkout-counter`, `self-checkout-kiosk`, `capsule-vending-globe`, `queue-barrier-post`, `coffee-grinder`, `serve-over-counter`, `power-rack`, `dumbbell-rack`, `loaded-barbell`, `adjustable-weight-bench`, `treadmill`, `exercise-bike`, `cable-weight-stack`, `examination-couch`, `wheelchair` + +**decor (19)** +`columnar-cactus`, `bonsai-tree`, `watering-can`, `tiered-plant-stand`, `geodesic-terrarium`, `sunburst-wall-mirror`, `branched-candlestick`, `wind-chime`, `hanging-birdcage`, `wheeled-suitcase`, `equipment-flight-case`, `skateboard`, `tennis-racket`, `chess-set`, `upright-piano`, `drum-kit`, `trumpet`, `xylophone`, `music-stand` + +--- + +## 3. CUT, AND WHY + +### Merged into another candidate's generator (33) + +These are not losses. Each becomes a parameter set or a preset on the surviving id. + +| dropped | into | clause | +|---|---|---| +| `bar-stool` (living), `bar-stool` (retail), `lab-stool` | `bar-stool` | one column, one foot ring, three seat and base presets | +| `bistro-pedestal-table` | `pedestal-dining-table` | the same lathe column at a taller height and smaller top | +| `dining-chair` (living) | `dining-chair` | identical spindle-back generator with a different back rake | +| `stacking-classroom-chair` | `stacking-chair` | a moulded shell option on the cantilever tube frame | +| `locker-bank` (school), `locker-bank` (retail) | `locker-bank` | one door grid, three tier and vent presets | +| `coat-stand` (living) | `coat-stand` | the same pole and polar hook array | +| `drafting-table` (school) | `drafting-table` | same tilting board, different leg frame preset | +| `teacher-lectern` | `lectern` | a panel-style flag on the same angled cap | +| `classroom-wall-clock`, `wall-clock` (decor) | `wall-clock` | one tick ring, one hand set, three bezel depths | +| `globe-on-stand`, `desk-globe` (decor) | `desk-globe` | one tilted sphere in a meridian arc | +| `tripod-projection-screen` | `tripod-projector-screen` | same mast, case and drop | +| `bench-vice` (school), `drill-press` (school) | tools versions | the same machine at a school scale | +| `pegboard-workbench` | `workbench` | the pegboard back is a flag on the bench | +| `desktop-3d-printer` (school) | computing version | identical extrusion cube and gantry | +| `whiteboard-stand` | `mobile-whiteboard` | one pivoting panel in an H frame | +| `pedal-bin` (living), `pedal-bin` (retail) | `pedal-bin` | one linkage, three body profiles | +| `water-cooler` (retail) | `water-cooler` | same inverted bottle on a slimmer cabinet | +| `espresso-machine` (kitchen) | `espresso-machine` | the domestic one is the single-group preset | +| `music-stand` (school) | decor version | the same lattice desk and telescopic column | +| `basketball-hoop` (decor) | `basketball-goal` | same pole, board, rim and net | +| `basin-mixer-tap` | `mixer-tap` | one spout family, shorter reach | +| `swing-arm-lamp` | `task-lamp` | the same jointed arm with springs | +| `shelving-unit` (living), `wire-shelving-unit` | `shelving-rack` | one upright and deck generator, three deck styles | +| `kitchen-trolley`, `supply-trolley`, `tray-rack-trolley` | `utility-trolley` | one castor frame, tier count and deck type do the rest | +| `garment-rail-trolley` | `garment-rack` | the same rail on a Z frame | +| `folding-privacy-screen` | `folding-room-divider` | identical concertina at a clinical height | +| `street-telecom-cabinet` | `utility-cabinet` | the same louvred cabinet on a plinth | + +### Duplicate silhouette (17) + +`desktop-nas-enclosure` reads as the rack chassis face at any distance; `information-kiosk-terminal` is the parking machine and self-checkout pedestal again; `channelizer-drum` is the traffic cone's banded family with a blunter top; `bike-storage-locker` is the skip and the cabinet with an arched lid; `food-vending-cart` is the pop-up canopy plus a counter plus wheels, all three already built; `tiered-produce-stand` is the gondola's stepped shelf profile; `tray-rack-trolley` and `iv-drip-stand` are the trolley frame and the five-star gas column with nothing added; `beam-seating` is the stacking chair shell repeated along a rail; `weight-plate-tree` is the barbell plate stack stood on a post; `dumbbell` (decor) is the loaded barbell short; `cable-reel` is the cable drum in a frame; `axle-stand` and `scissor-jack` are subsumed by the floor jack's job in a garage scene; `drum-fan` is the case fan cage scaled up on a yoke; `track-hurdle` is the work-zone barricade with fewer rails; `glockenspiel` and `djembe-drum` are the xylophone bar ramp and the drum kit shell; `trophy-cup` is the vase lathe family with handles; `cool-box` is the flight case as a tub; `shoe-rack` is a tilted version of the wall bar array; `rotary-card-file` is the cable drum at desk scale; `letter-tray-stack` is a shelf tier without a carcass. + +### Needs a texture or a lit display to read (3) + +`gym-scoreboard` is a blank wall panel until segments are lit and read as numbers, which is a display rather than geometry; `webcam` is a lump whose only distinguishing feature at any distance is the lens ring; `conference-speakerphone` is a perforated disc, and a perforated disc says nothing from more than two metres. + +### Organic form code builds badly (8) + +`artists-lay-figure` is a human figure however it is jointed; `vr-headset-stand` needs a sculpted head form to hold the visor; `macrame-hanging-planter` is a knotted cord net; `hiking-backpack`, `duffel-bag` and `golf-bag` are soft goods whose whole read is slump; `dome-tent` is a tensioned fabric skin over poles and will build as a lump; `pleated-curtain-rail` is cloth, and regular sine pleats look like corrugated metal rather than fabric. + +### Not a thing, or a box with nothing to say (13) + +`floor-cable-ramp` is closer to a floor covering than an object; `archive-box`, `vaulting-box` and `lever-arch-file` are boxes whose added structure does not survive at distance; `paper-trimmer` is a flat plate with an arm on it; `pencil-sharpener` is a small lump with a crank; `drawing-compass` is two sticks on a hinge; `wheel-brace` is an X of four bars; `bar-clamp` is a notched bar; `panelled-football` is a sphere, and seams do not change a sphere's outline; `metronome` is a blank truncated wedge; `hourglass` and `kettlebell` each have exactly one correct form with only a scale parameter, which fails the family test; `kayak` is one correct hull that would require a section-series loft used nowhere else; `citrus-press` and `tiered-cake-stand` are stacked plates and a lever, both already covered; `pottery-wheel` is a pan and a disc, carried entirely by the stool and pedal beside it; `filament-spool` ships as part of the 3D printer rather than as a prop; `alloy-road-wheel` belongs to a vehicle kit and on its own is a disc against a wall. + +### Brand shaped (0 cut, 4 kept under condition) + +Nothing was cut for this outright, because every candidate here is an archetype rather than a product. Four need an explicit rule at build time: `stand-mixer` must not take the tilting-head-plus-plinth proportions of the one famous example, `espresso-machine` must not reproduce a specific eagle-topped body, `single-board-computer` must not copy a named board's port stack and mounting-hole positions, and `capsule-vending-globe` must keep a plain pedestal. Generate the proportions from the parameter ranges, never from a photograph of one product. + +--- + +## 4. THE SHARED VOCABULARY + +### Geometry helpers the core module must provide + +Ordered by how many of the core 100 depend on each. + +1. **`box(size, chamfer)`** with per-edge chamfer radius and per-face inset. Used by roughly 80 of the core. The chamfer is not cosmetic; it is what stops the fridge, the microwave and the locker bank reading as untextured cubes. +2. **`lathe(profile, segments, sweep, wall)`** where `profile` is a polyline with per-vertex tangency and an optional wall thickness for open vessels. Rows 1 to 10 exist to prove it. Consumers: every vessel, every column, every bollard, cone, cylinder, tap, knob, foot and finial. +3. **`extrude(polyline, length, taper, endCaps)`**. The jersey barrier, every aluminium and steel profile, every slat, every rail, the gondola upright, the shelving angle. +4. **`sweep(profile, path, twist)`** with path from arcs and lines. Handles, spouts, bent tube frames, hoses, the swan-neck lamp arm, the trolley chassis. +5. **`tubeFrame(points, radius, bendRadius)`** as a specialisation of sweep that keeps a constant bend radius at every corner. The stacking chair, sack truck, garment rack, bike rack, step ladder, tripod legs. Without this the tube objects will have visibly different corner treatments from each other. +6. **`loft(sections, spine)`**. The extractor hood, the sofa arm, the guitar body, the wheelbarrow tray, the trolley basket taper. +7. **`dish(outline, depth, rim)`** for pressed sheet: the sink basin, the wheelbarrow tray, the seat pan, the bench seat shell, the litter bin hood. +8. **`helix(radius, pitch, turns, profile)`**. Springs on the task lamp, the cable drum winding, the vending machine coil, the shower hose, coiled cable. +9. **`arrayLinear(count, pitch, jitter, transformFn)`**, **`arrayPolar(count, radius, phase)`**, **`arrayGrid(rows, cols, pitch)`**. The three most-called functions in the kit. `transformFn` is what makes the size-ramp objects (gondola shelf depths, drawer heights, dumbbell racks) work without special cases. +10. **`perforate(target, pattern, holeShape, margin)`** supporting grid, staggered, radial-ring and slot patterns, with an inset rim so holes read at low angles. Mesh bin, colander, litter bin, locker louvre, radiator grille, PC front, speaker face, breadboard. +11. **`louvre(count, angle, depth)`** built on perforate, because slats-in-an-opening appears on six core objects with the same failure mode if hand-rolled each time. +12. **`toothRow(count, profile, set)`**. Saw, tape dispenser, ratchet, vice jaw, chain link, worm wheel. +13. **`lattice(bays, pattern)`** for truss and cross-brace. Scaffold, sign gantry, light tower mast, wall bars. +14. **`profileLibrary`**: rolled rim, ogee, plinth, waist, cove, quirk bead, chamfer stop. Named curves shared across the lathe and extrude callers so a rolled rim on a stockpot and on a litter bin are the same curve. +15. **`seededRng`** feeding jitter on pen splay, hanger spacing, slat gap, wear bevels, and colour variation. Determinism is the contract, so every consumer takes the rng explicitly rather than reading a global. + +### Mechanism parts (shared, each owning its origin) + +`hinge(axis, range)`, `slider(axis, travel, detents)`, `telescope(stages, collapse)`, `fourBar(links)`, `scissorLink(pairs)`, `ratchet(teeth, pawl)`, `screwJoint(pitch, travel)`, `castor(diameter, offset, swivel)`, `gasColumn(range)`, `spin(axis, decay)`. Thirty-three of the core hundred declare an action, and all of them decompose into these ten. Settle them before object 1. + +### Material slots + +The medieval kit's slots do not cover this kit, and the mismatch is specific rather than general. + +**Carry over unchanged (5):** `wood` (workbench top, dining chair, bookcase, drafting board, piano case, guitar body), `steel-painted` (from `iron`: lockers, filing cabinet, shelving rack, barriers, tool bodies), `fabric` (from `cloth`: sofa, partition infill, canopy, whiteboard felt), `ceramic-glazed` (from `clay`: basin, toilet, mug, vase), `brass` (from `bronze`: trumpet, bunsen barrel, candlestick, valve trim). + +**Carry over with a changed meaning (2):** `cord` narrows from `rope` to nylon and PVC (blind ladder cord, chime cord, pull cords, hose); `glass-clear` becomes a first-class slot rather than an occasional one, because 11 core objects (wine glass, bus shelter, microwave door, oven door, display case, cooler, shower cubicle, terrarium, vending machine, monitor, PC window) fail without it. + +**Dropped (5):** `leather`, `thatch`, `bone`, `gold`, `wax` have no consumer in 250 objects. + +**New, each argued from at least three core objects (11):** + +| slot | argued from | +|---|---| +| `plastic-matte` | keyboard caps, wheeled waste bin, portable toilet, trolley shell, router body, tool housings; the single most common material in the kit and it must not look like painted steel | +| `plastic-gloss` | kettle body, toaster shell, laptop lid, appliance fascia; the specular difference from matte is the only thing separating a kettle from a bin at a glance | +| `rubber` | castor tyres, chair glides, tool grips, hose, cable jacket, wheelbarrow tyre, door seals; needed on 20+ objects and it is what makes the castor part read as a castor | +| `steel-galvanised` | fence mesh, cable tray, dish rack, shopping trolley, wire basket, wheelbarrow frame; the spangled zinc read is different enough from painted steel that sharing one slot flattens every wire object | +| `stainless-satin` | sink, stockpot, extractor hood, fridge front, espresso body, range trim; the kitchen collapses without it | +| `chrome-polished` | mixer tap, scissors, towel rail, stool column, cutlery, whisk, bar frames; a mirror slot, distinct from satin in its reflection behaviour rather than its colour | +| `aluminium-brushed` | 3D printer extrusions, monitor stand, laptop chassis, heatsink fins, rack rails, ladder stiles; extruded profile is the signature modern material and it is neither steel nor chrome | +| `concrete` | jersey barrier, planter, bollard base, cabinet plinth, barrier feet, worktop; grey and matte with an aggregate speckle, and it anchors every street scene | +| `glass-tinted` | PC side panel, shower screen, sunglasses of the display case, projector lens, cooler door in the dark; a separate slot because transmission is the parameter, and reusing clear glass with an alpha loses the surface | +| `paper` | printer paper stack, till roll, paper towel roll, book block edges, filter, literature rack contents; matte, near-white, zero specular, and it looks wrong rendered as plastic | +| `emissive` | lamp shade lining, traffic signal aspect, bulb, status pole, lava lamp, screen-on state; the medieval kit had firelight but not a switchable emitter with a colour parameter | + +**One special case:** `retroreflective` for the traffic cone collars, barricade stripes and sign plates. It is arguably a vertex-colour treatment rather than a material, but it must not tone-map like paint, so give it its own slot and let it be a no-op in renderers that do not care. + +That is 23 slots. Every object in the core 100 is coverable with at most 5 of them, and the median is 3. + +--- + +## 5. WHAT WORRIES ME + +### The three most likely to look wrong when built + +**`modular-sofa` (94).** It is the only core object whose entire read depends on looking soft. Chamfered box cushions with piping ridges is the honest description of what the code will produce, and the honest prediction is a stack of rounded blocks on legs. The medieval kit has no vocabulary for a compressed mass, and none of the 93 objects before it develop one. Either build a `cushion(outline, loft, seam, compression)` helper deliberately, with a real crown on the top face and a slump at the front edge, or accept that the sofa is the one object where the kit looks like a kit. I would build the helper, because the ottoman, the mattress, the exam couch, the weight bench and the chair pads in the next 150 all need it too, so the cost is amortised across six objects rather than charged to one. + +**`close-coupled-toilet` (92).** The pan is not a lathe and not an extrusion. It is a compound blend from a rectangular footprint through a swept bowl to a rolled rim, and every generated toilet fails at exactly the same place: the trap bulge on the side. Nothing else in the core needs a blend of that kind, so it will be a bespoke object dressed as a parametric one. It is worth keeping because a bathroom without one is not a bathroom, but I would build it late, build it from a section series rather than pretending it is a revolve, and give it exactly two shape presets rather than a continuous family. + +**`potted-snake-plant` (96).** It is in the core because a kit of 100 objects with no living thing in it produces scenes that look sterile, and the snake plant is the plant whose leaves are genuinely stiff twisted tapered strips. The risk is that the twist plus the edge band plus the seeded lean produces green knives standing in a pot. The fix is per-blade curvature that varies along the blade length rather than a single twist parameter, and a blade cross-section that is a flattened lens rather than a rectangle. If the first build looks wrong, move it to the next 150 and ship the core with no greenery rather than shipping something that undermines every scene it appears in. + +### The structural decision I would push back on + +**Spreading the first hundred across all nine domains.** + +The core 100 above covers 21 kitchen objects, 17 street, 15 office, 14 living, 13 tools, 9 computing, 4 retail, 4 decor, 3 school. That distribution came from asking which objects best establish the shared vocabulary, which is the right question for the code and the wrong question for the user. Nobody can build a shop with 4 retail objects. Nobody can build a classroom with 3. What they can build is nine partial rooms, each of which announces what is missing. + +The alternative I would argue for: pick three domains, ship them complete, and let the vocabulary fall out of that rather than driving it. Kitchen, office and street would be my three, because between them they exercise every helper in section 4 (lathe, perforation, carcass, drawer, tube frame, louvre, extrusion, emissive, concrete, glass) and each produces a scene somebody can actually assemble on day one. That is roughly 35 kitchen, 33 office and 32 street objects, which is a hundred, and the follow-on 150 becomes three more complete domains rather than a thinning-out of nine. + +The counter-argument, which is why I built the catalogue the way I did, is that vocabulary discovered inside one domain calcifies around that domain's needs, and the fourth domain then fights the helpers. Building `perforate` for the mesh bin, the colander and the fence panel in the same week is what keeps it general. Both positions are defensible. The one I would not defend is the middle, which is what happens by default: nine domains at 30 percent completion each, with the helper set shaped by whichever domain happened to get built first. diff --git a/contemporary-props/LICENSE b/contemporary-props/LICENSE new file mode 100644 index 0000000..2e4bee1 --- /dev/null +++ b/contemporary-props/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 CRTkafa + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/contemporary-props/build.ts b/contemporary-props/build.ts new file mode 100644 index 0000000..e05728d --- /dev/null +++ b/contemporary-props/build.ts @@ -0,0 +1,202 @@ +/** + * The script that builds your own registry. + * + * It scans every folder under `models/`: + * - contains `model.ts` -> vibe3d:model + * - does not -> vibe3d:lib (shared support item) + * + * Dependencies are derived from the source: if a model imports from under + * `../core/`, `@contemporary-props/core` automatically becomes a dependency. There is + * no hand-maintained list, so the list cannot go stale either. + * + * Run: bun contemporary-props/build.ts + * Validate: bunx vibe3d registry validate contemporary-props/dist/registry.json + */ +import { createHash } from 'node:crypto' +import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises' +import { dirname, join, relative, resolve, sep } from 'node:path' +import { fileURLToPath } from 'node:url' + +const registryRoot = dirname(fileURLToPath(import.meta.url)) +const sourceRoot = join(registryRoot, 'models') +const outputRoot = join(registryRoot, 'dist') + +const NAMESPACE = '@contemporary-props' +const THREE_RANGE = 'three@>=0.185.0' + +/** Catalogue data per model. The source files themselves are read from disk. */ +import { MODEL_META } from './meta.ts' + +const LIB_DESCRIPTION: Record = { + core: { + title: 'Contemporary Props Core', + description: + 'The shared foundation of the kit: deterministic randomness, vertex-colored materials ' + + 'and stave/band/head geometry generators.', + }, +} + +function sha256(content: string): string { + return createHash('sha256').update(content).digest('hex') +} + +function posix(path: string): string { + return path.split(sep).join('/') +} + +async function collectTypeScript(root: string): Promise { + const files: string[] = [] + const visit = async (directory: string): Promise => { + for (const entry of await readdir(directory, { withFileTypes: true })) { + const path = join(directory, entry.name) + if (entry.isDirectory()) await visit(path) + else if (entry.isFile() && entry.name.endsWith('.ts')) files.push(path) + } + } + await visit(root) + return files.sort() +} + +async function registryFiles(itemId: string, paths: readonly string[]) { + const directory = join(sourceRoot, itemId) + return Promise.all(paths.map(async (path) => { + const content = await readFile(path, 'utf8') + return { + path: posix(relative(registryRoot, path)), + // {models} and {vibe3d} are replaced with the paths from the consumer's + // models.json — the registry does not have to assume its folder layout. + target: `{models}/contemporary-props/${itemId}/${posix(relative(directory, path))}`, + content, + hash: sha256(content), + } + })) +} + +/** Every import of the form `from '..//'` is a registry dependency. */ +function dependenciesFrom(contents: readonly string[], selfId: string): string[] { + const found = new Set() + const pattern = /from\s+['"]\.\.\/([a-z0-9][a-z0-9-]*)\//g + for (const content of contents) { + for (const match of content.matchAll(pattern)) { + const id = match[1] + if (id && id !== selfId) found.add(`${NAMESPACE}/${id}`) + } + } + return [...found].sort() +} + +async function main(): Promise { + const entries = await readdir(sourceRoot, { withFileTypes: true }) + const models: string[] = [] + const libs: string[] = [] + + for (const entry of entries) { + if (!entry.isDirectory()) continue + // Folders starting with a dot are not items. Tools (editor, VCS, agent + // state) may leave folders here; registry names, on the other hand, have to + // be `[a-z0-9-]+`, so such a folder would break the build. + if (entry.name.startsWith('.')) continue + // The criterion for being a model: model.ts at the folder ROOT. Searching + // the subtree is wrong: `core/model.ts` is a shared helper, not a model. + const paths = await collectTypeScript(join(sourceRoot, entry.name)) + const root = join(sourceRoot, entry.name, 'model.ts') + if (paths.includes(root)) models.push(entry.name) + else libs.push(entry.name) + } + models.sort() + libs.sort() + + const items: unknown[] = [] + + for (const id of libs) { + const paths = await collectTypeScript(join(sourceRoot, id)) + const contents = await Promise.all(paths.map((path) => readFile(path, 'utf8'))) + const meta = LIB_DESCRIPTION[id] ?? { title: id, description: 'Shared kit source.' } + items.push({ + name: id, + type: 'vibe3d:lib', + title: meta.title, + description: meta.description, + dependencies: [THREE_RANGE], + registryDependencies: dependenciesFrom(contents, id), + files: await registryFiles(id, paths), + }) + } + + for (const id of models) { + const paths = await collectTypeScript(join(sourceRoot, id)) + const contents = await Promise.all(paths.map((path) => readFile(path, 'utf8'))) + const meta = MODEL_META[id] + if (!meta) throw new Error(`no MODEL_META entry for ${id}`) + items.push({ + name: id, + type: 'vibe3d:model', + title: meta.title, + description: meta.description, + dependencies: [THREE_RANGE], + registryDependencies: dependenciesFrom(contents, id), + files: await registryFiles(id, paths), + meta: { + title: meta.title, + description: meta.description, + category: meta.category, + tags: meta.tags, + controls: meta.controls, + materialSlots: meta.materialSlots, + parts: meta.parts, + sockets: [], + }, + }) + } + + // defaultItem is required: `vibe3d add @contemporary-props` (with no item name) installs this. + items.push({ + name: 'kit', + type: 'vibe3d:kit', + title: 'Contemporary Props', + description: 'The complete contemporary props kit.', + dependencies: [], + registryDependencies: models.map((id) => `${NAMESPACE}/${id}`), + files: [], + }) + + const registry = { + $schema: 'https://vibe3d.dev/schema/registry.json', + schemaVersion: 1, + namespace: NAMESPACE, + name: 'Contemporary Props', + description: 'Present-day procedural prop library for Three.js.', + license: 'MIT', + defaultItem: 'kit', + compatibility: { + vibe3d: '^0.0.1', + engine: 'three', + three: '>=0.185.0', + // scifi-kit requires ['webgpu','tsl']; this kit runs on classic WebGL. + capabilities: [], + }, + items, + } + + await mkdir(outputRoot, { recursive: true }) + await writeFile( + resolve(outputRoot, 'registry.json'), + `${JSON.stringify(registry, null, 2)}\n`, + 'utf8', + ) + + const fileCount = items.reduce( + (total, item) => total + (item as { files: unknown[] }).files.length, + 0, + ) + console.log(`${items.length} items built · ${models.length} models · ${libs.length} libs · ${fileCount} files`) + for (const id of [...libs, ...models]) { + const item = items.find((candidate) => (candidate as { name: string }).name === id) as { + registryDependencies: string[] + } + const deps = item.registryDependencies.length > 0 ? ` -> ${item.registryDependencies.join(', ')}` : '' + console.log(` ${NAMESPACE}/${id}${deps}`) + } +} + +await main() diff --git a/contemporary-props/check.ts b/contemporary-props/check.ts new file mode 100644 index 0000000..6a7973a --- /dev/null +++ b/contemporary-props/check.ts @@ -0,0 +1,122 @@ +/** + * Checks one model, straight from the folder it is written in. + * + * bun contemporary-props/check.ts ceramic-vase + * bun contemporary-props/check.ts ceramic-vase --size 900 --angles 6 + * + * Why this exists rather than reusing the kit-wide gate: the gate rebuilds the + * registry and reinstalls it into the demo before it checks anything, and those + * two steps write files the whole repository shares. One person can run them + * safely. Several workers cannot, because each install overwrites the last and + * every one of them then verifies somebody else's code. That has already + * happened once here: a cart was fixed, the reinstall was skipped, and the old + * geometry passed while the new geometry was never looked at. + * + * So this touches nothing outside `renders/`. It imports the model directly, + * builds it, measures it, asks whether any of it floats, and draws it. The + * kit-wide gate still runs afterwards, once, in one place. + * + * The render is the point. Every measurement below can pass on a model that + * looks nothing like the thing it is named after, and no geometric check ever + * written can say "that is not a vase". + */ +import { mkdir, writeFile } from 'node:fs/promises' + +import { Box3, Vector3, type Object3D } from 'three/webgpu' + +import { encodePng, renderObject, tile, type Frame } from '../scripts/raster.ts' +import { findFloating } from '../scripts/support.ts' + +const args = process.argv.slice(2) +const flag = (name: string): string | undefined => { + const at = args.indexOf(`--${name}`) + return at >= 0 ? args[at + 1] : undefined +} + +const id = args.find((a) => !a.startsWith('--') && args[args.indexOf(a) - 1]?.startsWith('--') !== true) +if (!id) throw new Error('usage: bun contemporary-props/check.ts [--size N] [--angles N]') + +const size = Number(flag('size') ?? 720) +const angles = Number(flag('angles') ?? 0) +const outDir = 'contemporary-props/renders' + +const module_ = await import(`./models/${id}/model.ts`) as { + createModel?: (overrides?: Record) => { + root: Object3D + parts: Record + actions?: Record + getConfig(): Record + update(dt: number): void + dispose(): void + } +} +if (!module_.createModel) throw new Error(`${id}/model.ts does not export createModel`) + +const model = module_.createModel() +model.update(0.42) // catch anything animated mid-motion +model.root.updateMatrixWorld(true) + +/* ----------------------------------------------------------------- measure */ + +let triangles = 0 +const slots = new Set() +model.root.traverse((object) => { + const mesh = object as { isMesh?: boolean; geometry?: { getIndex(): { count: number } | null; getAttribute(n: string): { count: number } }; userData?: Record } + if (!mesh.isMesh || !mesh.geometry) return + const index = mesh.geometry.getIndex() + triangles += (index ? index.count : mesh.geometry.getAttribute('position').count) / 3 + const slot = mesh.userData?.vibe3d?.materialSlot + if (slot) slots.add(slot) +}) + +const box = new Box3().setFromObject(model.root) +const size3 = box.getSize(new Vector3()) +const support = findFloating(model.root, { resolution: 96 }) + +console.log(`\n${id}`) +console.log(` ${triangles} triangles · ${size3.x.toFixed(2)} x ${size3.y.toFixed(2)} x ${size3.z.toFixed(2)} m`) +console.log(` parts: ${Object.keys(model.parts).join(', ') || '(none)'}`) +console.log(` slots: ${[...slots].sort().join(', ') || '(none)'}`) +console.log(` actions: ${Object.keys(model.actions ?? {}).join(', ') || '(none)'}`) +console.log(` config: ${Object.keys(model.getConfig()).join(', ')}`) + +/* -------------------------------------------------------------- structure */ + +let failed = false +const fail = (message: string): void => { console.log(` FAIL ${message}`); failed = true } + +if (triangles === 0) fail('no geometry at all') +if (!Number.isFinite(size3.x + size3.y + size3.z)) fail('bounds are not finite') +if (support.floating.length > 0) { + fail(`${support.floating.length} piece(s) float, in ${support.components} components:`) + for (const piece of support.floating) { + console.log(` ${(piece.clearance * 1000).toFixed(0)}mm clear, ${piece.voxels} voxels, parts: ${piece.parts.join(', ')}`) + } +} else { + console.log(` rests on the ground · ${support.components} connected component(s)`) +} + +/* ---------------------------------------------------------------- picture */ + +await mkdir(outDir, { recursive: true }) +let frame: Frame +if (angles > 1) { + // A single three-quarter view is how a model gets called finished while it is + // still wrong from the other side. The fence only looks thin edge on. + const frames: Frame[] = [] + for (let i = 0; i < angles; i += 1) { + const spun = module_.createModel!() + spun.update(0.42) + frames.push(renderObject(spun.root, { size, spin: (i / angles) * Math.PI * 2 })) + spun.dispose() + } + frame = tile(frames, size, angles) +} else { + frame = renderObject(model.root, { size }) +} +const file = `${outDir}/${id}${angles > 1 ? '-turntable' : ''}.png` +await writeFile(file, encodePng(frame)) +console.log(`\n ${file} — now LOOK at it`) + +model.dispose() +process.exit(failed ? 1 : 0) diff --git a/contemporary-props/meta.ts b/contemporary-props/meta.ts new file mode 100644 index 0000000..7d7f3df --- /dev/null +++ b/contemporary-props/meta.ts @@ -0,0 +1,56 @@ +/** + * The SINGLE source of the kit catalogue. + * + * This table is read from two places: `build.ts` when it produces registry.json, + * and the viewer when it builds its sliders and descriptions. The two used to be + * written out by hand separately; at seventeen models that is no longer + * sustainable, and they had already started to drift apart. + * + * The `controls` here are a CONTRACT: every key has to be a config field of the + * model. The viewer checks this through `keyof Config`, so a renamed field is a + * compile error. + */ + +export interface ControlSpec { + readonly type: 'number' + readonly label: string + readonly min: number + readonly max: number + readonly step: number + readonly unit?: string +} + +export interface ModelMeta { + readonly title: string + readonly description: string + readonly category: string + readonly tags: readonly string[] + readonly controls: Readonly> + readonly materialSlots: readonly string[] + readonly parts: readonly string[] +} + +export const MODEL_META: Readonly> = { + // One entry per model, added as each model is built. The registry build + // fails on a model with no entry here, which is deliberate: an item nobody + // described is an item nobody can find. + 'ceramic-vase': { + title: 'Ceramic Vase', + description: + 'Glazed ceramic vase turned as a single revolve. The belly height decides ' + + 'whether it reads as a bud vase or an urn, and the lip stands proud of the ' + + 'neck so the mouth has an edge rather than being a hole in the top.', + category: 'Decor', + tags: ['contemporary', 'decor', 'vessel', 'procedural'], + controls: { + height: { type: 'number', label: 'Height', min: 0.12, max: 0.9, step: 0.01, unit: 'm' }, + bellyRadius: { type: 'number', label: 'Belly radius', min: 0.03, max: 0.3, step: 0.005, unit: 'm' }, + bellyAt: { type: 'number', label: 'Belly height', min: 0.18, max: 0.72, step: 0.01 }, + mouth: { type: 'number', label: 'Mouth', min: 0.2, max: 0.9, step: 0.01 }, + segments: { type: 'number', label: 'Sides', min: 8, max: 64, step: 1 }, + seed: { type: 'number', label: 'Variation seed', min: 1, max: 64, step: 1 }, + }, + materialSlots: ['ceramic'], + parts: ['body'], + }, +} diff --git a/contemporary-props/models/ceramic-vase/model.ts b/contemporary-props/models/ceramic-vase/model.ts new file mode 100644 index 0000000..8f93ff1 --- /dev/null +++ b/contemporary-props/models/ceramic-vase/model.ts @@ -0,0 +1,123 @@ +/** + * @contemporary-props/ceramic-vase + * + * First object in the kit, and it is here to settle the revolve. + * + * Almost everything with a round section that follows depends on the same + * profile machinery: the mug, the pepper mill, the stockpot, the basin, the + * bollard, the traffic cone, every knob, foot and column. So the vase is built + * as a curve rather than as a shape. Four control heights carry it, and each + * one is named after what it does to the silhouette: + * + * foot where it meets the table, narrower than the belly so the vase + * looks placed rather than poured + * belly the widest point, and the parameter that decides whether this is + * a bud vase or an urn + * shoulder where the wall turns back in, and the one place a generated + * vessel usually goes wrong: put it too high and the profile reads + * as a bottle, too low and it reads as a bowl + * lip the mouth, rolled slightly proud of the neck so the rim catches + * light and the opening does not look like a hole cut in a solid + * + * The wall has no thickness. A vase is looked at from outside and the inside of + * the neck is dark at every angle a prop is seen from, so modelling the bore + * would spend triangles on something nothing ever sees. The rim reads because + * the lip steps out, not because there is a wall behind it. + * + * Parts: `body` alone. There is nothing here that moves or that a consumer + * would want to reach separately, and inventing parts to look thorough makes + * the protocol noisier without making the model more useful. + */ +import { type BufferGeometry } from 'three' + +import { + createKitModel, + createTinter, + jitter, + latheGeometry, + mergeColoured, + type Level, +} from '../core/index.ts' + +export interface CeramicVaseConfig { + /** Overall height (metres). */ + readonly height: number + /** Widest radius, at the belly (metres). */ + readonly bellyRadius: number + /** Where the belly sits, as a fraction of the height. */ + readonly bellyAt: number + /** Mouth radius as a fraction of the belly radius. */ + readonly mouth: number + /** Sides around the revolve. Low values are a deliberate faceted look. */ + readonly segments: number + readonly seed: number +} + +export const ceramicVaseDefaults: CeramicVaseConfig = { + height: 0.32, + bellyRadius: 0.105, + // Just below the middle. A belly at or above half height reads as a bottle, + // and this is the single number that decides whether the silhouette is right. + bellyAt: 0.42, + mouth: 0.52, + segments: 32, + seed: 11, +} + +export type CeramicVaseParts = 'body' + +export function createModel(overrides: Partial = {}) { + return createKitModel({ + id: 'ceramic-vase', + defaults: ceramicVaseDefaults, + slots: ['ceramic'], + + build: ({ config, random }) => { + const tint = createTinter(random) + const H = config.height + const belly = config.bellyRadius + const bellyY = H * Math.min(0.72, Math.max(0.18, config.bellyAt)) + const mouth = belly * Math.min(0.9, Math.max(0.2, config.mouth)) + + // The foot is a fraction of the belly rather than a free parameter: a + // vase whose base can be set independently can be given a base wider + // than its body, and there is no value of that which looks like a vase. + const foot = belly * 0.62 + const shoulderY = bellyY + (H - bellyY) * 0.58 + const neck = mouth * 1.04 + + const levels: Level[] = [ + { y: 0, radius: foot * 0.94 }, + // A short straight rise off the table before the curve starts. Without + // it the profile leaves the ground at an angle and the vase looks like + // it is sinking into the surface. + { y: H * 0.035, radius: foot }, + { y: bellyY * 0.55, radius: belly * 0.93 }, + { y: bellyY, radius: belly }, + { y: shoulderY, radius: belly * 0.74 }, + { y: H * 0.93, radius: neck }, + // The lip: proud of the neck by a hair, so the mouth has an edge to + // catch light rather than being a hole in the top. + { y: H * 0.97, radius: neck * 1.09 }, + { y: H, radius: neck * 1.06 }, + ] + + const pieces: BufferGeometry[] = [ + latheGeometry( + levels, + Math.max(8, Math.round(config.segments)), + [0, 0, 0], + tint('ceramic', jitter(random, 0.02)), + // Glaze pools slightly toward the foot and thins over the shoulder, + // so the top is a touch lighter. It is a small difference and it is + // what stops a single-slot object reading as flat plastic. + { colourTop: tint('ceramic', 0.05), capBottom: true, capTop: false }, + ), + ] + + return { + body: { slot: 'ceramic' as const, geometry: mergeColoured(pieces) }, + } + }, + }, overrides) +} diff --git a/contemporary-props/models/core/geometry.ts b/contemporary-props/models/core/geometry.ts new file mode 100644 index 0000000..46d4a0c --- /dev/null +++ b/contemporary-props/models/core/geometry.ts @@ -0,0 +1,870 @@ +import { BufferAttribute, BufferGeometry, Color } from 'three' +import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js' + +/** + * The kit's geometry vocabulary. + * + * Everything is generated NON-INDEXED. The reason: on non-indexed geometry + * computeVertexNormals() gives every triangle its own normal, so flat shading + * becomes a natural consequence of the geometry — no material flag is needed. + * In lowpoly that is exactly what we want. + * + * Position frame: point(a, r, y) = (sin a · r, y, cos a · r) + * So a = 0 → the +Z direction; as a grows it turns toward +X. + * + * The windings were worked out by hand and the audit inside + * `scripts/verify-model.ts` tests them by mutation: radial faces on the outer + * shell must point away from the axis. + */ + +export type Vec3 = readonly [number, number, number] + +export interface Level { + /** Vertical position (metres). */ + readonly y: number + /** OUTER radius at that height (metres). */ + readonly radius: number +} + +function point(angle: number, radius: number, y: number): Vec3 { + return [Math.sin(angle) * radius, y, Math.cos(angle) * radius] +} + +interface Sink { + readonly position: number[] + readonly color: number[] +} + +function tri(sink: Sink, a: Vec3, b: Vec3, c: Vec3, colour: Color): void { + sink.position.push(a[0], a[1], a[2], b[0], b[1], b[2], c[0], c[1], c[2]) + for (let i = 0; i < 3; i += 1) sink.color.push(colour.r, colour.g, colour.b) +} + +/** Triangle with a separate colour per corner — for vertical colour ramps. */ +function triShaded(sink: Sink, a: Vec3, b: Vec3, c: Vec3, ca: Color, cb: Color, cc: Color): void { + sink.position.push(a[0], a[1], a[2], b[0], b[1], b[2], c[0], c[1], c[2]) + sink.color.push(ca.r, ca.g, ca.b, cb.r, cb.g, cb.b, cc.r, cc.g, cc.b) +} + +/** Splits the quad (a,b,c,d) in order into two triangles. The normal follows from the a→b→c winding. */ +function quad(sink: Sink, a: Vec3, b: Vec3, c: Vec3, d: Vec3, colour: Color): void { + tri(sink, a, b, c, colour) + tri(sink, a, c, d, colour) +} + +function finish(sink: Sink): BufferGeometry { + const geometry = new BufferGeometry() + geometry.setAttribute('position', new BufferAttribute(new Float32Array(sink.position), 3)) + geometry.setAttribute('color', new BufferAttribute(new Float32Array(sink.color), 3)) + return geometry +} + +/** + * Axis-aligned box. The kit's most used part: boards, rails, iron straps, + * feet — all of them are this. + */ +export function boxGeometry( + size: Vec3, + centre: Vec3, + colour: Color, +): BufferGeometry { + const sink: Sink = { position: [], color: [] } + const [hx, hy, hz] = [size[0] / 2, size[1] / 2, size[2] / 2] + const [cx, cy, cz] = centre + const v = (sx: number, sy: number, sz: number): Vec3 => [cx + sx * hx, cy + sy * hy, cz + sz * hz] + + quad(sink, v(-1, -1, 1), v(1, -1, 1), v(1, 1, 1), v(-1, 1, 1), colour) // +Z + quad(sink, v(1, -1, -1), v(-1, -1, -1), v(-1, 1, -1), v(1, 1, -1), colour) // -Z + quad(sink, v(1, -1, 1), v(1, -1, -1), v(1, 1, -1), v(1, 1, 1), colour) // +X + quad(sink, v(-1, -1, -1), v(-1, -1, 1), v(-1, 1, 1), v(-1, 1, -1), colour) // -X + quad(sink, v(-1, 1, 1), v(1, 1, 1), v(1, 1, -1), v(-1, 1, -1), colour) // +Y + quad(sink, v(-1, -1, -1), v(1, -1, -1), v(1, -1, 1), v(-1, -1, 1), colour) // -Y + + return finish(sink) +} + +/** + * Chamfered box — the kit's most important primitive. It can taper. + * + * A sharp 90° corner does not exist in nature. The edge of a hand-planed board + * chips, the corner of forged iron rounds over. The chamfer band catches light + * at a different angle than its neighbouring faces, and the object stops being + * a "box" and turns into a physical part. The first version of the kit was + * chamferless boxes from end to end and all of it looked like toys. + * + * Because the bottom and top cross sections can be given separately, it stands + * in for both the straight box and the tapering box — keeping the two as + * separate primitives would have permanently left open the risk of chamfering + * one and leaving the other sharp. + * + * Single-facet chamfer (vibe3d modelling rule 2: one facet by default, a second + * only on masses that carry the silhouette). The cost is 44 triangles instead of 12. + * + * Winding: the 6 faces were worked out by hand; the 12 edges and 8 corners + * CORRECT THEMSELVES against the expected outward direction. Deriving the + * winding of twenty pieces by hand invites mistakes, while the expected normal + * is already known — flipping whatever comes out reversed is both shorter and certain. + */ +export function chamferedBoxGeometry( + bottom: readonly [number, number], + top: readonly [number, number], + height: number, + chamfer: number, + centre: Vec3, + colour: Color, + colourTop?: Color, +): BufferGeometry { + const sink: Sink = { position: [], color: [] } + const [cx, cy, cz] = centre + const hy = height / 2 + const minHalf = Math.min(bottom[0], bottom[1], top[0], top[1]) / 2 + const c = Math.max(1e-6, Math.min(chamfer, minHalf * 0.5, hy * 0.5)) + const upper = colourTop ?? colour + + /** + * `full` sits exactly at the end on its axis, the others a chamfer inside. + * The horizontal half-measures are interpolated between the bottom and top + * cross section according to height. + */ + const p = (sx: number, sy: number, sz: number, full: 0 | 1 | 2): Vec3 => { + const y = cy + sy * (full === 1 ? hy : hy - c) + const t = height <= 1e-9 ? 0 : (y - (cy - hy)) / height + const hx = (bottom[0] + (top[0] - bottom[0]) * t) / 2 + const hz = (bottom[1] + (top[1] - bottom[1]) * t) / 2 + return [ + cx + sx * (full === 0 ? hx : hx - c), + y, + cz + sz * (full === 2 ? hz : hz - c), + ] + } + const shade = (v: Vec3): Color => + colourTop ? new Color().copy(colour).lerp(upper, (v[1] - (cy - hy)) / Math.max(1e-9, height)) : colour + + const face = (a: Vec3, b: Vec3, d: Vec3, e: Vec3): void => { + tri(sink, a, b, d, shade(a)); tri(sink, a, d, e, shade(a)) + } + face(p(-1, -1, 1, 2), p(1, -1, 1, 2), p(1, 1, 1, 2), p(-1, 1, 1, 2)) // +Z + face(p(1, -1, -1, 2), p(-1, -1, -1, 2), p(-1, 1, -1, 2), p(1, 1, -1, 2)) // -Z + face(p(1, -1, 1, 0), p(1, -1, -1, 0), p(1, 1, -1, 0), p(1, 1, 1, 0)) // +X + face(p(-1, -1, -1, 0), p(-1, -1, 1, 0), p(-1, 1, 1, 0), p(-1, 1, -1, 0)) // -X + face(p(-1, 1, 1, 1), p(1, 1, 1, 1), p(1, 1, -1, 1), p(-1, 1, -1, 1)) // +Y + face(p(-1, -1, -1, 1), p(1, -1, -1, 1), p(1, -1, 1, 1), p(-1, -1, 1, 1)) // -Y + + /** Writes the triangle against the expected outward direction, flipping it if needed. */ + const oriented = (a: Vec3, b: Vec3, d: Vec3, outward: readonly number[]): void => { + const e1 = [b[0] - a[0], b[1] - a[1], b[2] - a[2]] + const e2 = [d[0] - a[0], d[1] - a[1], d[2] - a[2]] + const n = [ + e1[1]! * e2[2]! - e1[2]! * e2[1]!, + e1[2]! * e2[0]! - e1[0]! * e2[2]!, + e1[0]! * e2[1]! - e1[1]! * e2[0]!, + ] + const dot = n[0]! * outward[0]! + n[1]! * outward[1]! + n[2]! * outward[2]! + if (dot >= 0) tri(sink, a, b, d, shade(a)) + else tri(sink, a, d, b, shade(a)) + } + + const signs = [-1, 1] as const + for (const axis of [0, 1, 2] as const) { + const [u, v] = [0, 1, 2].filter((i) => i !== axis) as [0 | 1 | 2, 0 | 1 | 2] + for (const su of signs) for (const sv of signs) { + const at = (along: number, full: 0 | 1 | 2): Vec3 => { + const sign: [number, number, number] = [0, 0, 0] + sign[axis] = along; sign[u] = su; sign[v] = sv + return p(sign[0], sign[1], sign[2], full) + } + const outward = [0, 1, 2].map((i) => (i === u ? su : i === v ? sv : 0)) + oriented(at(-1, u), at(-1, v), at(1, v), outward) + oriented(at(-1, u), at(1, v), at(1, u), outward) + } + } + for (const sx of signs) for (const sy of signs) for (const sz of signs) { + oriented(p(sx, sy, sz, 0), p(sx, sy, sz, 1), p(sx, sy, sz, 2), [sx, sy, sz]) + } + + return finish(sink) +} + +/** + * Truncated cone / prism: feet, shafts, bowls, flame tongues. + * + * If `colourTop` is given the colour ramps with height — needed for the flame, + * because the base of a flame is not the same colour as its tip. + */ +export function prismGeometry( + radiusBottom: number, + radiusTop: number, + height: number, + segments: number, + centre: Vec3, + colour: Color, + options: { readonly capTop?: boolean; readonly capBottom?: boolean; readonly colourTop?: Color } = {}, +): BufferGeometry { + const sink: Sink = { position: [], color: [] } + const { capTop = true, capBottom = true } = options + const top = options.colourTop ?? colour + const [cx, cy, cz] = centre + const low = cy - height / 2 + const high = cy + height / 2 + const stepAngle = (Math.PI * 2) / segments + const shift = (p: Vec3): Vec3 => [p[0] + cx, p[1], p[2] + cz] + + for (let i = 0; i < segments; i += 1) { + const a0 = i * stepAngle + const a1 = (i + 1) * stepAngle + const l0 = shift(point(a0, radiusBottom, low)) + const l1 = shift(point(a1, radiusBottom, low)) + const h0 = shift(point(a0, radiusTop, high)) + const h1 = shift(point(a1, radiusTop, high)) + + // Side face: points outward. + triShaded(sink, l0, l1, h1, colour, colour, top) + triShaded(sink, l0, h1, h0, colour, top, top) + + if (capTop && radiusTop > 0) tri(sink, [cx, high, cz], h0, h1, top) + if (capBottom && radiusBottom > 0) tri(sink, [cx, low, cz], l1, l0, colour) + } + + return finish(sink) +} + +/** + * Turned surface: revolves a profile around the Y axis. + * + * `prismGeometry` is the two-level version of this. When more levels are needed + * this one is used and NO INTERIOR SURFACE FORMS in between — that is the real + * reason to use this instead of stacking prisms on top of each other: stacked + * prisms leave a pair of coincident faces where they touch, a single lathe + * does not. + * + * Everything round in the kit comes out of this: tool shafts and grip bulges, + * conical sockets, pitchfork tines, and later jugs/candlesticks/wheel hubs. + */ +export function latheGeometry( + levels: readonly Level[], + segments: number, + centre: Vec3, + colour: Color, + options: { readonly capTop?: boolean; readonly capBottom?: boolean; readonly colourTop?: Color } = {}, +): BufferGeometry { + if (levels.length < 2) throw new Error('latheGeometry needs at least two levels') + const sink: Sink = { position: [], color: [] } + const { capTop = true, capBottom = true } = options + const top = options.colourTop ?? colour + const [cx, cy, cz] = centre + const stepAngle = (Math.PI * 2) / segments + const shift = (p: Vec3): Vec3 => [p[0] + cx, p[1] + cy, p[2] + cz] + const lerp = (t: number): Color => new Color().copy(colour).lerp(top, t) + + for (let i = 0; i < levels.length - 1; i += 1) { + const low = levels[i]! + const high = levels[i + 1]! + const tLow = i / (levels.length - 1) + const tHigh = (i + 1) / (levels.length - 1) + const cLow = lerp(tLow) + const cHigh = lerp(tHigh) + + for (let j = 0; j < segments; j += 1) { + const a0 = j * stepAngle + const a1 = (j + 1) * stepAngle + const l0 = shift(point(a0, low.radius, low.y)) + const l1 = shift(point(a1, low.radius, low.y)) + const h0 = shift(point(a0, high.radius, high.y)) + const h1 = shift(point(a1, high.radius, high.y)) + // At a level whose radius is zero that edge collapses to a point; it is + // closed with a single triangle so no degenerate triangle is produced. + if (low.radius <= 1e-6) { triShaded(sink, l0, h1, h0, cLow, cHigh, cHigh); continue } + if (high.radius <= 1e-6) { triShaded(sink, l0, l1, h0, cLow, cLow, cHigh); continue } + triShaded(sink, l0, l1, h1, cLow, cLow, cHigh) + triShaded(sink, l0, h1, h0, cLow, cHigh, cHigh) + } + } + + const first = levels[0]! + const last = levels.at(-1)! + for (let j = 0; j < segments; j += 1) { + const a0 = j * stepAngle + const a1 = (j + 1) * stepAngle + if (capBottom && first.radius > 1e-6) { + tri(sink, shift([0, first.y, 0]), + shift(point(a1, first.radius, first.y)), shift(point(a0, first.radius, first.y)), colour) + } + if (capTop && last.radius > 1e-6) { + tri(sink, shift([0, last.y, 0]), + shift(point(a0, last.radius, last.y)), shift(point(a1, last.radius, last.y)), top) + } + } + return finish(sink) +} + +/** + * A single barrel stave: one slice of the ring, a closed solid with thickness. + * + * Every level has four corners: + * A = outer/start angle B = outer/end angle + * C = inner/end angle D = inner/start angle + */ +export function staveGeometry( + levels: readonly Level[], + angleStart: number, + angleEnd: number, + thickness: number, + colour: Color, +): BufferGeometry { + if (levels.length < 2) throw new Error('staveGeometry needs at least two levels') + + const sink: Sink = { position: [], color: [] } + + const corners = levels.map((level) => { + // Thickness cannot exceed half the thinnest radius; otherwise the inner surface breaks out. + const inner = Math.max(level.radius * 0.5, level.radius - thickness) + return { + a: point(angleStart, level.radius, level.y), + b: point(angleEnd, level.radius, level.y), + c: point(angleEnd, inner, level.y), + d: point(angleStart, inner, level.y), + } + }) + + for (let i = 0; i < corners.length - 1; i += 1) { + const low = corners[i]! + const high = corners[i + 1]! + quad(sink, low.a, low.b, high.b, high.a, colour) // outer face → points outward + quad(sink, low.c, low.d, high.d, high.c, colour) // inner face → points at the axis + quad(sink, low.d, low.a, high.a, high.d, colour) // start edge + quad(sink, low.b, low.c, high.c, high.b, colour) // end edge + } + + const top = corners.at(-1)! + const bottom = corners[0]! + quad(sink, top.a, top.b, top.c, top.d, colour) // top cap → +Y + quad(sink, bottom.d, bottom.c, bottom.b, bottom.a, colour) // bottom cap → -Y + + return finish(sink) +} + +/** + * Iron hoop: a ring with a rectangular cross section. + * + * The inner surface is deliberately not generated — the body it leans against + * hides it from every camera. A quarter of the triangle budget is won here. + */ +export function bandGeometry( + radius: number, + y: number, + height: number, + thickness: number, + segments: number, + colour: Color, + options: { + /** + * Generate the inner face as well. + * + * Not generated by default, because a hoop always wraps a body and the + * inner face is not visible — not generating it is a free triangle saving. + * But a free-standing ring (the cord of a sack, the tie of a bale) becomes + * a solid that is NOT CLOSED this way, and the "no reversed faces" check in + * the validation rightly fails. This flag is for that case. + */ + readonly inner?: boolean + } = {}, +): BufferGeometry { + const sink: Sink = { position: [], color: [] } + const half = height / 2 + const inner = radius - thickness + const stepAngle = (Math.PI * 2) / segments + + for (let i = 0; i < segments; i += 1) { + const a0 = i * stepAngle + const a1 = (i + 1) * stepAngle + + const outerLow0 = point(a0, radius, y - half) + const outerLow1 = point(a1, radius, y - half) + const outerHigh0 = point(a0, radius, y + half) + const outerHigh1 = point(a1, radius, y + half) + const innerHigh0 = point(a0, inner, y + half) + const innerHigh1 = point(a1, inner, y + half) + const innerLow0 = point(a0, inner, y - half) + const innerLow1 = point(a1, inner, y - half) + + quad(sink, outerLow0, outerLow1, outerHigh1, outerHigh0, colour) // outer → outward + quad(sink, outerHigh0, outerHigh1, innerHigh1, innerHigh0, colour) // top → +Y + quad(sink, innerLow0, innerLow1, outerLow1, outerLow0, colour) // bottom → -Y + // Inner face: the corner order is the reverse of the outer one so the normal points AT THE AXIS. + if (options.inner) { + quad(sink, innerHigh0, innerHigh1, innerLow1, innerLow0, colour) + } + } + + return finish(sink) +} + +/** + * Fan disc: barrel head, bowl bottom. + * + * So that it reads as built from several boards rather than one piece of wood, + * every triangle falls into a "board band" according to the X position of its + * centre, and the tone of that band is written into the vertex colour. The + * geometry cost is zero. + */ +export function headGeometry( + radius: number, + y: number, + segments: number, + facing: 'up' | 'down', + colour: Color, + plankCount: number, + plankShade: number, +): BufferGeometry { + const sink: Sink = { position: [], color: [] } + const centre: Vec3 = [0, y, 0] + const stepAngle = (Math.PI * 2) / segments + const plankWidth = (radius * 2) / Math.max(1, plankCount) + const tint = new Color() + + for (let i = 0; i < segments; i += 1) { + const p0 = point(i * stepAngle, radius, y) + const p1 = point((i + 1) * stepAngle, radius, y) + + // The boards are strips sliced along the X axis; whichever strip the X of + // the triangle's centroid falls into gives it its tone. + const centroidX = (p0[0] + p1[0]) / 3 + const band = Math.floor((centroidX + radius) / plankWidth) + tint.copy(colour).multiplyScalar(1 + (band % 2 === 0 ? plankShade : -plankShade)) + + if (facing === 'up') tri(sink, centre, p0, p1, tint) + else tri(sink, centre, p1, p0, tint) + } + + return finish(sink) +} + +/** + * Tapering box: a body whose bottom and top rectangles may differ. + * + * Anvil horn, stool leg, fence post tip, tool handle — every "box but carved" + * part of the kit is this. The winding follows the same logic as boxGeometry. + */ +export function taperedBoxGeometry( + bottom: readonly [number, number], + top: readonly [number, number], + height: number, + centre: Vec3, + colour: Color, + colourTop?: Color, +): BufferGeometry { + const sink: Sink = { position: [], color: [] } + const [cx, cy, cz] = centre + const low = cy - height / 2 + const high = cy + height / 2 + const upper = colourTop ?? colour + + // b = bottom corners, t = top corners; both in the same order: + // (-x,+z) (+x,+z) (+x,-z) (-x,-z) + const corner = (size: readonly [number, number], y: number, sx: number, sz: number): Vec3 => + [cx + (sx * size[0]) / 2, y, cz + (sz * size[1]) / 2] + + const b0 = corner(bottom, low, -1, 1), b1 = corner(bottom, low, 1, 1) + const b2 = corner(bottom, low, 1, -1), b3 = corner(bottom, low, -1, -1) + const t0 = corner(top, high, -1, 1), t1 = corner(top, high, 1, 1) + const t2 = corner(top, high, 1, -1), t3 = corner(top, high, -1, -1) + + const side = (bl: Vec3, br: Vec3, tr: Vec3, tl: Vec3): void => { + triShaded(sink, bl, br, tr, colour, colour, upper) + triShaded(sink, bl, tr, tl, colour, upper, upper) + } + side(b0, b1, t1, t0) // +Z + side(b2, b3, t3, t2) // -Z + side(b1, b2, t2, t1) // +X + side(b3, b0, t0, t3) // -X + + quad(sink, t0, t1, t2, t3, upper) // top → +Y + quad(sink, b3, b2, b1, b0, colour) // bottom → -Y + return finish(sink) +} + +/** + * Square-section bar swept along an arc — bucket handle, ring, hook. + * + * The cross section is laid out counter-clockwise relative to the sweep + * direction (the tangent); that is what makes the outer faces point outward. + * The arc is generated in the XY plane, the model rotates it as it likes. + */ +export function arcBarGeometry( + radius: number, + thickness: number, + fromAngle: number, + toAngle: number, + segments: number, + centre: Vec3, + colour: Color, +): BufferGeometry { + const sink: Sink = { position: [], color: [] } + const h = thickness / 2 + const [cx, cy, cz] = centre + const rings: Vec3[][] = [] + + for (let i = 0; i <= segments; i += 1) { + const a = fromAngle + ((toAngle - fromAngle) * i) / segments + // p: the point on the arc. r: the radial direction. z: the plane normal. + const px = cx + Math.cos(a) * radius + const py = cy + Math.sin(a) * radius + const rx = Math.cos(a), ry = Math.sin(a) + const at = (su: number, sv: number): Vec3 => + [px + sv * h * rx, py + sv * h * ry, cz + su * h] + // u = the plane normal, v = the radial direction. Since u×v equals the + // tangent, this ordering is counter-clockwise relative to the sweep direction. + rings.push([at(1, 1), at(-1, 1), at(-1, -1), at(1, -1)]) + } + + for (let i = 0; i < segments; i += 1) { + const a = rings[i]!, b = rings[i + 1]! + for (let j = 0; j < 4; j += 1) { + const k = (j + 1) % 4 + quad(sink, a[j]!, a[k]!, b[k]!, b[j]!, colour) + } + } + + const first = rings[0]!, last = rings[segments]! + quad(sink, first[0]!, first[3]!, first[2]!, first[1]!, colour) // start cap + quad(sink, last[0]!, last[1]!, last[2]!, last[3]!, colour) // end cap + return finish(sink) +} + +export interface SheetLevel { + /** Vertical position. */ + readonly y: number + /** Half width at that height. */ + readonly halfWidth: number + /** Sheet thickness. */ + readonly thickness: number + /** Curve height: how far the edges rise relative to the middle. 0 = flat. */ + readonly curve: number +} + +/** + * Dished sheet — a single piece, a seamless concave surface. + * + * I tried twice to build the shovel blade from three separate flat panels and + * both times the result was "three boards side by side": because each panel + * rotates around its own centre, a step is left between them and the eye did + * not read it as one surface. + * + * The right way is to produce ONE sheet whose cross section is curved. The + * cross section is an arc bent by `curve` at every level; width and thickness + * can change from level to level. The hollow faces the +Z direction. + * + * Besides the shovel, the shield, the trough, the roof covering and the mill + * sail all want this. + */ +export function dishedSheetGeometry( + levels: readonly SheetLevel[], + segments: number, + colour: Color, + colourTop?: Color, +): BufferGeometry { + if (levels.length < 2) throw new Error('dishedSheetGeometry needs at least two levels') + const sink: Sink = { position: [], color: [] } + const top = colourTop ?? colour + const shade = (i: number): Color => + colourTop ? new Color().copy(colour).lerp(top, i / (levels.length - 1)) : colour + + // front[i][j] / back[i][j]: level i, position j along the cross section + const front: Vec3[][] = [] + const back: Vec3[][] = [] + for (const level of levels) { + const f: Vec3[] = [] + const b: Vec3[] = [] + for (let j = 0; j <= segments; j += 1) { + const u = (j / segments) * 2 - 1 // -1 .. +1 + const x = u * level.halfWidth + // Parabolic cross section: 0 in the middle, `curve` at the edges. The + // rise of the edges is what forms the hollow. + const z = level.curve * u * u + f.push([x, level.y, z + level.thickness / 2]) + b.push([x, level.y, z - level.thickness / 2]) + } + front.push(f) + back.push(b) + } + + const last = levels.length - 1 + for (let i = 0; i < last; i += 1) { + for (let j = 0; j < segments; j += 1) { + // Front face: points at +Z. (a→b = +X, a→c = +X+Y, cross product +Z.) + triShaded(sink, front[i]![j]!, front[i]![j + 1]!, front[i + 1]![j + 1]!, + shade(i), shade(i), shade(i + 1)) + triShaded(sink, front[i]![j]!, front[i + 1]![j + 1]!, front[i + 1]![j]!, + shade(i), shade(i + 1), shade(i + 1)) + // Back face: reversed winding. + triShaded(sink, back[i]![j]!, back[i + 1]![j + 1]!, back[i]![j + 1]!, + shade(i), shade(i + 1), shade(i)) + triShaded(sink, back[i]![j]!, back[i + 1]![j]!, back[i + 1]![j + 1]!, + shade(i), shade(i + 1), shade(i + 1)) + } + + // Side edges: the right one points at +X, the left one at -X. + quad(sink, front[i]![segments]!, back[i]![segments]!, + back[i + 1]![segments]!, front[i + 1]![segments]!, shade(i)) + quad(sink, back[i]![0]!, front[i]![0]!, + front[i + 1]![0]!, back[i + 1]![0]!, shade(i)) + } + + // Top and bottom edge strips. + for (let j = 0; j < segments; j += 1) { + quad(sink, front[last]![j]!, front[last]![j + 1]!, + back[last]![j + 1]!, back[last]![j]!, shade(last)) + quad(sink, back[0]![j]!, back[0]![j + 1]!, + front[0]![j + 1]!, front[0]![j]!, shade(0)) + } + + return finish(sink) +} + +/** + * Reverses the winding of every triangle, i.e. turns all the normals around. + * + * Needed for vessels whose inside is visible: the outer surface of a bowl must + * point outward, the inner surface inward. Instead of writing the two + * separately, we generate the same cone and flip one of them. + */ +export function flipGeometry(geometry: BufferGeometry): BufferGeometry { + for (const name of ['position', 'color'] as const) { + const attribute = geometry.getAttribute(name) + if (!attribute) continue + const array = attribute.array as Float32Array + const stride = attribute.itemSize + // Swapping the 2nd and 3rd corner of a triangle reverses the winding. + for (let i = 0; i < attribute.count; i += 3) { + for (let k = 0; k < stride; k += 1) { + const b = (i + 1) * stride + k + const c = (i + 2) * stride + k + const swap = array[b]! + array[b] = array[c]! + array[c] = swap + } + } + attribute.needsUpdate = true + } + return geometry +} + +/** + * Reduces parts that share the same material into a single geometry — one draw + * call per material. The normals are computed AFTER merging: on non-indexed + * geometry that gives every triangle its own normal, i.e. flat shading. + */ +export function mergeColoured(geometries: readonly BufferGeometry[]): BufferGeometry { + // The normals of the inputs are dropped. The reason is a trap: because this + // function computes normals AFTER merging, its output has a `normal` + // attribute while the raw geometries do not. Trying to merge the two + // together made mergeGeometries fail with "attribute counts do not match". + // Since they are recomputed below anyway, the input normal data is worthless. + for (const geometry of geometries) geometry.deleteAttribute('normal') + + const merged = mergeGeometries(geometries as BufferGeometry[], false) + if (!merged) throw new Error('Could not merge geometries: attribute sets do not match') + for (const geometry of geometries) geometry.dispose() + merged.computeVertexNormals() + return merged +} + +/** + * Bends a straight body into an arc (along the Y axis, in the YZ plane). + * + * Written for pitchfork tines. A straight tine, however thick it is, looks + * like a technical drawing; a slight curve turns it into a forged tool. Hooks, + * horns and scythes have the same need. + * + * The simple "rotate every point in proportion to its own height" approach + * stretched the body and thinned it. The transform here is a real arc mapping: + * the body is WRAPPED onto a circle of radius 1/curvature, so the length of the + * centre line is preserved. + * + * TWO TRAPS, both found by measuring: + * + * 1. The arc is wrapped around y=0, so THE RESULT DEPENDS ON WHERE THE GEOMETRY + * SITS IN Y. A bar whose base is at the origin really does curve; a body + * CENTRED on y=0 bends symmetrically — its two ends go the same way, its + * middle stays put, and the silhouette barely changes at all. That is exactly + * what happened with the hoe blade: on a 0.235 m blade the bend produced + * 14 mm of displacement but DROPPED the Z range from 0.0337 to 0.0327. Build + * the same blade with its base at the origin and bend it, and the offset is + * 44 mm and the range 0.078. START whatever you want to bend at the origin. + * + * 2. The arc is only as smooth as the number of CROSS SECTIONS the geometry has + * along the Y axis. A two-level box (chamferedBoxGeometry) bent gives not an + * arc but a skewed box. A real arc needs a body with intermediate levels, + * like `latheGeometry`. + * + * @param curvature 1/radius. A positive value bends toward +Z. 0 does nothing. + */ +export function bendGeometry(geometry: BufferGeometry, curvature: number): BufferGeometry { + if (Math.abs(curvature) < 1e-9) return geometry + const position = geometry.getAttribute('position') + + // A bend needs something to bend. + // + // Every vertex is mapped by its own Y, so the curve only exists where there + // are Y levels to sample it at. Hand this a `boxGeometry` -- two levels, top + // and bottom -- and there is no midpoint to displace: the top face swings to + // one angle, the bottom to another, and the result is a sheared wedge that + // looks nothing like an arc. It fails silently, which is the expensive part. + // + // This session found the same mistake in three separate models: the + // tankard's handle, and both the brace and the curl of the tavern sign. In + // each the author had written a curve, the geometry had never curved, and + // the renders had been shipping the wedge. Three is a pattern, so the + // helper refuses rather than waiting for a fourth. + // + // The fix is never to nudge the curvature -- it is to give the piece levels + // (a lathe or a stack of them), or to use `arcBarGeometry`, which sweeps a + // real arc and takes the two things that actually matter: where the ends go. + const seen = new Set() + for (let i = 0; i < position.count && seen.size < 3; i += 1) { + seen.add(Math.round(position.getY(i) * 1e5)) + } + if (seen.size < 3) { + throw new Error( + `bendGeometry: geometry has ${seen.size} distinct Y level(s); a bend needs at least 3. ` + + 'Two levels shear into a wedge instead of curving. Build the piece with ' + + 'levels (latheGeometry / staveGeometry) or use arcBarGeometry.', + ) + } + + const radius = 1 / curvature + for (let i = 0; i < position.count; i += 1) { + const y = position.getY(i) + const z = position.getZ(i) + const angle = y * curvature + const sin = Math.sin(angle) + const cos = Math.cos(angle) + // Centre line + the cross section's offset perpendicular to the tangent. + position.setY(i, radius * sin - z * sin) + position.setZ(i, radius * (1 - cos) + z * cos) + } + position.needsUpdate = true + geometry.computeVertexNormals() + return geometry +} + +/** Deterministic hash derived from position. The same point always gives the same value. */ +function positionHash(x: number, y: number, z: number, salt: number): number { + // The point is rounded to a 0.1 mm grid: "identical" corners getting + // different hashes because of floating point noise was the one bug that tore + // the surface open. + let h = Math.imul(Math.round(x * 1e4) | 0, 0x27d4eb2d) + h ^= Math.imul(Math.round(y * 1e4) | 0, 0x165667b1) + h ^= Math.imul(Math.round(z * 1e4) | 0, 0x9e3779b1) + h = Math.imul(h ^ salt, 0x85ebca6b) + h ^= h >>> 13 + return ((h >>> 0) / 0xffffffff) * 2 - 1 +} + +export interface RoughenOptions { + /** For distorting the same geometry in a different way. */ + readonly salt?: number + /** Deviation multiplier on the Y axis. Kept low on the straw bale. */ + readonly scaleY?: number +} + +/** + * Makes the surface irregular: every corner shifts by a fixed amount derived + * from its own position. + * + * Why it is derived from position: these geometries are NON-INDEXED, i.e. every + * triangle carries its own corners and three or four copies sit at one point. + * Moving the corners independently tears the surface — on the first attempt the + * straw bale ended up riddled with holes. Because the position hash gives all + * the copies at the same point the SAME shift, the surface stays closed. + * + * This is the only thing that makes straw look like straw: a tidy box looks + * like a sponge whatever colour you give it. + */ +export function roughenGeometry( + geometry: BufferGeometry, + amount: number, + options: RoughenOptions = {}, +): BufferGeometry { + if (amount <= 0) return geometry + const salt = options.salt ?? 0 + const scaleY = options.scaleY ?? 1 + const position = geometry.getAttribute('position') + for (let i = 0; i < position.count; i += 1) { + const x = position.getX(i) + const y = position.getY(i) + const z = position.getZ(i) + position.setXYZ( + i, + x + positionHash(x, y, z, salt + 1) * amount, + y + positionHash(x, y, z, salt + 2) * amount * scaleY, + z + positionHash(x, y, z, salt + 3) * amount, + ) + } + position.needsUpdate = true + geometry.computeVertexNormals() + return geometry +} + +export interface MottleOptions { + /** For giving the same geometry a different pattern. */ + readonly salt?: number + /** + * The size of the specks (metres). Because positions are rounded to this + * grid and then hashed, corners in the same cell take the same tone — so what + * forms is not noise but MOTTLE. A small value gives sand, a large one a + * mottled surface. + */ + readonly cell?: number + /** The ratio of the hue shift to the brightness shift. A high value colours the mottle. */ + readonly hue?: number +} + +/** + * Works surface mottle into the vertex colours. + * + * This is this kit's answer to the question "what are we going to do about + * texture?". A bitmap texture would have wanted three things: UV coordinates + * (our geometry has none), image files the registry would have to carry, and a + * change to the kit's identity. All three cost more than they give back. + * + * Instead, a mottle pattern derived from the surface's OWN position is used. + * `bakeOcclusion` produced shadow from the SHAPE of the surface; this gives the + * surface a material texture. Together, with no texture file at all, the two + * make a flat-coloured lowpoly surface look like material. + * + * The limit should be stated honestly: the specks are sampled at the corners of + * the geometry, so triangle density sets their resolution. On a wide, sparsely + * subdivided surface shrinking `cell` does not help — there the cure is to + * subdivide the triangle, which eats into the lowpoly budget. + */ +export function mottleGeometry( + geometry: BufferGeometry, + amount: number, + options: MottleOptions = {}, +): BufferGeometry { + const colour = geometry.getAttribute('color') + if (!colour || amount <= 0) return geometry + const position = geometry.getAttribute('position') + const salt = options.salt ?? 0 + const cell = options.cell ?? 0.05 + const hue = options.hue ?? 0.35 + + for (let i = 0; i < colour.count; i += 1) { + const x = Math.round(position.getX(i) / cell) * cell + const y = Math.round(position.getY(i) / cell) * cell + const z = Math.round(position.getZ(i) / cell) * cell + const shade = 1 + positionHash(x, y, z, salt + 7) * amount + // A small difference between the channels: on a real material a lightened + // spot does not just get brighter, it also loses a little saturation. + const warm = positionHash(x, y, z, salt + 8) * amount * hue + colour.setXYZ( + i, + Math.max(0, colour.getX(i) * (shade + warm)), + Math.max(0, colour.getY(i) * shade), + Math.max(0, colour.getZ(i) * (shade - warm)), + ) + } + colour.needsUpdate = true + return geometry +} diff --git a/contemporary-props/models/core/index.ts b/contemporary-props/models/core/index.ts new file mode 100644 index 0000000..369a420 --- /dev/null +++ b/contemporary-props/models/core/index.ts @@ -0,0 +1,31 @@ +export { createRandom, jitter } from './random.ts' +export { + arcBarGeometry, + bandGeometry, + bendGeometry, + boxGeometry, + chamferedBoxGeometry, + dishedSheetGeometry, + flipGeometry, + headGeometry, + latheGeometry, + mergeColoured, + mottleGeometry, + prismGeometry, + roughenGeometry, + staveGeometry, + taperedBoxGeometry, +} from './geometry.ts' +export type { Level, MottleOptions, RoughenOptions, SheetLevel, Vec3 } from './geometry.ts' +export { bakeOcclusion } from './occlusion.ts' +export type { OcclusionOptions } from './occlusion.ts' +export { createKitModel } from './kit.ts' +export type { BuildContext, BuiltPart, KitModelOptions, PartBody, RuntimeContext } from './kit.ts' +export { createPart } from './parts.ts' +export type { PartSlot } from './parts.ts' +export { ironTint, steelTint, toolShaft, toolSocket } from './tool.ts' +export type { ShaftOptions, SocketOptions, ToolShaft } from './tool.ts' +export { PROP_PALETTE, createPropMaterials } from './materials.ts' +export { createTinter } from './tint.ts' +export type { Tinter } from './tint.ts' +export type { PropPalette, PropSlot } from './materials.ts' diff --git a/contemporary-props/models/core/kit.ts b/contemporary-props/models/core/kit.ts new file mode 100644 index 0000000..4c73a6e --- /dev/null +++ b/contemporary-props/models/core/kit.ts @@ -0,0 +1,341 @@ +import { Group, Mesh, type BufferGeometry, type Material } from 'three' + +import type { ConfigureResult, MaterialBindings, ModelInstance, PartHandle } from '@vibe3d/model.ts' +import { ResourceScope } from '@vibe3d/ownership.ts' + +import type { Vec3 } from './geometry.ts' +import { mottleGeometry } from './geometry.ts' +import { bakeOcclusion, type OcclusionOptions } from './occlusion.ts' +import { createPart, type PartSlot } from './parts.ts' +import { createRandom } from './random.ts' +import { createPropMaterials, type PropSlot, type SlotMaterial } from './materials.ts' + +/** + * Kit model scaffold. + * + * Every model has to set up the same contract: resource ownership, material + * resolution and overrides, fixed anchor + replaceable content, a configure() + * that does not break identity, an idempotent dispose(). Writing that by hand + * in every model means ~80 lines of repetition plus a chance to get it wrong + * on each repetition — and indeed I got the anchor/content split wrong in the + * first three models at once. + * + * From here on, writing a model is just producing geometry: `build` returns a + * part name → geometry mapping, this function handles the rest. + */ + +/** The body of a part that uses a single material slot. */ +export interface PartBody { + readonly slot: S + readonly geometry: BufferGeometry +} + +export interface BuiltPart extends PartBody { + /** + * Extra bodies belonging to the same part that use a DIFFERENT slot. + * + * Parts are sibling children of the root, so when one moves the others + * cannot follow it. A chest's lid is oak boards and iron bands and the + * lock's hasp all at once, and the three MUST rotate together — if they were + * separate parts, the bands would hang in mid-air as the lid opened. + * + * So this field does not preserve the assumption "one part = one mesh", it + * preserves the principle "one part = one meaning". The meaning is not + * split, only the material is. + */ + readonly extras?: readonly PartBody[] + /** + * The part's own centre of rotation (in model space). + * + * When given, the anchor is positioned here and the geometry is assumed to + * have been written RELATIVE TO THIS POINT. This is the only thing needed + * for a chest lid to rotate around its hinge: the lid geometry is produced + * at the hinge origin, the anchor is moved to the hinge, and + * `anchor.rotation.x` now opens the lid. + * + * Objects the consumer attached to the anchor join this rotation too — a + * candle placed on top of the lid rises with the lid. That is the correct + * behaviour. + */ + readonly origin?: Vec3 +} + +export interface BuildContext { + readonly config: Readonly + /** Seed-bound deterministic randomness. Starts over on every rebuild. */ + readonly random: () => number + /** The slot's current material (the override, if there is one). */ + resolve(slot: S): Material + /** The slot's default material — even if it has been overridden. */ + readonly defaults: Pick +} + +/** + * The runtime context handed to actions and to `update`. + * + * It gives access to the PARTS, not to the geometry: an action must not + * trigger a rebuild, it should only move something in the scene graph. Opening + * the lid does not change the model's identity, so it is not `configure()`'s + * job. + */ +export interface RuntimeContext { + readonly parts: Record> + getConfig(): Readonly +} + +export interface KitModelOptions< + C extends { seed: number }, + S extends PropSlot, + P extends string, + A extends object = Record, +> { + /** Registry item name; used in mesh names and in userData. */ + readonly id: string + readonly defaults: C + readonly slots: readonly S[] + /** Part name → geometry. `undefined` means absent in that configuration. */ + build(context: BuildContext): Record | undefined> + /** + * Ambient occlusion to bake into the vertex colours. `false` turns it off. + * + * All parts are evaluated TOGETHER: the place where a board darkens is the + * surface of the neighbouring post, not its own surface. + */ + readonly occlusion?: OcclusionOptions | false + /** + * Surface mottle written into the vertex colours. `false` turns it off. + * + * The amount is scaled BY SLOT (see the table below): burnished steel is not + * mottled, straw is mottled badly. The model does not have to do anything + * else. + */ + readonly mottle?: { readonly amount?: number; readonly cell?: number } | false + /** + * The model's typed actions. Set up once, after the first build — so state + * held in the closure (is the lid open, which flame phase) survives a + * rebuild. + */ + actions?(context: RuntimeContext): A + /** Called each frame. If the consumer never calls it, the model stays fully static. */ + update?(deltaSeconds: number, context: RuntimeContext): void +} + +/** + * Mottle multiplier per slot. + * + * The rule comes from the physics of the material: the more polished a surface + * is, the more it becomes a SINGLE COLOUR, because the light reaching the eye + * comes from the reflection rather than from the surface's own pigment. For + * straw and cloth the exact opposite holds. + * + * Tying this to the slot is better than tuning it separately in every model: + * within the kit the same material looks the same everywhere. + */ +const MOTTLE_BY_SLOT: Readonly> = { + /* + * Lower across the board than the medieval kit's, and that is the point. + * + * Those materials were worked by hand and every one of them varied: a stave + * differs from the stave beside it, straw is never twice the same. These are + * manufactured. An injection moulding is the same colour everywhere it is + * the same part, and mottling it is what makes a new plastic bin look like a + * salvaged one. + * + * So the high values here are the exceptions, and each is a surface that + * genuinely varies at the scale you see it: grain in timber, weave in + * fabric, aggregate in concrete, and the spangle that hot-dip zinc actually + * has and that nothing else in the kit does. + */ + wood: 1, + fabric: 1.1, + concrete: 0.9, + galvanised: 0.8, + cord: 0.6, + rubber: 0.45, + steelPainted: 0.35, + brass: 0.3, + paper: 0.25, + aluminium: 0.25, + stainless: 0.2, + plastic: 0.18, + retroreflective: 0.15, + ceramic: 0.12, + glass: 0.1, + glassTinted: 0.1, + plasticGloss: 0.1, + chrome: 0.08, + // The vertex colour IS the result on an unlit material, so any variation + // here is variation in the light itself rather than in the surface. + emissive: 0, +} + + +export function createKitModel< + C extends { seed: number }, + S extends PropSlot, + P extends string, + A extends object = Record, +>( + options: KitModelOptions, + overrides: Partial = {}, +): ModelInstance>, A> { + let config: C = { ...options.defaults, ...overrides } + + // The resources the model owns. Materials handed in by the consumer never + // enter here, so dispose() does not touch them. + const scope = new ResourceScope() + const defaults = createPropMaterials(scope, options.slots) + const overridesBySlot = new Map() + const resolve = (slot: S): Material => overridesBySlot.get(slot) ?? defaults[slot] + + const root = new Group() + root.name = options.id + + const parts = {} as Record + let owned: BufferGeometry[] = [] + + function build(): void { + for (const geometry of owned) geometry.dispose() + owned = [] + + const produced = options.build({ + config, + random: createRandom(config.seed), + resolve, + defaults, + }) + + const built = Object.values(produced) + .filter((part): part is BuiltPart => part !== undefined) + const geometriesOf = (part: BuiltPart): BufferGeometry[] => + [part, ...(part.extras ?? [])] + // An emitter neither TAKES shadow nor CASTS one. `emissive` is an + // unlit material, so its vertex colour is the final colour going + // straight to the screen, and darkening it with occlusion is the same + // as switching the light off. The rule is tied to the slot itself + // rather than to a per-model flag, so it cannot be forgotten on the + // one object that needed it. + .filter((body) => body.slot !== 'emissive') + .map((body) => body.geometry) + + if (options.occlusion !== false) { + // Occlusion has to be computed in ASSEMBLY space: a lid written at its + // own origin looks as though it sits inside the body rather than beside + // it, and darkens the wrong places. So everything is first moved into + // place, baked, then moved back — the resulting geometries stay + // hinge-local. + const moved = built.filter((part) => part.origin !== undefined) + for (const part of moved) { + const [x, y, z] = part.origin! + for (const geometry of geometriesOf(part)) geometry.translate(x, y, z) + } + bakeOcclusion(built.flatMap(geometriesOf), options.occlusion ?? {}) + for (const part of moved) { + const [x, y, z] = part.origin! + for (const geometry of geometriesOf(part)) geometry.translate(-x, -y, -z) + } + } + + if (options.mottle !== false) { + const amount = options.mottle?.amount ?? 0.125 + // The mottle size is derived from the model's scale, but WITH ABSOLUTE + // BOUNDS. + // + // The bounds were added later and closed a real bug: with scale used on + // its own, a 4.89 m fence got a 0.27 m cell. The fence's post is 0.09 m + // — so the entire post fell into ONE cell and came out completely flat. + // The model paid the cost of the texture system and got nothing back. + // + // The truth is this: wood grain mottle is 2–8 cm and has nothing to do + // with the size of the object. A fence post and a tankard stave come out + // of the same tree. + const extent = built.reduce((largest, part) => { + part.geometry.computeBoundingBox() + const box = part.geometry.boundingBox + if (!box) return largest + return Math.max(largest, box.max.x - box.min.x, box.max.y - box.min.y, box.max.z - box.min.z) + }, 0) + const cell = options.mottle?.cell ?? Math.min(0.08, Math.max(0.015, extent * 0.055)) + for (const part of built) { + for (const body of [part, ...(part.extras ?? [])]) { + mottleGeometry(body.geometry, amount * MOTTLE_BY_SLOT[body.slot], { cell, salt: 3 }) + } + } + } + + for (const [name, part] of Object.entries(produced) as Array<[P, BuiltPart | undefined]>) { + // The anchor is created on first setup and NEVER changes again; only its + // content is renewed. That is why objects the consumer attached to the + // anchor survive a rebuild. + let slot = parts[name] + if (!slot) { + slot = createPart(`${options.id}/${name}`) + parts[name] = slot + root.add(slot.anchor) + } + const target = slot.reset() + if (!part) continue + + // The position is updated but the ROTATION is not: the angle an action + // moved has to survive a rebuild, otherwise the chest's lid slams shut + // every time `configure()` is called. + if (part.origin) slot.anchor.position.set(...part.origin) + + for (const body of [part, ...(part.extras ?? [])]) { + owned.push(body.geometry) + const mesh = new Mesh(body.geometry, resolve(body.slot)) + mesh.name = `${options.id}/${name}` + mesh.userData.vibe3d = { + model: `@contemporary-props/${options.id}`, + part: name, + materialSlot: body.slot, + } + target.add(mesh) + } + } + } + + build() + + const runtime: RuntimeContext = { + parts: parts as unknown as Record>, + getConfig: () => config, + } + const actions = (options.actions?.(runtime) ?? {}) as A + + const materials: MaterialBindings = { + get: (slot) => (options.slots.includes(slot as S) ? resolve(slot as S) : undefined), + override: (slot, material) => { + if (!options.slots.includes(slot as S)) return + overridesBySlot.set(slot as S, material) + build() + }, + reset: (slot) => { + if (!overridesBySlot.delete(slot as S)) return + build() + }, + } + + return { + root, + parts: parts as unknown as Record>, + actions, + materials, + getConfig: () => config, + configure: (patch): ConfigureResult => { + const next = { ...config, ...patch } + const changed = (Object.keys(next) as Array).some((key) => next[key] !== config[key]) + if (!changed) return { rebuilt: false } + config = next + build() + return { rebuilt: true } + }, + update: (deltaSeconds) => options.update?.(deltaSeconds, runtime), + dispose: () => { + for (const geometry of owned) geometry.dispose() + owned = [] + for (const part of Object.values(parts) as PartSlot[]) part.reset() + scope.dispose() + }, + } +} diff --git a/contemporary-props/models/core/materials.ts b/contemporary-props/models/core/materials.ts new file mode 100644 index 0000000..8ba27df --- /dev/null +++ b/contemporary-props/models/core/materials.ts @@ -0,0 +1,351 @@ +/** + * The kit's material slots, and the palette behind them. + * + * A slot exists when a single material cannot carry a difference that a viewer + * can see. That test is stricter than it sounds, and it is what keeps this list + * at nineteen rather than fifty: two objects that differ only in COLOUR share a + * slot, because colour travels in the vertex attribute. A slot is earned by + * roughness, by metalness, by transparency, or by not receiving light at all. + * + * Every slot below is argued from at least three objects in the catalogue. If a + * slot ever ends up with one consumer, it was a colour and it should be folded + * back into whatever it was split from. + * + * Inherited from the medieval kit: `wood`, `steelPainted` (was `iron`), + * `fabric` (was `cloth`), `ceramic` (was `clay`), `brass`, and `cord`, which + * narrows from rope to nylon and PVC. Dropped: leather, thatch, bone, gold and + * wax, none of which has a consumer across 250 present-day objects. + */ +import { + Color, + MeshBasicMaterial, + MeshStandardMaterial, + DoubleSide, +} from 'three' + +import type { ResourceScope } from '@vibe3d/ownership.ts' + +export type PropSlot = + | 'wood' + | 'steelPainted' + | 'galvanised' + | 'stainless' + | 'chrome' + | 'aluminium' + | 'brass' + | 'plastic' + | 'plasticGloss' + | 'rubber' + | 'concrete' + | 'ceramic' + | 'glass' + | 'glassTinted' + | 'fabric' + | 'cord' + | 'paper' + | 'emissive' + | 'retroreflective' + +export interface SlotMaterial { + readonly wood: MeshStandardMaterial + readonly steelPainted: MeshStandardMaterial + readonly galvanised: MeshStandardMaterial + readonly stainless: MeshStandardMaterial + readonly chrome: MeshStandardMaterial + readonly aluminium: MeshStandardMaterial + readonly brass: MeshStandardMaterial + readonly plastic: MeshStandardMaterial + readonly plasticGloss: MeshStandardMaterial + readonly rubber: MeshStandardMaterial + readonly concrete: MeshStandardMaterial + readonly ceramic: MeshStandardMaterial + readonly glass: MeshStandardMaterial + readonly glassTinted: MeshStandardMaterial + readonly fabric: MeshStandardMaterial + readonly cord: MeshStandardMaterial + readonly paper: MeshStandardMaterial + readonly emissive: MeshBasicMaterial + readonly retroreflective: MeshStandardMaterial +} + +export interface PropPalette { + /** Pale contemporary timber: beech, birch ply, light oak veneer. */ + readonly wood: Color + /** Cut ends and edge banding, lighter and cooler than the face. */ + readonly woodEnd: Color + /** Powder-coated steel: lockers, shelving, barriers, tool bodies. */ + readonly steelPainted: Color + /** Hot-dip zinc, cooler and lighter than paint, with a spangle. */ + readonly galvanised: Color + /** Brushed stainless: sinks, pans, appliance fronts. */ + readonly stainless: Color + /** Polished chrome, near white because it is mostly reflecting the room. */ + readonly chrome: Color + /** Brushed aluminium extrusion, cooler and darker than chrome. */ + readonly aluminium: Color + /** Brass and copper trim: valves, instrument bells, fittings. */ + readonly brass: Color + /** Matte injection-moulded plastic, the most common surface in the kit. */ + readonly plastic: Color + /** Gloss plastic: kettles, toasters, appliance fascias. */ + readonly plasticGloss: Color + /** Rubber and soft PVC: tyres, grips, seals, cable jacket. */ + readonly rubber: Color + /** Cast concrete with an aggregate speckle. */ + readonly concrete: Color + /** Glazed ceramic: basins, mugs, vases. */ + readonly ceramic: Color + /** Clear glass. Thin, so it reads by its edges rather than its face. */ + readonly glass: Color + /** Tinted glass: side panels, screens, cooler doors. */ + readonly glassTinted: Color + /** Upholstery and woven panel infill. */ + readonly fabric: Color + /** Nylon and PVC cord: blind ladders, pull cords, hose. */ + readonly cord: Color + /** Paper stock: near white, no specular at all. */ + readonly paper: Color + /** Default emitter colour. Models override it per object. */ + readonly emissive: Color + /** High-visibility retroreflective sheeting. */ + readonly retroreflective: Color +} + +export const PROP_PALETTE: PropPalette = { + wood: new Color(0xbfa079), + woodEnd: new Color(0xd0b795), + steelPainted: new Color(0x767c82), + galvanised: new Color(0xa9b0b5), + stainless: new Color(0xb4b8bb), + chrome: new Color(0xd6dade), + aluminium: new Color(0xa4a9ae), + brass: new Color(0xb08d57), + plastic: new Color(0xc6c8c6), + plasticGloss: new Color(0xe6e8e9), + rubber: new Color(0x2e3134), + concrete: new Color(0x9a9691), + ceramic: new Color(0xf0efea), + glass: new Color(0xb9cbd2), + glassTinted: new Color(0x3a4750), + fabric: new Color(0x6c6f73), + cord: new Color(0xd6d3cc), + paper: new Color(0xf2f0ea), + emissive: new Color(0xffd9a0), + retroreflective: new Color(0xf4562a), +} + +export function createPropMaterials( + scope: ResourceScope, + slots: readonly S[], +): Pick { + const build: { [K in PropSlot]: () => SlotMaterial[K] } = { + // White base on every lit material: all colour comes from the vertex + // attribute, so the material must not multiply it away. + wood: () => new MeshStandardMaterial({ + name: 'contemporary-props / wood', + color: 0xffffff, + vertexColors: true, + roughness: 0.74, + metalness: 0, + }), + + /* + * The four metals, and why one slot will not do. + * + * They differ in ROUGHNESS and in how much of the room they return, and + * neither of those is something a vertex colour can carry. Put a sink and + * a locker on one slot and the kitchen goes flat: the sink stops looking + * wet and the locker starts looking wet. + */ + steelPainted: () => new MeshStandardMaterial({ + name: 'contemporary-props / painted steel', + color: 0xffffff, + vertexColors: true, + // Powder coat is a thick even film. It is matte, but not as matte as + // plastic, and that small gap is what separates a locker from a bin. + roughness: 0.62, + metalness: 0.15, + }), + galvanised: () => new MeshStandardMaterial({ + name: 'contemporary-props / galvanised steel', + color: 0xffffff, + vertexColors: true, + roughness: 0.55, + metalness: 0.65, + }), + stainless: () => new MeshStandardMaterial({ + name: 'contemporary-props / stainless steel', + color: 0xffffff, + vertexColors: true, + roughness: 0.28, + metalness: 0.92, + }), + chrome: () => new MeshStandardMaterial({ + name: 'contemporary-props / polished chrome', + color: 0xffffff, + vertexColors: true, + // Distinct from stainless by reflection, not by colour. A tap next to a + // sink is the test: if they share a slot, the tap disappears into it. + roughness: 0.06, + metalness: 1, + }), + aluminium: () => new MeshStandardMaterial({ + name: 'contemporary-props / brushed aluminium', + color: 0xffffff, + vertexColors: true, + roughness: 0.38, + metalness: 0.85, + }), + brass: () => new MeshStandardMaterial({ + name: 'contemporary-props / brass', + color: 0xffffff, + vertexColors: true, + roughness: 0.34, + metalness: 0.88, + }), + + /* + * Matte and gloss plastic are two slots for one substance, and it is the + * only split here justified by a highlight alone. A kettle and a waste bin + * can be the same colour and the same shape family; what says which is + * which is whether the light comes back off it in a hard spot. + */ + plastic: () => new MeshStandardMaterial({ + name: 'contemporary-props / matte plastic', + color: 0xffffff, + vertexColors: true, + roughness: 0.78, + metalness: 0, + }), + plasticGloss: () => new MeshStandardMaterial({ + name: 'contemporary-props / gloss plastic', + color: 0xffffff, + vertexColors: true, + roughness: 0.18, + metalness: 0, + }), + rubber: () => new MeshStandardMaterial({ + name: 'contemporary-props / rubber', + color: 0xffffff, + vertexColors: true, + // Almost no specular at all. This is what makes a castor read as a + // castor rather than as a small dark wheel. + roughness: 0.92, + metalness: 0, + }), + concrete: () => new MeshStandardMaterial({ + name: 'contemporary-props / concrete', + color: 0xffffff, + vertexColors: true, + roughness: 0.95, + metalness: 0, + }), + ceramic: () => new MeshStandardMaterial({ + name: 'contemporary-props / glazed ceramic', + color: 0xffffff, + vertexColors: true, + // Glaze is a glass layer over a matte body, so it is smooth without + // being metal. Sharing gloss plastic here makes a basin look moulded. + roughness: 0.14, + metalness: 0.04, + }), + + /* + * Two glasses, because the parameter that separates them is transmission + * and not colour. Reusing clear glass with a darker vertex colour loses + * the surface: a tinted panel still has a bright edge and a visible sheen, + * and a darkened clear panel has neither. + */ + glass: () => new MeshStandardMaterial({ + name: 'contemporary-props / clear glass', + color: 0xffffff, + vertexColors: true, + roughness: 0.04, + metalness: 0, + transparent: true, + opacity: 0.24, + // A pane is seen from both faces at once and it must not cull one away, + // and it must not hide what is behind it in the depth buffer. + side: DoubleSide, + depthWrite: false, + }), + glassTinted: () => new MeshStandardMaterial({ + name: 'contemporary-props / tinted glass', + color: 0xffffff, + vertexColors: true, + roughness: 0.08, + metalness: 0.1, + transparent: true, + opacity: 0.62, + side: DoubleSide, + depthWrite: false, + }), + + fabric: () => new MeshStandardMaterial({ + name: 'contemporary-props / fabric', + color: 0xffffff, + vertexColors: true, + roughness: 0.96, + metalness: 0, + }), + cord: () => new MeshStandardMaterial({ + name: 'contemporary-props / cord', + color: 0xffffff, + vertexColors: true, + roughness: 0.68, + metalness: 0, + }), + paper: () => new MeshStandardMaterial({ + name: 'contemporary-props / paper', + color: 0xffffff, + vertexColors: true, + // Zero specular. Paper rendered with any highlight at all reads as + // plastic sheet, which is the single most common way a stack of forms + // or a till roll goes wrong. + roughness: 1, + metalness: 0, + }), + + /** + * Unlit. The vertex colour IS the result, so nothing may darken it. + * + * The medieval kit had firelight; this kit has switchable emitters with a + * colour parameter, which is a different thing: a traffic aspect, a status + * lamp, a screen in its on state, a bulb. Anything in this slot is skipped + * by the occlusion and mottle passes, because shading an emitter is the + * same as switching it off. + */ + emissive: () => new MeshBasicMaterial({ + name: 'contemporary-props / emissive', + color: 0xffffff, + vertexColors: true, + }), + + /** + * Retroreflective sheeting: cone collars, barricade stripes, sign plates. + * + * Arguably a treatment rather than a material. It gets its own slot because + * it must not tone-map like paint: the whole point of the surface is that + * it returns light toward wherever the light came from, so it stays bright + * when everything around it has gone dark. Modelled here as a very smooth, + * very bright dielectric, which is the closest a standard material gets + * without a custom shader. + */ + retroreflective: () => new MeshStandardMaterial({ + name: 'contemporary-props / retroreflective', + color: 0xffffff, + vertexColors: true, + roughness: 0.32, + metalness: 0, + }), + } + + const materials = {} as { [K in S]: SlotMaterial[K] } + for (const slot of slots) { + // TypeScript cannot follow correlated unions: `build[slot]` widens to a + // union of functions, so it cannot know the return is exactly + // SlotMaterial[slot]. The cast is safe because the map is built by hand. + materials[slot] = scope.ownMaterial(build[slot]()) as SlotMaterial[S] + } + return materials +} diff --git a/contemporary-props/models/core/occlusion.ts b/contemporary-props/models/core/occlusion.ts new file mode 100644 index 0000000..2a5af03 --- /dev/null +++ b/contemporary-props/models/core/occlusion.ts @@ -0,0 +1,176 @@ +import type { BufferGeometry } from 'three' + +/** + * Ambient occlusion baked into vertex colours. + * + * Why this and not a texture: a bitmap texture would bring three things — UV + * coordinates (our geometry has none), image files the registry would have to + * carry, and a change to the kit's identity. Lowpoly + flat shading + vertex + * colour is a coherent style; a half-hearted texture breaks it. + * + * Instead we derive the darkening from the surface's OWN shape: the more + * neighbouring surfaces surround a point, the less sky it sees. The result is + * darkening in cavities and at contact points — between the boards, under the + * hoop, where the logs touch. The models suddenly look "used" and it costs + * zero memory, zero textures. + * + * Method: a grid is built from the triangle centroids, then for each vertex + * the neighbour density within its own normal hemisphere is measured. No ray + * tracing — at this scale (hundreds of triangles) it would be needlessly + * expensive and the difference is negligible. + */ + +export interface OcclusionOptions { + /** Radius searched for neighbours. Derived from the model's size if omitted. */ + readonly radius?: number + /** How much the darkest point is darkened. 0 = off. */ + readonly strength?: number + /** Neighbour weight where saturation is reached. Raising it softens the darkening. */ + readonly saturation?: number +} + +interface Sample { + readonly x: number + readonly y: number + readonly z: number + readonly area: number +} + +/** Simple spatial grid: for quickly finding the samples within a radius. */ +class Grid { + readonly #cells = new Map() + readonly #size: number + + constructor(samples: readonly Sample[], cellSize: number) { + this.#size = cellSize + for (const sample of samples) { + const key = this.#key(sample.x, sample.y, sample.z) + const bucket = this.#cells.get(key) + if (bucket) bucket.push(sample) + else this.#cells.set(key, [sample]) + } + } + + #key(x: number, y: number, z: number): string { + return `${Math.floor(x / this.#size)},${Math.floor(y / this.#size)},${Math.floor(z / this.#size)}` + } + + /** The samples of the 27 cells surrounding the given point. */ + near(x: number, y: number, z: number): Sample[] { + const cx = Math.floor(x / this.#size) + const cy = Math.floor(y / this.#size) + const cz = Math.floor(z / this.#size) + const found: Sample[] = [] + for (let i = -1; i <= 1; i += 1) { + for (let j = -1; j <= 1; j += 1) { + for (let k = -1; k <= 1; k += 1) { + const bucket = this.#cells.get(`${cx + i},${cy + j},${cz + k}`) + if (bucket) found.push(...bucket) + } + } + } + return found + } +} + +/** + * Computes the occlusion of the given geometries TOGETHER and writes it into + * their colours. + * + * They all have to be evaluated as one: the place where a board darkens is the + * surface of the neighbouring post, not its own surface. Processing them one + * by one would miss the contact points entirely. + */ +export function bakeOcclusion( + geometries: readonly BufferGeometry[], + options: OcclusionOptions = {}, +): void { + const strength = options.strength ?? 0.42 + if (strength <= 0 || geometries.length === 0) return + + // --- 1. Samples: each triangle's centroid, weighted by its area --- + const samples: Sample[] = [] + let minX = Infinity, minY = Infinity, minZ = Infinity + let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity + + for (const geometry of geometries) { + const position = geometry.getAttribute('position') + if (!position) continue + const index = geometry.getIndex() + const count = index ? index.count : position.count + for (let i = 0; i < count; i += 3) { + const at = (k: number): [number, number, number] => { + const v = index ? index.getX(i + k) : i + k + return [position.getX(v), position.getY(v), position.getZ(v)] + } + const [ax, ay, az] = at(0) + const [bx, by, bz] = at(1) + const [cx, cy, cz] = at(2) + const ux = bx - ax, uy = by - ay, uz = bz - az + const vx = cx - ax, vy = cy - ay, vz = cz - az + const nx = uy * vz - uz * vy + const ny = uz * vx - ux * vz + const nz = ux * vy - uy * vx + const area = Math.hypot(nx, ny, nz) / 2 + if (area <= 0) continue + const x = (ax + bx + cx) / 3 + const y = (ay + by + cy) / 3 + const z = (az + bz + cz) / 3 + samples.push({ x, y, z, area }) + minX = Math.min(minX, x); maxX = Math.max(maxX, x) + minY = Math.min(minY, y); maxY = Math.max(maxY, y) + minZ = Math.min(minZ, z); maxZ = Math.max(maxZ, z) + } + } + if (samples.length === 0) return + + const extent = Math.max(maxX - minX, maxY - minY, maxZ - minZ, 1e-6) + // The radius is derived from the scale but has an ABSOLUTE ceiling. Without + // the ceiling a 4.89 m fence gets a 0.69 m radius and the definition of + // "neighbour" loses its meaning: everything is everything's neighbour, and + // instead of showing the contact points the occlusion smears a flat + // darkening over the whole model. + // + // The physical meaning says the same thing: what shades a surface is what is + // NEAR it. A post half a metre away is not making the shadow between the + // boards. + const radius = options.radius ?? Math.min(0.16, Math.max(0.015, extent * 0.14)) + const grid = new Grid(samples, radius) + // Saturation has to be proportional to the model's scale: as the radius + // grows so does the area it covers, and a fixed threshold would turn small + // models pitch black. + const saturation = options.saturation ?? radius * radius * 1.9 + + // --- 2. Neighbour density for each vertex --- + for (const geometry of geometries) { + const position = geometry.getAttribute('position') + const colour = geometry.getAttribute('color') + if (!position || !colour) continue + if (!geometry.getAttribute('normal')) geometry.computeVertexNormals() + const normal = geometry.getAttribute('normal')! + + for (let i = 0; i < position.count; i += 1) { + const px = position.getX(i), py = position.getY(i), pz = position.getZ(i) + const nx = normal.getX(i), ny = normal.getY(i), nz = normal.getZ(i) + + let weight = 0 + for (const sample of grid.near(px, py, pz)) { + const dx = sample.x - px, dy = sample.y - py, dz = sample.z - pz + const distance = Math.hypot(dx, dy, dz) + if (distance < 1e-6 || distance > radius) continue + // Only neighbours in the hemisphere the vertex FACES occlude it. + const facing = (dx * nx + dy * ny + dz * nz) / distance + if (facing <= 0) continue + // The effect fades with distance; a soft falloff instead of the + // inverse-square law, because the goal is not physical accuracy but a + // readable cavity shadow. + weight += sample.area * facing * (1 - distance / radius) + } + + const occlusion = Math.min(1, weight / saturation) + const factor = 1 - strength * occlusion + colour.setXYZ(i, colour.getX(i) * factor, colour.getY(i) * factor, colour.getZ(i) * factor) + } + colour.needsUpdate = true + } +} diff --git a/contemporary-props/models/core/parts.ts b/contemporary-props/models/core/parts.ts new file mode 100644 index 0000000..3f30689 --- /dev/null +++ b/contemporary-props/models/core/parts.ts @@ -0,0 +1,49 @@ +import { Group } from 'three' + +import type { PartHandle } from '@vibe3d/model.ts' + +/** + * Semantic part slot: fixed anchor + replaceable content. + * + * This is the most easily misunderstood contract in vibe3d. `PartHandle` + * declares two separate objects and they CANNOT BE THE SAME: + * + * anchor the same object for the lifetime of the model. The consumer + * attaches its light, its label, its collision body, its gameplay + * object here. + * content the geometry that is thrown away and rebuilt every time + * configure() is called. + * + * Making both the same Group and calling `clear()` on rebuild silently deletes + * everything the consumer attached too — the model keeps working, but the + * protocol's actual promise is broken. `scripts/verify-model.ts` tests this + * separately. + */ +export interface PartSlot extends PartHandle { + readonly anchor: Group + readonly content: Group + /** Replaces the content with a fresh Group and returns it. Leaves the anchor alone. */ + reset(): Group +} + +export function createPart(name: string): PartSlot { + const anchor = new Group() + anchor.name = name + let content = new Group() + content.name = `${name}/content` + anchor.add(content) + + return { + anchor, + get content(): Group { + return content + }, + reset(): Group { + anchor.remove(content) + content = new Group() + content.name = `${name}/content` + anchor.add(content) + return content + }, + } +} diff --git a/contemporary-props/models/core/random.ts b/contemporary-props/models/core/random.ts new file mode 100644 index 0000000..20eae4a --- /dev/null +++ b/contemporary-props/models/core/random.ts @@ -0,0 +1,26 @@ +/** + * Deterministic randomness. + * + * A procedural kit needs variation — perfect symmetry reads as "generated". + * But the variation has to be repeatable: the same seed must always give the + * same model, otherwise neither previews, nor tests, nor art direction hold + * up. That is why Math.random() is not used. + * + * mulberry32: 32-bit state, fast, not cryptographic but far more than enough + * for visual variation. + */ +export function createRandom(seed: number): () => number { + let state = seed >>> 0 + return () => { + state = (state + 0x6d2b79f5) >>> 0 + let t = state + t = Math.imul(t ^ (t >>> 15), t | 1) + t ^= t + Math.imul(t ^ (t >>> 7), t | 61) + return ((t ^ (t >>> 14)) >>> 0) / 4294967296 + } +} + +/** Symmetric deviation in the range -amount .. +amount. */ +export function jitter(random: () => number, amount: number): number { + return (random() * 2 - 1) * amount +} diff --git a/contemporary-props/models/core/tint.ts b/contemporary-props/models/core/tint.ts new file mode 100644 index 0000000..225b6de --- /dev/null +++ b/contemporary-props/models/core/tint.ts @@ -0,0 +1,52 @@ +import { Color } from 'three' + +import { PROP_PALETTE, type PropPalette } from './materials.ts' +import { jitter } from './random.ts' + +/** + * Factory that produces colours deviated from the palette. + * + * Every model used to rewrite this inline — the same five lines thirteen + * times. The cost of the repetition was not just line count: the deviation + * amounts had drifted from model to model, so when two models were put side + * by side one of them visibly had more variation than the other. + * + * Every call returns A NEW Color. + * + * It used to return one shared object and mutate it, on the reasoning that the + * geometry helpers read the colour immediately and an allocation per call is + * waste. The reasoning holds right up until two tints appear as arguments of + * the SAME call: + * + * latheGeometry(profile, 7, origin, tint('char', 0.06), + * { colourTop: tint('charHot', -0.12) }) + * + * Both arguments are the same object, so both carry whatever the second call + * computed. That is not a hypothetical: it is why the torch's pitch head + * rendered hot orange instead of black, and the same mistake was made twice + * more in one session -- once in the anvil's stump, which came out painted in + * end grain on every face, and once nearly in the shovel. Three times means + * the hazard is in the helper, not in the callers. + * + * A few hundred Color allocations at build time is not a cost worth one class + * of silent, invisible bug. + */ +export function createTinter(random: () => number) { + return ( + key: keyof PropPalette, + /** Lightness shift. Negative darkens. */ + lift = 0, + /** Deviation multiplier. 0 gives a completely flat colour. */ + spread = 1, + ): Color => { + const scratch = new Color(PROP_PALETTE[key]) + scratch.offsetHSL( + jitter(random, 0.012 * spread), + jitter(random, 0.05 * spread), + lift + jitter(random, 0.05 * spread), + ) + return scratch + } +} + +export type Tinter = ReturnType diff --git a/contemporary-props/models/core/tool.ts b/contemporary-props/models/core/tool.ts new file mode 100644 index 0000000..3fafa90 --- /dev/null +++ b/contemporary-props/models/core/tool.ts @@ -0,0 +1,131 @@ +import { Color, type BufferGeometry } from 'three' + +import { latheGeometry, mergeColoured, type Level } from './geometry.ts' +import { jitter } from './random.ts' +import { PROP_PALETTE } from './materials.ts' + +/** + * The shared language of hand tools. + * + * In the first attempt all three tools were just a straight prismatic shaft + + * a boxy head, and they looked like toys. The reasons were small, individual + * things: + * + * - The shaft was the same thickness end to end. A real shaft has a swell + * at its base (the grip) — so the hand does not slip off. That is the one + * detail that makes the silhouette readable. + * - The head was stuck directly onto the shaft. A real tool has a conical + * socket; the shaft goes inside it. + * - There was no geometric variation anywhere, only the colour changed. A + * forged tool is not perfectly symmetric. + * + * This module supplies all three from one place, so adding a new tool to the + * kit is now just a matter of answering "what is the head". + */ + +export interface ShaftOptions { + readonly length: number + readonly radius: number + /** How many sides. 6 is enough: on a hand-held stick 8 adds nothing to the silhouette. */ + readonly segments?: number + readonly random: () => number +} + +export interface ToolShaft { + readonly geometry: BufferGeometry + /** Y position of the shaft's top end — the head sits here. */ + readonly top: number + /** The shaft's radius at the top end. */ + readonly topRadius: number +} + +/** + * Tool shaft: grip swell at the bottom, a long straight body in the middle, a + * slight taper towards the top. Produced as a single lathe — stacking prisms + * on top of each other would leave coplanar face pairs between them. + */ +export function toolShaft(options: ShaftOptions): ToolShaft { + const { length, radius, random } = options + const segments = options.segments ?? 6 + const bottom = -length / 2 + const top = length / 2 + const r = (scale: number): number => radius * scale * (1 + jitter(random, 0.02)) + + const profile: Level[] = [ + { y: bottom, radius: r(0.78) }, // bottom: rounded end + { y: bottom + length * 0.012, radius: r(1.18) }, // underside of the grip swell + { y: bottom + length * 0.075, radius: r(1.1) }, // top of the grip + { y: bottom + length * 0.14, radius: r(0.94) }, // waist between grip and body + { y: bottom + length * 0.55, radius: r(1) }, // body + { y: top, radius: r(0.9) }, // taper towards the head + ] + + const tint = new Color(PROP_PALETTE.wood) + tint.offsetHSL(jitter(random, 0.012), jitter(random, 0.05), 0.05 + jitter(random, 0.05)) + const tintTop = new Color(PROP_PALETTE.wood) + // The head end passes through the hand less often, so it stays a bit darker. + tintTop.offsetHSL(jitter(random, 0.01), jitter(random, 0.04), -0.02 + jitter(random, 0.04)) + + return { + geometry: latheGeometry(profile, segments, [0, 0, 0], tint, { colourTop: tintTop }), + top, + topRadius: profile.at(-1)!.radius, + } +} + +export interface SocketOptions { + /** Y position where the socket sits (the shaft's top end). */ + readonly y: number + /** The shaft's radius at that point. */ + readonly shaftRadius: number + /** Socket length. */ + readonly length: number + readonly segments?: number + readonly random: () => number +} + +/** + * Forged socket: a cone that wraps the shaft and widens upwards, with a collar + * on top. + * + * It is extended DOWN INTO the shaft — because its lower end stays inside the + * shaft's body, no surface ends up coplanar with the shaft's surface. + */ +export function toolSocket(options: SocketOptions): BufferGeometry { + const { y, shaftRadius, length, random } = options + const segments = options.segments ?? 6 + const tint = new Color(PROP_PALETTE.steelPainted) + tint.offsetHSL(0, jitter(random, 0.02), jitter(random, 0.05)) + const collar = new Color(PROP_PALETTE.steelPainted) + collar.offsetHSL(0, jitter(random, 0.02), 0.04 + jitter(random, 0.04)) + + const profile: Level[] = [ + { y: y - length * 0.9, radius: shaftRadius * 1.12 }, + { y: y - length * 0.45, radius: shaftRadius * 1.34 }, + { y: y + length * 0.1, radius: shaftRadius * 1.5 }, + { y: y + length * 0.22, radius: shaftRadius * 1.72 }, // collar + { y: y + length * 0.34, radius: shaftRadius * 1.46 }, + ] + return mergeColoured([latheGeometry(profile, segments, [0, 0, 0], tint, { colourTop: collar })]) +} + +/** Iron tone with a small deviation. So all three tools look like one hand made them. */ +export function ironTint(random: () => number, lift = 0): Color { + const tint = new Color(PROP_PALETTE.steelPainted) + tint.offsetHSL(0, jitter(random, 0.02), lift + jitter(random, 0.05)) + return tint +} + +/** + * Burnished steel tone — for the `steel` slot. + * + * The deviation is kept narrower than in `ironTint`: what determines the + * colour of a polished surface is not its own pigment but the environment it + * reflects. Shifting hue in the vertex colour looks dirty here, so there is + * only a tiny wobble in lightness. + */ +export function steelTint(random: () => number, lift = 0): Color { + const tint = new Color(PROP_PALETTE.stainless) + tint.offsetHSL(0, jitter(random, 0.008), lift + jitter(random, 0.025)) + return tint +} diff --git a/contemporary-props/package.json b/contemporary-props/package.json new file mode 100644 index 0000000..c26a527 --- /dev/null +++ b/contemporary-props/package.json @@ -0,0 +1,36 @@ +{ + "name": "@contemporary-props/registry", + "version": "0.0.0", + "description": "Present-day props generated from TypeScript, for Vibe3D and Three.js.", + "type": "module", + "license": "MIT", + "author": "CRTkafa", + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + }, + "keywords": [ + "vibe3d", + "vibe3d-registry", + "threejs", + "3d-models", + "props", + "procedural" + ], + "vibe3d": { + "registry": "./dist/registry.json" + }, + "files": [ + "dist", + "README.md", + "LICENSE" + ], + "scripts": { + "build": "bun build.ts", + "validate": "vibe3d registry validate dist/registry.json", + "prepublishOnly": "bun build.ts && vibe3d registry validate dist/registry.json" + }, + "peerDependencies": { + "three": ">=0.185.0" + } +} diff --git a/models.json b/models.json index f57b89f..7b51d53 100644 --- a/models.json +++ b/models.json @@ -18,6 +18,10 @@ "@medieval-kit": { "source": "file:my-registry/dist/registry.json", "version": "workspace" + }, + "@contemporary-props": { + "source": "file:contemporary-props/dist/registry.json", + "version": "workspace" } } } diff --git a/models.lock.json b/models.lock.json index 37da000..deeed4e 100644 --- a/models.lock.json +++ b/models.lock.json @@ -672,6 +672,53 @@ "dependencies": [ "three@>=0.185.0" ] + }, + "@contemporary-props/core": { + "address": "@contemporary-props/core", + "source": "file:contemporary-props/dist/registry.json", + "version": "workspace", + "installedAt": "2026-08-28T11:55:55.316Z", + "files": [ + { + "path": "src\\models\\contemporary-props\\core\\geometry.ts", + "sourceHash": "b47141c115c48d48e3a4c643fe9634343458288688ea586f044e6a7e7cdbaad5" + }, + { + "path": "src\\models\\contemporary-props\\core\\index.ts", + "sourceHash": "82ec12371362c5e72d4b5049f35c3c249276f4dde0f2a94c6db97dc8789d172e" + }, + { + "path": "src\\models\\contemporary-props\\core\\kit.ts", + "sourceHash": "c9063637b59bece2491efb8ddb0d8aa98c1521cf35783ea1cd614aa47db39a46" + }, + { + "path": "src\\models\\contemporary-props\\core\\materials.ts", + "sourceHash": "9ad9297a997c1e2691032f481f0fe502aa670ff3183eb2ca91fc0d69928ebb15" + }, + { + "path": "src\\models\\contemporary-props\\core\\occlusion.ts", + "sourceHash": "6abb37ba737d80279f8af5b3dce94367028af99340baf495c8727e7e5a6dcd7c" + }, + { + "path": "src\\models\\contemporary-props\\core\\parts.ts", + "sourceHash": "6554e1092e02d46fbb78c44462124ec2980a10cbf6f014d01d86ffbf0308e975" + }, + { + "path": "src\\models\\contemporary-props\\core\\random.ts", + "sourceHash": "8294a81f783f53333dbedcae5ee2511b94d333f957ee51d553c439ee6884c510" + }, + { + "path": "src\\models\\contemporary-props\\core\\tint.ts", + "sourceHash": "96a18dca8d0f02c988741c6222efbc5da7cce403900a5192bb01eb4f2c0f9315" + }, + { + "path": "src\\models\\contemporary-props\\core\\tool.ts", + "sourceHash": "a6a5f1a5d2cde798556330638fc113f88d72bb707fd8a607f5d11a56ce2857a4" + } + ], + "dependencies": [ + "three@>=0.185.0" + ] } } } diff --git a/scripts/raster.ts b/scripts/raster.ts index 6709df5..0bee7a7 100644 --- a/scripts/raster.ts +++ b/scripts/raster.ts @@ -519,23 +519,36 @@ export interface RenderOptions { readonly towards?: readonly [number, number, number] } +/** + * Renders anything with a transform tree, catalogued or not. + * + * Split out of `renderOne` so a model can be drawn straight from the folder it + * is being written in, before it has a catalogue entry, a registry build or an + * install. That is the whole difference between looking at your work now and + * looking at it after a four step round trip. + */ +export function renderObject(root: Object3D, options: RenderOptions): Frame { + const { size, tall = options.size, spin = 0, ground, towards = [0.78, 0.5, 1] } = options + // We rotate the MODEL, not the camera: framing and the shadow computation + // stay in a fixed direction, so turntable frames compare one to one. + root.rotation.y = spin + const triangles = collect(root) + const frame = newFrame(size, tall, ground) + const { camera, floor } = frameCamera(root, size, tall, towards) + contactShadow(frame, camera, triangles, floor) + raster(frame, camera, triangles) + return frame +} + export function renderOne(id: string, options: RenderOptions): Frame { - const { size, tall = options.size, patch, spin = 0, ground, towards = [0.78, 0.5, 1] } = options const entry = CATALOG[id] if (!entry) throw new Error(`not in catalog: ${id}`) const built = entry.build() - if (patch && built.params) built.params.apply(patch) + if (options.patch && built.params) built.params.apply(options.patch) // Catch animated models mid-motion: a frozen flame does not show that the // flame flickers. built.update?.(0.42) - // We rotate the MODEL, not the camera: framing and the shadow computation - // stay in a fixed direction, so turntable frames compare one to one. - built.root.rotation.y = spin - const triangles = collect(built.root) - const frame = newFrame(size, tall, ground) - const { camera, floor } = frameCamera(built.root, size, tall, towards) - contactShadow(frame, camera, triangles, floor) - raster(frame, camera, triangles) + const frame = renderObject(built.root, options) built.dispose() return frame } diff --git a/scripts/support.ts b/scripts/support.ts index 40cd562..a9804ec 100644 --- a/scripts/support.ts +++ b/scripts/support.ts @@ -103,16 +103,23 @@ export function findFloating(root: Object3D, options: SupportOptions = {}): Supp const cells = new Map() const vertex = new Vector3() root.traverse((object) => { - if (!(object instanceof Mesh)) return - const position = object.geometry.getAttribute('position') + // `.isMesh`, not `instanceof Mesh`. Two copies of three can be loaded at + // once (plain `three` and `three/webgpu` are separate builds, and a second + // project brings its own install), and across copies instanceof matches + // nothing at all. The failure is silent and total: the traversal samples + // no geometry, finds no components, and reports every model clean. That is + // exactly what it did the first time this ran against another repository. + if (!(object as { isMesh?: boolean }).isMesh) return + const mesh = object as unknown as Mesh + const position = mesh.geometry.getAttribute('position') if (!position) return - const index = object.geometry.getIndex() + const index = mesh.geometry.getIndex() const count = index ? index.count : position.count - const name = object.name || 'unnamed' + const name = mesh.name || 'unnamed' const at = (i: number): Vector3 => { const v = index ? index.getX(i) : i - return vertex.fromBufferAttribute(position, v).applyMatrix4(object.matrixWorld).clone() + return vertex.fromBufferAttribute(position, v).applyMatrix4(mesh.matrixWorld).clone() } for (let i = 0; i < count; i += 3) { diff --git a/src/models/contemporary-props/core/geometry.ts b/src/models/contemporary-props/core/geometry.ts new file mode 100644 index 0000000..46d4a0c --- /dev/null +++ b/src/models/contemporary-props/core/geometry.ts @@ -0,0 +1,870 @@ +import { BufferAttribute, BufferGeometry, Color } from 'three' +import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js' + +/** + * The kit's geometry vocabulary. + * + * Everything is generated NON-INDEXED. The reason: on non-indexed geometry + * computeVertexNormals() gives every triangle its own normal, so flat shading + * becomes a natural consequence of the geometry — no material flag is needed. + * In lowpoly that is exactly what we want. + * + * Position frame: point(a, r, y) = (sin a · r, y, cos a · r) + * So a = 0 → the +Z direction; as a grows it turns toward +X. + * + * The windings were worked out by hand and the audit inside + * `scripts/verify-model.ts` tests them by mutation: radial faces on the outer + * shell must point away from the axis. + */ + +export type Vec3 = readonly [number, number, number] + +export interface Level { + /** Vertical position (metres). */ + readonly y: number + /** OUTER radius at that height (metres). */ + readonly radius: number +} + +function point(angle: number, radius: number, y: number): Vec3 { + return [Math.sin(angle) * radius, y, Math.cos(angle) * radius] +} + +interface Sink { + readonly position: number[] + readonly color: number[] +} + +function tri(sink: Sink, a: Vec3, b: Vec3, c: Vec3, colour: Color): void { + sink.position.push(a[0], a[1], a[2], b[0], b[1], b[2], c[0], c[1], c[2]) + for (let i = 0; i < 3; i += 1) sink.color.push(colour.r, colour.g, colour.b) +} + +/** Triangle with a separate colour per corner — for vertical colour ramps. */ +function triShaded(sink: Sink, a: Vec3, b: Vec3, c: Vec3, ca: Color, cb: Color, cc: Color): void { + sink.position.push(a[0], a[1], a[2], b[0], b[1], b[2], c[0], c[1], c[2]) + sink.color.push(ca.r, ca.g, ca.b, cb.r, cb.g, cb.b, cc.r, cc.g, cc.b) +} + +/** Splits the quad (a,b,c,d) in order into two triangles. The normal follows from the a→b→c winding. */ +function quad(sink: Sink, a: Vec3, b: Vec3, c: Vec3, d: Vec3, colour: Color): void { + tri(sink, a, b, c, colour) + tri(sink, a, c, d, colour) +} + +function finish(sink: Sink): BufferGeometry { + const geometry = new BufferGeometry() + geometry.setAttribute('position', new BufferAttribute(new Float32Array(sink.position), 3)) + geometry.setAttribute('color', new BufferAttribute(new Float32Array(sink.color), 3)) + return geometry +} + +/** + * Axis-aligned box. The kit's most used part: boards, rails, iron straps, + * feet — all of them are this. + */ +export function boxGeometry( + size: Vec3, + centre: Vec3, + colour: Color, +): BufferGeometry { + const sink: Sink = { position: [], color: [] } + const [hx, hy, hz] = [size[0] / 2, size[1] / 2, size[2] / 2] + const [cx, cy, cz] = centre + const v = (sx: number, sy: number, sz: number): Vec3 => [cx + sx * hx, cy + sy * hy, cz + sz * hz] + + quad(sink, v(-1, -1, 1), v(1, -1, 1), v(1, 1, 1), v(-1, 1, 1), colour) // +Z + quad(sink, v(1, -1, -1), v(-1, -1, -1), v(-1, 1, -1), v(1, 1, -1), colour) // -Z + quad(sink, v(1, -1, 1), v(1, -1, -1), v(1, 1, -1), v(1, 1, 1), colour) // +X + quad(sink, v(-1, -1, -1), v(-1, -1, 1), v(-1, 1, 1), v(-1, 1, -1), colour) // -X + quad(sink, v(-1, 1, 1), v(1, 1, 1), v(1, 1, -1), v(-1, 1, -1), colour) // +Y + quad(sink, v(-1, -1, -1), v(1, -1, -1), v(1, -1, 1), v(-1, -1, 1), colour) // -Y + + return finish(sink) +} + +/** + * Chamfered box — the kit's most important primitive. It can taper. + * + * A sharp 90° corner does not exist in nature. The edge of a hand-planed board + * chips, the corner of forged iron rounds over. The chamfer band catches light + * at a different angle than its neighbouring faces, and the object stops being + * a "box" and turns into a physical part. The first version of the kit was + * chamferless boxes from end to end and all of it looked like toys. + * + * Because the bottom and top cross sections can be given separately, it stands + * in for both the straight box and the tapering box — keeping the two as + * separate primitives would have permanently left open the risk of chamfering + * one and leaving the other sharp. + * + * Single-facet chamfer (vibe3d modelling rule 2: one facet by default, a second + * only on masses that carry the silhouette). The cost is 44 triangles instead of 12. + * + * Winding: the 6 faces were worked out by hand; the 12 edges and 8 corners + * CORRECT THEMSELVES against the expected outward direction. Deriving the + * winding of twenty pieces by hand invites mistakes, while the expected normal + * is already known — flipping whatever comes out reversed is both shorter and certain. + */ +export function chamferedBoxGeometry( + bottom: readonly [number, number], + top: readonly [number, number], + height: number, + chamfer: number, + centre: Vec3, + colour: Color, + colourTop?: Color, +): BufferGeometry { + const sink: Sink = { position: [], color: [] } + const [cx, cy, cz] = centre + const hy = height / 2 + const minHalf = Math.min(bottom[0], bottom[1], top[0], top[1]) / 2 + const c = Math.max(1e-6, Math.min(chamfer, minHalf * 0.5, hy * 0.5)) + const upper = colourTop ?? colour + + /** + * `full` sits exactly at the end on its axis, the others a chamfer inside. + * The horizontal half-measures are interpolated between the bottom and top + * cross section according to height. + */ + const p = (sx: number, sy: number, sz: number, full: 0 | 1 | 2): Vec3 => { + const y = cy + sy * (full === 1 ? hy : hy - c) + const t = height <= 1e-9 ? 0 : (y - (cy - hy)) / height + const hx = (bottom[0] + (top[0] - bottom[0]) * t) / 2 + const hz = (bottom[1] + (top[1] - bottom[1]) * t) / 2 + return [ + cx + sx * (full === 0 ? hx : hx - c), + y, + cz + sz * (full === 2 ? hz : hz - c), + ] + } + const shade = (v: Vec3): Color => + colourTop ? new Color().copy(colour).lerp(upper, (v[1] - (cy - hy)) / Math.max(1e-9, height)) : colour + + const face = (a: Vec3, b: Vec3, d: Vec3, e: Vec3): void => { + tri(sink, a, b, d, shade(a)); tri(sink, a, d, e, shade(a)) + } + face(p(-1, -1, 1, 2), p(1, -1, 1, 2), p(1, 1, 1, 2), p(-1, 1, 1, 2)) // +Z + face(p(1, -1, -1, 2), p(-1, -1, -1, 2), p(-1, 1, -1, 2), p(1, 1, -1, 2)) // -Z + face(p(1, -1, 1, 0), p(1, -1, -1, 0), p(1, 1, -1, 0), p(1, 1, 1, 0)) // +X + face(p(-1, -1, -1, 0), p(-1, -1, 1, 0), p(-1, 1, 1, 0), p(-1, 1, -1, 0)) // -X + face(p(-1, 1, 1, 1), p(1, 1, 1, 1), p(1, 1, -1, 1), p(-1, 1, -1, 1)) // +Y + face(p(-1, -1, -1, 1), p(1, -1, -1, 1), p(1, -1, 1, 1), p(-1, -1, 1, 1)) // -Y + + /** Writes the triangle against the expected outward direction, flipping it if needed. */ + const oriented = (a: Vec3, b: Vec3, d: Vec3, outward: readonly number[]): void => { + const e1 = [b[0] - a[0], b[1] - a[1], b[2] - a[2]] + const e2 = [d[0] - a[0], d[1] - a[1], d[2] - a[2]] + const n = [ + e1[1]! * e2[2]! - e1[2]! * e2[1]!, + e1[2]! * e2[0]! - e1[0]! * e2[2]!, + e1[0]! * e2[1]! - e1[1]! * e2[0]!, + ] + const dot = n[0]! * outward[0]! + n[1]! * outward[1]! + n[2]! * outward[2]! + if (dot >= 0) tri(sink, a, b, d, shade(a)) + else tri(sink, a, d, b, shade(a)) + } + + const signs = [-1, 1] as const + for (const axis of [0, 1, 2] as const) { + const [u, v] = [0, 1, 2].filter((i) => i !== axis) as [0 | 1 | 2, 0 | 1 | 2] + for (const su of signs) for (const sv of signs) { + const at = (along: number, full: 0 | 1 | 2): Vec3 => { + const sign: [number, number, number] = [0, 0, 0] + sign[axis] = along; sign[u] = su; sign[v] = sv + return p(sign[0], sign[1], sign[2], full) + } + const outward = [0, 1, 2].map((i) => (i === u ? su : i === v ? sv : 0)) + oriented(at(-1, u), at(-1, v), at(1, v), outward) + oriented(at(-1, u), at(1, v), at(1, u), outward) + } + } + for (const sx of signs) for (const sy of signs) for (const sz of signs) { + oriented(p(sx, sy, sz, 0), p(sx, sy, sz, 1), p(sx, sy, sz, 2), [sx, sy, sz]) + } + + return finish(sink) +} + +/** + * Truncated cone / prism: feet, shafts, bowls, flame tongues. + * + * If `colourTop` is given the colour ramps with height — needed for the flame, + * because the base of a flame is not the same colour as its tip. + */ +export function prismGeometry( + radiusBottom: number, + radiusTop: number, + height: number, + segments: number, + centre: Vec3, + colour: Color, + options: { readonly capTop?: boolean; readonly capBottom?: boolean; readonly colourTop?: Color } = {}, +): BufferGeometry { + const sink: Sink = { position: [], color: [] } + const { capTop = true, capBottom = true } = options + const top = options.colourTop ?? colour + const [cx, cy, cz] = centre + const low = cy - height / 2 + const high = cy + height / 2 + const stepAngle = (Math.PI * 2) / segments + const shift = (p: Vec3): Vec3 => [p[0] + cx, p[1], p[2] + cz] + + for (let i = 0; i < segments; i += 1) { + const a0 = i * stepAngle + const a1 = (i + 1) * stepAngle + const l0 = shift(point(a0, radiusBottom, low)) + const l1 = shift(point(a1, radiusBottom, low)) + const h0 = shift(point(a0, radiusTop, high)) + const h1 = shift(point(a1, radiusTop, high)) + + // Side face: points outward. + triShaded(sink, l0, l1, h1, colour, colour, top) + triShaded(sink, l0, h1, h0, colour, top, top) + + if (capTop && radiusTop > 0) tri(sink, [cx, high, cz], h0, h1, top) + if (capBottom && radiusBottom > 0) tri(sink, [cx, low, cz], l1, l0, colour) + } + + return finish(sink) +} + +/** + * Turned surface: revolves a profile around the Y axis. + * + * `prismGeometry` is the two-level version of this. When more levels are needed + * this one is used and NO INTERIOR SURFACE FORMS in between — that is the real + * reason to use this instead of stacking prisms on top of each other: stacked + * prisms leave a pair of coincident faces where they touch, a single lathe + * does not. + * + * Everything round in the kit comes out of this: tool shafts and grip bulges, + * conical sockets, pitchfork tines, and later jugs/candlesticks/wheel hubs. + */ +export function latheGeometry( + levels: readonly Level[], + segments: number, + centre: Vec3, + colour: Color, + options: { readonly capTop?: boolean; readonly capBottom?: boolean; readonly colourTop?: Color } = {}, +): BufferGeometry { + if (levels.length < 2) throw new Error('latheGeometry needs at least two levels') + const sink: Sink = { position: [], color: [] } + const { capTop = true, capBottom = true } = options + const top = options.colourTop ?? colour + const [cx, cy, cz] = centre + const stepAngle = (Math.PI * 2) / segments + const shift = (p: Vec3): Vec3 => [p[0] + cx, p[1] + cy, p[2] + cz] + const lerp = (t: number): Color => new Color().copy(colour).lerp(top, t) + + for (let i = 0; i < levels.length - 1; i += 1) { + const low = levels[i]! + const high = levels[i + 1]! + const tLow = i / (levels.length - 1) + const tHigh = (i + 1) / (levels.length - 1) + const cLow = lerp(tLow) + const cHigh = lerp(tHigh) + + for (let j = 0; j < segments; j += 1) { + const a0 = j * stepAngle + const a1 = (j + 1) * stepAngle + const l0 = shift(point(a0, low.radius, low.y)) + const l1 = shift(point(a1, low.radius, low.y)) + const h0 = shift(point(a0, high.radius, high.y)) + const h1 = shift(point(a1, high.radius, high.y)) + // At a level whose radius is zero that edge collapses to a point; it is + // closed with a single triangle so no degenerate triangle is produced. + if (low.radius <= 1e-6) { triShaded(sink, l0, h1, h0, cLow, cHigh, cHigh); continue } + if (high.radius <= 1e-6) { triShaded(sink, l0, l1, h0, cLow, cLow, cHigh); continue } + triShaded(sink, l0, l1, h1, cLow, cLow, cHigh) + triShaded(sink, l0, h1, h0, cLow, cHigh, cHigh) + } + } + + const first = levels[0]! + const last = levels.at(-1)! + for (let j = 0; j < segments; j += 1) { + const a0 = j * stepAngle + const a1 = (j + 1) * stepAngle + if (capBottom && first.radius > 1e-6) { + tri(sink, shift([0, first.y, 0]), + shift(point(a1, first.radius, first.y)), shift(point(a0, first.radius, first.y)), colour) + } + if (capTop && last.radius > 1e-6) { + tri(sink, shift([0, last.y, 0]), + shift(point(a0, last.radius, last.y)), shift(point(a1, last.radius, last.y)), top) + } + } + return finish(sink) +} + +/** + * A single barrel stave: one slice of the ring, a closed solid with thickness. + * + * Every level has four corners: + * A = outer/start angle B = outer/end angle + * C = inner/end angle D = inner/start angle + */ +export function staveGeometry( + levels: readonly Level[], + angleStart: number, + angleEnd: number, + thickness: number, + colour: Color, +): BufferGeometry { + if (levels.length < 2) throw new Error('staveGeometry needs at least two levels') + + const sink: Sink = { position: [], color: [] } + + const corners = levels.map((level) => { + // Thickness cannot exceed half the thinnest radius; otherwise the inner surface breaks out. + const inner = Math.max(level.radius * 0.5, level.radius - thickness) + return { + a: point(angleStart, level.radius, level.y), + b: point(angleEnd, level.radius, level.y), + c: point(angleEnd, inner, level.y), + d: point(angleStart, inner, level.y), + } + }) + + for (let i = 0; i < corners.length - 1; i += 1) { + const low = corners[i]! + const high = corners[i + 1]! + quad(sink, low.a, low.b, high.b, high.a, colour) // outer face → points outward + quad(sink, low.c, low.d, high.d, high.c, colour) // inner face → points at the axis + quad(sink, low.d, low.a, high.a, high.d, colour) // start edge + quad(sink, low.b, low.c, high.c, high.b, colour) // end edge + } + + const top = corners.at(-1)! + const bottom = corners[0]! + quad(sink, top.a, top.b, top.c, top.d, colour) // top cap → +Y + quad(sink, bottom.d, bottom.c, bottom.b, bottom.a, colour) // bottom cap → -Y + + return finish(sink) +} + +/** + * Iron hoop: a ring with a rectangular cross section. + * + * The inner surface is deliberately not generated — the body it leans against + * hides it from every camera. A quarter of the triangle budget is won here. + */ +export function bandGeometry( + radius: number, + y: number, + height: number, + thickness: number, + segments: number, + colour: Color, + options: { + /** + * Generate the inner face as well. + * + * Not generated by default, because a hoop always wraps a body and the + * inner face is not visible — not generating it is a free triangle saving. + * But a free-standing ring (the cord of a sack, the tie of a bale) becomes + * a solid that is NOT CLOSED this way, and the "no reversed faces" check in + * the validation rightly fails. This flag is for that case. + */ + readonly inner?: boolean + } = {}, +): BufferGeometry { + const sink: Sink = { position: [], color: [] } + const half = height / 2 + const inner = radius - thickness + const stepAngle = (Math.PI * 2) / segments + + for (let i = 0; i < segments; i += 1) { + const a0 = i * stepAngle + const a1 = (i + 1) * stepAngle + + const outerLow0 = point(a0, radius, y - half) + const outerLow1 = point(a1, radius, y - half) + const outerHigh0 = point(a0, radius, y + half) + const outerHigh1 = point(a1, radius, y + half) + const innerHigh0 = point(a0, inner, y + half) + const innerHigh1 = point(a1, inner, y + half) + const innerLow0 = point(a0, inner, y - half) + const innerLow1 = point(a1, inner, y - half) + + quad(sink, outerLow0, outerLow1, outerHigh1, outerHigh0, colour) // outer → outward + quad(sink, outerHigh0, outerHigh1, innerHigh1, innerHigh0, colour) // top → +Y + quad(sink, innerLow0, innerLow1, outerLow1, outerLow0, colour) // bottom → -Y + // Inner face: the corner order is the reverse of the outer one so the normal points AT THE AXIS. + if (options.inner) { + quad(sink, innerHigh0, innerHigh1, innerLow1, innerLow0, colour) + } + } + + return finish(sink) +} + +/** + * Fan disc: barrel head, bowl bottom. + * + * So that it reads as built from several boards rather than one piece of wood, + * every triangle falls into a "board band" according to the X position of its + * centre, and the tone of that band is written into the vertex colour. The + * geometry cost is zero. + */ +export function headGeometry( + radius: number, + y: number, + segments: number, + facing: 'up' | 'down', + colour: Color, + plankCount: number, + plankShade: number, +): BufferGeometry { + const sink: Sink = { position: [], color: [] } + const centre: Vec3 = [0, y, 0] + const stepAngle = (Math.PI * 2) / segments + const plankWidth = (radius * 2) / Math.max(1, plankCount) + const tint = new Color() + + for (let i = 0; i < segments; i += 1) { + const p0 = point(i * stepAngle, radius, y) + const p1 = point((i + 1) * stepAngle, radius, y) + + // The boards are strips sliced along the X axis; whichever strip the X of + // the triangle's centroid falls into gives it its tone. + const centroidX = (p0[0] + p1[0]) / 3 + const band = Math.floor((centroidX + radius) / plankWidth) + tint.copy(colour).multiplyScalar(1 + (band % 2 === 0 ? plankShade : -plankShade)) + + if (facing === 'up') tri(sink, centre, p0, p1, tint) + else tri(sink, centre, p1, p0, tint) + } + + return finish(sink) +} + +/** + * Tapering box: a body whose bottom and top rectangles may differ. + * + * Anvil horn, stool leg, fence post tip, tool handle — every "box but carved" + * part of the kit is this. The winding follows the same logic as boxGeometry. + */ +export function taperedBoxGeometry( + bottom: readonly [number, number], + top: readonly [number, number], + height: number, + centre: Vec3, + colour: Color, + colourTop?: Color, +): BufferGeometry { + const sink: Sink = { position: [], color: [] } + const [cx, cy, cz] = centre + const low = cy - height / 2 + const high = cy + height / 2 + const upper = colourTop ?? colour + + // b = bottom corners, t = top corners; both in the same order: + // (-x,+z) (+x,+z) (+x,-z) (-x,-z) + const corner = (size: readonly [number, number], y: number, sx: number, sz: number): Vec3 => + [cx + (sx * size[0]) / 2, y, cz + (sz * size[1]) / 2] + + const b0 = corner(bottom, low, -1, 1), b1 = corner(bottom, low, 1, 1) + const b2 = corner(bottom, low, 1, -1), b3 = corner(bottom, low, -1, -1) + const t0 = corner(top, high, -1, 1), t1 = corner(top, high, 1, 1) + const t2 = corner(top, high, 1, -1), t3 = corner(top, high, -1, -1) + + const side = (bl: Vec3, br: Vec3, tr: Vec3, tl: Vec3): void => { + triShaded(sink, bl, br, tr, colour, colour, upper) + triShaded(sink, bl, tr, tl, colour, upper, upper) + } + side(b0, b1, t1, t0) // +Z + side(b2, b3, t3, t2) // -Z + side(b1, b2, t2, t1) // +X + side(b3, b0, t0, t3) // -X + + quad(sink, t0, t1, t2, t3, upper) // top → +Y + quad(sink, b3, b2, b1, b0, colour) // bottom → -Y + return finish(sink) +} + +/** + * Square-section bar swept along an arc — bucket handle, ring, hook. + * + * The cross section is laid out counter-clockwise relative to the sweep + * direction (the tangent); that is what makes the outer faces point outward. + * The arc is generated in the XY plane, the model rotates it as it likes. + */ +export function arcBarGeometry( + radius: number, + thickness: number, + fromAngle: number, + toAngle: number, + segments: number, + centre: Vec3, + colour: Color, +): BufferGeometry { + const sink: Sink = { position: [], color: [] } + const h = thickness / 2 + const [cx, cy, cz] = centre + const rings: Vec3[][] = [] + + for (let i = 0; i <= segments; i += 1) { + const a = fromAngle + ((toAngle - fromAngle) * i) / segments + // p: the point on the arc. r: the radial direction. z: the plane normal. + const px = cx + Math.cos(a) * radius + const py = cy + Math.sin(a) * radius + const rx = Math.cos(a), ry = Math.sin(a) + const at = (su: number, sv: number): Vec3 => + [px + sv * h * rx, py + sv * h * ry, cz + su * h] + // u = the plane normal, v = the radial direction. Since u×v equals the + // tangent, this ordering is counter-clockwise relative to the sweep direction. + rings.push([at(1, 1), at(-1, 1), at(-1, -1), at(1, -1)]) + } + + for (let i = 0; i < segments; i += 1) { + const a = rings[i]!, b = rings[i + 1]! + for (let j = 0; j < 4; j += 1) { + const k = (j + 1) % 4 + quad(sink, a[j]!, a[k]!, b[k]!, b[j]!, colour) + } + } + + const first = rings[0]!, last = rings[segments]! + quad(sink, first[0]!, first[3]!, first[2]!, first[1]!, colour) // start cap + quad(sink, last[0]!, last[1]!, last[2]!, last[3]!, colour) // end cap + return finish(sink) +} + +export interface SheetLevel { + /** Vertical position. */ + readonly y: number + /** Half width at that height. */ + readonly halfWidth: number + /** Sheet thickness. */ + readonly thickness: number + /** Curve height: how far the edges rise relative to the middle. 0 = flat. */ + readonly curve: number +} + +/** + * Dished sheet — a single piece, a seamless concave surface. + * + * I tried twice to build the shovel blade from three separate flat panels and + * both times the result was "three boards side by side": because each panel + * rotates around its own centre, a step is left between them and the eye did + * not read it as one surface. + * + * The right way is to produce ONE sheet whose cross section is curved. The + * cross section is an arc bent by `curve` at every level; width and thickness + * can change from level to level. The hollow faces the +Z direction. + * + * Besides the shovel, the shield, the trough, the roof covering and the mill + * sail all want this. + */ +export function dishedSheetGeometry( + levels: readonly SheetLevel[], + segments: number, + colour: Color, + colourTop?: Color, +): BufferGeometry { + if (levels.length < 2) throw new Error('dishedSheetGeometry needs at least two levels') + const sink: Sink = { position: [], color: [] } + const top = colourTop ?? colour + const shade = (i: number): Color => + colourTop ? new Color().copy(colour).lerp(top, i / (levels.length - 1)) : colour + + // front[i][j] / back[i][j]: level i, position j along the cross section + const front: Vec3[][] = [] + const back: Vec3[][] = [] + for (const level of levels) { + const f: Vec3[] = [] + const b: Vec3[] = [] + for (let j = 0; j <= segments; j += 1) { + const u = (j / segments) * 2 - 1 // -1 .. +1 + const x = u * level.halfWidth + // Parabolic cross section: 0 in the middle, `curve` at the edges. The + // rise of the edges is what forms the hollow. + const z = level.curve * u * u + f.push([x, level.y, z + level.thickness / 2]) + b.push([x, level.y, z - level.thickness / 2]) + } + front.push(f) + back.push(b) + } + + const last = levels.length - 1 + for (let i = 0; i < last; i += 1) { + for (let j = 0; j < segments; j += 1) { + // Front face: points at +Z. (a→b = +X, a→c = +X+Y, cross product +Z.) + triShaded(sink, front[i]![j]!, front[i]![j + 1]!, front[i + 1]![j + 1]!, + shade(i), shade(i), shade(i + 1)) + triShaded(sink, front[i]![j]!, front[i + 1]![j + 1]!, front[i + 1]![j]!, + shade(i), shade(i + 1), shade(i + 1)) + // Back face: reversed winding. + triShaded(sink, back[i]![j]!, back[i + 1]![j + 1]!, back[i]![j + 1]!, + shade(i), shade(i + 1), shade(i)) + triShaded(sink, back[i]![j]!, back[i + 1]![j]!, back[i + 1]![j + 1]!, + shade(i), shade(i + 1), shade(i + 1)) + } + + // Side edges: the right one points at +X, the left one at -X. + quad(sink, front[i]![segments]!, back[i]![segments]!, + back[i + 1]![segments]!, front[i + 1]![segments]!, shade(i)) + quad(sink, back[i]![0]!, front[i]![0]!, + front[i + 1]![0]!, back[i + 1]![0]!, shade(i)) + } + + // Top and bottom edge strips. + for (let j = 0; j < segments; j += 1) { + quad(sink, front[last]![j]!, front[last]![j + 1]!, + back[last]![j + 1]!, back[last]![j]!, shade(last)) + quad(sink, back[0]![j]!, back[0]![j + 1]!, + front[0]![j + 1]!, front[0]![j]!, shade(0)) + } + + return finish(sink) +} + +/** + * Reverses the winding of every triangle, i.e. turns all the normals around. + * + * Needed for vessels whose inside is visible: the outer surface of a bowl must + * point outward, the inner surface inward. Instead of writing the two + * separately, we generate the same cone and flip one of them. + */ +export function flipGeometry(geometry: BufferGeometry): BufferGeometry { + for (const name of ['position', 'color'] as const) { + const attribute = geometry.getAttribute(name) + if (!attribute) continue + const array = attribute.array as Float32Array + const stride = attribute.itemSize + // Swapping the 2nd and 3rd corner of a triangle reverses the winding. + for (let i = 0; i < attribute.count; i += 3) { + for (let k = 0; k < stride; k += 1) { + const b = (i + 1) * stride + k + const c = (i + 2) * stride + k + const swap = array[b]! + array[b] = array[c]! + array[c] = swap + } + } + attribute.needsUpdate = true + } + return geometry +} + +/** + * Reduces parts that share the same material into a single geometry — one draw + * call per material. The normals are computed AFTER merging: on non-indexed + * geometry that gives every triangle its own normal, i.e. flat shading. + */ +export function mergeColoured(geometries: readonly BufferGeometry[]): BufferGeometry { + // The normals of the inputs are dropped. The reason is a trap: because this + // function computes normals AFTER merging, its output has a `normal` + // attribute while the raw geometries do not. Trying to merge the two + // together made mergeGeometries fail with "attribute counts do not match". + // Since they are recomputed below anyway, the input normal data is worthless. + for (const geometry of geometries) geometry.deleteAttribute('normal') + + const merged = mergeGeometries(geometries as BufferGeometry[], false) + if (!merged) throw new Error('Could not merge geometries: attribute sets do not match') + for (const geometry of geometries) geometry.dispose() + merged.computeVertexNormals() + return merged +} + +/** + * Bends a straight body into an arc (along the Y axis, in the YZ plane). + * + * Written for pitchfork tines. A straight tine, however thick it is, looks + * like a technical drawing; a slight curve turns it into a forged tool. Hooks, + * horns and scythes have the same need. + * + * The simple "rotate every point in proportion to its own height" approach + * stretched the body and thinned it. The transform here is a real arc mapping: + * the body is WRAPPED onto a circle of radius 1/curvature, so the length of the + * centre line is preserved. + * + * TWO TRAPS, both found by measuring: + * + * 1. The arc is wrapped around y=0, so THE RESULT DEPENDS ON WHERE THE GEOMETRY + * SITS IN Y. A bar whose base is at the origin really does curve; a body + * CENTRED on y=0 bends symmetrically — its two ends go the same way, its + * middle stays put, and the silhouette barely changes at all. That is exactly + * what happened with the hoe blade: on a 0.235 m blade the bend produced + * 14 mm of displacement but DROPPED the Z range from 0.0337 to 0.0327. Build + * the same blade with its base at the origin and bend it, and the offset is + * 44 mm and the range 0.078. START whatever you want to bend at the origin. + * + * 2. The arc is only as smooth as the number of CROSS SECTIONS the geometry has + * along the Y axis. A two-level box (chamferedBoxGeometry) bent gives not an + * arc but a skewed box. A real arc needs a body with intermediate levels, + * like `latheGeometry`. + * + * @param curvature 1/radius. A positive value bends toward +Z. 0 does nothing. + */ +export function bendGeometry(geometry: BufferGeometry, curvature: number): BufferGeometry { + if (Math.abs(curvature) < 1e-9) return geometry + const position = geometry.getAttribute('position') + + // A bend needs something to bend. + // + // Every vertex is mapped by its own Y, so the curve only exists where there + // are Y levels to sample it at. Hand this a `boxGeometry` -- two levels, top + // and bottom -- and there is no midpoint to displace: the top face swings to + // one angle, the bottom to another, and the result is a sheared wedge that + // looks nothing like an arc. It fails silently, which is the expensive part. + // + // This session found the same mistake in three separate models: the + // tankard's handle, and both the brace and the curl of the tavern sign. In + // each the author had written a curve, the geometry had never curved, and + // the renders had been shipping the wedge. Three is a pattern, so the + // helper refuses rather than waiting for a fourth. + // + // The fix is never to nudge the curvature -- it is to give the piece levels + // (a lathe or a stack of them), or to use `arcBarGeometry`, which sweeps a + // real arc and takes the two things that actually matter: where the ends go. + const seen = new Set() + for (let i = 0; i < position.count && seen.size < 3; i += 1) { + seen.add(Math.round(position.getY(i) * 1e5)) + } + if (seen.size < 3) { + throw new Error( + `bendGeometry: geometry has ${seen.size} distinct Y level(s); a bend needs at least 3. ` + + 'Two levels shear into a wedge instead of curving. Build the piece with ' + + 'levels (latheGeometry / staveGeometry) or use arcBarGeometry.', + ) + } + + const radius = 1 / curvature + for (let i = 0; i < position.count; i += 1) { + const y = position.getY(i) + const z = position.getZ(i) + const angle = y * curvature + const sin = Math.sin(angle) + const cos = Math.cos(angle) + // Centre line + the cross section's offset perpendicular to the tangent. + position.setY(i, radius * sin - z * sin) + position.setZ(i, radius * (1 - cos) + z * cos) + } + position.needsUpdate = true + geometry.computeVertexNormals() + return geometry +} + +/** Deterministic hash derived from position. The same point always gives the same value. */ +function positionHash(x: number, y: number, z: number, salt: number): number { + // The point is rounded to a 0.1 mm grid: "identical" corners getting + // different hashes because of floating point noise was the one bug that tore + // the surface open. + let h = Math.imul(Math.round(x * 1e4) | 0, 0x27d4eb2d) + h ^= Math.imul(Math.round(y * 1e4) | 0, 0x165667b1) + h ^= Math.imul(Math.round(z * 1e4) | 0, 0x9e3779b1) + h = Math.imul(h ^ salt, 0x85ebca6b) + h ^= h >>> 13 + return ((h >>> 0) / 0xffffffff) * 2 - 1 +} + +export interface RoughenOptions { + /** For distorting the same geometry in a different way. */ + readonly salt?: number + /** Deviation multiplier on the Y axis. Kept low on the straw bale. */ + readonly scaleY?: number +} + +/** + * Makes the surface irregular: every corner shifts by a fixed amount derived + * from its own position. + * + * Why it is derived from position: these geometries are NON-INDEXED, i.e. every + * triangle carries its own corners and three or four copies sit at one point. + * Moving the corners independently tears the surface — on the first attempt the + * straw bale ended up riddled with holes. Because the position hash gives all + * the copies at the same point the SAME shift, the surface stays closed. + * + * This is the only thing that makes straw look like straw: a tidy box looks + * like a sponge whatever colour you give it. + */ +export function roughenGeometry( + geometry: BufferGeometry, + amount: number, + options: RoughenOptions = {}, +): BufferGeometry { + if (amount <= 0) return geometry + const salt = options.salt ?? 0 + const scaleY = options.scaleY ?? 1 + const position = geometry.getAttribute('position') + for (let i = 0; i < position.count; i += 1) { + const x = position.getX(i) + const y = position.getY(i) + const z = position.getZ(i) + position.setXYZ( + i, + x + positionHash(x, y, z, salt + 1) * amount, + y + positionHash(x, y, z, salt + 2) * amount * scaleY, + z + positionHash(x, y, z, salt + 3) * amount, + ) + } + position.needsUpdate = true + geometry.computeVertexNormals() + return geometry +} + +export interface MottleOptions { + /** For giving the same geometry a different pattern. */ + readonly salt?: number + /** + * The size of the specks (metres). Because positions are rounded to this + * grid and then hashed, corners in the same cell take the same tone — so what + * forms is not noise but MOTTLE. A small value gives sand, a large one a + * mottled surface. + */ + readonly cell?: number + /** The ratio of the hue shift to the brightness shift. A high value colours the mottle. */ + readonly hue?: number +} + +/** + * Works surface mottle into the vertex colours. + * + * This is this kit's answer to the question "what are we going to do about + * texture?". A bitmap texture would have wanted three things: UV coordinates + * (our geometry has none), image files the registry would have to carry, and a + * change to the kit's identity. All three cost more than they give back. + * + * Instead, a mottle pattern derived from the surface's OWN position is used. + * `bakeOcclusion` produced shadow from the SHAPE of the surface; this gives the + * surface a material texture. Together, with no texture file at all, the two + * make a flat-coloured lowpoly surface look like material. + * + * The limit should be stated honestly: the specks are sampled at the corners of + * the geometry, so triangle density sets their resolution. On a wide, sparsely + * subdivided surface shrinking `cell` does not help — there the cure is to + * subdivide the triangle, which eats into the lowpoly budget. + */ +export function mottleGeometry( + geometry: BufferGeometry, + amount: number, + options: MottleOptions = {}, +): BufferGeometry { + const colour = geometry.getAttribute('color') + if (!colour || amount <= 0) return geometry + const position = geometry.getAttribute('position') + const salt = options.salt ?? 0 + const cell = options.cell ?? 0.05 + const hue = options.hue ?? 0.35 + + for (let i = 0; i < colour.count; i += 1) { + const x = Math.round(position.getX(i) / cell) * cell + const y = Math.round(position.getY(i) / cell) * cell + const z = Math.round(position.getZ(i) / cell) * cell + const shade = 1 + positionHash(x, y, z, salt + 7) * amount + // A small difference between the channels: on a real material a lightened + // spot does not just get brighter, it also loses a little saturation. + const warm = positionHash(x, y, z, salt + 8) * amount * hue + colour.setXYZ( + i, + Math.max(0, colour.getX(i) * (shade + warm)), + Math.max(0, colour.getY(i) * shade), + Math.max(0, colour.getZ(i) * (shade - warm)), + ) + } + colour.needsUpdate = true + return geometry +} diff --git a/src/models/contemporary-props/core/index.ts b/src/models/contemporary-props/core/index.ts new file mode 100644 index 0000000..369a420 --- /dev/null +++ b/src/models/contemporary-props/core/index.ts @@ -0,0 +1,31 @@ +export { createRandom, jitter } from './random.ts' +export { + arcBarGeometry, + bandGeometry, + bendGeometry, + boxGeometry, + chamferedBoxGeometry, + dishedSheetGeometry, + flipGeometry, + headGeometry, + latheGeometry, + mergeColoured, + mottleGeometry, + prismGeometry, + roughenGeometry, + staveGeometry, + taperedBoxGeometry, +} from './geometry.ts' +export type { Level, MottleOptions, RoughenOptions, SheetLevel, Vec3 } from './geometry.ts' +export { bakeOcclusion } from './occlusion.ts' +export type { OcclusionOptions } from './occlusion.ts' +export { createKitModel } from './kit.ts' +export type { BuildContext, BuiltPart, KitModelOptions, PartBody, RuntimeContext } from './kit.ts' +export { createPart } from './parts.ts' +export type { PartSlot } from './parts.ts' +export { ironTint, steelTint, toolShaft, toolSocket } from './tool.ts' +export type { ShaftOptions, SocketOptions, ToolShaft } from './tool.ts' +export { PROP_PALETTE, createPropMaterials } from './materials.ts' +export { createTinter } from './tint.ts' +export type { Tinter } from './tint.ts' +export type { PropPalette, PropSlot } from './materials.ts' diff --git a/src/models/contemporary-props/core/kit.ts b/src/models/contemporary-props/core/kit.ts new file mode 100644 index 0000000..e631a22 --- /dev/null +++ b/src/models/contemporary-props/core/kit.ts @@ -0,0 +1,341 @@ +import { Group, Mesh, type BufferGeometry, type Material } from 'three' + +import type { ConfigureResult, MaterialBindings, ModelInstance, PartHandle } from '@/lib/vibe3d/model.ts' +import { ResourceScope } from '@/lib/vibe3d/ownership.ts' + +import type { Vec3 } from './geometry.ts' +import { mottleGeometry } from './geometry.ts' +import { bakeOcclusion, type OcclusionOptions } from './occlusion.ts' +import { createPart, type PartSlot } from './parts.ts' +import { createRandom } from './random.ts' +import { createPropMaterials, type PropSlot, type SlotMaterial } from './materials.ts' + +/** + * Kit model scaffold. + * + * Every model has to set up the same contract: resource ownership, material + * resolution and overrides, fixed anchor + replaceable content, a configure() + * that does not break identity, an idempotent dispose(). Writing that by hand + * in every model means ~80 lines of repetition plus a chance to get it wrong + * on each repetition — and indeed I got the anchor/content split wrong in the + * first three models at once. + * + * From here on, writing a model is just producing geometry: `build` returns a + * part name → geometry mapping, this function handles the rest. + */ + +/** The body of a part that uses a single material slot. */ +export interface PartBody { + readonly slot: S + readonly geometry: BufferGeometry +} + +export interface BuiltPart extends PartBody { + /** + * Extra bodies belonging to the same part that use a DIFFERENT slot. + * + * Parts are sibling children of the root, so when one moves the others + * cannot follow it. A chest's lid is oak boards and iron bands and the + * lock's hasp all at once, and the three MUST rotate together — if they were + * separate parts, the bands would hang in mid-air as the lid opened. + * + * So this field does not preserve the assumption "one part = one mesh", it + * preserves the principle "one part = one meaning". The meaning is not + * split, only the material is. + */ + readonly extras?: readonly PartBody[] + /** + * The part's own centre of rotation (in model space). + * + * When given, the anchor is positioned here and the geometry is assumed to + * have been written RELATIVE TO THIS POINT. This is the only thing needed + * for a chest lid to rotate around its hinge: the lid geometry is produced + * at the hinge origin, the anchor is moved to the hinge, and + * `anchor.rotation.x` now opens the lid. + * + * Objects the consumer attached to the anchor join this rotation too — a + * candle placed on top of the lid rises with the lid. That is the correct + * behaviour. + */ + readonly origin?: Vec3 +} + +export interface BuildContext { + readonly config: Readonly + /** Seed-bound deterministic randomness. Starts over on every rebuild. */ + readonly random: () => number + /** The slot's current material (the override, if there is one). */ + resolve(slot: S): Material + /** The slot's default material — even if it has been overridden. */ + readonly defaults: Pick +} + +/** + * The runtime context handed to actions and to `update`. + * + * It gives access to the PARTS, not to the geometry: an action must not + * trigger a rebuild, it should only move something in the scene graph. Opening + * the lid does not change the model's identity, so it is not `configure()`'s + * job. + */ +export interface RuntimeContext { + readonly parts: Record> + getConfig(): Readonly +} + +export interface KitModelOptions< + C extends { seed: number }, + S extends PropSlot, + P extends string, + A extends object = Record, +> { + /** Registry item name; used in mesh names and in userData. */ + readonly id: string + readonly defaults: C + readonly slots: readonly S[] + /** Part name → geometry. `undefined` means absent in that configuration. */ + build(context: BuildContext): Record | undefined> + /** + * Ambient occlusion to bake into the vertex colours. `false` turns it off. + * + * All parts are evaluated TOGETHER: the place where a board darkens is the + * surface of the neighbouring post, not its own surface. + */ + readonly occlusion?: OcclusionOptions | false + /** + * Surface mottle written into the vertex colours. `false` turns it off. + * + * The amount is scaled BY SLOT (see the table below): burnished steel is not + * mottled, straw is mottled badly. The model does not have to do anything + * else. + */ + readonly mottle?: { readonly amount?: number; readonly cell?: number } | false + /** + * The model's typed actions. Set up once, after the first build — so state + * held in the closure (is the lid open, which flame phase) survives a + * rebuild. + */ + actions?(context: RuntimeContext): A + /** Called each frame. If the consumer never calls it, the model stays fully static. */ + update?(deltaSeconds: number, context: RuntimeContext): void +} + +/** + * Mottle multiplier per slot. + * + * The rule comes from the physics of the material: the more polished a surface + * is, the more it becomes a SINGLE COLOUR, because the light reaching the eye + * comes from the reflection rather than from the surface's own pigment. For + * straw and cloth the exact opposite holds. + * + * Tying this to the slot is better than tuning it separately in every model: + * within the kit the same material looks the same everywhere. + */ +const MOTTLE_BY_SLOT: Readonly> = { + /* + * Lower across the board than the medieval kit's, and that is the point. + * + * Those materials were worked by hand and every one of them varied: a stave + * differs from the stave beside it, straw is never twice the same. These are + * manufactured. An injection moulding is the same colour everywhere it is + * the same part, and mottling it is what makes a new plastic bin look like a + * salvaged one. + * + * So the high values here are the exceptions, and each is a surface that + * genuinely varies at the scale you see it: grain in timber, weave in + * fabric, aggregate in concrete, and the spangle that hot-dip zinc actually + * has and that nothing else in the kit does. + */ + wood: 1, + fabric: 1.1, + concrete: 0.9, + galvanised: 0.8, + cord: 0.6, + rubber: 0.45, + steelPainted: 0.35, + brass: 0.3, + paper: 0.25, + aluminium: 0.25, + stainless: 0.2, + plastic: 0.18, + retroreflective: 0.15, + ceramic: 0.12, + glass: 0.1, + glassTinted: 0.1, + plasticGloss: 0.1, + chrome: 0.08, + // The vertex colour IS the result on an unlit material, so any variation + // here is variation in the light itself rather than in the surface. + emissive: 0, +} + + +export function createKitModel< + C extends { seed: number }, + S extends PropSlot, + P extends string, + A extends object = Record, +>( + options: KitModelOptions, + overrides: Partial = {}, +): ModelInstance>, A> { + let config: C = { ...options.defaults, ...overrides } + + // The resources the model owns. Materials handed in by the consumer never + // enter here, so dispose() does not touch them. + const scope = new ResourceScope() + const defaults = createPropMaterials(scope, options.slots) + const overridesBySlot = new Map() + const resolve = (slot: S): Material => overridesBySlot.get(slot) ?? defaults[slot] + + const root = new Group() + root.name = options.id + + const parts = {} as Record + let owned: BufferGeometry[] = [] + + function build(): void { + for (const geometry of owned) geometry.dispose() + owned = [] + + const produced = options.build({ + config, + random: createRandom(config.seed), + resolve, + defaults, + }) + + const built = Object.values(produced) + .filter((part): part is BuiltPart => part !== undefined) + const geometriesOf = (part: BuiltPart): BufferGeometry[] => + [part, ...(part.extras ?? [])] + // An emitter neither TAKES shadow nor CASTS one. `emissive` is an + // unlit material, so its vertex colour is the final colour going + // straight to the screen, and darkening it with occlusion is the same + // as switching the light off. The rule is tied to the slot itself + // rather than to a per-model flag, so it cannot be forgotten on the + // one object that needed it. + .filter((body) => body.slot !== 'emissive') + .map((body) => body.geometry) + + if (options.occlusion !== false) { + // Occlusion has to be computed in ASSEMBLY space: a lid written at its + // own origin looks as though it sits inside the body rather than beside + // it, and darkens the wrong places. So everything is first moved into + // place, baked, then moved back — the resulting geometries stay + // hinge-local. + const moved = built.filter((part) => part.origin !== undefined) + for (const part of moved) { + const [x, y, z] = part.origin! + for (const geometry of geometriesOf(part)) geometry.translate(x, y, z) + } + bakeOcclusion(built.flatMap(geometriesOf), options.occlusion ?? {}) + for (const part of moved) { + const [x, y, z] = part.origin! + for (const geometry of geometriesOf(part)) geometry.translate(-x, -y, -z) + } + } + + if (options.mottle !== false) { + const amount = options.mottle?.amount ?? 0.125 + // The mottle size is derived from the model's scale, but WITH ABSOLUTE + // BOUNDS. + // + // The bounds were added later and closed a real bug: with scale used on + // its own, a 4.89 m fence got a 0.27 m cell. The fence's post is 0.09 m + // — so the entire post fell into ONE cell and came out completely flat. + // The model paid the cost of the texture system and got nothing back. + // + // The truth is this: wood grain mottle is 2–8 cm and has nothing to do + // with the size of the object. A fence post and a tankard stave come out + // of the same tree. + const extent = built.reduce((largest, part) => { + part.geometry.computeBoundingBox() + const box = part.geometry.boundingBox + if (!box) return largest + return Math.max(largest, box.max.x - box.min.x, box.max.y - box.min.y, box.max.z - box.min.z) + }, 0) + const cell = options.mottle?.cell ?? Math.min(0.08, Math.max(0.015, extent * 0.055)) + for (const part of built) { + for (const body of [part, ...(part.extras ?? [])]) { + mottleGeometry(body.geometry, amount * MOTTLE_BY_SLOT[body.slot], { cell, salt: 3 }) + } + } + } + + for (const [name, part] of Object.entries(produced) as Array<[P, BuiltPart | undefined]>) { + // The anchor is created on first setup and NEVER changes again; only its + // content is renewed. That is why objects the consumer attached to the + // anchor survive a rebuild. + let slot = parts[name] + if (!slot) { + slot = createPart(`${options.id}/${name}`) + parts[name] = slot + root.add(slot.anchor) + } + const target = slot.reset() + if (!part) continue + + // The position is updated but the ROTATION is not: the angle an action + // moved has to survive a rebuild, otherwise the chest's lid slams shut + // every time `configure()` is called. + if (part.origin) slot.anchor.position.set(...part.origin) + + for (const body of [part, ...(part.extras ?? [])]) { + owned.push(body.geometry) + const mesh = new Mesh(body.geometry, resolve(body.slot)) + mesh.name = `${options.id}/${name}` + mesh.userData.vibe3d = { + model: `@contemporary-props/${options.id}`, + part: name, + materialSlot: body.slot, + } + target.add(mesh) + } + } + } + + build() + + const runtime: RuntimeContext = { + parts: parts as unknown as Record>, + getConfig: () => config, + } + const actions = (options.actions?.(runtime) ?? {}) as A + + const materials: MaterialBindings = { + get: (slot) => (options.slots.includes(slot as S) ? resolve(slot as S) : undefined), + override: (slot, material) => { + if (!options.slots.includes(slot as S)) return + overridesBySlot.set(slot as S, material) + build() + }, + reset: (slot) => { + if (!overridesBySlot.delete(slot as S)) return + build() + }, + } + + return { + root, + parts: parts as unknown as Record>, + actions, + materials, + getConfig: () => config, + configure: (patch): ConfigureResult => { + const next = { ...config, ...patch } + const changed = (Object.keys(next) as Array).some((key) => next[key] !== config[key]) + if (!changed) return { rebuilt: false } + config = next + build() + return { rebuilt: true } + }, + update: (deltaSeconds) => options.update?.(deltaSeconds, runtime), + dispose: () => { + for (const geometry of owned) geometry.dispose() + owned = [] + for (const part of Object.values(parts) as PartSlot[]) part.reset() + scope.dispose() + }, + } +} diff --git a/src/models/contemporary-props/core/materials.ts b/src/models/contemporary-props/core/materials.ts new file mode 100644 index 0000000..d068eec --- /dev/null +++ b/src/models/contemporary-props/core/materials.ts @@ -0,0 +1,351 @@ +/** + * The kit's material slots, and the palette behind them. + * + * A slot exists when a single material cannot carry a difference that a viewer + * can see. That test is stricter than it sounds, and it is what keeps this list + * at nineteen rather than fifty: two objects that differ only in COLOUR share a + * slot, because colour travels in the vertex attribute. A slot is earned by + * roughness, by metalness, by transparency, or by not receiving light at all. + * + * Every slot below is argued from at least three objects in the catalogue. If a + * slot ever ends up with one consumer, it was a colour and it should be folded + * back into whatever it was split from. + * + * Inherited from the medieval kit: `wood`, `steelPainted` (was `iron`), + * `fabric` (was `cloth`), `ceramic` (was `clay`), `brass`, and `cord`, which + * narrows from rope to nylon and PVC. Dropped: leather, thatch, bone, gold and + * wax, none of which has a consumer across 250 present-day objects. + */ +import { + Color, + MeshBasicMaterial, + MeshStandardMaterial, + DoubleSide, +} from 'three' + +import type { ResourceScope } from '@/lib/vibe3d/ownership.ts' + +export type PropSlot = + | 'wood' + | 'steelPainted' + | 'galvanised' + | 'stainless' + | 'chrome' + | 'aluminium' + | 'brass' + | 'plastic' + | 'plasticGloss' + | 'rubber' + | 'concrete' + | 'ceramic' + | 'glass' + | 'glassTinted' + | 'fabric' + | 'cord' + | 'paper' + | 'emissive' + | 'retroreflective' + +export interface SlotMaterial { + readonly wood: MeshStandardMaterial + readonly steelPainted: MeshStandardMaterial + readonly galvanised: MeshStandardMaterial + readonly stainless: MeshStandardMaterial + readonly chrome: MeshStandardMaterial + readonly aluminium: MeshStandardMaterial + readonly brass: MeshStandardMaterial + readonly plastic: MeshStandardMaterial + readonly plasticGloss: MeshStandardMaterial + readonly rubber: MeshStandardMaterial + readonly concrete: MeshStandardMaterial + readonly ceramic: MeshStandardMaterial + readonly glass: MeshStandardMaterial + readonly glassTinted: MeshStandardMaterial + readonly fabric: MeshStandardMaterial + readonly cord: MeshStandardMaterial + readonly paper: MeshStandardMaterial + readonly emissive: MeshBasicMaterial + readonly retroreflective: MeshStandardMaterial +} + +export interface PropPalette { + /** Pale contemporary timber: beech, birch ply, light oak veneer. */ + readonly wood: Color + /** Cut ends and edge banding, lighter and cooler than the face. */ + readonly woodEnd: Color + /** Powder-coated steel: lockers, shelving, barriers, tool bodies. */ + readonly steelPainted: Color + /** Hot-dip zinc, cooler and lighter than paint, with a spangle. */ + readonly galvanised: Color + /** Brushed stainless: sinks, pans, appliance fronts. */ + readonly stainless: Color + /** Polished chrome, near white because it is mostly reflecting the room. */ + readonly chrome: Color + /** Brushed aluminium extrusion, cooler and darker than chrome. */ + readonly aluminium: Color + /** Brass and copper trim: valves, instrument bells, fittings. */ + readonly brass: Color + /** Matte injection-moulded plastic, the most common surface in the kit. */ + readonly plastic: Color + /** Gloss plastic: kettles, toasters, appliance fascias. */ + readonly plasticGloss: Color + /** Rubber and soft PVC: tyres, grips, seals, cable jacket. */ + readonly rubber: Color + /** Cast concrete with an aggregate speckle. */ + readonly concrete: Color + /** Glazed ceramic: basins, mugs, vases. */ + readonly ceramic: Color + /** Clear glass. Thin, so it reads by its edges rather than its face. */ + readonly glass: Color + /** Tinted glass: side panels, screens, cooler doors. */ + readonly glassTinted: Color + /** Upholstery and woven panel infill. */ + readonly fabric: Color + /** Nylon and PVC cord: blind ladders, pull cords, hose. */ + readonly cord: Color + /** Paper stock: near white, no specular at all. */ + readonly paper: Color + /** Default emitter colour. Models override it per object. */ + readonly emissive: Color + /** High-visibility retroreflective sheeting. */ + readonly retroreflective: Color +} + +export const PROP_PALETTE: PropPalette = { + wood: new Color(0xbfa079), + woodEnd: new Color(0xd0b795), + steelPainted: new Color(0x767c82), + galvanised: new Color(0xa9b0b5), + stainless: new Color(0xb4b8bb), + chrome: new Color(0xd6dade), + aluminium: new Color(0xa4a9ae), + brass: new Color(0xb08d57), + plastic: new Color(0xc6c8c6), + plasticGloss: new Color(0xe6e8e9), + rubber: new Color(0x2e3134), + concrete: new Color(0x9a9691), + ceramic: new Color(0xf0efea), + glass: new Color(0xb9cbd2), + glassTinted: new Color(0x3a4750), + fabric: new Color(0x6c6f73), + cord: new Color(0xd6d3cc), + paper: new Color(0xf2f0ea), + emissive: new Color(0xffd9a0), + retroreflective: new Color(0xf4562a), +} + +export function createPropMaterials( + scope: ResourceScope, + slots: readonly S[], +): Pick { + const build: { [K in PropSlot]: () => SlotMaterial[K] } = { + // White base on every lit material: all colour comes from the vertex + // attribute, so the material must not multiply it away. + wood: () => new MeshStandardMaterial({ + name: 'contemporary-props / wood', + color: 0xffffff, + vertexColors: true, + roughness: 0.74, + metalness: 0, + }), + + /* + * The four metals, and why one slot will not do. + * + * They differ in ROUGHNESS and in how much of the room they return, and + * neither of those is something a vertex colour can carry. Put a sink and + * a locker on one slot and the kitchen goes flat: the sink stops looking + * wet and the locker starts looking wet. + */ + steelPainted: () => new MeshStandardMaterial({ + name: 'contemporary-props / painted steel', + color: 0xffffff, + vertexColors: true, + // Powder coat is a thick even film. It is matte, but not as matte as + // plastic, and that small gap is what separates a locker from a bin. + roughness: 0.62, + metalness: 0.15, + }), + galvanised: () => new MeshStandardMaterial({ + name: 'contemporary-props / galvanised steel', + color: 0xffffff, + vertexColors: true, + roughness: 0.55, + metalness: 0.65, + }), + stainless: () => new MeshStandardMaterial({ + name: 'contemporary-props / stainless steel', + color: 0xffffff, + vertexColors: true, + roughness: 0.28, + metalness: 0.92, + }), + chrome: () => new MeshStandardMaterial({ + name: 'contemporary-props / polished chrome', + color: 0xffffff, + vertexColors: true, + // Distinct from stainless by reflection, not by colour. A tap next to a + // sink is the test: if they share a slot, the tap disappears into it. + roughness: 0.06, + metalness: 1, + }), + aluminium: () => new MeshStandardMaterial({ + name: 'contemporary-props / brushed aluminium', + color: 0xffffff, + vertexColors: true, + roughness: 0.38, + metalness: 0.85, + }), + brass: () => new MeshStandardMaterial({ + name: 'contemporary-props / brass', + color: 0xffffff, + vertexColors: true, + roughness: 0.34, + metalness: 0.88, + }), + + /* + * Matte and gloss plastic are two slots for one substance, and it is the + * only split here justified by a highlight alone. A kettle and a waste bin + * can be the same colour and the same shape family; what says which is + * which is whether the light comes back off it in a hard spot. + */ + plastic: () => new MeshStandardMaterial({ + name: 'contemporary-props / matte plastic', + color: 0xffffff, + vertexColors: true, + roughness: 0.78, + metalness: 0, + }), + plasticGloss: () => new MeshStandardMaterial({ + name: 'contemporary-props / gloss plastic', + color: 0xffffff, + vertexColors: true, + roughness: 0.18, + metalness: 0, + }), + rubber: () => new MeshStandardMaterial({ + name: 'contemporary-props / rubber', + color: 0xffffff, + vertexColors: true, + // Almost no specular at all. This is what makes a castor read as a + // castor rather than as a small dark wheel. + roughness: 0.92, + metalness: 0, + }), + concrete: () => new MeshStandardMaterial({ + name: 'contemporary-props / concrete', + color: 0xffffff, + vertexColors: true, + roughness: 0.95, + metalness: 0, + }), + ceramic: () => new MeshStandardMaterial({ + name: 'contemporary-props / glazed ceramic', + color: 0xffffff, + vertexColors: true, + // Glaze is a glass layer over a matte body, so it is smooth without + // being metal. Sharing gloss plastic here makes a basin look moulded. + roughness: 0.14, + metalness: 0.04, + }), + + /* + * Two glasses, because the parameter that separates them is transmission + * and not colour. Reusing clear glass with a darker vertex colour loses + * the surface: a tinted panel still has a bright edge and a visible sheen, + * and a darkened clear panel has neither. + */ + glass: () => new MeshStandardMaterial({ + name: 'contemporary-props / clear glass', + color: 0xffffff, + vertexColors: true, + roughness: 0.04, + metalness: 0, + transparent: true, + opacity: 0.24, + // A pane is seen from both faces at once and it must not cull one away, + // and it must not hide what is behind it in the depth buffer. + side: DoubleSide, + depthWrite: false, + }), + glassTinted: () => new MeshStandardMaterial({ + name: 'contemporary-props / tinted glass', + color: 0xffffff, + vertexColors: true, + roughness: 0.08, + metalness: 0.1, + transparent: true, + opacity: 0.62, + side: DoubleSide, + depthWrite: false, + }), + + fabric: () => new MeshStandardMaterial({ + name: 'contemporary-props / fabric', + color: 0xffffff, + vertexColors: true, + roughness: 0.96, + metalness: 0, + }), + cord: () => new MeshStandardMaterial({ + name: 'contemporary-props / cord', + color: 0xffffff, + vertexColors: true, + roughness: 0.68, + metalness: 0, + }), + paper: () => new MeshStandardMaterial({ + name: 'contemporary-props / paper', + color: 0xffffff, + vertexColors: true, + // Zero specular. Paper rendered with any highlight at all reads as + // plastic sheet, which is the single most common way a stack of forms + // or a till roll goes wrong. + roughness: 1, + metalness: 0, + }), + + /** + * Unlit. The vertex colour IS the result, so nothing may darken it. + * + * The medieval kit had firelight; this kit has switchable emitters with a + * colour parameter, which is a different thing: a traffic aspect, a status + * lamp, a screen in its on state, a bulb. Anything in this slot is skipped + * by the occlusion and mottle passes, because shading an emitter is the + * same as switching it off. + */ + emissive: () => new MeshBasicMaterial({ + name: 'contemporary-props / emissive', + color: 0xffffff, + vertexColors: true, + }), + + /** + * Retroreflective sheeting: cone collars, barricade stripes, sign plates. + * + * Arguably a treatment rather than a material. It gets its own slot because + * it must not tone-map like paint: the whole point of the surface is that + * it returns light toward wherever the light came from, so it stays bright + * when everything around it has gone dark. Modelled here as a very smooth, + * very bright dielectric, which is the closest a standard material gets + * without a custom shader. + */ + retroreflective: () => new MeshStandardMaterial({ + name: 'contemporary-props / retroreflective', + color: 0xffffff, + vertexColors: true, + roughness: 0.32, + metalness: 0, + }), + } + + const materials = {} as { [K in S]: SlotMaterial[K] } + for (const slot of slots) { + // TypeScript cannot follow correlated unions: `build[slot]` widens to a + // union of functions, so it cannot know the return is exactly + // SlotMaterial[slot]. The cast is safe because the map is built by hand. + materials[slot] = scope.ownMaterial(build[slot]()) as SlotMaterial[S] + } + return materials +} diff --git a/src/models/contemporary-props/core/occlusion.ts b/src/models/contemporary-props/core/occlusion.ts new file mode 100644 index 0000000..2a5af03 --- /dev/null +++ b/src/models/contemporary-props/core/occlusion.ts @@ -0,0 +1,176 @@ +import type { BufferGeometry } from 'three' + +/** + * Ambient occlusion baked into vertex colours. + * + * Why this and not a texture: a bitmap texture would bring three things — UV + * coordinates (our geometry has none), image files the registry would have to + * carry, and a change to the kit's identity. Lowpoly + flat shading + vertex + * colour is a coherent style; a half-hearted texture breaks it. + * + * Instead we derive the darkening from the surface's OWN shape: the more + * neighbouring surfaces surround a point, the less sky it sees. The result is + * darkening in cavities and at contact points — between the boards, under the + * hoop, where the logs touch. The models suddenly look "used" and it costs + * zero memory, zero textures. + * + * Method: a grid is built from the triangle centroids, then for each vertex + * the neighbour density within its own normal hemisphere is measured. No ray + * tracing — at this scale (hundreds of triangles) it would be needlessly + * expensive and the difference is negligible. + */ + +export interface OcclusionOptions { + /** Radius searched for neighbours. Derived from the model's size if omitted. */ + readonly radius?: number + /** How much the darkest point is darkened. 0 = off. */ + readonly strength?: number + /** Neighbour weight where saturation is reached. Raising it softens the darkening. */ + readonly saturation?: number +} + +interface Sample { + readonly x: number + readonly y: number + readonly z: number + readonly area: number +} + +/** Simple spatial grid: for quickly finding the samples within a radius. */ +class Grid { + readonly #cells = new Map() + readonly #size: number + + constructor(samples: readonly Sample[], cellSize: number) { + this.#size = cellSize + for (const sample of samples) { + const key = this.#key(sample.x, sample.y, sample.z) + const bucket = this.#cells.get(key) + if (bucket) bucket.push(sample) + else this.#cells.set(key, [sample]) + } + } + + #key(x: number, y: number, z: number): string { + return `${Math.floor(x / this.#size)},${Math.floor(y / this.#size)},${Math.floor(z / this.#size)}` + } + + /** The samples of the 27 cells surrounding the given point. */ + near(x: number, y: number, z: number): Sample[] { + const cx = Math.floor(x / this.#size) + const cy = Math.floor(y / this.#size) + const cz = Math.floor(z / this.#size) + const found: Sample[] = [] + for (let i = -1; i <= 1; i += 1) { + for (let j = -1; j <= 1; j += 1) { + for (let k = -1; k <= 1; k += 1) { + const bucket = this.#cells.get(`${cx + i},${cy + j},${cz + k}`) + if (bucket) found.push(...bucket) + } + } + } + return found + } +} + +/** + * Computes the occlusion of the given geometries TOGETHER and writes it into + * their colours. + * + * They all have to be evaluated as one: the place where a board darkens is the + * surface of the neighbouring post, not its own surface. Processing them one + * by one would miss the contact points entirely. + */ +export function bakeOcclusion( + geometries: readonly BufferGeometry[], + options: OcclusionOptions = {}, +): void { + const strength = options.strength ?? 0.42 + if (strength <= 0 || geometries.length === 0) return + + // --- 1. Samples: each triangle's centroid, weighted by its area --- + const samples: Sample[] = [] + let minX = Infinity, minY = Infinity, minZ = Infinity + let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity + + for (const geometry of geometries) { + const position = geometry.getAttribute('position') + if (!position) continue + const index = geometry.getIndex() + const count = index ? index.count : position.count + for (let i = 0; i < count; i += 3) { + const at = (k: number): [number, number, number] => { + const v = index ? index.getX(i + k) : i + k + return [position.getX(v), position.getY(v), position.getZ(v)] + } + const [ax, ay, az] = at(0) + const [bx, by, bz] = at(1) + const [cx, cy, cz] = at(2) + const ux = bx - ax, uy = by - ay, uz = bz - az + const vx = cx - ax, vy = cy - ay, vz = cz - az + const nx = uy * vz - uz * vy + const ny = uz * vx - ux * vz + const nz = ux * vy - uy * vx + const area = Math.hypot(nx, ny, nz) / 2 + if (area <= 0) continue + const x = (ax + bx + cx) / 3 + const y = (ay + by + cy) / 3 + const z = (az + bz + cz) / 3 + samples.push({ x, y, z, area }) + minX = Math.min(minX, x); maxX = Math.max(maxX, x) + minY = Math.min(minY, y); maxY = Math.max(maxY, y) + minZ = Math.min(minZ, z); maxZ = Math.max(maxZ, z) + } + } + if (samples.length === 0) return + + const extent = Math.max(maxX - minX, maxY - minY, maxZ - minZ, 1e-6) + // The radius is derived from the scale but has an ABSOLUTE ceiling. Without + // the ceiling a 4.89 m fence gets a 0.69 m radius and the definition of + // "neighbour" loses its meaning: everything is everything's neighbour, and + // instead of showing the contact points the occlusion smears a flat + // darkening over the whole model. + // + // The physical meaning says the same thing: what shades a surface is what is + // NEAR it. A post half a metre away is not making the shadow between the + // boards. + const radius = options.radius ?? Math.min(0.16, Math.max(0.015, extent * 0.14)) + const grid = new Grid(samples, radius) + // Saturation has to be proportional to the model's scale: as the radius + // grows so does the area it covers, and a fixed threshold would turn small + // models pitch black. + const saturation = options.saturation ?? radius * radius * 1.9 + + // --- 2. Neighbour density for each vertex --- + for (const geometry of geometries) { + const position = geometry.getAttribute('position') + const colour = geometry.getAttribute('color') + if (!position || !colour) continue + if (!geometry.getAttribute('normal')) geometry.computeVertexNormals() + const normal = geometry.getAttribute('normal')! + + for (let i = 0; i < position.count; i += 1) { + const px = position.getX(i), py = position.getY(i), pz = position.getZ(i) + const nx = normal.getX(i), ny = normal.getY(i), nz = normal.getZ(i) + + let weight = 0 + for (const sample of grid.near(px, py, pz)) { + const dx = sample.x - px, dy = sample.y - py, dz = sample.z - pz + const distance = Math.hypot(dx, dy, dz) + if (distance < 1e-6 || distance > radius) continue + // Only neighbours in the hemisphere the vertex FACES occlude it. + const facing = (dx * nx + dy * ny + dz * nz) / distance + if (facing <= 0) continue + // The effect fades with distance; a soft falloff instead of the + // inverse-square law, because the goal is not physical accuracy but a + // readable cavity shadow. + weight += sample.area * facing * (1 - distance / radius) + } + + const occlusion = Math.min(1, weight / saturation) + const factor = 1 - strength * occlusion + colour.setXYZ(i, colour.getX(i) * factor, colour.getY(i) * factor, colour.getZ(i) * factor) + } + colour.needsUpdate = true + } +} diff --git a/src/models/contemporary-props/core/parts.ts b/src/models/contemporary-props/core/parts.ts new file mode 100644 index 0000000..cb9a585 --- /dev/null +++ b/src/models/contemporary-props/core/parts.ts @@ -0,0 +1,49 @@ +import { Group } from 'three' + +import type { PartHandle } from '@/lib/vibe3d/model.ts' + +/** + * Semantic part slot: fixed anchor + replaceable content. + * + * This is the most easily misunderstood contract in vibe3d. `PartHandle` + * declares two separate objects and they CANNOT BE THE SAME: + * + * anchor the same object for the lifetime of the model. The consumer + * attaches its light, its label, its collision body, its gameplay + * object here. + * content the geometry that is thrown away and rebuilt every time + * configure() is called. + * + * Making both the same Group and calling `clear()` on rebuild silently deletes + * everything the consumer attached too — the model keeps working, but the + * protocol's actual promise is broken. `scripts/verify-model.ts` tests this + * separately. + */ +export interface PartSlot extends PartHandle { + readonly anchor: Group + readonly content: Group + /** Replaces the content with a fresh Group and returns it. Leaves the anchor alone. */ + reset(): Group +} + +export function createPart(name: string): PartSlot { + const anchor = new Group() + anchor.name = name + let content = new Group() + content.name = `${name}/content` + anchor.add(content) + + return { + anchor, + get content(): Group { + return content + }, + reset(): Group { + anchor.remove(content) + content = new Group() + content.name = `${name}/content` + anchor.add(content) + return content + }, + } +} diff --git a/src/models/contemporary-props/core/random.ts b/src/models/contemporary-props/core/random.ts new file mode 100644 index 0000000..20eae4a --- /dev/null +++ b/src/models/contemporary-props/core/random.ts @@ -0,0 +1,26 @@ +/** + * Deterministic randomness. + * + * A procedural kit needs variation — perfect symmetry reads as "generated". + * But the variation has to be repeatable: the same seed must always give the + * same model, otherwise neither previews, nor tests, nor art direction hold + * up. That is why Math.random() is not used. + * + * mulberry32: 32-bit state, fast, not cryptographic but far more than enough + * for visual variation. + */ +export function createRandom(seed: number): () => number { + let state = seed >>> 0 + return () => { + state = (state + 0x6d2b79f5) >>> 0 + let t = state + t = Math.imul(t ^ (t >>> 15), t | 1) + t ^= t + Math.imul(t ^ (t >>> 7), t | 61) + return ((t ^ (t >>> 14)) >>> 0) / 4294967296 + } +} + +/** Symmetric deviation in the range -amount .. +amount. */ +export function jitter(random: () => number, amount: number): number { + return (random() * 2 - 1) * amount +} diff --git a/src/models/contemporary-props/core/tint.ts b/src/models/contemporary-props/core/tint.ts new file mode 100644 index 0000000..225b6de --- /dev/null +++ b/src/models/contemporary-props/core/tint.ts @@ -0,0 +1,52 @@ +import { Color } from 'three' + +import { PROP_PALETTE, type PropPalette } from './materials.ts' +import { jitter } from './random.ts' + +/** + * Factory that produces colours deviated from the palette. + * + * Every model used to rewrite this inline — the same five lines thirteen + * times. The cost of the repetition was not just line count: the deviation + * amounts had drifted from model to model, so when two models were put side + * by side one of them visibly had more variation than the other. + * + * Every call returns A NEW Color. + * + * It used to return one shared object and mutate it, on the reasoning that the + * geometry helpers read the colour immediately and an allocation per call is + * waste. The reasoning holds right up until two tints appear as arguments of + * the SAME call: + * + * latheGeometry(profile, 7, origin, tint('char', 0.06), + * { colourTop: tint('charHot', -0.12) }) + * + * Both arguments are the same object, so both carry whatever the second call + * computed. That is not a hypothetical: it is why the torch's pitch head + * rendered hot orange instead of black, and the same mistake was made twice + * more in one session -- once in the anvil's stump, which came out painted in + * end grain on every face, and once nearly in the shovel. Three times means + * the hazard is in the helper, not in the callers. + * + * A few hundred Color allocations at build time is not a cost worth one class + * of silent, invisible bug. + */ +export function createTinter(random: () => number) { + return ( + key: keyof PropPalette, + /** Lightness shift. Negative darkens. */ + lift = 0, + /** Deviation multiplier. 0 gives a completely flat colour. */ + spread = 1, + ): Color => { + const scratch = new Color(PROP_PALETTE[key]) + scratch.offsetHSL( + jitter(random, 0.012 * spread), + jitter(random, 0.05 * spread), + lift + jitter(random, 0.05 * spread), + ) + return scratch + } +} + +export type Tinter = ReturnType diff --git a/src/models/contemporary-props/core/tool.ts b/src/models/contemporary-props/core/tool.ts new file mode 100644 index 0000000..3fafa90 --- /dev/null +++ b/src/models/contemporary-props/core/tool.ts @@ -0,0 +1,131 @@ +import { Color, type BufferGeometry } from 'three' + +import { latheGeometry, mergeColoured, type Level } from './geometry.ts' +import { jitter } from './random.ts' +import { PROP_PALETTE } from './materials.ts' + +/** + * The shared language of hand tools. + * + * In the first attempt all three tools were just a straight prismatic shaft + + * a boxy head, and they looked like toys. The reasons were small, individual + * things: + * + * - The shaft was the same thickness end to end. A real shaft has a swell + * at its base (the grip) — so the hand does not slip off. That is the one + * detail that makes the silhouette readable. + * - The head was stuck directly onto the shaft. A real tool has a conical + * socket; the shaft goes inside it. + * - There was no geometric variation anywhere, only the colour changed. A + * forged tool is not perfectly symmetric. + * + * This module supplies all three from one place, so adding a new tool to the + * kit is now just a matter of answering "what is the head". + */ + +export interface ShaftOptions { + readonly length: number + readonly radius: number + /** How many sides. 6 is enough: on a hand-held stick 8 adds nothing to the silhouette. */ + readonly segments?: number + readonly random: () => number +} + +export interface ToolShaft { + readonly geometry: BufferGeometry + /** Y position of the shaft's top end — the head sits here. */ + readonly top: number + /** The shaft's radius at the top end. */ + readonly topRadius: number +} + +/** + * Tool shaft: grip swell at the bottom, a long straight body in the middle, a + * slight taper towards the top. Produced as a single lathe — stacking prisms + * on top of each other would leave coplanar face pairs between them. + */ +export function toolShaft(options: ShaftOptions): ToolShaft { + const { length, radius, random } = options + const segments = options.segments ?? 6 + const bottom = -length / 2 + const top = length / 2 + const r = (scale: number): number => radius * scale * (1 + jitter(random, 0.02)) + + const profile: Level[] = [ + { y: bottom, radius: r(0.78) }, // bottom: rounded end + { y: bottom + length * 0.012, radius: r(1.18) }, // underside of the grip swell + { y: bottom + length * 0.075, radius: r(1.1) }, // top of the grip + { y: bottom + length * 0.14, radius: r(0.94) }, // waist between grip and body + { y: bottom + length * 0.55, radius: r(1) }, // body + { y: top, radius: r(0.9) }, // taper towards the head + ] + + const tint = new Color(PROP_PALETTE.wood) + tint.offsetHSL(jitter(random, 0.012), jitter(random, 0.05), 0.05 + jitter(random, 0.05)) + const tintTop = new Color(PROP_PALETTE.wood) + // The head end passes through the hand less often, so it stays a bit darker. + tintTop.offsetHSL(jitter(random, 0.01), jitter(random, 0.04), -0.02 + jitter(random, 0.04)) + + return { + geometry: latheGeometry(profile, segments, [0, 0, 0], tint, { colourTop: tintTop }), + top, + topRadius: profile.at(-1)!.radius, + } +} + +export interface SocketOptions { + /** Y position where the socket sits (the shaft's top end). */ + readonly y: number + /** The shaft's radius at that point. */ + readonly shaftRadius: number + /** Socket length. */ + readonly length: number + readonly segments?: number + readonly random: () => number +} + +/** + * Forged socket: a cone that wraps the shaft and widens upwards, with a collar + * on top. + * + * It is extended DOWN INTO the shaft — because its lower end stays inside the + * shaft's body, no surface ends up coplanar with the shaft's surface. + */ +export function toolSocket(options: SocketOptions): BufferGeometry { + const { y, shaftRadius, length, random } = options + const segments = options.segments ?? 6 + const tint = new Color(PROP_PALETTE.steelPainted) + tint.offsetHSL(0, jitter(random, 0.02), jitter(random, 0.05)) + const collar = new Color(PROP_PALETTE.steelPainted) + collar.offsetHSL(0, jitter(random, 0.02), 0.04 + jitter(random, 0.04)) + + const profile: Level[] = [ + { y: y - length * 0.9, radius: shaftRadius * 1.12 }, + { y: y - length * 0.45, radius: shaftRadius * 1.34 }, + { y: y + length * 0.1, radius: shaftRadius * 1.5 }, + { y: y + length * 0.22, radius: shaftRadius * 1.72 }, // collar + { y: y + length * 0.34, radius: shaftRadius * 1.46 }, + ] + return mergeColoured([latheGeometry(profile, segments, [0, 0, 0], tint, { colourTop: collar })]) +} + +/** Iron tone with a small deviation. So all three tools look like one hand made them. */ +export function ironTint(random: () => number, lift = 0): Color { + const tint = new Color(PROP_PALETTE.steelPainted) + tint.offsetHSL(0, jitter(random, 0.02), lift + jitter(random, 0.05)) + return tint +} + +/** + * Burnished steel tone — for the `steel` slot. + * + * The deviation is kept narrower than in `ironTint`: what determines the + * colour of a polished surface is not its own pigment but the environment it + * reflects. Shifting hue in the vertex colour looks dirty here, so there is + * only a tiny wobble in lightness. + */ +export function steelTint(random: () => number, lift = 0): Color { + const tint = new Color(PROP_PALETTE.stainless) + tint.offsetHSL(0, jitter(random, 0.008), lift + jitter(random, 0.025)) + return tint +} diff --git a/tsconfig.json b/tsconfig.json index 814f74a..113d9e7 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -12,7 +12,17 @@ "types": ["vite/client", "node", "@webgpu/types"], "baseUrl": ".", "paths": { - "@/*": ["./src/*"] + "@/*": ["./src/*"], + // The authoring trees under my-registry/ and contemporary-props/ write + // their imports as "@vibe3d/...", which `vibe3d add` rewrites to + // "@/lib/vibe3d/..." on the way in. Mapping the pre-install form too is + // what lets a model be built and looked at straight from the folder it + // is written in, without a registry rebuild and a reinstall first. + // + // It changes nothing about the installed copy, which still resolves + // through "@/*", and nothing about typecheck scope: "include" does not + // cover either authoring tree. + "@vibe3d/*": ["./src/lib/vibe3d/*"] } }, "include": ["src", "scripts", "vite.config.ts"]