diff --git a/README.md b/README.md index 06484392..79591915 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ Personal site hosted with GitHub Pages at **https://ascoding11.github.io**, the - `e63334287a3deaa3/chromaflage/`: Chromaflage (Back Room), paint-yourself hide and seek for up to 8 players (Three.js, Firebase Realtime Database rooms under `rooms/cf-…`, same project and rules as Rumble Karts; Quick match uses `rooms/cf-pub-1` to `cf-pub-4`; invite links go through the home page as `#cf-`). Hiders paint their own bodies in a paint studio (brush, an eyedropper that reads the true colour of whatever surface you click, fill, undo, glossiness) and pose to hide (crouch under tables, lie under beds, flatten, or stick to a wall with G or the Stick button and slide up, down and along it at any height, upright or sideways, until they jump to let go); seekers tag them with a blaster that fires a shot every 0.18 s (`FIRE_GAP`) for as long as the mouse button or the touch Tag button is held, with no reload pause: a miss costs one of 10 ink (`INK_MAX`), a hit costs nothing, and ink trickles back all the time at one shot every 2.5 s (`INK_REGEN`), so a seeker can keep firing at a hider who jumps about but blind spraying soon runs the tank dry and then gets a shot every 2.5 s. Fire rate and ink live only on the seeker's computer, which also decides hits (a ray against the hiders as it draws them) and sends a tag claim (`tg`) for the host to check, so changing them needs no change to the room data. Modes: Classic and Infection. Like Showdown, everything travels through each player's own node at `rooms/cf-/players/`, because the shared rules expect `n, c, x, z, h, ts` there and refuse other paths (such as `events`) for new prefixes: position and pose (`y, po, fl, p`, and `wl`: 0, or 1 to 4 for the way the wall a hider is stuck to faces, with `y` its height), body (`s` shape, `sz` size, `rf` glossiness), paint (`pv` version and `pd`, the 256 × 256 body texture as a WebP data URL, or JPEG where the browser can't make WebP; about 1 KB for a plain colour and 10–20 KB for a detailed pattern, re-sent at most every 1.2 s and only when it changed, so late joiners read it straight from the node), the last shot (`sh`), squeak (`ta`) and tag claim (`tg`). The host (newest host number `he`, else whoever has been in the room longest) publishes the round as JSON in its own `rs` and checks tag claims loosely; if it leaves, the next player carries on from the last round it saw. Anything read from another player's node is untrusted (any player can make itself host with a high `he`): `sanitizeRS` rebuilds a received round state field by field (known phases, numbers clamped, player ids checked and lists capped, settings through `cleanSet`), `remoteTarget` keeps positions inside the map and angles finite, and scores are shown as numbers, so keep new round-state fields going through `sanitizeRS` and escape anything put in `innerHTML`. A tab in the background gets no animation frames, so a 1 s timer keeps its node's `ts` fresh and, for the host, keeps the round ticking. Bodies are modelled about 1.7 units tall and drawn at `BODY` (0.64) times their size setting, so Normal is about 1.08 m. The Doll is a soft, rounded figure (a big round head on a short neck, a plump body, thick arms and legs with rounded ends, two small eyes), each part turned on a lathe (`latheGeo`, `dollParts`) with the texture spread evenly up the profile and normals taken from the profile so there are no shading seams; the Block is a slim slab. Each body shape has a 256 × 256 texture atlas where every texel knows its 3D spot on the body, so brushes paint by distance in 3D (`atlasOf`, `Paint`). Keep each part's region of the atlas (the `rect` passed to `latheGeo`) when reshaping a body, or saved and synced paint jobs land on the wrong parts; the Doll was reshaped inside the same regions, so paint saved before that lands on roughly the same places. Maps are axis-aligned boxes plus round props, built by `buildManor` (Hollyhock Manor: 48 × 38 m, a party night in a country house, with an 8 m grand hall whose staircase climbs to a gallery, ten rooms under 4.2 m ceilings), `buildMuseum` (Marlowe Museum: 58 × 50 m, a 7 m lobby, a top-lit grand gallery with free-standing walls, six galleries, a gift shop, a café and the storeroom) `buildRyokan` (Kirinoya Inn: 50 × 40 m, a Japanese inn round a glass-roofed garden courtyard, with four tatami guest rooms, a banquet hall, a tea room, a futon store, the hot-spring bath, the kitchen and a games lounge), and six everyday places: `buildSchool` (Birchwood High: 44 × 32 m, a locker-lined corridor, two classrooms, a science lab, a library, an art room, the staff room, toilets and the PE store), `buildOffice` (Larkspur & Co: 48 × 34 m, a reception, an open-plan floor of desk pods, a meeting room, the manager's office, a kitchenette, a server room, a store, a lounge and toilets), `buildMarket` (Greenleaf Market: 50 × 36 m, a 4.2 m supermarket floor of aisles, produce tables, chillers, freezer islands, a bakery, a deli and six checkouts, a café, the bakery kitchen, a stockroom with pallet racking and a forklift, the staff room, an office, toilets and a cold room), `buildHotel` (Hotel Bellamy: 48 × 36 m, a marble lobby with columns, a piano and a reception desk, a bar with a pool table, a restaurant, and off a carpeted corridor five guest rooms, each with a bathroom whose bath you can climb into, plus housekeeping and the laundry), `buildLeisure` (Riverside Leisure Centre: 50 × 38 m, a 7 m sports hall with bleachers, hoops and a climbing wall, a gym, a dance studio, the reception and café, two changing rooms with lockers and showers, first aid, the equipment store, an office and the plant room) and `buildFlats` (Maple Court: 46 × 31 m, four flats off a landing, each with a living room and kitchen, a bedroom, a children's room with bunk beds, a study, a hall and a bathroom, plus the residents' laundry and the bike and bin store; the north flats are the south ones mirrored by `flat()`). The everyday maps share painters, `everydayMats` and the `everyday` furniture (desks, office and school chairs, lockers, gondola shelving, counters, divans and bunk beds, bathroom pieces, gym kit, bleachers, trolleys, pallets). Walls, floors and ceilings come from `kit`: `wallX`/`wallZ` build a wall as two half-thick slabs, one per room, each reaching 1 cm past the centre line so the two overlap and leave no seam to slip into, each from a side spec (`w` wallpaper, `lo` and `lh` lower panelling, `h` height, `base`, `rail`, `crown`, `casing`), with door openings and their casings; `win`, `pic`, `flat` and `sconce` hang windows (an evening view), framed pictures, signs and wall lights, and `ag` places furniture with its back to a wall. Wall slabs are marked `wall`, and trims, pictures and curtains are not solid, so a hider can still stick to the wall behind them. The `Builder` helpers are `box`, `at` for turned furniture, `prop` for round things from the shared `geo()` cache (baked with the boxes into one mesh per material, so a map is about one draw call per material), `ceil` for ceilings drawn from below only so the menu's view from above looks into the rooms, `spot` for places bots hide under tables, beds and the inn's futon cupboard, and `lamp` for point lights, of which only six spread-out ones are used, three on the Fast setting; the furniture helpers are in `furn` (tables, round tables with cloths, chairs, benches, sofas, beds, a grand piano, a fireplace, plants and palms, lamps and chandeliers, washing lines, curtains you can walk into, vending machines, plinths and mannequins, which make good decoys). The bots only walk the floor: the manor's gallery and the inn's raised entrance step are for players. Each map gives `spawns`, a `seek` start and an `attract` spot for the menu's doll. Boxes marked `soft` (cloth and leaves) block the view and the seeker bot's line of sight but not the blaster's pellets. The boxes are also the colliders, the bots' navigation grid, line of sight and the surfaces the eyedropper and bots sample; they are filed in a 2 m grid (`buildGrid`, `solidsIn`, `rayMap`) so rays and collisions stay quick. Every pattern is drawn on a canvas by the `P` painters (damask and striped wallpapers, wood panelling, marble, tatami, shoji and fusuma, rugs, portraits, landscapes and modern paintings, and so on), from a fixed seed so all players get the same map. Every room must keep a ceiling. To add a map, write a `build…` function and add it to `MAPS`, then check it the way the existing ones were checked: every spawn, the seeker start and every bot `spot` free and reachable from the seeker start, a ceiling and a floor everywhere, no ray escaping the shell, and no solid furniture cut into a wall. Bodies collide as their pose's footprint circles against the boxes (`moveEnt`): each move is cut into steps shorter than the body's radius and anything it runs into pushes it back out the face it came in through (`pushOut`), so nothing can be crossed in one frame; a box whose top is within a step of the feet (`stepOf`: 0.45 m standing, half the body's height crouching or lying) is climbed only when there is room to stand on it, otherwise it is solid (a chair seat over its legs, a bed frame under its quilt); a box whose bottom is within 1 cm of the top of the head doesn't block, so a body that just fits under a table fits; low furniture is solid down to the floor unless the gap under it is at least as tall as the smallest lying body (`minGap`, the Petite Block, about 0.15 m: `Builder.finish` adds an invisible collider under anything lower); a body that finds itself inside something (after growing, say) moves to the nearest free spot that isn't across a wall (`freeSpot`, `wallBetween`), and a move never ends on the far side of a wall. The practice seeker bot "sees" by rendering a small view of you with and without you and comparing the colours (`perceive`, delta E), so better paint really does keep you hidden; it sweeps its gaze up and down so it can spot hiders high on walls, and furniture blocks its view. Practice hider bots sometimes hang on walls or tuck under furniture. Online rooms follow a daily map rotation: `dayMaps` shuffles all the maps with the day number as the seed (days start at midnight US Eastern standard time, `DAY_SHIFT`) and keeps the first three, and the map is `dayMaps(now)[floor(now / 15 min) % 3]` (`rotMap`), worked out from the shared server clock (`Net.now`). The host publishes it as `rs.map` in the lobby and when it starts a round, so a round in progress finishes on its map and the next round or the lobby moves on; the lobby shows the map now and "Next map in m:ss" with the next map's name (`rotText`), and the menu names today's three. The host of a private room can still pick a single map instead of "Daily rotation" (the `map` round setting, -1 for the rotation); Practice has a picker of every map; Quick match and invite links are unchanged. Nothing is stored online between rounds; your name, body, last paint job and settings are saved in the browser under `chroma-…`. Parties can launch it (its row in `GAMES` in `party.js`). On touch screens the page adds `touch` to `body`, and the `body.touch` rules at the end of the stylesheet place the HUD, the lobby card and the paint studio for phones held upright or sideways (keep them clear of the stick and buttons when adding HUD pieces). The lobby card and the paint studio scroll an inner box (`.lb-body`, `.st-body`) instead of the card itself, because Chrome can leave a blank patch in the 3D view under a scrolling box with a solid background. Effects (`splat`, `pellet`, `confetti`, `puff`, all under `fxRoot`) are drawn only on each player's own computer and are hidden from the practice bot's eyes (`perceive` hides `fxRoot`), so they can be restyled without changing what can be hidden against: a pellet is a short streak with a pale tail and a small flash at the blaster, the mark it leaves is one of five splat shapes made once by `splatGeo` (a wobbly blob with lobes and stray drops, in the same pink and about the same size as a plain round mark) that pops open and throws off a few drops, and a find adds a gold ring and a sparkle to the confetti. The Fast setting gets fewer drops and less confetti (`fxHigh`). On the HUD the crosshair kicks on each shot, the FOUND banner, the "Found …" text and the Still hidden number pop when they change (`hudPop`), the clock turns pink and beats in the last ten seconds of hide or seek time, and the results card rises into place; all of these are skipped when the device asks for reduced motion. Lighting, shadows, map colours and patterns, the paint palette and how paint is sampled were deliberately left alone, because in this game any change to how a surface is lit changes how well a paint job matches it. **Turkey Week** (`../events.js`, November 15 to 26, 2026): seekers wear a pilgrim hat as part of their gear; hiders never do, because a hat would give them away: one shared hat geometry and material from `events.js` (`tkHat`), one extra draw call each. The game reads the one Turkey Week switch on the Back Room page (see `events.js` below) once, when it loads (off means no hats are made); it has no button of its own. **Seeker kit** (hidden: captains only for now; `KIT_PUBLIC = false` and `kitOn()` in `index.html`, and `?seekerkit=1` turns it on for testing, on localhost or in an automated browser only): seven hats (a detective deerstalker, a safari hat, a painter's beret, a museum guard cap, a hard hat, an exterminator cap and goggles), four tools that take the blaster's place in the hand (a magnifying glass, a paint scraper, a spray bottle and a feather duster), plus, from 19 Nov, twelve more hats (8 to 19: team cap, football helmet, sweatband, referee cap, pirate hat with an eye patch, fedora, top hat, robot antenna, champion headband, hockey helmet, bowler hat, mascot ears) and eight more tools (5 to 12: foam finger, pirate hook, walking cane, whistle, tennis racket, hockey stick, spyglass, robot claw), each still one merged mesh, a paint splash when the wearer catches someone (a ring of see-through droplets that flies outward and is gone within 0.6 s, and a small SPLAT! above the caught hider's head) and a caught animation for the hider they catch (it hops and pops along its own up direction, spinning only when it was upright), all drawn by `kit.js`, which the page fetches only when this player may open the Seeker kit (a button under the body choices on the menu opens a screen with a model of you as a seeker) or someone in the room wears a kit; for everyone else it never loads and every hook (`if(CK)`) does nothing. Seekers only: hats and tools are added inside the seeker gear (`Avatar.gear` and `Avatar.gun`), which the page shows only while a body is a seeker, and the two effects start only once the host has marked a hider found, are drawn under `fxRoot` for at most 1.2 s and leave no marks, so nothing changes how a hider looks or how easy a hider is to see while hiding. Shooting is still the camera's ray, so a tool changes neither reach nor tagging (the pellet still starts at the hand), hats stay low and above the visor, and your own hat and tool are hidden while the camera is pulled in close to them. A kit is four item numbers, the `no` of Chromaflage's items in `cosmetics.js` ([hat, tool, splash, caught], 0 for none; `kit.js` keeps its lists in the same order, so never reorder them), saved as `chroma-kit` and sent in the player's own node as `kt` (`'3.1.1.0'`, only when something is worn; older pages ignore it, and `kit.js` checks every number and draws the plain gear for one it does not know). Each hat and tool is one mesh (its pieces merged with vertex colours, one geometry per item, one shared material); a dressed seeker's blaster becomes one merged mesh too and a hat replaces the Turkey Week hat, so a dressed seeker is never more draw calls than a plain one. It has Spanish: its words are in `chromaflage/es.js` (lang.js; map names and the signs inside the maps stay in English), with a Language switch in Settings and the pause menu. - `e63334287a3deaa3/backrooms-1v1/`: Backrooms 1v1–4v4 (Back Room; the folder keeps its original `backrooms-1v1` name), a third-person build-fight shooter in Level 0 of the Backrooms (Three.js). Practice is you against the Entity, a bot that runs only in your browser. Online rooms hold up to 8 players split into Red and Blue (1v1 to 4v4, uneven teams like 4v3 are allowed and never filled with bots) in the Firebase Realtime Database under `rooms/br-…` (same project and rules as Rumble Karts; invite links go through the home page as `#br-`). Quick match waits in `rooms/br-queue/players` and pairs two people into a `br-q…` room for a 1v1. Each player writes only their own node `players/`: `n`, `c`, `x`, `z`, `h` and `ts` always (the shared rules expect that shape), plus height, pitch, health, shield, weapon, a dead flag, the match `m` and round `rd` the position belongs to, the team picked in the lobby `t`, kills this match `k`, join time `j`, `mv`, the newest map version the page can build (3), and `ev`, set to 1 by a page that can edit builds; about 20 times a second during a round (15 in rooms of 5 or more) while something changed, and twice a second otherwise or while nothing has. The host is the live player who has been in the room longest (the next in line takes over when they leave; a newcomer only starts judging who the host is once the room's players and round have loaded, so a slow phone joining mid-match can't take over and reset it) and is the only one who changes `round`: `{id, ends, seed, ns, ph, pt, to, rn, sr, sb, ro, dd, rw, mw, fm, rz, mv, ed}`, where `id` is the match, `ph` the phase (`lobby`, `cd` countdown, `fight`, `over`, `end`), `pt` when the phase ends, `to` the rounds to win (3, 5 or 10, host's choice), `rn` the round, `sr`/`sb` the team scores, `ro` the roster (`uid:r;uid:b`), `dd` who is out this round, `rw`/`mw` the round and match winners, `fm` a forfeit, `rz` the host's "Randomize teams" draw (each player then moves themself), `mv` the map version for this match (see below) and `ed` whether builds can be edited in it (see Editing builds). The host writes with transactions guarded on `id`, `ph` and `rn`, and keeps `ends` at the time of writing because the rules cap how far ahead it can be. Shots, builds and deaths go through `events/` (deleted after 5 s): the shooter's rays pass through teammates and the shot lists only the enemies it hit; the victim applies damage only from someone on the other team of the same match, and reports its own death naming the last shooter, which gives the kill credit. A round ends when one team has nobody left: dead, or silent for 10 s (a closed tab removes its node at once). A team with nobody left in the room (disconnected, or silent for 20 s) forfeits the match. A host whose own tab has just frozen waits a moment for the queued updates before judging anyone. Players who join mid-match wait in the lobby or watch until the next one, and dead players watch a living teammate (click, or tap Next on a touch screen, for the next one). **Find tags:** once a round's fight has run for 1 minute 30 seconds (`FIND_AT`), every 15 seconds (`FIND_EVERY`) a name tag shows over every living player for 2 seconds (`FIND_SHOW`), through walls, with how far away they are, so players who can't find each other can; it pops in white, holds in the team colour and blinks out (a plain fade with reduced motion), with a soft ping. A tag for someone off the screen is pinned to the nearest edge with an arrow showing which way to turn. Nothing is sent for this: the clock (`findClock`) is the round's own, online the server-clock time since the fight began (the round node's `pt`, which is when the countdown ended and is left alone for the whole fight phase), so every browser flashes at the same moments, and in practice the seconds fought this round (the tag is the Entity's). Between flashes nothing changes: teammates' tags show all the time, as before, and an enemy's only while in sight. From ten seconds before the first flash a small chip (`#find`, under the score; on a phone, under the health bars sideways and in the top right corner upright) counts down to the next one, and the first flash of a match adds one line to the feed. The tags are the same HTML labels as the ordinary name tags (a fixed size on screen, so readable far away and not huge up close), so they add no draw calls. An older copy of the page in the room just never shows them. **Maps:** every round is a new, randomly generated Level 0, in practice and online, on a grid of 4 m cells with walls on the cell edges and posts on the corners (`layoutV3`, map version 3). Every map is built the same way, so they all feel like the same place: a 3 × 3 room round each spawn, then rooms of 2 × 2 to 2 × 4 cells dropped at random until about two fifths of the floor is rooms, and everything else one-cell-wide (4 m) corridor. Every wall is full height: no low partitions, stray wall slabs, open halls or pillar fields (the most a room gets is one column in the middle, about one room in three). The rooms and corridor cells are joined into a tree and then given a few loops (a second or third way into some rooms, the odd extra link between corridors, most dead ends opened onto something), with three rules: never two openings side by side in one room wall, never four corridor cells open as a square (corridors stay one cell wide), and never a short piece of wall left standing on its own. Where a room opens onto something else the opening is a doorway, with a 0.8 m jamb of wall (`JAMB`) each side wherever the wall carries on past it. Any straight line of more than six cells (`V3_RUN`, 24 m) gets a wall across it near the middle, and the corridor jogs round it. The lighting is the same everywhere: about one ceiling panel in twelve is dead (the floor under it a little darker), up to three flicker on their own, and most maps have one or two banks (a room or a stretch of corridor) that flicker together and dim the walls, floor and ceiling around them; there are no tinted wallpapers, damp carpets or special rooms. Then each spawn is cleared to an open, lit 3 × 3 area, anything that can't be reached on foot is opened up, and the layout is checked for fairness (`fairV2`: both teams' spawns about as far from the middle on foot, the two halves within about a third of each other's cover, no huge detour between the teams); one that fails is redrawn (about one in four), and if sixteen in a row fail (in practice never), the closest is made point-symmetric, which is fair by construction but can leave a few open patches along the middle. Checked on 600 generated maps of every size and roster: no low partitions or free-standing wall pieces, no 3 × 3 block of cells without a wall inside it outside the spawn areas, no straight run longer than six cells, every cell reachable, the same seed always gives the same map; the longest sightline on a map is 23–53 m (v2: 42–69 m). A v3 map has more walls, so its collision boxes are joined up along each wall line (`solidsV3`: walls and jambs that touch end to end become one box, and posts in the middle of a straight run are left out), which leaves fewer boxes than a v2 map (about 210 against 310) and less work per frame for movement and shots. Size depends on the number of players and a little chance: 11–13 cells across for a 1v1 (and practice), 12–14 for 3–4 players, 14–15 for 5–6, 15–16 for 7–8. Red spawns along the west edge and Blue along the east. Online, the layout of round `rn` comes from the match's `seed` and `rn` (`roundSeed`), and its size from that and the roster size, so every player builds the same rooms without anything new being sent; a short blackout covers the change between rounds. **Older copies of the page** (still open in someone's tab after an update) only know earlier layouts, which are kept unchanged in the page and checked to build exactly the same walls, pillars and lights for the same seed: the original maze (`layoutV1`: one per match from `seed`, 12, 14 or 16 cells by room size (`ns`), Red's and Blue's spawn areas cleared), and the previous random layout (`layoutV2`, map version 2: the floor split into areas furnished in different ways (twisty corridors, small rooms, open halls with stray wall slabs, pillar fields, office cubicles behind 1.25 m grey partitions you can see and jump over, solid blocks of wall), joined by doorways or with no wall at all, each lit its own way, sometimes with a different wallpaper or a special room). Each player's node says which maps their page can build (`mv`), and the host writes into a new match the newest version every player in the room has: `mv: 3`, `mv: 2`, or no `mv`, in which case everyone, new pages included, plays the original maze for that match, so a mixed room always agrees on the walls (an older page that joins in the middle of a newer match only watches, and may see the wrong walls until the next match). A host on a v2 page writes `mv: 2` at most, and one on a v1 page never writes `mv`, so the same applies. The collision rules below hold for every layout: automated walks and jumps into walls, doorway jambs, partitions, big pillars and wall blocks, spawns for every roster shape and shots at every kind of solid, run on hundreds of generated layouts, found nothing passing through or stuck inside a wall; and scripted runs and jumps at built walls, floors and ramps from every side, at 60, 30 and 20 frames a second and thrown at up to 20 m/s, with random building and with the Entity's own code, found nothing inside or through a build. Builds can't be placed inside a solid block of wall. **Editing builds:** aim at a wall, floor or ramp your team built (in practice, one you built; never the other team's or the Entity's) from within 6 m (`EDIT_RANGE`) and press Edit (G, or the Edit touch button): the piece turns into a grid of tiles, 3 × 3 on a wall and 2 × 2 on a floor or a ramp (a ramp's are its low and high halves, left and right). **Edit on release** (a setting, on by default, in the menu under Look sensitivity and on the pause screen, saved as `br1v1-editOnRelease`; a `br1v1-editRelease` saved by the first version is still read; the Edit key itself is rebindable in Change keys like any other): hold Edit and the tile under the crosshair is picked at once, every tile the crosshair then sweeps across is picked too (no need to hold Shoot / place, though it does the same), and letting go of Edit confirms (`editHold`, `editKeyUp`, `paintTile`). The first tile of a sweep decides whether it opens or closes tiles. A quick tap of Edit (under 0.25 s, `EDIT_TAP`) that did no more than pick that first tile leaves the grid open with that tile still picked (so two taps make a one-tile window), the setting-off way: Shoot / place opens or closes the tile under the crosshair (hold and sweep for several) and Edit again confirms. A longer hold that changes nothing cancels. Either way Reload resets the piece to whole (the touch button reads Reset) and Aim cancels; on a touch screen the buttons read Tile, Done, Reset and Cancel while editing, and a finger put down on the grid picks the tiles it touches instead of turning the view (`editFingerDown`, `screenRay`), so you hold Edit with one thumb, drag the other over the tiles and let go. While you edit, the line of help names the shape so far (Door, Window, Arch, Half wall, Narrow ramp…, `edName`) and what to press next; until your first confirmed edit it spells the whole thing out (`br1v1-editHelp`). The tile under the crosshair is worked out on the grid's own plane, and a point up to a third of a tile off the edge counts as the edge tile (`edTileAt`, `EDIT_EDGE`), so the bottom row of a wall you stand against is easy to pick; when the line of sight finds none of your builds, eight lines just around it are tried (`EDIT_FAN`), so an edge or a seam up close still opens. Your own body is hidden while the grid is up, so it doesn't cover the tiles. That gives a window, a door, a half wall, an arch, a floor with a corner cut, a half-width ramp and so on. At least one tile has to stay. Nothing changes until you confirm, and then the new shape is there at once (it used to land 0.4 s later, `EDIT_T`, now gone); you can't shoot while the grid is up, and a Shoot / place still held from picking tiles doesn't fire until it's let go (`editLatch`). The build message is the same as before. A piece's shape is `ed`, one bit per tile cut out (tile (u,v) is bit `v*n+u`; 0 is the whole piece). The tiles left are joined into as few rectangles as it takes (`edRects`), and each rectangle is one ordinary solid box, or for a ramp one ordinary ramp sheet with a smaller footprint (`pieceShape`), so there is no second collision system: movement, `pushOut` / `rampOut` and shots run the same code as for a whole piece, you walk through a door and shoot through a window because no box is there, and what is left blocks from every side (tiles that come back on a body move it out, as a new build does). The picture is one mesh made of the same rectangles (`pieceGeo`), so an edited piece is still one draw call; the grid you see while editing is three, in place of the piece, and only on your screen. Checked with the game's own movement and shots against the tiles themselves: every one of the 511 wall shapes both ways round (shots straight and slanted through every tile from both sides, walks at it along its length, thrown and jumping bodies), all 15 floor shapes and all 15 ramp shapes in all four directions, at 60, 30 and 20 frames a second, and whole pieces compared number for number with the page before editing. Online an edit travels as the build message for that spot again with `ed` added, the host answers anyone who comes into a round late (`bq`) with every piece standing, its health, shape and team (`bs`), and only the team that built a piece may reshape it (a message from anyone else is ignored). A page from before editing ignores a build for a spot that is taken, so it would keep the whole piece; to keep a mixed room agreeing on the shapes, every page says in its player node whether it can edit (`ev`), and the host turns editing on for a match (`ed: 1` in the round node, written like `mv`) only if every page in the room can: otherwise the Edit key says a player needs to refresh. The Entity does not edit; when a build stops it, it shoots the part it walked into (`bump`), whatever the shape, and it sees and shoots through openings only. Keys and mouse buttons can be changed in the Controls panel (`keybinds.js`, saved as `keybinds:backrooms-1v1`; the Change keys button under Controls in the menu, and Controls on the pause screen): move, jump, shoot / place, aim (Shift and right click), the three guns, reload, the three build pieces (two keys each), Edit (G), the arrow keys that look around when the mouse can't be locked, and pause (P; Esc is fixed). Clicking to watch the next teammate stays on the left mouse button, and the mouse wheel still switches guns. On touch screens it has a move stick, drag-to-look, Fire/Place, Jump, Aim, Reload, Edit and pause buttons, with the weapon and build slots as buttons along the top; while you watch, those give way to a Next button, and the lobby, pause and results screens are plain buttons that fit a phone either way up. Each browser is trusted for its own health and hits, so it isn't cheat-proof. A test hook (`window.__br`) exists only when `navigator.webdriver` is set (its `findShift` moves the find-tag clock forward so a test need not wait a minute and a half). **How it's drawn** (the picture only: nothing here is sent to other players or changes collision, damage or movement): the scene is lit by a soft overall light plus a warm light from one side and a weak cool one from the other, so walls facing different ways, and the two sides of a character, come out in different shades. The carpet is darker than the walls, and its texture repeats once per cell with a pool of light baked into the middle, so the floor is brightest under each ceiling panel and darkest along the walls. Walls, posts, pillars and doorway jambs have a dark skirting board, which is part of the same geometry (`joinGeos`, `skirtW`), so each kind is still one instanced mesh and the collision boxes are unchanged; working ceiling panels have a soft glow round them (one more instanced mesh). A character's suit is a few meshes, each made of several boxes joined together (`parts`), and each of the three guns is one shared mesh coloured per corner (`GUN_GEO`; `GUN_TIP` is how far each muzzle is from the hands), so the detail costs no extra draw calls; every character has a round shadow on the ground under it, which shrinks during a jump and lies along a ramp. The detail stays inside the outline the plain characters had, so nobody is drawn bigger than before: the suit's body, legs and head are the same boxes, each gun is squeezed along its barrel to the length of the plain one it replaced (`gunFit`: rifle 0.78 m, shotgun 0.86 m, sniper 1.18 m), and the shadow is 1 m across, about the width of the figure (a wider one made characters read as larger). Keep to that if you add more detail. A shot shows a muzzle flash at the end of the shooter's barrel and kicks the gun back; tracers are thin glowing beams sized to stay about two pixels wide near and far, and are drawn from the end of the barrel, though the shot itself still starts at `muzzleOf` as before; where a shot lands there is a flash and three sparks. The tracers, flashes and sparks come from small pools made once (`pool`; the sparks are one instanced mesh), so shooting creates no new objects. With the browser's reduced-motion setting on, the muzzle flash, gun kick and sparks are left out. **Turkey Week** (`../events.js`, November 15 to 26, 2026): every suit wears a pilgrim hat: one shared hat geometry and material from `events.js` (`tkHat`), one extra draw call each. The game reads the one Turkey Week switch on the Back Room page (see `events.js` below) once, when it loads (off means no hats are made); it has no button of its own. **Locker** (hidden: captains only for now): `locker.js` holds 36 outfits (18 sports kits, 4 robots, 4 pirates with eye patches, 6 costume-party suits, astronaut, wizard, firefighter and knight), 19 gun skins (7 of them animated: Gold, Chrome, Neon Pulse, Frostbite, Lava, Galaxy, Rainbow Flow and Circuit Board shine, pulse, flow or twinkle on one shared clock), 6 build skins, 8 elimination effects and 8 round-win celebrations, all drawn in code; the same items, by number, are Backrooms' block in `../cosmetics.js` (`backrooms-1v1`, prefix `br`). `BR_PUBLIC = false` near the top of the page is the one switch that opens it to everyone; until then `lockerOn()` asks `../captains.js` (`BackRoomCaptains.may(false, 'locker', 'br1v1-locker')`, so `?locker=1` works on localhost or in an automated browser), and a Locker button and screen appear in the menu only for those players. `locker.js` is fetched only for them, or when someone in the room wears something; for everyone else it is never loaded, `LK` stays null and the page draws, sends and saves exactly what it did before. While the shop is off everything is free to wear and what is worn is saved as `br1v1-kit`. Online it travels in the player's own node as one optional field, `lk` (a letter per slot and the item's number, e.g. `o12g3c2`: o outfit, g gun skin, b build skin, e elimination, c celebration), checked strictly; an unknown number draws the default for that slot, and a page from before the Locker ignores the field and draws the plain suit. Looks only and fair in ranked play: every outfit is built on the plain suit's own boxes (legs, body, head, sleeves, gloves) with a pack the size of the air tank on its back, so none is drawn smaller; the main colour is the team colour online (an outfit's own colours only in practice). The test hook's `__lk.fair()` draws each outfit flat from four sides against the plain suit in both team colours: outline 100–120% (hats add height), brightness never lower, colour distance from the walls and carpet never more than 0.02 lower, no more of it close to the wall or carpet colours, at least 40% of it in team colours (the rest is bold white, black, gold, silver and bright accents, never wall yellow, carpet brown or the other team's colour). Locker items use their own shared material (`lockerMat`), which adds a little of each item's own colour as light, because the dim yellow room light turns bright colours muddy; the plain suit and plain guns keep the game's own materials. Gun skins recolour the same three guns (`GUN_SRC`, cut into stripes or patches, through the same `gunFit`, so length and shape are unchanged; the sniper's lens stays). Build skins only change the picture on a piece (opaque, the same frame and brace; each measured at least as far from the walls, carpet and team colours as plywood), and a piece takes its builder's skin (a late joiner's `bs` copy of the round draws plywood). Elimination effects play where the player falls (centred on the body), for everyone, when the player who got them wears one, and are over in 1.5 s (the falling body takes 2.2 s). Celebrations play only while the round is over and the wearer's team won it, and stop as soon as they move or shoot; they move only the picture. An outfit is fewer draw calls than the plain suit (6–7 against 12) with geometry cached per outfit and team colour; skins and effects add none except two instanced meshes while an effect plays. During Turkey Week an outfit with its own hat hides the pilgrim hat. **Spanish** (lang.js): its words are in `backrooms-1v1/es.js`, text it puts together (banners, lobby, help line, results) goes through `TX()`, HUD parts that change during play are `data-noi18n`, and only team and room keys go over the network, never words. - `e63334287a3deaa3/drop-zone/`: Driftfall (Back Room; the folder is `drop-zone`), a third-person battle royale for up to 30 players on Gullrock Isle (Three.js; Firebase Realtime Database rooms under `rooms/dz-…`, same project and rules as Rumble Karts; invite links go through the home page as `#dz-`; Quick match uses the public rooms `dz-pub-1` to `dz-pub-4`, the fullest one still boarding first; online matches are people only, at least 2). Everyone rides the Drifter (a big blue cargo plane, see The Drifter below) across the island, jumps when they like on a line that changes every match, jumps when they like (Space, or Jump on a phone; anyone still aboard drops automatically as it leaves the island), falls, opens a steerable glider (Space again, or automatically about 44 m up) and lands anywhere, on roofs and hillsides too. Then it's loot, build and fight until one is left. **Island:** 240 × 240 m, with real terrain since map version 5 (hills, a ridge, cliffs, a reservoir and a shore: see Land) (it was 320 m until map version 2: the seven places were moved closer together as whole blocks on the 4 m grid, the buildings themselves are unchanged), about 40 s' run across and 57 s corner to corner at 6 m/s, built by `buildWorld()` from a few tools; each place is built inside `grp(dx, dz, dy, …)` with its shift from the old layout and the height of its pad in `OFS`, so the place code still reads in the old coordinates: `house()` (walls with doors and windows, a floor per 4 m level and a flat roof, both sitting between the walls rather than under them, zigzag ramp stairs from `zigzag()` that need a free cell at each end, a parapet, and a trim band round the outside between levels; how each is drawn is in Buildings below), `wallRun`, `slab`, `staticRamp`, props (`crate`, `bale`, `car`, `fence`, `pine`, `oak`, `rock`, `bush`). Seven places: Haybale Farm (barn with a loft and roof stairs, farmhouse, silo), Signal Point (a 20 m lattice tower with zigzag ramps), Pinecone Plaza (a two-level mall round an atrium, shops along the north side, car park), Spillway Dam (a 12 m dam wall with stair towers at both ends, a pump house), Moonbeam Motel (two wings of rooms, a balcony reached by a ramp, an empty pool), Starfall Crater (a ring of boulders round a fallen star, two sheds) and Timber Camp (log cabins and a sawmill shed), plus sheds along the tracks. Every floor and roof is at a multiple of 4 m on the same 4 m grid as builds (each place's pad is too). All static geometry is merged into 16 chunk meshes with vertex colours (one material; on the plain look no textures except the builds', the ground's and the buildings' own (see Buildings), which are mipmapped and anisotropic, and no shadow maps), the ground is one mesh over the height grid, chests, floor loot, each build kind, tracers and particles are one instanced mesh each, so a view with 30 players in the match measured 16–55 draw calls; each player is one mesh (the merged body, plus the glider when it's out), and everyone's legs are one instanced mesh and the held items one instanced mesh per kind (`legIM`, `gunIM`, filled by `syncLimbs()` just before each render from the models' leg and item `Object3D`s, which only carry the pose), so 30 players close together cost about 36 draw calls instead of about 120 (legs and items are hidden past 70 m). Solid boxes sit in a spatial hash of 8 m cells (`hash`, `rhash` for ramps), which movement, `groundAt` and the ray walk (`raycast`, cell by cell) use instead of the whole list. **Look:** characters are built from `ROUND_BOX` (a box with rounded edges and smooth shading, added with `bagRBox`), still one merged body per player with instanced legs; hitboxes were unchanged by that (they shrank with the characters later, see Character size). The Graphics setting (`driftfall:gfx`, Pretty or Fast) and `fxWatch()` pick one of three levels, applied by `lookSync()` from `drawScene()`: 0 is the plain look above (always on touch screens and on Fast); 1 adds a surface grain to the one shared material (`MAT.onBeforeCompile` lays a drawn noise texture over every face from three sides using each mesh's own coordinates, compiled in only while `MAT.defines.FINE` is set), real shadows from the sun (one 2048 px map covering 92 m around the camera, moved in whole-texel steps by `followSun()`; everything using `MAT` and the builds cast and receive, flagged by `shadowFlags()`), a sky dome with a soft sun (hidden inside the storm, where the flat purple sky takes over) and a sea that catches the light; 2 adds a light colour grade (`grade`: the finished frame is copied to a texture and redrawn with a little more colour and contrast and darker corners; there is no bloom, because in daylight most pale surfaces are already at full brightness). Because it is a shooter the frame rate comes first: it starts at level 1, steps up to 2 only after about 6 s of frames under 12.5 ms, and steps down after 2 s over 18 ms once `autores.js` has lowered the resolution to 0.8 or less; a level it had to leave is not tried again that visit (`fxMax`). Level 1 roughly doubles the draw calls near buildings (the shadow pass draws the chunks around you again). Nothing about the look is sent to other players. **Flicker fixes (map version 2):** no two faces share a plane any more (floors and roofs used to share the walls' outer faces, partitions reached into the floor above, posts shared faces with slabs and railings, and the trim band was a solid slab over each upper floor that also hid the mall's atrium and the stair holes); the camera's near plane follows the view (0.08 m pulled in against a wall, 0.15 m on foot, 0.5 m in the air, 1 m on the Drifter) and the far plane is 800 m, so distant faces a few centimetres apart don't fight; the farm's stripes were 4 m wide to match the ground's 2 m vertex grid (they are 1 m furrows now that the ground is a picture, see Ground). Keep new boxes off each other's faces (stop a box 1–2 cm short, or let it pass through the other) rather than flush with them. **Movement, building and shooting** started as a copy of Backrooms 1v1–4v4 (the same jump, step and `moveEntity`/`pushOut`; the speed, the collision box and the ramp rules have since changed, see Collision, Character size and Pace), the same wall/floor/ramp binds (Q/Z, F/X, C/E) and pieces on the 4 m grid (up to 8 levels above the land under them; see Land for how they meet a slope), the same over-the-shoulder aim from the camera with rays from the muzzle, headshots and damage numbers. Builds cost 10 scrap (you start with 30); the Crowbar (V or 5, or an empty slot) gathers scrap from trees (14 a hit), rocks and walls (6–10), and loot has scrap bundles. **Destruction:** builds and most of the map break. Each weapon has its own structure damage `sd` per bullet (Pistol 24, Heavy Pistol 55, SMG 12, Drum SMG 15, Pump Shotgun 13 and Auto Shotgun 9 a pellet with their close-range falloff, AR 22, Heavy AR 40, Bolt Sniper 150, Scout Sniper 80; the Crowbar 50), scaled by rarity and distance like player damage. Builds have 150 (walls) or 140 health and darken in three stages. On the map, `buildWorld()` makes breakable *pieces* with `brk(health, scrap, fn)` (everything `fn` adds is one piece): each 4 m cell of a house wall per level (with its trim band and, on top, its parapet; 240), each 4 × 4 m cell of a floor or roof (200), partitions (150 a cell), trees (170), rocks (80 + 60 per metre of size), cars (260), the farm truck, crates, bales, fence sections, railings (in up to 4 m lengths), the motel's balcony, posts and sign, the sawmill's posts and roof and the log pile. The ground, the dam's wall, ribs and stair towers, the tower's posts and floors, the silo, the star, stairs and ground-level decorations never break, so the map stays playable. A piece is a range of vertices in the chunk meshes plus its boxes; breaking it squashes the vertices to a point (one small buffer update a frame, `mpFlush`, no extra draw calls) and takes its boxes out of the hash, so players, shots, builds and bots go through; the pieces left standing round a broken wall, floor or railing keep a ragged edge (see Buildings). Damage darkens a piece in three stages the same way. Boxes of pieces in a line (a wall's cells, a floor's row) are merged into one solid per unbroken stretch (`runs()`), so movement and rays check about as many boxes as before. `mpLink()` records which pieces touch and which touch the ground or something unbreakable; when a piece breaks, anything that has lost every path to the ground breaks too (a roof whose walls are gone), and chests and loot on it drop (`mpBreak`). The breaker gets twice the piece's crowbar scrap. Pieces are numbered in build order (1,185 of them), the same in every browser; a new match restores them (`resetMap`). **Loot** is decided by the match seed, so nobody has to send it: about 82% of the 40 chest spots have a chest each match (`spawnLoot`), and each floor spot has a 72% chance of an item (`FLOOR_R` odds); a chest gives a weapon (`CHEST_R` odds, better than the floor's) with its ammo, often a heal and sometimes scrap (`chestLoot`). Weapons (`WEAP`): ten, two in each of five families (`fam`: pistols, SMGs, shotguns, rifles, snipers), each with its own model, colour, sound, damage, fire rate, spread, range and falloff, magazine and reload, and ammo type (light, rifle, shells, heavy); see Weapons below; rarity (Common to Legendary, grey/green/blue/purple/gold) adds 7% damage a step and trims the reload. Heals (`HEALS`): Bandage +25 health (2.5 s), Medkit to full (6 s), Shield Fizz +25 shield (2 s), Shield Jug +50 shield (4.5 s); shield caps at 100 and you walk slowly while using one. Four slots (1–4, the mouse wheel, or tapping the slots); ammo, scrap, heals and weapons are picked up by walking over them when there's room, and G (or the touch Open/Take/Swap button) opens chests and swaps the item in your hand for one on the floor (with nothing in reach it edits the build you are aiming at, see Building and editing). Knocked-out players drop everything. **Storm** (`STORM`, `makeStorm`): the circle (180 m radius, `R0`) covers the island at first, then closes in six phases toward seeded centres, each pulled toward the middle if it would fall at sea (first close 70 s after the Drifter sets off; the last closes to nothing about 4¾ minutes in), and damage outside (health only) grows from 1 to 15 a second. The Drifter's line starts and ends 230 m either side of a point within 37 m of the middle, so it's always over the sea at both ends. The minimap (tap it, or M, for the big map with place names) shows the circle, the next one (dashed), the Drifter's line with a little plane on it, and you. **Rooms and matches:** each player writes only their own node `rooms/dz-/players/`: `n, c, x, z, h, ts` always (as the shared rules expect), plus `y`, `p` (pitch), `hp`, `sh`, `st` (state: `l` lobby, `b` on the Drifter, `f` falling, `g` gliding, `a` on the ground, `d` knocked out, `o` watching), `w` (what's in hand), `m` (the match), `j` (join time), `k` (knockouts), `pl` (placing), `dm` (damage), `oc` (chests they opened this match, dot-separated) and `pk` (loot they took, comma-separated, so a late joiner or a new host sees the right island), and `ev/e0`…`ev/e23`, a ring of their recent events (each with a number `i` that only goes up, the match `m` and a time `t`): `s` shots (muzzle, tracer ends, the new health of builds hit `pd` `[key, hp]` and of map pieces hit `md` `[id, hp]`, hits on players `hs`), `b` builds and edits of them (see Building and editing), `o` chest opened, `u` item taken, `dr` item dropped, `x` knocked out (by whom, placing, the dropped items). Writes are `update()`s of only the fields that changed: about 12 a second while you're moving in a match (10 with 10+ others in the room, 8 with 20+), a heartbeat every second or two otherwise. Every node also carries `mv`, the map version (2 since the island shrank, 3 for the slower pace, 4 for the November 2026 fixes: solid ramps, and later the smaller characters, the pace and the new weapons, 5 for real terrain, 6 for edited builds; a node without it is version 1). The host is the live player on the same map version who has been in the room longest; its node also carries `ms`, the match state (`{id, ph: 'lobby'|'play'|'end', ce: countdown end, sd: seed, t0: when the Drifter sets off, ro: roster, nh: people at the start, wn: winner, we: when the results end, mv: map version}`), and during a match `br: {m: match, b: …}`, the broken map pieces as a base64 bitset with trailing zeros dropped (about 200 characters with everything broken). Players apply the shooter's reported health for builds and pieces, the lowest anyone reports, but never more than one shot of that weapon could take; a late joiner, anyone who missed an event, and the next host take the rest from `br`. The host's node also lists the builds standing (`bd`, see Building and editing), so a late joiner gets them too; there's no list of broken builds, because a broken one is just not in it. **Map versions:** the host only counts people on its own version for the lobby, the countdown and the roster, and only those elect a host; a page that sees someone on a newer version says "This match uses a newer map, reload to join." with a Reload button and sits matches out; the host's lobby says how many people have an older copy. Pages from before map versions existed don't know any of this: they're simply left out of the new pages' matches. Next time the island changes, raise `MAPV`. A match starts when the host presses Start (with 2 or more people) or 60 s after a second person joins the lobby; a lone player can't start one; the Drifter line, the storm and the loot all come from `sd`, and the clock from `t0` (server time), so everyone agrees without sending them. **Bots** are in Practice only (11 of them; online matches are people only, so no bot slots, no bot list in the host's node and no bot hand-over). They're marked BOT in tags, the feed and the results, and this browser runs them: they jump, glide to a chest, loot, fight, heal, run from the storm and now and then wall up when shot; they walk straight at things where the way is clear, round cliffs, boulders and buildings by `landPath` (see Land) and in and out of buildings by the nearest ground-floor door (`setGoal`), stepping to one side when something holds them up, shoot through breakable cover (builds, walls, trees) at someone within 35 m, break through a breakable thing they're stuck against (up to ten tries) or a line of builds they can't get round (see Building and editing), and leave loot they get stuck on alone for 25 s; they don't use stairs, so upstairs loot is for people. They're tuned to be beatable: a reaction of 1–1.6 s, loose aim (0.085–0.135 rad error, more until they've watched you a while), a little over half their weapon's fire rate and rare building; a rifle bot 20 m from someone standing still does about a quarter of the damage it used to. **Hits:** the shooter's browser decides what its shots hit (`resolveShot`) and lists hits in the shot event; the victim's browser applies them only after a sanity check (`acceptHit`: a real weapon, no more than one shot of it can do, from within 16 m of where the shooter really is, within the weapon's range, and not faster than it fires), and reports its own knockout, which credits the shooter; hits on bots go to the host. If the host leaves, the next in line carries on the same match from the last `ms` it saw, with the broken pieces it already has. Someone who joins mid-match waits in the lobby panel or watches (Watch the match), and drops in at the next one; a room holds 30 (`MAX_ROOM`). Other players and bots are drawn with `netsmooth.js`. Results: placing, knockouts, damage and time, with the room's final order when the match ends. Leaderboards hooks (online matches only, which always start with at least two people): `add('matches', 1)`, `add('wins', 1)`, `max('kills', n)` (most knockouts in a match) and `min('place', n)` (best placing; `place` is in stats.js's `LOWER`). Saved in the browser under `driftfall:` keys: `name`, `col` (your colour), `sens`, `room`; keys in `keybinds:drop-zone`. Touch: a move stick, drag-to-look, Fire (Place, Use or Hit as it fits), Jump, Aim, Reload, an Open/Take/Swap button that appears when something's in reach, an Edit button that appears when the crosshair is on a build of yours, and the Crowbar, four slots and the scrap chip as buttons along the top (tap the chip to build: the three pieces appear next to it; tap it again, or a slot, to stop); the map is top right. Practice (offline) is the same match against 11 bots with no database at all, on its own clock that stops while paused. A slow frame is played in steps of at most 1/20 s (up to a quarter of a second), since the Drifter and the storm run on the clock. **Keeping it smooth (November 2026 audit):** every shader is compiled while the page loads (`warmShaders`, with the hidden meshes shown for a moment; the storm wall's used to compile, and freeze a frame, the first time it closed in), and the minimap's island picture is drawn during the menu rather than on a match's first frame (it takes about 30 ms). Sounds have a budget (`voice`: 14 nodes per 1/20 s, then only loud ones, and your own hit, hurt and pick-up sounds always), so a big fight or a building coming down doesn't build hundreds of audio nodes in one frame. The HUD only writes a value to the page when it changes (`hudSet`), name tags reuse their vectors and only move when they move a pixel, banners restart their slide-in without forcing a layout, and the storm (`stormAt`), hitboxes, the camera and movement no longer make new objects every frame. The lobby list is only drawn while the lobby is showing (every update from anyone used to redraw it, four times a second, mid-match), player names go through the name filter once (`cleanName` keeps them), and an update with no new events doesn't sort the event ring, so taking in another player's update costs about a fifth of what it did with 30 in a room. Writes are unchanged (`update()`s of the changed fields, about 50 bytes each, 10–12 a second while moving), so it plays with pages from before the audit. Each browser is trusted for its own health and hits, so it isn't cheat-proof. A test hook (`window.__dz`) exists only when `navigator.webdriver` is set. **Turkey Week** (`../events.js`, November 15 to 26, 2026): every player's cap is a pilgrim hat, built into the same body geometry (`bodyGeo`), so no extra draw calls; the game reads the one Turkey Week switch on the Back Room page (see `events.js` below) once, when it loads, and has no button of its own. **Collision (November 2026 fix):** ramps used to be a walking surface only, so a body could walk into one from the side or from under its high end and jump up through it from below, which is how people came up through stairs, ramp builds and the floors the stairs lead to. A ramp is now also a solid slab 0.36 m thick under its surface (`rampIn`, `rampBlocked`, `rampUnder` next to `moveEntity`): its side and its underside stop a body, its underside is a ceiling for a jump, and like a box it carries a body whose footprint overlaps it at all. So the map's zigzag stairs have to be walked round to the foot of each flight (the free cell at each end is for that), and two ramps built in one cell facing opposite ways no longer make a staircase. A body on the ground follows a ramp up as it moves rather than afterwards. Something built on a body (`pushOut`) moves it out the side its middle is already on, by no more than 1.2 m, never across the piece and never into a ramp; while a body is inside something it can only move back out, and can't rise. A piece built by this browser (you, a Practice bot) isn't placed if someone here would be left inside it (a floor through the head of someone on a ramp used to pop them up through it); a ramp built on someone stands them on it. Pieces arriving from other players are always placed. Loot heights come from `groundAt`, which now counts a ramp's edge, one more reason old and new pages mustn't share a match (see map versions). **Character size (November 2026):** characters were a fifth too big for the world, so everything about them is 0.8 of what it was (`BS`): the model is 1.72 m tall with its cap instead of 2.15 m and about 0.8 m across the shoulders instead of 1.0 m (the group is scaled, so the legs, the held item and the glider shrink with it); the collision box is 0.6 m wide and 1.6 m tall (`R` 0.3, `H` 1.6; was 0.72 and 1.95); the hit areas are a head box 0.45 m wide from 1.2 to 1.67 m up and a body box 0.67 m wide up to 1.2 m (were 0.56 m, 1.5 to 2.08 m, and 0.84 m up to 1.5 m), so everyone is a smaller target by about a third in area; the eye and bot-aim heights (`EYE` 1.3, `AIM_Y` 0.9), the muzzle (`MUZ_Y` 1.1) and the name tag (2 m up) follow. The camera sits 4 m behind instead of 3.5 m and 0.7 m to the side instead of 0.78 m, so a character takes about a third of the screen's height instead of nearly half. Jump height (1.7 m), step height (0.6 m), doors, walls and builds are unchanged, so doors and windows are roomier and a jump clears relatively more than it did. **Pace:** everything that sets how fast a match feels is in one block near the top (`SPEED`, `AIR`, `BUS_V`, then `WEAP`'s `dmg` and `STORM`'s times). In November 2026 it was all slowed by a sixth to a fifth (running 6.6 to 5.4 m/s, weapon damage about a sixth lower, the storm's times 1.2 times longer so the last circle closes 5:41 in rather than 4:44); running then felt sluggish, so the movement speeds came most of the way back while damage and the storm's times stayed: running 5.4 to 6.0 m/s (bots still 0.92 of it; aiming 0.7 and healing 0.45 of it as before), steering while falling 13.5 to 15 m/s and falling 25 to 28 m/s, gliding 9.2 to 10.3 m/s forward and 5.5 to 6.1 m/s down, the Drifter 20 to 22.5 m/s (it crosses the island in about 20 s instead of 23 s). **Weapons (November 2026: ten instead of five):** each family has a quick, light one and a slow, hard-hitting one, so two finds of the same family play differently. Damage a shot (headshot), seconds between shots, magazine, reload: Pistol 20 (35), 0.2, 12, 1.3 s and Heavy Pistol `hc` 42 (74), 0.55, 6, 1.7 s (silver, a fat cylinder, wood grip); SMG 12 (18), 0.075, 28, 2 s and Drum SMG `ds` 15 (23), 0.11, 40, 2.6 s (yellow, a drum under it; slower but tighter, longer range, a bigger magazine); Pump Shotgun 9 pellets of 8, 0.9, 5, 2.1 s and Auto Shotgun `as` 7 pellets of 6, 0.4, 8, 2.6 s (dark red; wider spread, 32 m instead of 40 m); AR 18 (27), 0.12, 30, 1.9 s and Heavy AR `hr` 34 (54), 0.28, 18, 2.2 s (dark teal; the most accurate when aimed, 180 m); Bolt Sniper 82 (164), 1.3, 4, 2.5 s and Scout Sniper `ss` 44 (88), 0.5, 8, 2.8 s (pale slate, a small green scope, less zoom). The old five keep their ids (`pi`, `sm`, `sg`, `ar`, `sr`) and numbers; the Shotgun and Sniper are now called Pump Shotgun and Bolt Sniper. **Names (November 2026, clearer guns):** every name is " " with the type one of Pistol, SMG, Shotgun, AR or Sniper, so it always says what kind of gun it is (the Rifle and Heavy Rifle became AR and Heavy AR; ids, saved data and network messages are unchanged); `name` is shown everywhere (hotbar, pickup prompt, pickup line, kill feed, ammo panel) and `short`, the type alone, only in a hotbar slot too narrow for the whole name (`fitSlotName`, so on a phone a slot reads PISTOL, SMG, SHOTGUN, AR or SNIPER and the ammo panel above the slots gives the whole name of the gun in hand). The two of a family share a colour, light and dark (pistols cream and silver, SMGs orange and yellow, shotguns red and dark red, ARs teal and dark teal, snipers slate and pale slate). Chests and floor loot roll all ten (`W_ODDS`: 12, 10, 11, 9, 11, 9, 15, 11, 7, 5 in the order above), so the loot a seed gives is different from before; the new ids travel in `w` (what's in hand), in shot events and in dropped and taken items, and a page from before them would reject them, which is why the map version went to 4: old pages are kept out of new matches and told to reload. To add a weapon: a row in `WEAP` (with `fam` and `col`), its id in `WIDS` and `W_ODDS`, a model in `GUN_GEO` (with the end of its barrel, which goes into `GUN_TIP`), a rarity-band position in `RTAG`, a sound in `sfxShot`, and optionally `TR_W`, `FLASH`, `KICK`, `PUNCH`, `RECOIL` and `RELOAD_ST`; then raise `MAPV`. Bots pick and use weapons by family. `ICONS` holds a small picture of every weapon, the crowbar, the two heal models and the three build pieces, drawn once at load from the same geometry the game uses (`makeIcons`). **Aiming (November 2026):** holding Aim is different for every weapon, set by four fields in its `WEAP` row: `fov` (the zoom; the normal view is 72), `ad` and `as` (how far behind and to the side the camera sits; the normal view is 4 m and 0.7 m) and `pose` (where the gun is held while aiming, seen over the shoulder: since the models were remade it is only a small lift from the normal hold, because the arms stay in the pose the body is drawn in while a weapon is held). Pistol fov 58, Heavy Pistol 50, SMG 62, Drum SMG 56, Pump Shotgun 60, Auto Shotgun 66: these six stay over the shoulder at 3 to 3.4 m; the two ARs go to the eye (`ad` 0, your own character hidden), AR fov 46 and Heavy AR 34. **Reticles (November 2026, clearer guns):** one style per family, the same from the hip and aimed (aiming only pulls it in, because the spread is smaller and the view zoomed), drawn by `RET` into `#cross` (an inline SVG, one CSS pixel per unit, put on a whole pixel in the middle of the view, 2 px white lines over a 1 px dark edge on each side so they stay sharp and read on bright sky and in dark rooms): Pistol a dot in a thin ring; SMG a small ring with four short ticks outside it; Shotgun a wide ring broken into four arcs; AR the classic four lines and a dot (the dot turns red when aimed, like a red-dot sight); Sniper from the hip a ring with cross hairs through it; the crowbar, heals and building a dot. Rings and gaps are the real spread of the shot in pixels at the current zoom (`RET.size`: `hip` or `ads`, more while moving, from `curSpread`, the same numbers the shot uses), plus a short kick of a few pixels after each of your own shots (`retKick`, `RET_KICK`) that eases back in about a tenth of a second. The snipers aim through a real scope (`#scope`: a round lens in a black surround with a rim and a darker edge to the glass, `SCOPE` sets its size and colours; Bolt Sniper fov 16, Scout Sniper fov 30 with a wider, green-rimmed lens), both with the same plain reticle (`SNIPER_RET`): thin cross hairs 1.5 px wide at any size with an open middle and a red centre point, two small marks on each arm and thick posts from the edge, with a faint pale edge so they show in a dark room. (Before, every weapon had its own sight picture in `SIGHT` and `#sight`; both are gone.) Look sensitivity already scales with the zoom. Nothing about aiming is sent to other players, so they don't see your gun raised. **Weapon models and feel (November 2026 remake):** all ten were rebuilt to the standard of Shell Crackers' guns; only looks, motion and sound changed, so damage, fire rates, magazines, spread, ranges and everything sent to other players are as they were and the map version is still 4. Each is still one merged mesh with its colours in the corners (one draw call for everyone holding that weapon and one for all of them on the ground, as before), now 300 to 770 triangles instead of 110 to 240 (Pistol 304, Heavy Pistol 508, SMG 504, Drum SMG 536, Pump Shotgun 612, Auto Shotgun 552, AR 556, Heavy AR 536, Bolt Sniper 772, Scout Sniper 676). In the clearer-guns pass (November 2026) each was pushed towards its stereotype so the family shows at a glance: the Pistol lost its under-barrel lamp (a plain slide on a frame); the Pump Shotgun's barrel is thicker; the Auto Shotgun lost its carry handle (it read as a rifle) and got shorter and chunkier: a fat barrel with a big square brake, a low rail, a fat box magazine and a solid stock; the AR has the classic black carry handle with the rear sight on it, a tall front sight post, a round ringed handguard and a black stock; the Heavy AR has a top rail with a small boxy red-dot sight, a long square handguard with a front grip, a big curved magazine and a shorter, thicker barrel with a brake (no bipod or wood any more, which made it look like a sniper); the Bolt Sniper's bipod legs now hang down and forward instead of lying folded. The Heavy Pistol stays a revolver (its reload works the cylinder) and the SMG, Drum SMG and Scout Sniper keep their shapes. `GUN_GEO` builds them from a few kinds of part: `bx` a box (optionally tilted), `ob` a bar with its long edges cut off and shaded smooth (so a body reads as rounded plastic), `cyl`, `pin` and `peg` a cylinder along the barrel, across it or upright, and `ex` a side outline pushed out sideways with bevelled edges (the stocks); `grip` and `guard` add the grip and the trigger guard every weapon shares. In a weapon's own coordinates -z is forward and the right hand (a 0.146 cube) is centred on (0, 0, 0.12): the grip goes down through the hand, the body sits on top of it, and a stock runs back over the forearm and stops at the chest (z 0.4), so with any outfit the weapon is in the hand and nothing passes through the arm or the body (before, the hand was inside the body of the gun and the stock ran through the forearm). `HOLD` is where a weapon is held: a little outside and above the middle of the hand and turned 4° outward, so its top shows over your shoulder from behind; it also tips up and down with the aim (yours, bots' and other players', from the pitch already sent). From directly behind your own character you still only see the back half of it past your shoulder (the colour, the scope, the drum, the carry handle of the AR), because the arms hold every weapon in the pose the body is drawn in; the whole outline shows on other players, on the ground, in the hotbar and when you aim over the shoulder. `GUN_TIP[id]` is the end of the barrel: the flash, the tracer and the spent case are drawn from the weapon as it is held (`gunTip`, `gunPoint`), while the shot itself still starts at `muzzleOf` and what is sent is unchanged; looking down the rifles' sights the flash and the tracer start just under the sight, and a scope shows no flash. `animModel` adds the motion, all of it turning about the hand: `KICK[id]` (how far a shot shoves the weapon back, how far the muzzle jumps and how fast it settles; the crowbar has its own swing, `SWING`, see Body and animation), the pump of the Pump Shotgun and the bolt of the Bolt Sniper worked between shots (0.2 to 1.1 s after the shot, two sounds and the case hopping out, `gunAct`; other players' too, from their shot events), a reload motion for each kind (`RELOAD_ST`: magazine out, magazine in, rack; the Pump Shotgun a shell at a time; the Heavy Pistol's cylinder; the Bolt Sniper's bolt) with a sound at each stage, and a swing up from below when an item is taken out (`userData.sw`). Reloads show for you and for bots only, since a reload is not sent. `FLASH[id]` is the size of the muzzle flash and the length of its tongue (shotguns wide and short, rifles and snipers long, SMGs a flicker; the big ones add a dimmer glow), `TR_TL` how long each family's tracer is, `shell` the spent case (a bit from the shared pool, only within 30 m; shotgun shells are red, the Heavy Pistol keeps its cases), and `PUNCH[id]` widens your view by up to 1.7° for a moment with each of your own shots (zoom only, so the aim point does not move; `updateCamera` eases it back). With reduced motion there is no kick, action, swing, case or view punch. Sounds are still made on the spot: `sfxShot` has ten shots that differ in pitch, length and tail (`burst` can now start late and sweep its filter), and `sfxPump`, `sfxBolt`, `sfxReload` (out, in, rack, shell, open, shut), `sfxSwitch` and `sfxDry` (the click of an empty weapon with nothing left to load) are new. Floor loot is the same model, turning about its own middle (`GUN_MID`) and nearly level so the outline reads, over a glow in the rarity colour with a clearer ring; past 75 m a weapon is only its glow. The rarity band on a held weapon is a cut-edged sleeve to match the bodies (`RTAG`, drawn by `rarIM` as before). **Hotbar (November 2026):** every slot shows a picture of what is in it, taken from `ICONS` (so it is the item's real model: the ten weapons, the crowbar, a first-aid box for Bandage and Medkit, a bottle for the two shields, and the three build pieces), with the rounds loaded or the count in the top right corner, the name underneath (a weapon's whole name, or just its type where the slot is too narrow) and the rarity as a bar along the bottom (`slotIcon`, `slotLabel`). Scrap has its own chip in the hotbar (`#matsBox`: a stack of planks and the count in big figures, which jumps when it changes and turns red below the cost of a piece) instead of a small line in the health panel, and each build piece shows its cost (10) next to the same little plank, greyed and red when you can't afford it. The three build pieces are only in the hotbar while you are building (`#slots.building`): the new Build key (B, `build` in the key settings, `toggleBuild`) or a tap on the scrap chip goes in with the piece you last used and comes back out, and Q/Z, F/X and C/E still go straight to a piece as before; a slot key, the crowbar or Aim leaves build mode and the pieces go away again. **Land (November 2026, map version 5):** the island is no longer flat. `designLand()` fills a grid of heights (`TH`, one every 2 m, reaching 16 m past the 240 m square for the sea bed) and `terrainH(x, z)` reads it with the very triangles the ground is drawn with, so what you see is what you stand on. Everything asks that one function: the drawn ground (`landGeo`), walking, falling, gliding and landing (`walkH`, `groundAt`, `moveEntity`), shots, sight lines and the camera (`rayTerrain` inside `raycast`), where loot, chests, props, trees and bots stand, builds, the storm's centres, the bots' paths and both maps. The grid is made from whole-number hashes, + − × ÷ and square roots only and rounded to 1/32 m, so every browser has the same land to the last bit and loot lies at the same height for everyone. Sea level is 0. Shape (`designH`): rolling noise for the low ground; smooth mounds measured from points pushed about by noise, the highest winning where they meet (Signal Point's hill at 16 m, a ridge from it east to the top of the dam at 20 m, the plateau that holds the reservoir, the farm's tableland at 8 m, a knoll on the west shore, a hillock south of the plaza, the timber shelf at 8 m); creased, ridged noise on the high ground; the crater is a real bowl whose rim is lower at four gaps; a wandering coast with round corners and beaches, and cliffs where the high north and east meet the sea. Each place stands on a level pad (`PADS`, `LVL`: farm 8 m, Signal Point 16, plaza 4, dam yard 8, motel 4, crater floor 4, timber camp 8; the five sheds on the multiple of 4 m nearest the land under them, `SHED_Y`) that blends back into the land over 6 to 12 m, and `grp()` raises everything the place adds by its level (`OFY`), so buildings, doors, stairs and ramps are exactly as they were. Single props (`onLand`: trees, rocks, bales, crates, fence sections, the crater's boulders) stand on the land under them, sunk a little. What moved: the farm's field is smaller and lies on the slope below the yard; the dam's paved yard is shorter (the valley closes in at both ends of the wall); the reservoir is real water 9 m above the yard and narrower than its old painted rectangle; one shed moved 12 m south; trees stand in clumps; two crater boulders that sat across a shed's doors are gone; a chest against a wall keeps its loot inside the room. **Slopes:** the steepest ground a body can walk up is 45° (`SLOPE_MAX`: 1 m up per metre along). Steeper land is a cliff: it stops a body like a wall, and a body that lands on one slides down it at 7.5 m/s (`SLIDE_V`) and can't jump until it is off (`e.slide`). Gentler ground is followed up as you move and stuck to on the way down, so nobody hops downhill. Where the sea is deeper than 1 m a body stays 1 m under the surface (`WADE`), and wading waist-deep is slower (0.72 of running). The camera is pushed in by the land as by a wall and is never under it. **Surface** (`landMaterial`; it replaces the 2048 px picture of the whole island, which was a blur up close): the shader decides what each pixel of ground is from its height, its slope and a small control map drawn once at load (`paintControl`: 1024 px, 512 on Fast and on phones; red is dirt, green is paving, blue is how much darker): grass with broad paler and darker patches, sand below about 1.4 m that is wet at the waterline with a line of foam, bare rock on faces steeper than about 40°, dirt for the tracks, yards, clearings and the ploughed field, paving with its joints drawn on the 4 m grid. Fine detail comes from one tiling texture made in code (`landDetail`: 512 px, 256 on Fast; blades, grain and pebbles, rock strata and concrete in its four channels), read once every 5 m and, for broad variation, at a 47 m scale, so it is sharp at your feet and the tiling never shows from the air; where two materials meet the grain decides which wins, so a track's edge is a crisp ragged line of pebbles and tufts rather than a fade. Every corner of the ground carries a baked shade: darker in hollows and where a hill or cliff stands between it and the sun. Pretty reads the 47 m scale from the texture, adds a finer layer of detail, strata mapped from both sides on cliffs and wind in the grass (six reads a pixel, as many as the old Pretty ground, one of them filtered at a slant); Fast reads two textures a pixel (the old ground read one) and takes its broad variation from a value stored at each corner of the ground. Water (`waterGeo`): the sea and the reservoir are sheets whose colour and clearness are set at each corner from the depth under them (clear turquoise shallows, solid blue further out). Scatter (`scatterLand`): grass tufts where the ground is grass (4,400 on Pretty, 1,600 on Fast, 1,200 on phones; they shrink away between 40 and 65 m) and small stones (420, or 150), two instanced meshes, neither solid. **Cost,** at the same five views before and after: draw calls are up by one to four (Pretty 18–32 before, 20–35 after; Fast 8–22 before, 9–24 after: the ground is still one mesh, the sea and the reservoir replace the sea and its shallow ring, tufts and stones add two); triangles went from 55–84 thousand to 84–114 thousand on Pretty and from 51–80 thousand to 64–94 thousand on Fast (the ground's own 37 thousand are unchanged; the rest is tufts, stones and a few more trees); the ground's textures went from about 21 MB of graphics memory to 7 MB on a computer and from 5.3 MB to 1.8 MB on Fast and phones. Frame times could only be measured in software drawing, where they were too noisy to rank (between the same and half as long again in both looks), so try it on a real school laptop before trusting it. Nothing new runs every frame except height lookups (one grid read and a few multiplies each) and the wind's clock; a 150 m ray over the land costs about 8 millionths of a second (6 before). **Builds on slopes:** the grid stays level, at multiples of 4 m, so builds still line up with buildings and each other. A wall must show at least 1.5 m above the highest land along it, and where its foot is above the land a skirt of darker planks fills the gap down to the ground (`skirtOf`, `skirtIM`: part of the same solid, one more draw call while any exist); a floor may not be more than 0.3 m under the land at the highest point of its cell; a ramp's top must stand 0.5 m clear of the land, its foot may run into the hillside and you walk onto it where it comes out; nothing may be more than 8 levels above the land under it (`landOk`). `playerBuildSpec()` and the bots take the lowest level that passes (`landFit`), so a piece is never placed underground; on a place's pad the levels are what they always were. The rule that a piece isn't built where it would trap someone is unchanged and counts the skirt. Every browser has the same land, so everyone agrees which pieces are allowed and nothing new is sent. **Bots on the land:** `buildNav()` cuts the island into 4 m cells and closes the ones that are cliff, inside a building, or filled by a boulder, the dam's wall or the foot of a stair; when the straight line to a goal crosses a closed cell (`landClear`), `landPath()` finds a way round (A*, run only when a bot picks a goal) and hands back a few corners to walk through. Deep water costs three times as much as land and high ground a little less than low; of two places to wander to, a bot usually takes the higher. Held up by a trunk or a corner, a bot steps to one side, then the other, before giving up. In stepped bots-only matches (tests only: `__dz.step`, `STUCK_LOG`) no bot gave up on a goal. **Maps:** `buildMapBg` draws the minimap and the big map from the land itself: sea by depth, sand, grass that pales with height, rock on steep faces, tracks and paving from the control map, lit from the north-west so slopes read, and a darker line every 4 m of height. To change the land: edit `designH` or `PADS` (keep every pad a multiple of 4 m), check that no cliff cuts a place off, then raise `MAPV`. **Buildings (November 2026, still map version 5):** every building, the props round them and the light they stand in were remade, without changing what is solid. `house()` makes exactly the boxes it always did, in the same order, so the 1,185 breakable pieces keep their numbers, sizes and neighbours, and stairs, doors, loot spots and the bots' paths are where they were (checked with a fingerprint of every box, piece, ramp, loot spot and nav cell before and after; a page from before the change and a new one play in the same room and break the same pieces). What changed is what is drawn. Each building has a style (`KS`: barn, farmhouse, hut, mall, pump, motel, office, mine, cabin, shed; pass `st` to `house()`): an outer and an inner wall surface, trim, a plinth, corners (boards, log ends, steel angles or concrete pilasters), window and door frames with sills, the door (a sliding barn pair, a leaf folded back against the wall, a steel leaf with a hazard band, or none), shutters, flower boxes, a canopy or porch roof over doors, the roof edge (eaves on rafter ends, a stepped cornice, or a fascia with a neon tube), a capped parapet, the roof, floors, a floor laid on the ground indoors, ceilings and skirting. `kitWall()` adds all of that to a wall cell inside the cell's own `brk()`, so it breaks with the cell and nothing is left hanging; a building can add its own extras per wall cell (`x`), roof cell (`rx`) and floor cell (`fx`): the barn's hatch, hoist, beams and vents, the mall's name, skylights, coolers and strip lights, the hut's cooler and dish, the pump house's risers, the office's and motel's signs, the cabins' chimney breasts. The drawing tools: `kb()` (a detail box: drawn only, never solid, only the faces asked for), `wk()` (the same in a wall's own terms: along it, up, out from its face), `deco()` (any other shape, turned any way), `sign()` (raised block letters from a small dot font, `FONT`, drawn cell by cell so each letter breaks with its piece of wall), `lampPost()` and `bays()`; `FK` makes `sbox()` draw its box with a different surface on each face, and `NOVIS` makes it count toward its piece's size without being drawn (the kit draws it instead). Detail drawn while `DECO` is set, and everything from `kb()`, doesn't count toward a piece's size, because that size decides which pieces touch and hold each other up. To add detail: draw it with these inside the piece's `brk()` and never call `solid()`; keep anything that isn't solid thin, low (under about 0.4 m), flat against a wall or above head height, so nobody can hide inside something shots pass through. Anything that changes a solid box, a doorway, a stair or the number or order of pieces needs `MAPV` raised. **Surfaces** (`KIT_TEX`, `TX`): one array texture with eighteen layers, each a 2 m tile drawn in code at load (upright boards, clapboard, brick, stucco, corrugated sheet, cast concrete, shingles, logs, floor tiles, roofing felt, glass, riveted panels, straw, stone blocks, hazard stripes, and since the audit natural rock with cracks and lichen for `rock()`, bark for trunks and leaf clumps for canopies and bushes, `TX.RK`, `TX.BK`, `TX.LV`), laid on in metres from each face's own position, so a plank or a brick is the same size on every wall (128 pixels a metre; 64 on phones). A layer is a pale pattern tinted by the wall's paint (its vertex colour), except where its alpha is 0, where it keeps its own colour (mortar, nail heads, stripes). The island's chunks carry one more attribute, `dzA`: the layer, the height above the foot of the thing (the shader darkens and dirties the bottom metre or so of every wall, post and trunk) and how far indoors a face is (indoor faces are dimmer, more so on Fast, which has no shadows to do it). Each building has its own slight colour cast (`TINT`). It needs WebGL 2; without it the island keeps plain paint. One texture read a pixel on both looks, and no new passes. **Stairs, railings, props:** the map's stairs are drawn as sixteen steps over a soffit (what is walked on is still the smooth ramp); railings are panels with a cap rail and a post; cars and the farm's tractor are rounded toy vehicles with wheels, lights and bumpers inside the same solid boxes; crates are banded planks and bales are straw; the motel has loungers, a tiled pool with lane lines and a ladder and its name in raised letters with neon round it; the plaza's planters have a timber seat round the rim and its cars stand in painted bays under lamp posts (drawn only: a pole is 12 cm thick); the silo is ribbed and hooped with a ladder; the tower has white bands, cross braces above the first floor and a mast with drums, panels and a beacon; the dam is cast concrete with sluice gates, its name and lamps along the walkway; the sawmill stands on stone pads under a tin roof on rafters, with plank stacks and stumps; shards stand out of the fallen star. **Broken edges:** a wall, floor, roof or railing piece that breaks no longer leaves a clean hole: the pieces still standing round it keep a few jagged stubs of it where it joined them, and a wall that stood on the ground leaves rubble along its foot (`shardsFor`, one instanced mesh, `shardIM`, up to 1,200 stubs, a draw call only while something is broken). Stubs are drawn only; a stub goes when the piece it hangs on goes (`shardsOff`); which stubs exist depends only on what is broken, so everyone sees the same and a late joiner gets them from the broken list. **Light:** the sun is where it was (a roof, the two sunlit sides and the two shaded sides of a building are different tones); the fill light's ground colour is pale stone instead of grass green and a little stronger (0.58, ambient 0.11), so walls in shade keep their own colour instead of going olive. Shadows (Pretty) are unchanged and sit under the new eaves, canopies, sills and the balcony; the darker foot round every building on the ground was already there. **Cost,** at five views, before and after: draw calls are unchanged (16–25 on Pretty, 16–24 on Fast, not counting the shadow pass, which draws the chunks near you again); triangles went from 96–111 thousand to 121–150 thousand on Pretty and from 79–94 thousand to 99–125 thousand on Fast (Fast, as set when the page loads, and phones leave out the kit's smallest pieces, `KLITE`); the chunks' vertices went from 109 thousand to 224 thousand (about 4 MB to 11 MB of graphics memory with the new attribute); the surfaces add one texture of 5.2 MB (1.3 MB on phones). Frame times could not be measured here (software drawing), so try it on a real school laptop and a phone. Not done: a simpler version of far buildings (the island is 240 m across and already 16 meshes), filmic tone mapping and sRGB output (they would change every colour in the game, guns and characters included), ambient occlusion and bloom passes, glass in windows (windows stay open holes because shots pass through them), pitched roofs (roofs are walked on), benches and big roof clutter such as tanks (they would need new solid boxes, which needs a new map version). **Building and editing (November 2026, map version 6):** building was a copy of Backrooms 1v1–4v4's from the start (the same placing from your own cell and the way you face, the same 0.09 s build clock, so holding Place while you move or turn puts up about ten pieces a second, the same ghost and sounds), and it now has Backrooms' editing too, on Driftfall's own pieces, so there is still one build system. Also carried over: a new piece pops in from 0.82 of its size in about a ninth of a second (`piecesTick`; not with reduced motion); the ghost shows what you will get, a wall's skirt included (it used to show only the 4 m box, which floats above a slope); every piece knows who built it (`owner`: a player's id, a Practice bot's, `me` in Practice). Kept from Driftfall: 10 scrap a piece (an edit is free), the land rules and skirts, the rule that a piece isn't built where it would trap someone, the 4 m grid, health and the three shades, build mode and the hotbar. **Editing:** aim at a wall, floor or ramp you built from within 6 m (`EDIT_RANGE`) and press Edit (H, `edit` in the key settings, because G is Open / Take here and T is the chat; G does it too when nothing is in reach to open or take; on a touch screen an Edit button appears while the crosshair is on a build of yours): the piece turns into a grid of tiles, 3 × 3 on a wall and 2 × 2 on a floor or a ramp (a ramp's are its low and high halves, left and right). It works as in Backrooms (one copy of the code, see there): **Edit on release** is a setting, on by default, in the menu next to the faces switch and on the pause screen (`driftfall:editOnRelease`): hold Edit (or G when it is doing the editing), the tiles the crosshair sweeps across are picked, and letting go confirms; a quick tap leaves the grid open, and then (or with the setting off) Fire opens or closes the tile under the crosshair and Edit again confirms. Reload resets the piece to whole and Aim cancels; the touch buttons read Tile, Done, Reset and Cancel meanwhile, and a finger put down on the grid picks the tiles it touches, so on a phone you hold Edit, drag the other thumb over the tiles and let go. The line of help names the shape and spells everything out until your first confirmed edit (`driftfall:editHelp`); targeting is as generous as Backrooms' (`edTileAt`, `EDIT_FAN`), and your own body is hidden while the grid is up. At least one tile has to stay. Nothing changes until you confirm, and then the new shape is there at once (it used to land 0.4 s later); you can't shoot while the grid is up, and a Fire still held from picking tiles doesn't fire until it's let go. Driftfall has no teams, so your side is you: the only builds you can edit are the ones you placed, never another player's or a bot's. Picking a slot, the crowbar or a build piece, opening the big map, being knocked out or going more than 10 m away closes the grid and changes nothing. **Shapes:** a piece's shape is `ed`, one bit per tile cut out (tile (u,v) is bit `v*n+u`; 0 is the whole piece), with Backrooms' own `ED_N`, `edRects` and `pieceShape`: the tiles left are joined into as few rectangles as it takes, and each rectangle is one ordinary box in the spatial hash, or for a ramp one ordinary ramp sheet with a smaller footprint, so there is no second collision system: you walk through a door and shoot through a window because no box is there. For that, every ramp (the map's stairs too) is now a sheet with a footprint `ax0`…`az1` and a range `t0`…`t1` up its slope (`addRamp` gives the map's the whole cell), and `rampH`, `rampUnder`, `rayRamp` and the ceiling test in `moveEntity` read those instead of assuming the cell; a whole piece is the one box or sheet it always was. A wall's skirt is not part of the grid: under an edited wall it is a box of its own, the full width, from the land up to the wall's foot, so a door cut where the land is lower has a sill (walked over if it is under 0.6 m, jumped onto if it is more). The trap rule covers edits: tiles are not put back onto someone in this browser who can't simply be nudged clear (`wouldTrap`; you are told someone is in the way), and a door put back with you standing in it moves you out. **Drawing:** whole pieces stay in the three instanced meshes; an edited piece's rectangles are unit boxes in one more instanced mesh shared by every edited piece of every kind (`partIM`, `partsOf`; each box's window of the plank texture is a per-instance attribute, `uvw`, so the planks run on across a cut), which makes thirty edited pieces one draw call, not thirty (measured: 36 calls with thirty whole pieces in view, 34 with the same thirty edited, the three kinds' own meshes then being empty); the grid you see while editing is three more, in place of the piece, and only on your screen. **Online:** an edit travels as the build event for that spot again with `ed` and `n` added (`n` counts the piece's edits, so an older shape never replaces a newer one), and is taken only from the player who built the piece. The host's node also carries `bd: {m, s}`, the builds standing, nine characters a piece (kind and direction, x, z, level, `ed`, `n`, and the builder as a place in the roster; `buildList`), written again at most every two seconds: a late joiner gets every piece in its shape from it, and a page that missed a build or an edit catches up (`applyBuilds`). A page never removes a piece because of the list (a build the host itself missed stays missing for the host), and doesn't put back one it saw break in the last 8 s. A page from before this would keep the whole piece where a door was cut, and the two would disagree about what is solid, so the map version went to 6: older pages are kept out of new matches and told to reload, the usual way. **Bots** don't edit. They see and shoot through openings only (their sight line and their shots are the game's rays), walk through a door that is in their way, and break the part of a build that holds them, looking at head and shin height as well as chest height (`botBreak`), since an edited piece can hold a body by its top or its bottom alone. A bot that slides to and fro along a line of builds for two seconds without getting nearer its goal now breaks through it (stepping aside never came to a stop, so it never counted as stuck; that was so before editing too). **Checked** with the game's own movement and shots against the tiles themselves: on flat ground every one of the 511 wall shapes both ways round (275,940 shots straight and slanted through every tile from both sides, 14,308 walks, 840,000 moves of thrown and jumping bodies at 60, 30 and 20 frames a second), all 15 floor shapes and all 15 ramp shapes in all four directions; on slopes 14 walls with skirts of 0.5 to 3.7 m in 20 shapes each (shots at every tile and at the skirt, 1.7 million moves, doors walked through where the land allows and stopped by the sill where it doesn't), and 8 floors and 8 ramps in every shape; whole pieces compared number for number with the page before (37 pieces on flat and sloping ground, 444,000 moves and 11,100 rays, all identical). Weak or not done: the first wall on rising ground can still show as little as 1.5 m above it (the land rule from map version 5 was left alone); you still start with 30 scrap, three pieces, so a build fight needs the crowbar first; on a phone the build pieces are still behind the scrap chip; a body that another player's build lands on can still be left inside it (as before: only this browser's own builds and edits are refused). **Spanish (November 2026):** the whole game has Spanish through `../lang.js` (switch in the menu's settings and the pause menu), with Driftfall's words in `drop-zone/es.js`; the menus, lobby, results, Creative tools, Face and Locker are translated by lang.js, while the HUD, banner and kill feed are `data-noi18n` and put their words through `T()` (an exact lookup in es.js's list, cheap enough for every frame), and player names, room codes and place names are never translated, nothing translated is sent, and a weapon's rarity is written out per weapon in es.js because Spanish adjectives agree with the noun (`'Rare Pump Shotgun'`), with an extra shorter word (`'Shotgun (tight)'`) for the narrowest phone slots. +- `e63334287a3deaa3/ironveil/`: Midnight Ops (**preview, admin page only**; Back Room folder; the folder keeps the working title `ironveil`, and the display name lives in ONE constant, `IV.GAME_NAME` in `js/core.js`, which fills the page title, the logo, the content note and the "turn your phone" card, so the name can change without touching anything else), a single-player first-person Second World War campaign (an over-the-shoulder view stays in Settings as "View") (three.js r128 from cdnjs plus `../autores.js`, `../keybinds.js`, `/e63334287a3deaa3/lang.js` with its own `es.js`, `stats.js`; Web Audio; no Firebase, nothing online). v1 has **Boot Camp** (a five-minute training course) and **Mission 1, Night Drop**; missions 2 to 8 are listed on the map table as "Coming soon" with their one-line briefings (`IV.menus.COMING` in `js/menus.js`). **Content note and blood:** the first time the game opens (until accepted) a screen before the title says it contains war violence and blood, with an "I understand, continue" button and a Back link (`localStorage` `ironveil:terms` = `1`). Settings has a **Blood effects** switch (on once accepted): off turns every blood effect (hit puffs, spray, the small fading decals, which are capped at `TUNING.blood.decals`, the screen-edge flecks) into dust. No dismemberment, gore close-ups or executions, no hate symbols: the enemy wears field grey with a plain invented white chevron on the helmet. **Files:** `index.html` (page, styles, HUD and menu markup), `js/core.js` (namespace, the one `TUNING` object with every feel number and its units, maths, seeded noise, settings and save), `world.js` (renderer, quality presets Low/Medium/High, sky, moon and fog, the heightfield, colliders in an 8 m spatial hash, ray casts, how lit a point is for stealth), `kit.js` (merged static geometry with world-space UVs, hedgerows, walls, fences, trees, buildings with real door and window openings, props, instanced grass and crops), `env/` (the environment kit, `window.IVEnv`, made separately: ground, grass, trees, hedges, walls, props, atmosphere, decals and the post stack, all generated in code; loaded with plain script tags before the game's own files; `?noenv` shows the old code-made stand-ins), `art.js` (the art factory: every hedge, wall, fence, tree, building, prop, pole, crop field, grass, the stream, the atmosphere and the bullet-impact hook go through `IV.art.*`; when `window.IVEnv` (the environment art module in `ironveil/env/`) is loaded it draws them and `kit.js` only makes the colliders, so layout, collision, nav and cover never change with the look), `nav.js` (0.5 m walk grid, A*, string pulling, cover points), `player.js`, `camera.js` (over-the-shoulder camera with collision, shoulder swap, the scope, aim assist), `weapons.js` (every bullet is a projectile with drag, gravity and wind; the scope's drop marks are computed from the same simulation), `ai.js`, `ally.js`, `fx.js`, `audio.js` (all synthesised), `hud.js`, `menus.js`, `touch.js`, `main.js` (fixed 60 Hz step with interpolation, app state, test hooks), `missions/bootcamp.js`, `missions/nightdrop.js`, and `js/chars-standin.js` (see Characters). **Saving:** `localStorage` `ironveil:save` = `{v: 1, diff, missions: {id: {done, medal, best, last}}, settings: {...}, cp: {mission, diff, idx, data}, tut}`; `cp` is the last checkpoint (its `data` holds the mission's flags, which soldiers are dead, objectives, ammunition, the clock and stats), so Continue on the title resumes there; finishing a mission clears it. Key bindings are `keybinds:ironveil`, the language is the Back Room's `lang:v1`. Bump `v` and migrate in `load()` if the shape changes. **Missions are data plus a few functions**, registered with `IV.missions.register({id, num, title, line, briefing: [...], preview: [{text, opt}], world: {size, day, height(x,z), surface(x,z), groundColor(x,z,y,n,c), waterLevel?, fog, fogColor}, build(M), setup(M, cpIndex, data), step?(M, dt), frame?(M, dt), sketch(g, w, h, sk), medals: [{text, ok(stats, M)}] x3})`. `build` makes the static world once (kept while you replay); `setup` places the player, squadmate and soldiers for a checkpoint and starts the script. The script uses `M.obj(id, text, {optional, marker})`, `M.done(id)`, `M.when(cond, fn)`, `M.after(sec, fn)`, `M.interact({x, z, r, text, hold, done})`, `M.say(text)` / `M.hq(text)` (radio subtitles, text only), `M.checkpoint(n)`, `M.fail(reason)` and `M.complete()`; three medal criteria give gold (all), silver (two) or bronze. To add a mission: copy `missions/nightdrop.js`, give it the next `num` and a new `id`, add its ` + + + + + + + + diff --git a/e63334287a3deaa3/ironveil/chars.js b/e63334287a3deaa3/ironveil/chars.js new file mode 100644 index 00000000..4649740c --- /dev/null +++ b/e63334287a3deaa3/ironveil/chars.js @@ -0,0 +1,1604 @@ +/* + * Ironveil characters (window.IVChars) for three.js r128 (global build). + * + * Load after three.min.js. It loads its own GLTFLoader / SkeletonUtils copies from assets/lib/ if the page has not. + * IVChars.load(onProgress) -> Promise fetches hero, ally, enemies, clips and weapons (about 9 MB) + * IVChars.spawn(kind) -> actor 'hero','ally','rifleman','officer','sniper','gunner' + * IVChars.weapon(kind[, {lod:true}]) -> Object3D 'rifleScoped','smg','pistol','enemyRifle','enemySmg','mg','knife','binoculars','grenade','stickGrenade' (lod: reduced rifle/SMG for others) + * IVChars.tris(kind), IVChars.info, IVChars.clips (names), IVChars.camera (set it for LOD + far-actor throttling) + * Actor (1 unit = 1 m, feet at the origin, facing +Z): + * actor.root, play(name,{fade,loop,speed,once}), setUpper(name|null), setAim(pitch,yaw), attach(obj,socket), detach(obj), + * bone(name), height, setVisible(b), update(dt), dispose(), plus: actor.clipLength(name), actor.isPlaying(name), + * actor.onFinished = fn(name) for one-shot clips, actor.leftHandIK (0..1 override, default automatic). + * If any file fails, a code-made skinned human with procedural animation is used instead (info.fallback = true). + * + * First person (fp.glb + fp.json, loaded by load()): + * IVChars.viewmodel(kind) -> vm | null kind 'rifleScoped' | 'smg' | 'pistol' + * vm.group THREE.Group: add it to the viewmodel camera. Its origin is the eye; it looks down -Z, +Y up, +X right + * (the camera's own frame), metres. Drawn with FOV ~55 and near 0.01 (nearest vertex in any clip: fp.json). + * vm.drive(state, dt) -> events[] call once per frame. state = { ads: 0..1, sprint: 0..1 } blends the looping + * base clips idle / ads / sprint; a one-shot from play() fades in over them and back out when it ends. + * Returns the clip events crossed this frame: [{ clip, name, time }] (also vm.onEvent(name, clip)). + * vm.play(name, { fade, speed, loop }) -> seconds one-shot clips (names in vm.clips): + * fire (fireAds is picked automatically when state.ads > 0.5), reload, reloadEmpty, boltCycle (rifle), + * charge (SMG), draw, holster, sprintIn, sprintOut, grenade, melee, interact, binoculars (holds at the + * eye until binocularsLower). Events: shot; magOut, magIn, done; boltUp, boltBack, eject, boltForward, + * boltDown; charge; slide; pin, release (throw the grenade from vm.sockets.prop at 'release'); hit; + * touch; atEye; ready. + * vm.stop(fade), vm.isPlaying(name), vm.current, vm.clipLength(name), vm.events(name) + * vm.sockets { muzzle, ejection, scopeEye (rifle), sightRear, sightFront, handR, handL, prop, weapon }: Object3Ds, + * read their world matrices after drive(). vm.muzzle, vm.ejection, vm.scopeEye are the same objects. + * vm.adsOffset { position, quaternion }: the group transform that moves the hip pose onto the sight line, for a + * game that moves the group itself instead of blending to the ads clip (do one or the other). + * vm.weapon (the weapon model; moving parts ride on bones w_bolt, w_mag ...), vm.bones, vm.mixer, vm.tris(), + * vm.setVisible(b), vm.dispose(). IVChars.fpClips(kind) lists the clip names. + * actor.setFirstPerson(true|false) the player's body for looking down: no head, neck or arms, eyes/hair and the + * held weapon hidden, a full shadow kept (an invisible copy casts it); call after attach(). + * + * Integration notes for the game: + * - Skeleton (all kinds share it): root, pelvis, spine_01..03, neck_01, Head, clavicle_l/r, upperarm_l/r, lowerarm_l/r, + * hand_l/r, finger bones, thigh_l/r, calf_l/r, foot_l/r, ball_l/r, plus weapon_r (a prop bone under hand_r that + * attach(obj,'handR') uses, so reload/bolt clips can move the gun independently of the hand). + * - Clips are in place (no root motion). vault: move the root ~1.3 m forward over its 1.1 s. takedown/takedownVictim: + * place the victim 0.42 m in front of the attacker, same facing, start both together (2.6 s). + * Deaths, hit, throw, reload, fire* etc. play once and hold their last frame (see ONESHOT); actor.onFinished(name). + * - Extra clips beyond the brief: holdRifle, holdPistol, aimPistol, firePistol, fire, fireCrouch, fireCover, aimCover, + * sprintRifle, stackUp, wallLean, breachKick, signalMoveUp, stagger, deathRun, limp. IVChars.clips lists them all. + * - A long gun or pistol in handR automatically layers holdRifle/holdPistol on the upper body unless setUpper() is used + * or the full-body clip already carries the weapon. The left hand is pulled onto weapon.userData.gripL by IK in the + * aim/hold/fire clips (actor.leftHandIK = 0..1 forces it). + * - Set IVChars.camera = yourCamera for the LOD switch (IVChars.lodDistances = [mid, far] metres, default [12, 30]; + * every kind has a ~5k mid and a ~1.8k far mesh; set lower distances on low quality) and for updating far + * actors (beyond IVChars.throttleDistance, default 45 m) every other frame. + * A full weapon model held by anyone but the hero switches to its reduced model beyond IVChars.weaponLodDistance (6 m). + * - Weapons: barrel along +Z, up +Y, origin at the right-hand grip; userData.muzzle (Object3D, use its world position), + * userData.gripR / gripL (hand frames). Drop a gun on death with actor.detach(gun) and add it to the scene. + * Assets and their licences: CREDITS.md. Pipeline notes: README section "Ironveil characters". + */ +(function () { + 'use strict'; + if (!window.THREE) { console.warn('IVChars: three.js missing'); return; } + var T = THREE; + var SCRIPT = document.currentScript && document.currentScript.src; + var BASE = SCRIPT ? SCRIPT.replace(/[^\/]*$/, '') : ''; + var ASSETS = BASE + 'assets/'; + var VERSION = '10'; // bump whenever any file in assets/ changes, so browsers fetch the new copies + + // ---------- kinds and files + var FILES = { + hero: 'hero.glb', ally: 'ally.glb', enemy: 'enemy.glb', anims: 'anims.glb', weapons: 'weapons.glb', fp: 'fp.glb' + }; + // which meshes of which file make each kind (enemy.glb holds all four enemy outfits + their LODs on one body) + var KINDS = { + hero: { file: 'hero', meshes: ['Hero', 'HeroHair', 'HeroEyes'], lod: ['HeroLOD1', 'HeroLOD2'] }, + ally: { file: 'ally', meshes: ['Ally', 'AllyHair', 'AllyEyes'], lod: ['AllyLOD1', 'AllyLOD2'] }, + rifleman: { file: 'enemy', meshes: ['Rifleman', 'EnemyHair', 'EnemyEyes'], lod: ['RiflemanLOD1', 'RiflemanLOD2'] }, + officer: { file: 'enemy', meshes: ['Officer', 'EnemyHair', 'EnemyEyes'], lod: ['OfficerLOD1', 'OfficerLOD2'] }, + sniper: { file: 'enemy', meshes: ['Sniper', 'EnemyHair', 'EnemyEyes'], lod: ['SniperLOD1', 'SniperLOD2'] }, + gunner: { file: 'enemy', meshes: ['Gunner', 'EnemyHair', 'EnemyEyes'], lod: ['GunnerLOD1', 'GunnerLOD2'] } + }; + var WEAPONS = ['rifleScoped', 'smg', 'pistol', 'enemyRifle', 'enemySmg', 'mg', 'knife', 'binoculars', 'grenade', 'stickGrenade', 'rifleScopedLod', 'smgLod']; + var LONG = { rifleScoped: 1, smg: 1, enemyRifle: 1, enemySmg: 1, mg: 1 }; + + // clip aliases: API names that are served by another clip (documented in README) + var ALIAS = { + takedownVictim: 'takedownVictim', crouchAimWalk: 'crouchWalk' + }; + // clips where the left hand belongs on the weapon's fore-end (left-hand IK on when a long gun is in handR) + var TWO_HAND = { aimIdle: 1, aimWalk: 1, crouchAim: 1, holdRifle: 1, sprintRifle: 1, fire: 1, fireCrouch: 1, fireCover: 1, + proneAim: 1, proneIdle: 1, stackUp: 1, boltCycle: 0, aimPistol: 1, firePistol: 1, holdPistol: 0, wallLean: 1, limp: 1, aimCover: 1 }; + // clips that play once and hold their last frame unless {loop:true} is passed + var ONESHOT = { deathLeft: 1, deathRight: 1, deathCover: 1, reload: 1, boltCycle: 1, throw: 1, melee: 1, takedown: 1, takedownVictim: 1, vault: 1, hit: 1, deathFront: 1, deathBack: 1, + deathRun: 1, salute: 1, fire: 1, firePistol: 1, fireCrouch: 1, fireCover: 1, breachKick: 1, signalMoveUp: 1, stagger: 1 }; + + var IV = window.IVChars = { + info: { loaded: false, fallback: false, files: {}, bytes: 0, errors: [], version: VERSION }, + clips: [], camera: null, lodDistance: 22, lodDistances: [12, 30], throttleDistance: 45, weaponLodDistance: 6 + }; + var META = {}, gltf = {}, CLIPS = {}, UPPER = {}, LOWER = {}, TEMPLATES = {}, WTEMPLATES = {}, TRIS = {}, upperSet = null; + + // ---------- script loading (own copies of the r128 example loaders) + function addScript(src) { + return new Promise(function (res, rej) { + var s = document.createElement('script'); s.src = src; s.onload = res; s.onerror = function () { rej(new Error('script ' + src)); }; + document.head.appendChild(s); + }); + } + function needLibs() { + var p = []; + if (!T.GLTFLoader) p.push(addScript(ASSETS + 'lib/GLTFLoader.js')); + return Promise.all(p).then(function () { + var q = []; + if (!T.SkeletonUtils) q.push(addScript(ASSETS + 'lib/SkeletonUtils.js')); + if (!window.MeshoptDecoder) q.push(addScript(ASSETS + 'lib/meshopt_decoder.js')); + return Promise.all(q); + }).then(function () { return window.MeshoptDecoder && MeshoptDecoder.ready; }); + } + + function loadGLB(name, prog) { + return new Promise(function (res, rej) { + var l = new T.GLTFLoader(); + if (window.MeshoptDecoder) l.setMeshoptDecoder(window.MeshoptDecoder); + l.load(ASSETS + FILES[name] + '?v=' + VERSION, function (g) { res(g); }, function (e) { prog(name, e.loaded, e.total || 0); }, function (e) { rej(e); }); + }); + } + + // ---------- material tweaks + function prepMaterial(m) { + if (!m) return; + if (/Eye/.test(m.name)) { m.roughness = 0.08; m.metalness = 0; m.envMapIntensity = 1.4; return; } // wet eye: sharp catchlight + if (/Hair/.test(m.name)) { + m.alphaTest = 0.5; m.transparent = false; m.depthWrite = true; m.side = T.DoubleSide; + m.roughness = 0.55; m.metalness = 0; + } else if (!m.metalnessMap) { + m.metalness = 0; + } + if (m.normalMap) m.normalScale.set(1, 1); + if (m.map) m.map.anisotropy = 4; + } + + // ---------- clips + function prepClips(anims) { + var bones = {}; + anims.forEach(function (c) { + c.tracks = c.tracks.filter(function (t) { + var bn = t.name.split('.')[0], prop = t.name.split('.')[1]; + bones[bn] = 1; + if (prop === 'scale') return false; + if (prop === 'position' && bn !== 'pelvis') return false; + return true; + }); + }); + // upper body = spine_01 and everything below it in the hierarchy (bone names from the shared skeleton) + upperSet = {}; + ['spine_01', 'spine_02', 'spine_03', 'neck_01', 'Head', 'weapon_r'].forEach(function (b) { upperSet[b] = 1; }); + Object.keys(bones).forEach(function (b) { + if (/(clavicle|upperarm|lowerarm|hand|thumb|index|middle|ring|pinky)_/.test(b)) upperSet[b] = 1; + }); + anims.forEach(function (c) { + CLIPS[c.name] = c; + UPPER[c.name] = new T.AnimationClip(c.name + '#U', c.duration, c.tracks.filter(function (t) { return upperSet[t.name.split('.')[0]]; })); + LOWER[c.name] = new T.AnimationClip(c.name + '#L', c.duration, c.tracks.filter(function (t) { return !upperSet[t.name.split('.')[0]]; })); + }); + IV.clips = Object.keys(CLIPS); + } + function clipName(n) { + if (CLIPS[n]) return n; + if (ALIAS[n] && CLIPS[ALIAS[n]]) return ALIAS[n]; + return null; + } + + // ---------- templates + function triCount(o) { + var n = 0; + o.traverse(function (m) { if (m.isMesh) { var g = m.geometry; n += (g.index ? g.index.count : g.attributes.position.count) / 3; } }); + return Math.round(n); + } + function buildTemplate(kind) { + var def = KINDS[kind], g = gltf[def.file]; + if (!g) return null; + var keep = {}; + def.meshes.concat(def.lod || []).forEach(function (n) { keep[n] = 1; }); + var src = g.scene; + // clone the whole file once per kind, then drop meshes of the other kinds + var root = T.SkeletonUtils.clone(src); + var drop = []; + root.traverse(function (o) { + if (o.isMesh) { + var nm = meshName(o); + if (!keep[nm]) drop.push(o); + } + }); + drop.forEach(function (o) { o.parent.remove(o); }); + var tris = 0, lodTris = [0, 0, 0]; + root.traverse(function (o) { + if (!o.isMesh) return; + prepMaterial(o.material); + o.castShadow = true; o.receiveShadow = false; + var g2 = o.geometry; + // skinned bounds: generous sphere around the body so animated limbs (prone, deaths) never pop out + g2.boundingSphere = new T.Sphere(new T.Vector3(0, 0.9, 0), 1.45); + var nm = meshName(o); + o.userData.lod = (def.lod || []).indexOf(nm) + 1; // 0 full, 1 mid (~5k), 2 far (~1.8k) + var c = (g2.index ? g2.index.count : g2.attributes.position.count) / 3; + if (o.userData.lod) lodTris[o.userData.lod] += c; else tris += c; + }); + TRIS[kind] = { tris: Math.round(tris), lod: Math.round(lodTris[1]), lod2: Math.round(lodTris[2]) }; + return root; + } + function meshName(o) { + // GLTFLoader names a single-primitive mesh after its node; multi-primitive meshes become groups + var n = o.name || ''; + if (o.parent && o.parent.isGroup && o.parent.name && !o.parent.isBone) n = o.parent.name; + return n.replace(/_\d+$/, ''); + } + + function prepWeapons(g) { + g.scene.updateMatrixWorld(true); + WEAPONS.forEach(function (k) { + var o = g.scene.getObjectByName(k); + if (!o) return; + o.traverse(function (m) { if (m.isMesh) { prepMaterial(m.material); m.castShadow = true; } }); + WTEMPLATES[k] = o; + TRIS[k] = { tris: triCount(o) }; + }); + } + + // ---------- load + IV.load = function (onProgress) { + if (IV._loading) return IV._loading; + var seen = {}, totals = { hero: 2.9e6, ally: 2.9e6, enemy: 3.2e6, anims: 1.2e6, weapons: 8e6, fp: 3e6 }; + function prog(name, loaded, total) { + seen[name] = loaded; if (total) totals[name] = total; + var a = 0, b = 0; + for (var k in totals) { a += Math.min(seen[k] || 0, totals[k]); b += totals[k]; } + if (onProgress) try { onProgress(Math.min(0.99, a / b)); } catch (e) {} + } + IV._loading = needLibs().then(function () { + var names = IV.forceFallback ? [] : Object.keys(FILES); + return Promise.all(names.map(function (n) { + return loadGLB(n, prog).then(function (g) { gltf[n] = g; IV.info.files[n] = 'ok'; }, function (e) { + IV.info.files[n] = 'failed'; IV.info.errors.push(n + ': ' + (e && e.message || e)); + }); + })); + }).then(function () { + if (gltf.anims) prepClips(gltf.anims.animations); + if (gltf.fp) prepFP(gltf.fp); + return Promise.all([ + fetch(ASSETS + 'anims.json?v=' + VERSION).then(function (r) { return r.json(); }).then(function (j) { META = j; }, function () { META = {}; }), + fetch(ASSETS + 'fp.json?v=' + VERSION).then(function (r) { return r.json(); }).then(function (j) { FPMETA = j; }, function () { FPMETA = null; }) + ]); + }).then(function () { + if (gltf.weapons) prepWeapons(gltf.weapons); + Object.keys(KINDS).forEach(function (k) { + var t = buildTemplate(k); + if (t) TEMPLATES[k] = t; + }); + if (!gltf.anims || !TEMPLATES.hero) IV.info.fallback = true; + IV.info.loaded = true; + for (var k in seen) IV.info.bytes += seen[k]; + if (onProgress) try { onProgress(1); } catch (e) {} + return IV; + }).catch(function (e) { + IV.info.errors.push(String(e && e.message || e)); IV.info.fallback = true; IV.info.loaded = true; + if (onProgress) try { onProgress(1); } catch (e2) {} + return IV; + }); + return IV._loading; + }; + + IV.tris = function (kind) { + if (TRIS[kind]) return TRIS[kind].tris; + return kind in KINDS || WEAPONS.indexOf(kind) >= 0 ? (FB.tris || 0) : 0; + }; + IV.lodTris = function (kind, level) { return TRIS[kind] ? (level === 2 ? TRIS[kind].lod2 : TRIS[kind].lod) || 0 : 0; }; // mid (1, default) or far (2) + + // ---------- weapons + IV.weapon = function (kind, opts) { + var src = opts && opts.lod && WTEMPLATES[kind + 'Lod'] ? kind + 'Lod' : kind; // reduced model (other characters, distance) + var t = WTEMPLATES[src], o; + if (t) { + o = t.clone(true); + o.position.set(0, 0, 0); o.quaternion.identity(); o.scale.set(1, 1, 1); + o.userData.kind = kind; + o.userData.muzzle = o.getObjectByName(src + '_muzzle') || o; + var gr = o.getObjectByName(src + '_gripR'), gl = o.getObjectByName(src + '_gripL'); + o.userData.grip = { r: gr || null, l: gl || null }; + o.userData.gripR = gr; o.userData.gripL = gl; + } else { + o = FB.weapon(kind); + } + o.userData.long = !!LONG[kind]; + return o; + }; + + // ---------- first-person viewmodel (fp.glb + fp.json) + // Arms and hands from the hero's body with rolled smock sleeves and a wristwatch, on their own skeleton whose + // origin is the eye (looking down -Z, +Y up, +X right: the camera's frame). The weapon is a clone of the normal + // weapon model whose moving parts ride on skeleton bones (w_root, w_bolt, w_boltHandle, w_mag, w_trigger, + // w_hammer, w_charging) and a w_prop bone carries the grenade or the binoculars. Every clip is per weapon kind. + var FPMETA = null, FPCLIPS = {}; + var FP_PARTS = ['bolt', 'boltHandle', 'mag', 'trigger', 'hammer', 'charging']; + var FP_BASE = { idle: 1, ads: 1, sprint: 1 }; + function prepFP(g) { + g.animations.forEach(function (c) { + c.tracks.forEach(function (t) { if (/\.scale$/.test(t.name) && !/^w_(mag|prop)\./.test(t.name)) t._drop = true; }); + c.tracks = c.tracks.filter(function (t) { return !t._drop; }); + FPCLIPS[c.name] = c; + }); + g.scene.traverse(function (o) { if (o.isMesh) { prepMaterial(o.material); if (o.material.map) o.material.map.anisotropy = 8; } }); + } + IV.fpClips = function (kind) { + return Object.keys(FPCLIPS).filter(function (n) { return n.indexOf(kind + '.') === 0; }).map(function (n) { return n.slice(kind.length + 1); }); + }; + IV.viewmodel = function (kind) { + var g = gltf.fp; + if (!g || !WTEMPLATES[kind] || !FPCLIPS[kind + '.idle']) return null; + var root = T.SkeletonUtils.clone(g.scene); + var group = new T.Group(); group.name = 'viewmodel_' + kind; group.add(root); + var bones = {}, meshes = []; + root.traverse(function (o) { + if (o.isBone) bones[o.name] = o; + if (o.isMesh) { o.frustumCulled = false; o.castShadow = false; o.receiveShadow = false; meshes.push(o); } + }); + var gun = IV.weapon(kind); + var parts = {}; + FP_PARTS.forEach(function (p) { var n = gun.getObjectByName(kind + '_' + p); if (n) parts[p] = n; }); + bones.w_root.add(gun); gun.position.set(0, 0, 0); gun.quaternion.identity(); + FP_PARTS.forEach(function (p) { + var n = parts[p], b = bones['w_' + p]; + if (!n || !b) return; + b.add(n); n.position.set(0, 0, 0); n.quaternion.identity(); n.scale.set(1, 1, 1); + }); + gun.traverse(function (o) { if (o.isMesh) { o.frustumCulled = false; o.castShadow = false; } }); + // contact shading: the gun darkens where the hands sit (palms, knuckle lines, thumbs), so hands and gun read as + // touching. Own material copies for this viewmodel; six points in view space, updated in drive(). + var occPts = []; for (var oi = 0; oi < 6; oi++) occPts.push(new T.Vector3(0, -99, 0)); + var occBones = ['hand_r', 'middle_01_r', 'thumb_02_r', 'hand_l', 'middle_01_l', 'thumb_02_l']; + gun.traverse(function (o) { + if (!o.isMesh) return; + var mats = Array.isArray(o.material) ? o.material : [o.material]; + mats = mats.map(function (m0) { + var m = m0.clone(); + m.onBeforeCompile = function (sh) { + sh.uniforms.uOccPts = { value: occPts }; + sh.vertexShader = 'varying vec3 vOccPos;\n' + sh.vertexShader.replace('#include ', + '#include \n vOccPos = (modelMatrix * vec4(transformed, 1.0)).xyz;'); + var f = 'uniform vec3 uOccPts[6];\nvarying vec3 vOccPos;\n' + + 'float vmOcc() { float o = 0.0; for (int i = 0; i < 6; i++) { vec3 d = vOccPos - uOccPts[i]; o += exp(-dot(d, d) / 0.0009); } return 1.0 - 0.5 * clamp(o, 0.0, 1.0); }\n'; + var tgt = 'gl_FragColor = vec4( outgoingLight, diffuseColor.a );'; + sh.fragmentShader = f + (sh.fragmentShader.indexOf(tgt) >= 0 ? sh.fragmentShader.replace(tgt, 'outgoingLight *= vmOcc();\n' + tgt) + : sh.fragmentShader.replace('#include ', 'outgoingLight *= vmOcc();\n#include ')); + }; + m.customProgramCacheKey = function () { return 'vmocc'; }; + return m; + }); + o.material = Array.isArray(o.material) ? mats : mats[0]; + }); + var sling = gun.getObjectByName(kind + '_sling'); if (sling) sling.visible = false; // a loose sling would hang across the view + var props = {}; + ['grenade', 'binoculars'].forEach(function (k) { + if (!WTEMPLATES[k]) return; + var o = IV.weapon(k); o.visible = false; bones.w_prop.add(o); props[k] = o; + o.traverse(function (m) { if (m.isMesh) m.frustumCulled = false; }); + }); + var mixer = new T.AnimationMixer(root); + var meta = (FPMETA && FPMETA.clips) || {}, kmeta = (FPMETA && FPMETA.kinds && FPMETA.kinds[kind]) || {}; + var base = {}, one = null, oneName = null, oneT = 0, fired = {}; + Object.keys(FP_BASE).forEach(function (n) { + var c = FPCLIPS[kind + '.' + n]; if (!c) return; + var a = mixer.clipAction(c); a.setLoop(T.LoopRepeat, Infinity); a.play(); a.setEffectiveWeight(n === 'idle' ? 1 : 0); base[n] = a; + }); + // the hip-to-sights raise: a solved clip held at time = ads (blending the hip and ADS loops in the mixer swings + // the hands off the gun half way) + var raise = null, raiseC = FPCLIPS[kind + '.adsRaise']; + if (raiseC) { raise = mixer.clipAction(raiseC); raise.setLoop(T.LoopOnce, 1); raise.clampWhenFinished = true; raise.timeScale = 0; raise.play(); raise.setEffectiveWeight(0); } + function sstep(a, b, x) { x = Math.max(0, Math.min(1, (x - a) / (b - a))); return x * x * (3 - 2 * x); } + var oneW = 0, oneFade = 0.1, oneOut = false, st = { ads: 0, sprint: 0 }; + function find(o, n) { return o.getObjectByName(kind + '_' + n) || null; } + var ao = kmeta.adsOffset; + var vm = { + kind: kind, group: group, weapon: gun, bones: bones, mixer: mixer, + clips: IV.fpClips(kind), + muzzle: find(gun, 'muzzle'), ejection: find(gun, 'ejection'), scopeEye: find(gun, 'scopeEye'), + sockets: { muzzle: find(gun, 'muzzle'), ejection: find(gun, 'ejection'), scopeEye: find(gun, 'scopeEye'), + sightRear: find(gun, 'sightRear'), sightFront: find(gun, 'sightFront'), + handR: bones.hand_r, handL: bones.hand_l, prop: bones.w_prop, weapon: bones.w_root }, + adsOffset: ao ? { position: new T.Vector3().fromArray(ao.position), quaternion: new T.Quaternion().fromArray(ao.quaternion) } : null, + current: null, onEvent: null, + clipLength: function (n) { var c = FPCLIPS[kind + '.' + n]; return c ? c.duration : 0; }, + events: function (n) { var m = meta[kind + '.' + n]; return m ? m.events : {}; }, + isPlaying: function (n) { return !!one && oneName === n && !oneOut; }, + play: function (name, o) { + o = o || {}; + if (name === 'fire' && st.ads > 0.5 && FPCLIPS[kind + '.fireAds']) name = 'fireAds'; + var c = FPCLIPS[kind + '.' + name]; + if (!c) return 0; + if (one && one.getClip() !== c) one.stop(); + one = mixer.clipAction(c); oneName = name; oneT = 0; fired = {}; oneOut = false; + one.reset(); one.setLoop(o.loop ? T.LoopRepeat : T.LoopOnce, o.loop ? Infinity : 1); one.clampWhenFinished = true; + one.timeScale = o.speed || 1; one.play(); + oneFade = o.fade != null ? o.fade : (/^(fire|fireAds)$/.test(name) ? 0.02 : 0.1); + if (oneFade <= 0) oneW = 1; + var pm = meta[kind + '.' + name], pr = pm && pm.prop; + Object.keys(props).forEach(function (k) { props[k].visible = k === pr; }); + vm.current = name; + return c.duration / (one.timeScale || 1); + }, + stop: function (fade) { if (one) { oneOut = true; oneFade = fade != null ? fade : 0.15; } }, + drive: function (state, dt) { + state = state || {}; + st.ads = Math.max(0, Math.min(1, state.ads || 0)); st.sprint = Math.max(0, Math.min(1, state.sprint || 0)); + // one-shot weight: fade in, hold, and fade out to the base layer when finished (binoculars hold until lowered) + if (one) { + var len = one.getClip().duration, m = meta[kind + '.' + oneName] || {}; + if (!oneOut && !m.hold && !m.loop && one.time >= len - 1e-4 && oneT > 0) { oneOut = true; oneFade = 0.12; } + oneW = oneOut ? Math.max(0, oneW - dt / oneFade) : Math.min(1, oneW + dt / Math.max(1e-3, oneFade)); + if (oneOut && oneW <= 0) { one.stop(); one = null; oneName = null; vm.current = null; Object.keys(props).forEach(function (k) { props[k].visible = false; }); } + } + var bw = 1 - (one ? oneW : 0); + var wa = st.ads * (1 - st.sprint), ws = st.sprint, wi = Math.max(0, 1 - wa - ws), wr = 0; + if (raise) { // near either end blend with the breathing loops, in between hold the solved raise + var ns = 1 - ws, lo = 1 - sstep(0, 0.12, st.ads), hi = sstep(0.88, 1, st.ads); + wi = ns * lo; wa = ns * hi; wr = ns * Math.max(0, 1 - lo - hi); + raise.time = Math.min(raiseC.duration - 1e-4, st.ads * raiseC.duration); + raise.setEffectiveWeight(wr * bw); + } + if (base.idle) base.idle.setEffectiveWeight(wi * bw); + if (base.ads) base.ads.setEffectiveWeight(wa * bw); + if (base.sprint) base.sprint.setEffectiveWeight(ws * bw); + if (one) one.setEffectiveWeight(oneW); + var t0 = one ? one.time : 0; + mixer.update(dt || 0); + root.updateMatrixWorld(true); + for (var bi = 0; bi < 6; bi++) { var bb = bones[occBones[bi]]; if (bb) occPts[bi].setFromMatrixPosition(bb.matrixWorld); } + if (bones.hand_r && bones.middle_01_r) { occPts[0].lerp(occPts[1], 0.5); occPts[3].lerp(occPts[4], 0.5); } // palm centres + var out = []; + if (one) { + oneT += dt; + var ev = (meta[kind + '.' + oneName] || {}).events || {}, t1 = one.time; + for (var e in ev) if (!fired[e] && t1 >= ev[e]) { fired[e] = 1; out.push({ clip: oneName, name: e, time: ev[e] }); if (vm.onEvent) try { vm.onEvent(e, oneName); } catch (x) {} } + } + return out; + }, + setVisible: function (b) { group.visible = b; }, + tris: function () { var n = 0; group.traverse(function (o) { if (o.isMesh && o.visible) { var gg = o.geometry; n += (gg.index ? gg.index.count : gg.attributes.position.count) / 3; } }); return Math.round(n); }, + dispose: function () { mixer.stopAllAction(); mixer.uncacheRoot(root); if (group.parent) group.parent.remove(group); } + }; + vm.drive({}, 0); + return vm; + }; + + // ---------- math helpers + var _v1 = new T.Vector3(), _v2 = new T.Vector3(), _v3 = new T.Vector3(), _v4 = new T.Vector3(), _v5 = new T.Vector3(); + var _q1 = new T.Quaternion(), _q2 = new T.Quaternion(), _q3 = new T.Quaternion(), _m1 = new T.Matrix4(); + function worldPos(o, v) { return v.setFromMatrixPosition(o.matrixWorld); } + function worldQuat(o, q) { o.matrixWorld.decompose(_v5, q, _v4); return q; } + // rotate bone by a world-space rotation q (pre-multiplied), keeping children attached + function rotWorld(bone, q) { + var p = bone.parent; + worldQuat(p, _q2); + // local' = inv(P) * q * P * local + _q3.copy(_q2).invert().multiply(q).multiply(_q2); + bone.quaternion.premultiply(_q3); + bone.updateMatrixWorld(true); + } + function setWorldQuat(bone, q) { + worldQuat(bone.parent, _q2); + bone.quaternion.copy(_q2.invert().multiply(q)); + bone.updateMatrixWorld(true); + } + function angleBetween(a, b) { return Math.acos(Math.max(-1, Math.min(1, a.dot(b) / (a.length() * b.length() || 1)))); } + // two-bone IK (keeps the clip's current bend plane), then matches the end rotation + function twoBone(a, b, c, tPos, tQuat, w) { + if (w <= 0) return; + var qa = a.quaternion.clone(), qb = b.quaternion.clone(), qc = c.quaternion.clone(); + var A = worldPos(a, new T.Vector3()), B = worldPos(b, new T.Vector3()), C = worldPos(c, new T.Vector3()); + var lab = B.distanceTo(A), lcb = C.distanceTo(B); + var lat = Math.max(0.01, Math.min(tPos.distanceTo(A), lab + lcb - 0.001)); + var ac = _v1.copy(C).sub(A), ab = _v2.copy(B).sub(A), ba = new T.Vector3().copy(A).sub(B), bc = new T.Vector3().copy(C).sub(B), at = _v3.copy(tPos).sub(A); + var ac_ab_0 = angleBetween(ac, ab), ba_bc_0 = angleBetween(ba, bc), ac_at_0 = angleBetween(ac, at); + var ac_ab_1 = Math.acos(Math.max(-1, Math.min(1, (lcb * lcb - lab * lab - lat * lat) / (-2 * lab * lat)))); + var ba_bc_1 = Math.acos(Math.max(-1, Math.min(1, (lat * lat - lab * lab - lcb * lcb) / (-2 * lab * lcb)))); + var axis0 = new T.Vector3().crossVectors(ac, ab); + if (axis0.lengthSq() < 1e-8) axis0.set(0, 1, 0); + axis0.normalize(); + var axis1 = new T.Vector3().crossVectors(ac, at); + if (axis1.lengthSq() < 1e-10) axis1.copy(axis0); else axis1.normalize(); + rotWorld(a, _q1.setFromAxisAngle(axis0, ac_ab_1 - ac_ab_0)); + rotWorld(b, _q1.setFromAxisAngle(axis0, ba_bc_1 - ba_bc_0)); + rotWorld(a, _q1.setFromAxisAngle(axis1, ac_at_0)); + if (tQuat) setWorldQuat(c, tQuat); + if (w < 1) { + a.quaternion.copy(qa.slerp(a.quaternion, w)); b.quaternion.copy(qb.slerp(b.quaternion, w)); + c.quaternion.copy(qc.slerp(c.quaternion, w)); a.updateMatrixWorld(true); + } + } + + // sockets for attach(): bone and, for back/hip, a carry pose in the bind-pose character frame + var SOCKET = { handR: 'weapon_r', handL: 'hand_l', back: 'spine_03', sling: 'spine_03', hip: 'pelvis', head: 'Head' }; + function carryMatrix(socket, obj) { + var m = new T.Matrix4(), q = new T.Quaternion(), p = new T.Vector3(); + var long = obj.userData.long; + if (socket === 'back') { + // slung across the back, muzzle up over the left shoulder + var z = new T.Vector3(0.42, 0.9, 0).normalize(), y = new T.Vector3(0, 0, -1), x = new T.Vector3().crossVectors(y, z); + m.makeBasis(x, y, z); p.set(-0.05, 1.28, -0.2); + if (!long) { m.identity(); p.set(0.12, 1.05, -0.17); } + } else if (socket === 'sling') { + // slung muzzle up across the back: butt low behind the right hip, muzzle above the left shoulder blade, the + // sights facing out from the back. Muzzle-down carry put a 1.2 m rifle's barrel beside the left knee (seen when + // looking down in first person) and the scope above the helmet when the torso bent to aim. + var z3 = new T.Vector3(0.36, 0.93, 0).normalize(), y3 = new T.Vector3(0, -0.05, -1).normalize(), x3 = new T.Vector3().crossVectors(y3, z3).normalize(); + y3.crossVectors(z3, x3); + m.makeBasis(x3, y3, z3); p.set(-0.03, 1.02, -0.27); + if (!long) { m.identity(); p.set(0.12, 1.05, -0.17); } + } else if (socket === 'hip') { + // holstered on the right hip, muzzle down + var z2 = new T.Vector3(0, -1, 0.15).normalize(), y2 = new T.Vector3(-1, 0, 0), x2 = new T.Vector3().crossVectors(y2, z2); + m.makeBasis(x2, y2, z2); p.set(-0.2, 0.98, 0.03); + if (long) { p.set(-0.25, 1.0, 0); } + } else { m.identity(); p.set(0, 0, 0); } + m.setPosition(p); + return m; + } + + // ---------- hand grips per weapon + // Curl of each finger (0 straight .. 1 closed) and thumb, per weapon class and hand, applied after the mixer on + // the finger bones whenever a weapon is in the right hand, so the fingers wrap the real-size grips instead of + // closing into the clip's fist through them. Right: round the wrist of the stock or the pistol grip with the + // index finger laid along the trigger guard (on the trigger while firing). Left: cupping the fore-end from + // below with the thumb up the side. Joint split per finger: base, middle, tip. + var GRIPF = { // fitted with tools/chars/gripopt.js: right/left hand offsets (weapon frame) and curl scales + rifle: { r: { index: 0.088, middle: 0.44, ring: 0.475, pinky: 0.51, thumb: 0.132, trigger: 0.334, off: [0.041, 0.04, 0] }, + l: { index: 0.18, middle: 0.34, ring: 0.38, pinky: 0.42, thumb: 0.05, off: [-0.016, -0.016, 0.01] } }, + enemyRifle: { r: { index: 0.091, middle: 0.455, ring: 0.491, pinky: 0.528, thumb: 0.137, trigger: 0.346, off: [0.035, 0.044, 0] }, + l: { index: 0.06, middle: 0.34, ring: 0.38, pinky: 0.42, thumb: 0.05, off: [-0.016, -0.04, 0] } }, + smg: { r: { index: 0.064, middle: 0.333, ring: 0.358, pinky: 0.384, thumb: 0.096, trigger: 0.4, off: [0.04, 0.04, -0.028] }, + l: { index: 0.2, middle: 0.36, ring: 0.4, pinky: 0.44, thumb: 0.06, off: [-0.014, -0.028, 0] } }, + pistol: { r: { index: 0.094, middle: 0.47, ring: 0.508, pinky: 0.545, thumb: 0.282, trigger: 0.338, off: [0.022, 0.014, -0.01] }, + l: { index: 0.36, middle: 0.34, ring: 0.26, pinky: 0.22, thumb: 0.145, off: [0, -0.014, 0] } }, + mg: { r: { index: 0.064, middle: 0.32, ring: 0.346, pinky: 0.371, thumb: 0.096, trigger: 0.243, off: [0.041, 0.04, 0.024] }, + l: { index: 0.18, middle: 0.34, ring: 0.38, pinky: 0.42, thumb: 0.05, off: [0.008, -0.044, -0.036] } } + }; + IV.grips = GRIPF; // per-weapon finger curls (tunable) + var GRIPCLASS = { rifleScoped: 'rifle', rifleScopedLod: 'rifle', enemyRifle: 'enemyRifle', smg: 'smg', smgLod: 'smg', enemySmg: 'smg', pistol: 'pistol', mg: 'mg' }; + var FSEG = { index: [0.9, 1.1, 0.8], middle: [0.9, 1.1, 0.8], ring: [0.9, 1.1, 0.8], pinky: [0.9, 1.1, 0.8], thumb: [0.5, 0.8, 0.9] }; + function fingerFrames(bones, root) { + root.updateMatrixWorld(true); + var out = {}, rq = new T.Quaternion(), p0 = new T.Vector3(), p1 = new T.Vector3(); + ['l', 'r'].forEach(function (s) { + var palm = new T.Vector3(0, -1, 0); // bind pose palms face down + Object.keys(FSEG).forEach(function (f) { + for (var j = 1; j <= 3; j++) { + var b = bones[f + '_0' + j + '_' + s], c = bones[f + '_0' + (j + 1) + (j === 3 ? '_leaf_' : '_') + s]; + if (!b) continue; + b.getWorldPosition(p0); + if (c) c.getWorldPosition(p1); else p1.copy(p0).add(new T.Vector3(s === 'l' ? 1 : -1, 0, 0)); + var dir = p1.clone().sub(p0).normalize(), ax = new T.Vector3().crossVectors(dir, palm); + if (ax.lengthSq() < 1e-6) continue; + b.getWorldQuaternion(rq); + out[b.name] = { bone: b, rest: b.quaternion.clone(), axis: ax.normalize().applyQuaternion(rq.clone().invert()), f: f, j: j - 1, s: s }; + } + }); + }); + return out; + } + // ---------- actor + function Actor(kind) { + var t = TEMPLATES[kind]; + this.kind = kind; + this.fb = !t || IV.info.fallback; + if (this.fb) { FB.init(this, kind); return; } + var root = T.SkeletonUtils.clone(t); + this.root = new T.Group(); this.root.name = 'IV_' + kind; this.root.add(root); + this.model = root; + var bones = {}, meshes = [], lods = []; + root.traverse(function (o) { + if (o.isBone) bones[o.name] = o; + if (o.isMesh) { if (o.userData.lod) lods.push(o); else meshes.push(o); } + }); + this.bones = bones; this.meshes = meshes; this.lods = lods; + lods.forEach(function (m) { m.visible = false; }); + this.lodLevel = 0; + this.mixer = new T.AnimationMixer(root); + this.base = []; this.upper = []; this.cur = null; this.curUpper = null; + this.aimP = 0; this.aimY = 0; this.aimPT = 0; this.aimYT = 0; + this.attached = []; + this.leftHandIK = null; this._lhW = 0; + this._acc = 0; this._frame = 0; + this.height = kind === 'hero' || kind === 'ally' ? 1.79 : (kind === 'officer' ? 1.83 : 1.80); + var self = this; + this.mixer.addEventListener('finished', function (e) { + var n = e.action._ivName; + if (self.driven && n && !/^death|takedownVictim/.test(n)) { + self.base.forEach(function (b) { if (b.full === e.action) { b.target = 0; b.rate = 1 / 0.25; } }); + if (self.cur && self.cur.full === e.action) self.cur = null; + } + if (self.onFinished && n) self.onFinished(n); + }); + // finger rest frames (bind pose) and each joint's curl axis in its own frame, for the per-weapon grips + this._fing = fingerFrames(bones, root); + this._fgW = 0; + // face morphs: 'faceB'/'faceC' pick one of three enemy faces; 'blink' closes the hero's and ally's lids + this._morphMeshes = meshes.filter(function (m) { return m.morphTargetDictionary && m.morphTargetInfluences; }); + this._blinkT = 1 + Math.random() * 3; this._blink = 0; + if (!/^(hero|ally)$/.test(kind)) this.setFace(Actor._faceN = ((Actor._faceN || 0) + 1) % 3); + this.play('idle', { fade: 0 }); + // settle on the idle pose now, so the first frame drawn after spawn is never the bind pose + // (a full update: play() only sets the weights that update() hands to the mixer) + this.update(0); this.root.updateMatrixWorld(true); + } + var AP = Actor.prototype; + // weapon moving parts driven by the clips: the rifle bolt follows the hand through boltCycle (lift, back, + // forward, down) and the pistol slide kicks back on each firePistol shot + function smooth01(a, b, t) { var x = Math.max(0, Math.min(1, (t - a) / (b - a))); return x * x * (3 - 2 * x); } + AP._parts = function (held) { + if (!held) return; + var kind = held.userData.kind, e = this.curUpper && this.curUpper.w > 0.3 ? this.curUpper : (this.cur && this.cur.w > 0.3 ? this.cur : null); + var n = e && (e.name || ''), t = e ? (e.action || e.full).time : 0; + var bolt = held.userData._bolt; + if (bolt === undefined) { bolt = held.userData._bolt = held.getObjectByName(kind + '_bolt') || null; if (bolt) bolt.userData.p0 = bolt.position.clone(); } + if (!bolt) return; + var lift = 0, back = 0; + if (n === 'boltCycle' && (kind === 'rifleScoped' || kind === 'enemyRifle')) { + lift = smooth01(0.18, 0.3, t) * (1 - smooth01(0.62, 0.72, t)); + back = smooth01(0.3, 0.48, t) * (1 - smooth01(0.48, 0.62, t)) * 0.085; + } else if (n === 'firePistol' && kind === 'pistol') { + back = t < 0.03 ? t / 0.03 * 0.028 : Math.max(0, 0.028 * (1 - (t - 0.03) / 0.07)); + } + bolt.position.copy(bolt.userData.p0); bolt.position.z -= back; + bolt.rotation.set(0, 0, -lift * 1.4); + }; + AP._grips = function (dt, held) { + var cls = held && GRIPCLASS[held.userData.kind], T0 = cls && GRIPF[cls]; + // clips where the right hand leaves the grip (working the bolt, reloading, throwing...) keep their own hand + var cn = (this.curUpper && this.curUpper.w > 0.3 && this.curUpper.name) || (this.cur && this.cur.w > 0.3 && this.cur.name) || ''; + var free = /^(boltCycle|reload|throw|melee|signal|salute|breach|takedown|vault|death|hit|stagger)/.test(cn); + this._fgW = this._snap ? (T0 && !free ? 1 : 0) : approach(this._fgW, T0 && !free ? 1 : 0, 5, dt); + if (T0) this._fgT = T0; + var w = this._fgW, G0 = this._fgT; if (w < 0.01 || !G0) return; + // right hand: our gloved hand is thicker than the hand the grip frames were fitted to, so the hand is moved + // off the weapon by a small per-class offset (weapon frame: x weapon-left, y up, z forward) with arm IK, + // while the weapon keeps its place on the sight line + var off = T0 && T0.r.off; + if (off && held.userData._ap && this.bones.weapon_r) { + held.position.copy(held.userData._ap); held.quaternion.copy(held.userData._aq); held.updateMatrixWorld(true); + var W0 = held.matrixWorld.clone(), hq = worldQuat(held, new T.Quaternion()); + var hr = this.bones.hand_r, tp = worldPos(hr, new T.Vector3()).sub(new T.Vector3(off[0], off[1], off[2]).applyQuaternion(hq).multiplyScalar(w)); + twoBone(this.bones.upperarm_r, this.bones.lowerarm_r, hr, tp, worldQuat(hr, new T.Quaternion()), 1); + this.bones.upperarm_r.updateMatrixWorld(true); + var Lm = new T.Matrix4().copy(held.parent.matrixWorld).invert().multiply(W0); + Lm.decompose(held.position, held.quaternion, new T.Vector3()); held.updateMatrixWorld(true); + } + var n = (this.curUpper && this.curUpper.name) || (this.cur && this.cur.name) || ''; + var firing = /^fire/.test(n), q = new T.Quaternion(), tq = new T.Quaternion(); + // the left hand only grips while it is on the fore-end (its IK weight); otherwise its clip pose stays + var wl = Math.min(w, this._lhW || 0); + if (cls === 'pistol') wl = w * Math.max(this._lhW || 0, /Pistol/.test(n) ? 1 : 0); + for (var k in this._fing) { + var e = this._fing[k], g = G0[e.s], ww = e.s === 'r' ? w : wl; + if (!g || ww < 0.01) continue; + var a = e.f === 'index' && e.s === 'r' && firing ? g.trigger : g[e.f]; + var ang = a * FSEG[e.f][e.j] * (e.f === 'thumb' ? 1.1 : 1.45); + tq.copy(e.rest).multiply(q.setFromAxisAngle(e.axis, ang)); + if (ww >= 0.999) e.bone.quaternion.copy(tq); else e.bone.quaternion.slerp(tq, ww); + } + if (this.bones.hand_r) this.bones.hand_r.updateMatrixWorld(true); + if (this.bones.hand_l) this.bones.hand_l.updateMatrixWorld(true); + }; + AP.setMorph = function (name, v) { + if (this.fb) return this; + for (var i = 0; i < this._morphMeshes.length; i++) { + var m = this._morphMeshes[i], k = m.morphTargetDictionary[name]; + if (k != null) m.morphTargetInfluences[k] = v; + } + return this; + }; + // one of three faces (0, 1, 2) on the enemy kinds; ignored where a model has no face morphs + AP.setFace = function (i) { + this.face = ((i | 0) % 3 + 3) % 3; + return this.setMorph('faceB', this.face === 1 ? 1 : 0).setMorph('faceC', this.face === 2 ? 1 : 0); + }; + // blinks every 2-6 s (close 0.07 s, open 0.13 s); dead or far actors do not blink + AP._blinkUpdate = function (dt, far) { + if (!this._morphMeshes.length || far > 15) return; + this._blinkT -= dt; + if (this._blinkT <= 0) { this._blink += dt; var b = this._blink, w = b < 0.07 ? b / 0.07 : (b < 0.11 ? 1 : Math.max(0, 1 - (b - 0.11) / 0.13)); + this.setMorph('blink', w * w * (3 - 2 * w)); + if (b > 0.24) { this._blink = 0; this._blinkT = 2 + Math.random() * 4; this.setMorph('blink', 0); } + } + }; + AP._action = function (clip, tag) { + var a = this.mixer.clipAction(clip); + a._ivName = tag; + return a; + }; + AP.clipLength = function (n) { var c = clipName(n); return c ? CLIPS[c].duration : 0; }; + AP.isPlaying = function (n) { return this.cur && this.cur.name === n; }; + AP.play = function (name, o) { + if (this.fb) return FB.play(this, name, o); + o = o || {}; + var c = clipName(name); + if (!c) { if (!this._warned) { console.warn('IVChars: no clip', name); this._warned = 1; } c = 'idle'; } + var fade = o.fade == null ? 0.2 : o.fade; + var once = o.once || o.loop === false || (ONESHOT[name] && o.loop !== true); + if (this.cur && this.cur.name === name && !once) { + if (o.speed != null) { this.cur.full.timeScale = this.cur.lower.timeScale = o.speed; } + return this; + } + var full = this._action(CLIPS[c], name), lower = this._action(LOWER[c], name); + [full, lower].forEach(function (a) { + a.reset(); a.enabled = true; + a.setLoop(once ? T.LoopOnce : T.LoopRepeat, Infinity); + a.clampWhenFinished = !!once; + a.timeScale = o.speed == null ? 1 : o.speed; + a.setEffectiveWeight(0); a.play(); + }); + lower._ivName = null; + var rate = fade > 0 ? 1 / fade : 1e9; + // fade everything else out at the same rate so the weights always sum to one (no blend toward the bind pose) + for (var i = 0; i < this.base.length; i++) { this.base[i].target = 0; this.base[i].rate = rate; } + var e = { name: name, clip: c, full: full, lower: lower, w: fade > 0 ? 0 : 1, target: 1, rate: fade > 0 ? 1 / fade : 1e9 }; + this.base = this.base.filter(function (b) { return b.full !== full; }); + if (fade <= 0) this.base.forEach(function (b) { b.w = 0; }); + this.base.push(e); this.cur = e; + return this; + }; + AP.setUpper = function (name, o) { + if (this.fb) return FB.setUpper(this, name, o); + o = o || {}; + var fade = o.fade == null ? 0.2 : o.fade; + if (this.curUpper && this.curUpper.name === name) return this; + for (var i = 0; i < this.upper.length; i++) { this.upper[i].target = 0; this.upper[i].rate = fade > 0 ? 1 / fade : 1e9; } + this.curUpper = null; + if (name) { + var c = clipName(name); + if (!c) { console.warn('IVChars: no clip', name); return this; } + var a = this._action(UPPER[c], name), once = o.once || o.loop === false || (ONESHOT[name] && o.loop !== true); + a.reset(); a.enabled = true; a.setLoop(once ? T.LoopOnce : T.LoopRepeat, Infinity); a.clampWhenFinished = !!once; + a.timeScale = o.speed == null ? 1 : o.speed; a.setEffectiveWeight(0); a.play(); + this.upper = this.upper.filter(function (u) { return u.action !== a; }); + var e = { name: name, clip: c, action: a, w: fade > 0 ? 0 : 1, target: 1, rate: fade > 0 ? 1 / fade : 1e9 }; + this.upper.push(e); this.curUpper = e; + } + this._autoUpper = !!o.auto; + return this; + }; + AP.setAim = function (p, y) { + this.aimPT = Math.max(-1.2, Math.min(1.2, p || 0)); + this.aimYT = Math.max(-1.1, Math.min(1.1, y || 0)); + return this; + }; + AP.bone = function (n) { return this.fb ? FB.bone(this, n) : (this.bones[n] || (n === 'handR' ? this.bones.hand_r : null) || null); }; + // ---------- first-person body: the player's own body seen when looking down (legs, torso, shadow) + // setFirstPerson(true) draws the full-detail body without the head, neck and arms (the viewmodel draws the arms), + // hides the eyes, hair and anything held in the hands, and keeps a complete shadow: an invisible copy of each + // hidden part (no colour, no depth) still casts it. Legs and feet keep following the clips and the drive graph. + // head, neck, arms and the upper chest kit (pouches, collar, pack top) are dropped: looking down shows the belt, + // legs and boots; the viewmodel draws the arms + var FP_DROP = /^(Head|neck_01|spine_03|clavicle_|upperarm_|lowerarm_|hand_|index_|middle_|ring_|pinky_|thumb_|weapon_r)/; + function attrComp(a, i, k) { // r128 has no BufferAttribute.getComponent; read the raw value and denormalise + var v = k === 0 ? a.getX(i) : k === 1 ? a.getY(i) : k === 2 ? a.getZ(i) : a.getW(i); + if (a.normalized) { + var arr = a.array; + if (arr instanceof Uint8Array) v /= 255; else if (arr instanceof Uint16Array) v /= 65535; + else if (arr instanceof Int8Array) v = Math.max(v / 127, -1); else if (arr instanceof Int16Array) v = Math.max(v / 32767, -1); + } + return v; + } + function fpGeometry(mesh) { + var g = mesh.geometry; + if (g.userData.fpGeom) return g.userData.fpGeom; + var si = g.attributes.skinIndex, sw = g.attributes.skinWeight, bones = mesh.skeleton.bones; + var isDrop = bones.map(function (b) { return FP_DROP.test(b ? b.name : '') ? 1 : 0; }); + var n = si.count, drop = new Uint8Array(n); + for (var i = 0; i < n; i++) { + var dw = 0, tot = 0; + for (var k = 0; k < 4; k++) { var w = attrComp(sw, i, k); tot += w; if (isDrop[attrComp(si, i, k) | 0]) dw += w; } + drop[i] = dw > 0.25 * (tot || 1) ? 1 : 0; // any real share of a dropped bone hides the vertex + } + var idx = g.index ? g.index.array : null, out = []; + var tri = idx ? idx.length : n; + // belt kit (pouches, grenade, rope) is in separate islands skinned to the waist: looking down it would float + // where the game masks the waist, so small islands mostly weighted to pelvis / spine_01 / spine_02 go too + var waist = bones.map(function (b) { return /^(pelvis|spine_01|spine_02)$/.test(b ? b.name : '') ? 1 : 0; }); + var pos0 = g.attributes.position, par = new Int32Array(n), wkey = {}; + for (var i0 = 0; i0 < n; i0++) { var kk0 = pos0.getX(i0) + ',' + pos0.getY(i0) + ',' + pos0.getZ(i0); par[i0] = wkey[kk0] != null ? wkey[kk0] : (wkey[kk0] = i0); } + function root(x) { while (par[x] !== x) { par[x] = par[par[x]]; x = par[x]; } return x; } + for (var t0 = 0; t0 < tri; t0 += 3) { + var a0 = root(idx ? idx[t0] : t0), b0 = root(idx ? idx[t0 + 1] : t0 + 1), c0 = root(idx ? idx[t0 + 2] : t0 + 2); + if (a0 !== b0) par[b0] = a0; a0 = root(a0); if (a0 !== c0) par[c0] = a0; + } + var csize = {}, cwaist = {}; + for (var i1 = 0; i1 < n; i1++) { + var r1 = root(i1), dom = 0, best = -1; + for (var k1 = 0; k1 < 4; k1++) { var w1 = attrComp(sw, i1, k1); if (w1 > best) { best = w1; dom = attrComp(si, i1, k1) | 0; } } + csize[r1] = (csize[r1] || 0) + 1; cwaist[r1] = (cwaist[r1] || 0) + waist[dom]; + } + for (var i2 = 0; i2 < n; i2++) { var r2 = root(i2); if (csize[r2] < n * 0.1 && cwaist[r2] > 0.5 * csize[r2]) drop[i2] = 1; } + for (var t = 0; t < tri; t += 3) { + var a = idx ? idx[t] : t, b = idx ? idx[t + 1] : t + 1, c = idx ? idx[t + 2] : t + 2; + if (!drop[a] && !drop[b] && !drop[c]) out.push(a, b, c); + } + var fg = g.clone(); + var kept = out.length; + capCut(fg, idx, tri, out); + fg.setIndex(out); + fg.boundingSphere = g.boundingSphere; fg.groups = []; + if (out.length > kept) { fg.addGroup(0, kept, 0); fg.addGroup(kept, out.length - kept, 1); } // 1: the dark cap + g.userData.fpGeom = fg; + return fg; + } + // Close the openings the cut leaves (looking straight down otherwise shows the inside of the torso ring): edges + // that bordered two triangles before and one after are chained into loops (welded by position, so UV seams do + // not break them) and each loop is fanned to a new centre vertex that copies the attributes of a rim vertex. + function capCut(fg, idx, tri, out) { + for (var an in fg.attributes) { // meshopt-decoded attributes can be interleaved: copy them out (raw values) + var ia = fg.attributes[an]; + if (!ia.isInterleavedBufferAttribute) continue; + var Ctor = ia.data.array.constructor, da = new Ctor(ia.count * ia.itemSize), gets = ['getX', 'getY', 'getZ', 'getW']; + for (var vi = 0; vi < ia.count; vi++) for (var ci_ = 0; ci_ < ia.itemSize; ci_++) da[vi * ia.itemSize + ci_] = ia[gets[ci_]](vi); + fg.setAttribute(an, new T.BufferAttribute(da, ia.itemSize, ia.normalized)); + } + var pos = fg.attributes.position, n0 = pos.count, key = {}, wid = new Int32Array(n0); + for (var i = 0; i < n0; i++) { var kk = pos.getX(i) + ',' + pos.getY(i) + ',' + pos.getZ(i); if (key[kk] == null) key[kk] = i; wid[i] = key[kk]; } + function ek(a, b) { a = wid[a]; b = wid[b]; return a < b ? a + '_' + b : b + '_' + a; } + var full = {}, kept = {}, t, e, a, b, c; + for (t = 0; t < tri; t += 3) { + a = idx ? idx[t] : t; b = idx ? idx[t + 1] : t + 1; c = idx ? idx[t + 2] : t + 2; + [[a, b], [b, c], [c, a]].forEach(function (p) { var k = ek(p[0], p[1]); full[k] = (full[k] || 0) + 1; }); + } + for (t = 0; t < out.length; t += 3) { + a = out[t]; b = out[t + 1]; c = out[t + 2]; + [[a, b], [b, c], [c, a]].forEach(function (p) { var k = ek(p[0], p[1]); (kept[k] = kept[k] || []).push(p); }); + } + var next = {}; // rim edge a->b of a kept triangle: the cap runs b->a + for (e in kept) if (kept[e].length === 1 && full[e] >= 2) { var p = kept[e][0]; next[wid[p[1]]] = p[0]; } + var seen = {}, loops = []; + Object.keys(next).forEach(function (s) { + if (seen[s]) return; + var loop = [], v = +s, guard = 0; + while (v != null && !seen[v] && guard++ < 4000) { seen[v] = 1; loop.push(v); var nv = next[v]; v = nv == null ? null : wid[nv]; } + if (loop.length >= 3 && v === +s) loops.push(loop); + }); + fg.userData.cap = { rim: Object.keys(next).length, loops: loops.length, sizes: loops.map(function (l) { return l.length; }) }; + if (!loops.length) return; + // the cap gets its own copies of the rim vertices (same skinning) with one flat UV and the cap's normal, so it + // reads as plain shadowed cloth instead of the rim's texture smeared to a point + var names = Object.keys(fg.attributes), add = 0; + loops.forEach(function (l) { add += l.length + 1; }); + names.forEach(function (nm) { // grow every attribute + var at = fg.attributes[nm], arr = new at.array.constructor((n0 + add) * at.itemSize); + arr.set(at.array); fg.setAttribute(nm, new T.BufferAttribute(arr, at.itemSize, at.normalized)); + }); + var base = n0; + loops.forEach(function (loop) { + var P = fg.attributes.position, N = fg.attributes.normal, UV = fg.attributes.uv, m = loop.length, ci = base + m, src = loop[0]; + var cx = 0, cy = 0, cz = 0, nx = 0, ny = 0, nz = 0, j, k; + for (j = 0; j <= m; j++) { + var from = j < m ? loop[j] : src, to = base + j; + names.forEach(function (nm) { var at = fg.attributes[nm]; for (k = 0; k < at.itemSize; k++) at.array[to * at.itemSize + k] = at.array[from * at.itemSize + k]; }); + if (UV) UV.setXY(to, UV.getX(src), UV.getY(src)); + } + loop.forEach(function (v) { cx += P.getX(v); cy += P.getY(v); cz += P.getZ(v); }); + cx /= m; cy /= m; cz /= m; + P.setXYZ(ci, cx, cy, cz); + for (j = 0; j < m; j++) { // the loop already runs opposite to the rim: faces A->B->centre + var A = base + j, B = base + (j + 1) % m; + var ax = P.getX(A) - cx, ay = P.getY(A) - cy, az = P.getZ(A) - cz, bx = P.getX(B) - cx, by = P.getY(B) - cy, bz = P.getZ(B) - cz; + nx += ay * bz - az * by; ny += az * bx - ax * bz; nz += ax * by - ay * bx; + out.push(A, B, ci); + } + var l = Math.sqrt(nx * nx + ny * ny + nz * nz) || 1; + if (N) { + var sc = !N.normalized ? 0 : N.array instanceof Int8Array ? 127 : N.array instanceof Int16Array ? 32767 : 0; + for (j = 0; j <= m; j++) { + if (sc) N.setXYZ(base + j, Math.round(nx / l * sc), Math.round(ny / l * sc), Math.round(nz / l * sc)); + else N.setXYZ(base + j, nx / l, ny / l, nz / l); + } + } + base += m + 1; + }); + } + function shadowOnly(m) { + if (!m.userData.shadowMat) { + var sm = m.material.clone(); sm.colorWrite = false; sm.depthWrite = false; sm.transparent = false; + m.userData.shadowMat = sm; + } + return m.userData.shadowMat; + } + AP.setFirstPerson = function (on) { + on = !!on; + if (this.fb || on === !!this.fpOn) return this; + this.fpOn = on; + var self = this; + this.meshes.forEach(function (m) { + var body = /^(Hero|Ally)$/.test(meshName(m)); // eyes, hair, brows, lashes and anything else: shadow only + if (on) { + if (body && m.isSkinnedMesh) { + if (!m.userData.fpShadow) { + var c = new T.SkinnedMesh(m.geometry, shadowOnly(m)); c.bind(m.skeleton, m.bindMatrix); + c.castShadow = true; c.receiveShadow = false; c.frustumCulled = false; c.name = m.name + '_fpShadow'; + m.parent.add(c); m.userData.fpShadow = c; + } + m.userData.fullGeom = m.geometry; m.geometry = fpGeometry(m); m.castShadow = false; + if (m.geometry.groups.length) { // the cap over the cut reads as the shadowed inside of the collar + if (!m.userData.capMat) { var cm = m.material.clone(); cm.color.multiplyScalar(0.18); cm.normalMap = null; m.userData.capMat = cm; } + m.userData.bodyMat = m.material; m.material = [m.material, m.userData.capMat]; + } + m.userData.fpShadow.visible = true; + } else { + m.userData.fullMat = m.material; m.material = shadowOnly(m); + } + } else { + if (m.userData.fullGeom) { m.geometry = m.userData.fullGeom; m.castShadow = true; if (m.userData.fpShadow) m.userData.fpShadow.visible = false; } + if (m.userData.bodyMat) { m.material = m.userData.bodyMat; m.userData.bodyMat = null; } + if (m.userData.fullMat) { m.material = m.userData.fullMat; m.userData.fullMat = null; } + } + }); + // the weapon in the hands: the viewmodel shows it; keep only its shadow + this.attached.forEach(function (a) { + if (a.socket !== 'handR' && a.socket !== 'handL') return; + a.obj.traverse(function (o) { + if (!o.isMesh) return; + if (on) { o.userData.fullMat = o.material; o.material = shadowOnly(o); } + else if (o.userData.fullMat) { o.material = o.userData.fullMat; o.userData.fullMat = null; } + }); + }); + // full-detail meshes only (no LOD switch on the player's own body) + if (on) { this.lodLevel = 0; this.meshes.forEach(function (m) { m.visible = true; }); this.lods.forEach(function (m) { m.visible = false; }); } + return this; + }; + + AP.setVisible = function (b) { this.root.visible = !!b; return this; }; + AP.attach = function (obj, socket) { + socket = socket || 'handR'; + var bn = SOCKET[socket] || socket, bone = this.bone(bn) || this.bone('hand_r'); + if (!bone) return this; + this.detach(obj); + bone.add(obj); + var grip = socket === 'handL' ? (obj.userData.gripL || obj.userData.gripR) : obj.userData.gripR; + if ((socket === 'handR' || socket === 'handL') && grip) { + // weapon placed so its grip frame coincides with the hand bone + grip.updateMatrix(); + var GM = grip.matrix.clone(); + var inv = GM.invert(); + inv.decompose(obj.position, obj.quaternion, obj.scale); + obj.userData._ap = obj.position.clone(); obj.userData._aq = obj.quaternion.clone(); + } else if (socket === 'back' || socket === 'sling' || socket === 'hip') { + // carry pose defined in the bind-pose character frame, converted into the bone's frame + var rest = this._restWorld(bn); + var m = new T.Matrix4().copy(rest).invert().multiply(carryMatrix(socket, obj)); + m.decompose(obj.position, obj.quaternion, obj.scale); + } else { + obj.position.set(0, 0, 0); obj.quaternion.identity(); + } + this.attached.push({ obj: obj, socket: socket }); + if (socket === 'handR') this.held = obj; + // pose at once with the weapon in its grip (hold layer, fingers and left hand at full weight), so an actor that + // is spawned and armed in the same frame is never drawn in the bind pose or with the weapon floating + if (socket === 'handR' && !this.fb) { this._snap = true; this.update(0); this._snap = false; } + // reduced weapon model for characters other than the player beyond IV.weaponLodDistance (see update) + if (socket === 'handR' && !obj.userData.lodTwin && WTEMPLATES[obj.userData.kind + 'Lod'] && WTEMPLATES[obj.userData.kind]) { + var tw = IV.weapon(obj.userData.kind, { lod: true }); + tw.visible = false; tw.userData.isLodTwin = true; obj.add(tw); obj.userData.lodTwin = tw; obj.userData.lodOn = false; + } + return this; + }; + AP._restWorld = function (bn) { + // bone's bind-pose matrix in the actor frame, from the skeleton's inverse bind matrices + var sk = this.meshes[0].skeleton, i = sk.bones.indexOf(this.bones[bn]); + var m = new T.Matrix4(); + if (i >= 0) m.copy(sk.boneInverses[i]).invert(); + return m; + }; + AP.detach = function (obj) { + if (obj.parent) obj.parent.remove(obj); + this.attached = this.attached.filter(function (a) { return a.obj !== obj; }); + if (this.held === obj) this.held = null; + return this; + }; + AP.update = function (dt) { + if (this.fb) return FB.update(this, dt); + dt = Math.min(dt || 0, 0.1); + // far actors: LOD mesh and update every other frame + var far = 0; + if (IV.camera && this.root.parent) { + worldPos(this.root, _v1); + far = _v1.distanceTo(IV.camera.position); + // three levels with 10 % hysteresis: full -> mid at IV.lodDistances[0], mid -> far at [1] (the hair goes at mid) + var D = IV.lodDistances || [IV.lodDistance * 0.55, IV.lodDistance * 1.4], cur = this.lodLevel || 0, lod = cur; + if (this.lods.length && !this.fpOn) { + if (cur < 2 && far > D[1] * 1.05) lod = 2; else if (cur < 1 && far > D[0] * 1.05) lod = 1; + else if (cur > 1 && far < D[1] * 0.95) lod = far > D[0] * 0.95 ? 1 : 0; else if (cur > 0 && far < D[0] * 0.95) lod = 0; + } + if (lod !== cur) { + this.lodLevel = lod; + this.meshes.forEach(function (m) { m.visible = !lod; }); + this.lods.forEach(function (m) { m.visible = m.userData.lod === lod; }); + } + } + // weapon in hand: full model for the player, the reduced one for others beyond a few metres + var hw = this.held && this.held.userData.lodTwin; + if (hw) { + var wl = this.kind !== 'hero' && IV.camera && far > (IV.weaponLodDistance || 6); + if (wl !== this.held.userData.lodOn) { + this.held.userData.lodOn = wl; hw.visible = wl; + this.held.children.forEach(function (c) { if (c !== hw && c.isMesh) c.visible = !wl; c !== hw && c.traverse && c.traverse(function (m) { if (m.isMesh && m !== c) m.visible = !wl; }); }); + } + } + this._frame++; + this._acc += dt; + if (far > IV.throttleDistance && (this._frame & 1)) return this; + dt = this._acc; this._acc = 0; + // automatic weapon hold when nothing is layered on top + var held = this.held, autoName = null; + if (held && (!this.curUpper || this._autoUpper)) { + var cn = this.cur && this.cur.w > 0.5 ? this.cur.name : ''; + var needs = !/^(aim|crouchAim|prone|death|takedown|vault|sit|salute|throw|melee|hit|stagger|reload|bolt|fire|sprintRifle|stackUp|breach|signal|wallLean|limp|alert)/.test(cn); + var pistol = held.userData.kind === 'pistol'; + if (this.driven && !cn) { + var st = this.ds; + needs = st.stance !== 'prone' && this._stW.prone < 0.5; + this._upperFade = 0.2; + if (needs && st.aiming) autoName = pistol ? 'aimPistol' : 'aimIdle'; + else if (needs && !pistol && this._sprintW > 0.5) autoName = 'sprintRifle'; + } + if (!autoName) autoName = needs ? (held.userData.long ? 'holdRifle' : (pistol ? 'holdPistol' : null)) : null; + if (autoName && !clipName(autoName)) autoName = null; + // the rifle travels furthest between the sprint carry and the shoulder: give that swap the longest fade + var swapF = (this.curUpper && this.curUpper.name === 'sprintRifle') || autoName === 'sprintRifle' ? 0.38 : (this._upperFade || 0.2); + if (autoName && (!this.curUpper || this.curUpper.name !== autoName)) this.setUpper(autoName, { auto: true, fade: this._snap ? 0 : swapF }); + if (!autoName && this._autoUpper && this.curUpper) this.setUpper(null); + } + // weights + var U = 0, i, e; + for (i = 0; i < this.upper.length; i++) { + e = this.upper[i]; + e.w += Math.sign(e.target - e.w) * Math.min(Math.abs(e.target - e.w), e.rate * dt); + U += e.w; + } + U = Math.min(1, U); + for (i = 0; i < this.upper.length; i++) this.upper[i].action.setEffectiveWeight(this.upper[i].w); + this.upper = this.upper.filter(function (u) { if (u.w <= 0 && u.target === 0) { u.action.stop(); return false; } return true; }); + var baseTot = 0; + for (i = 0; i < this.base.length; i++) { + e = this.base[i]; + e.w += Math.sign(e.target - e.w) * Math.min(Math.abs(e.target - e.w), e.rate * dt); + e.full.setEffectiveWeight(e.w * (1 - U)); + e.lower.setEffectiveWeight(e.w * U); + baseTot += e.w; + } + if (this.driven) this._graph(dt, Math.max(0, 1 - baseTot), U); + this.base = this.base.filter(function (b) { if (b.w <= 0 && b.target === 0) { b.full.stop(); b.lower.stop(); return false; } return true; }); + // three.js only writes a bone when the mixed value differs from last frame's, so a bone whose clip value is + // steady (a held aim pose) would keep last frame's post-process edits (lean, IK, aim offset) and accumulate them. + // Marking the previous-frame slot as unknown makes every bound property be written again each update. + var bs = this.mixer._bindings, ai = this.mixer._accuIndex; + if (bs && ai != null) for (i = 0; i < bs.length; i++) { var pm = bs[i]; if (pm.buffer) pm.buffer[(ai + 1) * pm.valueSize] = NaN; } + this.mixer.update(dt); + for (i = 0; i < this.base.length; i++) { e = this.base[i]; e.lower.time = e.full.time; } + if (this.driven) for (var gk in this.gr) { e = this.gr[gk]; e.lower.time = e.full.time; } + this.root.updateMatrixWorld(true); + // aim offset over spine, neck and head + var k = 1 - Math.exp(-dt * 14); + this.aimP += (this.aimPT - this.aimP) * k; this.aimY += (this.aimYT - this.aimY) * k; + if (Math.abs(this.aimP) > 1e-4 || Math.abs(this.aimY) > 1e-4) this._applyAim(); + if (this.driven) this._post(dt, far); else this._flinch(dt); + if (!(this.cur && /^death|takedownVictim/.test(this.cur.name))) this._blinkUpdate(dt, far); else this.setMorph('blink', 1); + this._grips(dt, held); + this._parts(held); + // left hand onto the fore-end + var want = 0; + if (held && held.userData.gripL && held.userData.long !== undefined) { + var on = (this.curUpper && TWO_HAND[this.curUpper.name]) || (!this.curUpper && this.cur && TWO_HAND[this.cur.name]); + want = on ? 1 : 0; + if (this.leftHandIK != null) want = this.leftHandIK; + } + this._lhW = this._snap ? want : approach(this._lhW, want, 5, dt); + if (this._lhW > 0.01 && held) { + held.userData.gripL.updateMatrixWorld(true); + var tp = worldPos(held.userData.gripL, new T.Vector3()), tq = worldQuat(held.userData.gripL, new T.Quaternion()); + // left hand target moved by a per-class offset in the weapon's frame (off the fore-end) + var lcls = GRIPF[GRIPCLASS[held.userData.kind]], loff = lcls && lcls.l.off; + if (loff) tp.add(new T.Vector3(loff[0], loff[1], loff[2]).applyQuaternion(worldQuat(held, new T.Quaternion()))); + this._reachL(tp, this._lhW); + twoBone(this.bones.upperarm_l, this.bones.lowerarm_l, this.bones.hand_l, tp, tq, this._lhW); + } + return this; + }; + // left-arm reach: when the fore-grip is further than the arm can stretch, bring the shoulder forward (clavicle, + // so the hand can close on the grip instead of stopping short of it + AP._reachL = function (tp, w) { + var b = this.bones, cl = b.clavicle_l, ua = b.upperarm_l, la = b.lowerarm_l, h = b.hand_l; + if (!cl || !ua || !la || !h) return; + var S = worldPos(ua, new T.Vector3()), E = worldPos(la, new T.Vector3()), W = worldPos(h, new T.Vector3()); + var reach = (S.distanceTo(E) + E.distanceTo(W)) * 0.995, q = new T.Quaternion(), used = 0; + for (var it = 0; it < 3; it++) { + S = worldPos(ua, S); + var d = S.distanceTo(tp) - reach; + if (d <= 0.001) break; + // clavicle: swing the shoulder joint toward the target, up to about 25 degrees in all + var C = worldPos(cl, new T.Vector3()), a0 = S.clone().sub(C), want = tp.clone().sub(C); + var ang = Math.min(0.6 - used, d / Math.max(a0.length(), 0.05)); + var axis = new T.Vector3().crossVectors(a0, want); + if (ang <= 0 || axis.lengthSq() < 1e-10) break; + used += ang; q.setFromAxisAngle(axis.normalize(), ang * w); rotWorld(cl, q); + } + this.root.updateMatrixWorld(true); + }; + // ---------------- driven locomotion graph (actor.drive) ---------------- + var DIRS = [['F', 0], ['FL', 45], ['L', 90], ['BL', 135], ['B', 180], ['BR', -135], ['R', -90], ['FR', -45]]; + var SPEED = { walk: 1.5, jog: 3.8, sprint: 6.4, crouch: 1.3, prone: 0.6 }; + function ease01(x) { x = Math.max(0, Math.min(1, x)); return x * x * (3 - 2 * x); } + function approach(v, t, rate, dt) { return v + Math.sign(t - v) * Math.min(Math.abs(t - v), rate * dt); } + AP.drive = function (st) { + if (this.fb) { FB.play(this, (st.speed || 0) > 0.3 ? (st.stance === 'crouch' ? 'crouchWalk' : (st.speed > 3 ? 'run' : 'walk')) : 'idle'); return this; } + if (!this.driven) { + this.driven = true; this.gr = {}; this.phase = 0; this._move = 0; this._stW = { stand: 1, crouch: 0, prone: 0 }; + this._sprintW = 0; this._turnW = 0; this._lean = 0; this._pitchLean = 0; this._lastSpeed = 0; this._acc = 0; this._t = 0; + this._dirA = 0; this._tier = 0; this._pelDrop = 0; + for (var i = 0; i < this.base.length; i++) { this.base[i].target = 0; this.base[i].rate = 1 / 0.3; } + this.cur = null; + } + this.ds = st; + if (st.aimPitch != null || st.aimYawOffset != null) this.setAim(st.aimPitch || 0, st.aimYawOffset || 0); + return this; + }; + AP.undrive = function () { this.driven = false; for (var k in this.gr) { this.gr[k].full.stop(); this.gr[k].lower.stop(); } this.gr = {}; return this; }; + var GCLIPS = {}, GLOWER = {}; + AP._gEntry = function (name) { + var e = this.gr[name]; + if (e) return e; + var c = clipName(name); if (!c) return null; + // the graph plays its own copies of the clips: three.js shares one action per clip, so using CLIPS[c] here would + // let play()/stop() on the same clip (the spawn idle, a one-shot) stop or reweight a graph entry mid-blend + if (!GCLIPS[c]) { GCLIPS[c] = CLIPS[c].clone(); GCLIPS[c].name = c + '#g'; GLOWER[c] = LOWER[c].clone(); GLOWER[c].name = c + '#gl'; } + var full = this._action(GCLIPS[c], null), lower = this._action(GLOWER[c], null); + [full, lower].forEach(function (a) { a.enabled = true; a.setLoop(T.LoopRepeat, Infinity); a.setEffectiveWeight(0); a.play(); }); + var m = META[c] || {}; + e = this.gr[name] = { full: full, lower: lower, w: 0, tw: 0, loco: !!m.stride || /turnStep|proneCrawl/.test(name), meta: m, dur: CLIPS[c].duration }; + return e; + }; + AP._graph = function (dt, scale, U) { + var st = this.ds, i, k, e; + var vx = st.vx || 0, vz = st.vz || 0, speed = Math.hypot(vx, vz); + var stance = st.stance || 'stand'; + // stance super-state weights, eased (~0.25 s) + // going down to or up from prone takes longer (about 0.6 s) than stand <-> crouch (0.25 s) + var stRate = stance === 'prone' || this._stW.prone > 0.01 ? 1.6 : 4; + for (k in this._stW) this._stW[k] = approach(this._stW[k], k === stance ? 1 : 0, stRate, dt); + var sw = this._stW, swSum = sw.stand + sw.crouch + sw.prone || 1; + // moving weight follows the speed: the stepping clips are blended with the stance idle at about speed / clip speed + // while the phase keeps the clips' own cadence (below), so a planted foot moves with the ground during starts, + // stops and slow walking instead of skating + var wantMove = speed > 0.08 ? 1 : 0; + // direction flips (over ~100 degrees): keep the old blend direction while the body slows, plant, and swap the + // direction only once nearly still, so opposing directions are never blended at speed + var aNow = Math.atan2(vx, vz) * 180 / Math.PI, dFlip = Math.abs(((aNow - this._dirA + 540) % 360) - 180); + if (speed > 0.08 && dFlip > 100 && this._move > 0.1) this._pivot = true; + if (this._pivot && (speed < 0.3 || this._move <= 0.1)) { this._dirA = aNow; this._pivot = false; } + var vRef = this._vRef || 1.5; + var mvT = wantMove && !this._pivot ? Math.min(1, speed / (0.8 * vRef)) : 0; + // starting from (nearly) still: re-seat the phase at the nearest foot contact (both feet down), so the first + // step starts from double support instead of mid-swing; the pose is idle here, so the jump is not visible + if (this._move < 0.04 && mvT > 0) this.phase = (Math.round(this.phase * 2) / 2) % 1; + this._move = approach(this._move, mvT, 5, dt); + var mv = this._move; + // direction (local: +x left, +z forward) and speed tier + if (speed > 0.05 && !this._pivot) { + var a = Math.atan2(vx, vz) * 180 / Math.PI, da = ((a - this._dirA + 540) % 360) - 180; + this._dirA += da * (1 - Math.exp(-dt / 0.18)); + } + var dirA = ((this._dirA + 540) % 360) - 180; + // walk or jog: the game scales speeds by direction (strafe 85 %, back 70 %), so judge the tier against this + // direction's own walk speed; a narrow walk->jog band (1.45-1.7x walk) keeps one gait at a time, played a + // little faster or slower, instead of mixing two cadences (which skates the planted foot) + var d2 = vx * vx + vz * vz, dirF = d2 > 1e-6 ? (vx * vx * 0.85 + vz * vz * (vz > 0 ? 1 : 0.7)) / d2 : 1; + var wv = SPEED.walk * dirF; + var tierT = Math.max(0, Math.min(1, (speed - wv * 1.45) / (wv * 0.25))); + this._tier = approach(this._tier, tierT, 4, dt); + var fwdish = Math.abs(dirA) < 35; + this._sprintW = approach(this._sprintW, st.sprinting && fwdish && speed > SPEED.jog * 0.9 && stance === 'stand' ? 1 : 0, 4, dt); + var turnWant = speed < 0.15 && Math.abs(st.yawRate || 0) > 0.9 && stance !== 'prone' ? 1 : 0; + this._turnW = approach(this._turnW, turnWant, 5, dt); + // two nearest of the eight directions + var ia = 0, ib = 0, fb = 0; + for (i = 0; i < 8; i++) { + var d0 = DIRS[i][1], d1 = DIRS[(i + 1) % 8][1]; + var span = ((d1 - d0 + 540) % 360) - 180, off = ((dirA - d0 + 540) % 360) - 180; + if (span < 0 ? (off <= 0 && off >= span) : (off >= 0 && off <= span)) { ia = i; ib = (i + 1) % 8; fb = off / span; break; } + } + var tw = {}; + function add(n, w) { if (w > 1e-4) tw[n] = (tw[n] || 0) + w; } + var idleW = 1 - mv; + var sStand = sw.stand / swSum, sCrouch = sw.crouch / swSum, sProne = sw.prone / swSum; + add(this._turnW > 0.01 ? 'turnStep' : 'idle', sStand * idleW * Math.max(this._turnW, 0) ); + add('idle', sStand * idleW * (1 - this._turnW)); + add(this._turnW > 0.01 ? 'crouchTurnStep' : 'crouchIdle', sCrouch * idleW * this._turnW); + add('crouchIdle', sCrouch * idleW * (1 - this._turnW)); + add(st.aiming ? 'proneAim' : 'proneIdle', sProne * idleW); // prone and aiming: elbows down, rifle level + add('proneCrawl', sProne * mv); + var dA = DIRS[ia][0], dB = DIRS[ib][0]; + var walkW = (1 - this._tier) * (1 - this._sprintW), jogW = this._tier * (1 - this._sprintW); + add('walk' + dA, sStand * mv * walkW * (1 - fb)); add('walk' + dB, sStand * mv * walkW * fb); + add('jog' + dA, sStand * mv * jogW * (1 - fb)); add('jog' + dB, sStand * mv * jogW * fb); + add('sprintF', sStand * mv * this._sprintW); + add('crouch' + dA, sCrouch * mv * (1 - fb)); add('crouch' + dB, sCrouch * mv * fb); + // ease every graph weight toward its target, then renormalise so the total is exactly one (no blend toward the bind pose) + for (k in tw) this._gEntry(k); + var tot = 0; + var chg = 0; + for (k in this.gr) { e = this.gr[k]; var w0 = e.w; e.w = approach(e.w, tw[k] || 0, 6, dt); chg += Math.abs(e.w - w0); tot += e.w; } + // how fast the blend is changing (0 in steady locomotion): the planted-foot lock only works while this is high, + // which is when a weight change would otherwise drag a planted foot (sharp stops, direction flips, stance changes) + var lockT = this._pivot ? 1 : Math.max(0, Math.min(1, (chg / Math.max(dt, 1e-3) - 0.8) / 2)); + this._lockK = approach(this._lockK || 0, lockT, lockT > (this._lockK || 0) ? 8 : 4, dt); + var strideW = 0, strideSum = 0, speedSum = 0; + for (k in this.gr) { + e = this.gr[k]; + var w = tot > 0 ? e.w / tot : 0; + e.full.setEffectiveWeight(w * scale * (1 - U)); e.lower.setEffectiveWeight(w * scale * U); + if (e.loco && e.meta.stride) { strideSum += w * e.meta.stride; strideW += w; speedSum += w * (e.meta.speed || 1.5); } + } + if (strideW > 0.05) this._vRef = speedSum / strideW; + // one shared phase. The blended pose moves a planted foot by sum(w * stride) per cycle (idle adds nothing), so the + // phase advances by speed / that; capped at 1.3x the clips' own cadence when the move weight lags behind the speed + var prev = this.phase; + if (strideW > 0.01) { + var natural = speedSum / strideSum; // cycles per second at the clips' own speed + this.phase += Math.min(speed / Math.max(strideSum, 1e-3), natural * 1.6) * dt; + } else if (this._turnW > 0.05) this.phase += dt / 0.9; + if (sProne > 0.5 && speed > 0.05) this.phase += dt * speed / 0.6 * 0.0; // crawl uses its own clock (below) + this.phase %= 1; + for (k in this.gr) { + e = this.gr[k]; + if (e.loco) { e.full.timeScale = 0; e.full.time = this.phase * e.dur; } + if (k === 'proneCrawl') { e.full.timeScale = 0; e.full.time = (this.phase) * e.dur; } + } + // foot contact events from phase windows (left at 0, right at 0.5) + if (this.onFoot && mv > 0.3 && sProne < 0.5) { + var crossed = function (p0, p1, c) { return p0 <= p1 ? (c > p0 && c <= p1) : (c > p0 || c <= p1); }; + var str = Math.min(1, 0.25 + speed / SPEED.sprint); + if (crossed(prev, this.phase, 0.0001)) try { this.onFoot('l', str); } catch (er) {} + if (crossed(prev, this.phase, 0.5)) try { this.onFoot('r', str); } catch (er) {} + } + // remove dead entries + for (k in this.gr) { e = this.gr[k]; if (e.w <= 0 && !tw[k]) { e.full.stop(); e.lower.stop(); delete this.gr[k]; } } + // lean: roll into turns, pitch into acceleration + var accel = (speed - this._lastSpeed) / Math.max(dt, 1e-3); + // stopping: from the moment the body is nearly stopped, the feet that are on the ground stay where they are and + // any that ended up away from the idle stance is brought in by a small lifted settle step (see _stopFeet) + var decel = (this._lastSpeed - speed) / Math.max(dt, 1e-3); + if (!this._stop && this._move > 0.15 && stance !== 'prone' && ((speed < 0.45 && speed <= this._lastSpeed) || (decel > 4 && speed < this._lastSpeed * 0.93))) this._stop = { t: 0, init: false }; + if (this._stop && (stance === 'prone' || (speed > this._lastSpeed + 0.01 && speed > 0.2))) { this._stop = null; this._lock = null; } + this._lastSpeed = speed; + this._lean += (Math.max(-0.14, Math.min(0.14, -(st.yawRate || 0) * speed * 0.035)) - this._lean) * Math.min(1, dt * 6); + this._pitchLean += (Math.max(-0.06, Math.min(0.06, accel * 0.012)) - this._pitchLean) * Math.min(1, dt * 5); + this._t += dt; + }; + // additive hit flinch (no physics): dir = world direction the bullet travels, part = 'head'|'chest'|'arm_l'|'arm_r'|'leg' + AP.flinch = function (dir, part, strength) { + var rq = worldQuat(this.root, new T.Quaternion()).invert(); + var d = (dir ? dir.clone() : new T.Vector3(0, 0, -1)).applyQuaternion(rq); d.y = 0; if (d.lengthSq() < 1e-6) d.set(0, 0, -1); d.normalize(); + this._fl = { t: 0, d: d, part: part || 'chest', k: strength == null ? 1 : strength }; + return this; + }; + AP._flinch = function (dt) { + var f = this._fl; if (!f) return; + f.t += dt; var T1 = 0.45; if (f.t > T1) { this._fl = null; return; } + // fast hit, damped spring back + var x = f.t / T1, a = Math.sin(Math.min(1, f.t / 0.06) * Math.PI / 2) * Math.exp(-x * 4) * f.k; + var rq = worldQuat(this.root, new T.Quaternion()); + var up = new T.Vector3(0, 1, 0).applyQuaternion(rq); + // bend away from the shot: rotate about the axis perpendicular to the shot direction + var axis = new T.Vector3().crossVectors(up, f.d.clone().applyQuaternion(rq)).normalize(); + var q = new T.Quaternion(), b = this.bones; + var map = { head: [['neck_01', 0.25], ['Head', 0.45], ['spine_03', 0.08]], chest: [['spine_02', 0.18], ['spine_03', 0.22], ['Head', 0.1]], + arm_l: [['clavicle_l', 0.35], ['upperarm_l', 0.3], ['spine_03', 0.08]], arm_r: [['clavicle_r', 0.35], ['upperarm_r', 0.3], ['spine_03', 0.08]], + leg: [['pelvis', 0.08], ['spine_01', 0.1], ['thigh_l', 0.1], ['thigh_r', 0.1]] }[f.part] || [['spine_03', 0.2]]; + for (var i = 0; i < map.length; i++) { var bn = b[map[i][0]]; if (!bn) continue; q.setFromAxisAngle(axis, a * map[i][1]); rotWorld(bn, q); } + }; + AP._post = function (dt, far) { + this._flinch(dt); + var b = this.bones, q = new T.Quaternion(); + var rq = worldQuat(this.root, new T.Quaternion()); + var fwd = new T.Vector3(0, 0, 1).applyQuaternion(rq), left = new T.Vector3(1, 0, 0).applyQuaternion(rq); + // lean (spine) and breathing (additive, small) + if (b.spine_01) { + q.setFromAxisAngle(fwd, this._lean * 0.5); rotWorld(b.spine_01, q); + q.setFromAxisAngle(left, this._pitchLean * 0.5); rotWorld(b.spine_01, q); + q.setFromAxisAngle(fwd, this._lean * 0.5); rotWorld(b.spine_02, q); + var br = Math.sin(this._t * 2 * Math.PI / 3.6) * 0.012 * (1 - Math.min(1, this._move)); + q.setFromAxisAngle(left, -br); rotWorld(b.spine_03, q); + } + // foot IK with pelvis drop against actor.groundAt(x, z) (if the game provides it), near the camera only + // foot IK fades out (not off in one frame) as the body goes down to prone + var ikW = Math.max(0, Math.min(1, 1 - this._stW.prone * 1.6)), ikOK = far < (IV.footIKDistance || 25) && ikW > 0.01; + this._ikW = ikW; + if (this.groundAt && ikOK) this._footIK(dt); + if (ikOK && this._stop) this._stopFeet(dt, fwd); + else if (ikOK && IV.footLock !== false && far < (IV.footLockDistance || 12)) this._footLock(dt); // transitions only (see _lockK) + }; + // planted-foot lock: while a foot is in its contact window (from the shared phase) it stays where it landed, + // so direction changes and turns do not skate it; eased in and out at the window edges + var LOCKW = { l: [0.0, 0.30], r: [0.5, 0.80] }; + // analytic two-bone leg IK with an explicit knee pole (the pelvis forward), so the knee can never flip + function legIK(thigh, calf, foot, target, pole, w) { + var fq = worldQuat(foot, new T.Quaternion()); + var A = worldPos(thigh, new T.Vector3()), B = worldPos(calf, new T.Vector3()), C = worldPos(foot, new T.Vector3()); + var l1 = A.distanceTo(B), l2 = B.distanceTo(C); + var tgt = C.clone().lerp(target, w); + var d = tgt.clone().sub(A), dist = Math.min(d.length(), (l1 + l2) * 0.985); d.normalize(); + tgt.copy(A).addScaledVector(d, dist); + var cosA = Math.max(-1, Math.min(1, (l1 * l1 + dist * dist - l2 * l2) / (2 * l1 * dist))), sinA = Math.sqrt(1 - cosA * cosA); + var pv = pole.clone().addScaledVector(d, -pole.dot(d)); if (pv.lengthSq() < 1e-8) return; pv.normalize(); + var K = A.clone().addScaledVector(d, cosA * l1).addScaledVector(pv, sinA * l1); + var q = new T.Quaternion(); + q.setFromUnitVectors(B.clone().sub(A).normalize(), K.clone().sub(A).normalize()); rotWorld(thigh, q); + var C2 = worldPos(foot, new T.Vector3()), K2 = worldPos(calf, new T.Vector3()); + q.setFromUnitVectors(C2.sub(K2).normalize(), tgt.clone().sub(K2).normalize()); rotWorld(calf, q); + setWorldQuat(foot, fq); + } + // planted-foot lock: while a foot is in its contact window (shared phase) it keeps the ground point where it landed, + // so blend direction changes do not skate it; eased in and out at the window edges, reach capped, knee pole fixed + var LOCKW = { l: [0.0, 0.30], r: [0.5, 0.80] }; + AP._footLock = function (dt) { + // While the blend is changing (this._lockK), a foot in stance keeps the ground point where it landed. When it + // lifts off, the offset between the locked and the animated foot is carried into the swing and eased out there, + // so the foot never jumps back while it bears weight. + var b = this.bones, m = this._lockK || 0; + if (!this._lock) this._lock = { l: { L: null, off: new T.Vector3(), w: 0 }, r: { L: null, off: new T.Vector3(), w: 0 } }; + var rq = worldQuat(this.root, new T.Quaternion()), fwd = new T.Vector3(0, 0, 1).applyQuaternion(rq); + var v = this._vRef || 1.5, stance = v < 2 ? 0.58 : (v > 3.5 ? 0.26 : 0.58 - (v - 2) / 1.5 * 0.32); + for (var i = 0; i < 2; i++) { + var s = i ? 'r' : 'l', st = this._lock[s], foot = b['foot_' + s], ball = b['ball_' + s]; + if (!foot || !ball) continue; + var u = (this.phase - (i ? 0.5 : 0) + 1) % 1; + var bp = worldPos(ball, new T.Vector3()), ap = worldPos(foot, new T.Vector3()); + var inStance = u < stance && this._stW.prone < 0.5; + if (inStance) { + if (!st.L) st.L = bp.clone(); + if (m < 0.02 && st.w < 0.02) { st.L.copy(bp); st.off.set(0, 0, 0); st.w = 0; continue; } + st.w = Math.max(st.w, m); + var sh = new T.Vector3(st.L.x - bp.x, 0, st.L.z - bp.z), sl = sh.length(); + // reach cap: past 30 cm the lock point is pulled along with the body instead of letting go in one frame + if (sl > 0.3) { sh.multiplyScalar(0.3 / sl); st.L.x = bp.x + sh.x; st.L.z = bp.z + sh.z; } + st.off.copy(sh); + if (m < 0.02) st.w = approach(st.w, 0, 4, dt); + } else { + st.L = null; + // swing: ease the carried offset out (about 0.2 s) + st.off.multiplyScalar(Math.exp(-dt / 0.07)); + if (st.off.lengthSq() < 1e-6) { st.w = 0; continue; } + } + if (st.w < 0.01 || st.off.lengthSq() < 1e-6) continue; + var tgt = ap.clone().addScaledVector(st.off, inStance ? 1 : 1); + var hip = worldPos(b['thigh_' + s], new T.Vector3()), knee = worldPos(b['calf_' + s], new T.Vector3()); + var axis = ap.clone().sub(hip).normalize(), kd = knee.clone().sub(hip); + // knee pole: the animated bend plus the body's forward, so a nearly straight leg cannot pick a flipped plane + var pole = kd.addScaledVector(axis, -kd.dot(axis)).addScaledVector(fwd, 0.08); + legIK(b['thigh_' + s], b['calf_' + s], foot, tgt, pole.normalize(), Math.min(1, st.w + (inStance ? 0 : 1))); + } + }; + AP._stopFeet = function (dt, fwd) { + var b = this.bones, S = this._stop, ry = worldPos(this.root, new T.Vector3()).y, i, s; + S.t += dt; + if (!S.init) { + S.init = true; S.f = {}; + for (i = 0; i < 2; i++) { + s = i ? 'r' : 'l'; + var p = worldPos(b['foot_' + s], new T.Vector3()); + // on the ground = ankle within 4 cm of standing height + S.f[s] = { L: p.clone(), planted: p.y - ry < 0.13, step: -1, done: false }; + } + } + var wIn = 1; // the pins start where the feet are, so they can take hold at once + // settle steps once the body has (nearly) reached the idle pose: the foot furthest from its idle spot first + var idle = this._move < 0.08; + for (i = 0; i < 2; i++) { + s = i ? 'r' : 'l'; + var f = S.f[s], foot = b['foot_' + s]; if (f.done) continue; + var A = worldPos(foot, new T.Vector3()); + // a foot that was in the air when the stop began follows its clip until it touches down, then stays there + if (!f.planted) { if (A.y - ry < 0.11) { f.planted = true; f.L.copy(A); } else continue; } + var off = Math.hypot(A.x - f.L.x, A.z - f.L.z); + var other = S.f[i ? 'l' : 'r']; + if (idle && f.step < 0 && off > 0.02 && !(other.step >= 0 && !other.done)) f.step = 0; + // a pinned foot the body has moved away from (the leg would be at full stretch) steps now instead of dragging + if (f.step < 0 && !(other.step >= 0 && !other.done)) { + var H0 = worldPos(b['thigh_' + s], new T.Vector3()), legL = H0.distanceTo(worldPos(b['calf_' + s], new T.Vector3())) + worldPos(b['calf_' + s], new T.Vector3()).distanceTo(A); + if (H0.distanceTo(new T.Vector3(f.L.x, A.y, f.L.z)) > legL * 0.95) f.step = 0; + } + var tgt = f.L.clone(); tgt.y = A.y; + if (f.step >= 0) { + f.step += dt; var u = Math.min(1, f.step / 0.28), e = u * u * (3 - 2 * u); + tgt.set(f.L.x + (A.x - f.L.x) * e, A.y + Math.sin(Math.PI * u) * 0.06, f.L.z + (A.z - f.L.z) * e); + if (u >= 1) { f.done = true; continue; } + } else if (idle && off <= 0.02) { f.done = true; continue; } + var hip = worldPos(b['thigh_' + s], new T.Vector3()), knee = worldPos(b['calf_' + s], new T.Vector3()); + var axis = A.clone().sub(hip).normalize(), kd = knee.clone().sub(hip); + var pole = kd.addScaledVector(axis, -kd.dot(axis)).addScaledVector(fwd, 0.08); + legIK(b['thigh_' + s], b['calf_' + s], foot, tgt, pole.normalize(), wIn); + } + }; + AP._footIK = function (dt) { + var b = this.bones, root = this.root, ry = new T.Vector3().setFromMatrixPosition(root.matrixWorld).y; + var sides = ['l', 'r'], off = {}, pos = {}, i; + for (i = 0; i < 2; i++) { + var s = sides[i], f = b['foot_' + s]; if (!f) return; + var p = worldPos(f, new T.Vector3()); + var g = this.groundAt(p.x, p.z); + pos[s] = p; off[s] = (g == null ? ry : g) - ry; + // ease each foot's ground height (a step edge would otherwise lift the foot in one frame); faster upward + // so a toe never sinks into a step + if (!this._gOff) this._gOff = {}; + var go = this._gOff[s] == null ? off[s] : this._gOff[s]; + go += (off[s] - go) * Math.min(1, dt * (off[s] > go ? 22 : 12)); + this._gOff[s] = go; off[s] = go; + } + var drop = Math.min(0, Math.min(off.l, off.r)) * (this._ikW == null ? 1 : this._ikW); + this._pelDrop += (drop - this._pelDrop) * Math.min(1, dt * 12); + var pel = b.pelvis, wp = worldPos(pel, new T.Vector3()); + wp.y += this._pelDrop; + var inv = new T.Matrix4().copy(pel.parent.matrixWorld).invert(); + pel.position.copy(wp.applyMatrix4(inv)); pel.updateMatrixWorld(true); + for (i = 0; i < 2; i++) { + var s2 = sides[i], foot = b['foot_' + s2]; + var cur = worldPos(foot, new T.Vector3()); + var target = cur.clone(); target.y = pos[s2].y + off[s2]; // animated height above local ground + var fq = worldQuat(foot, new T.Quaternion()); + twoBone(b['thigh_' + s2], b['calf_' + s2], foot, target, fq, this._ikW == null ? 1 : this._ikW); + } + }; + var AIM_P = [['spine_01', 0.15], ['spine_02', 0.2], ['spine_03', 0.35], ['neck_01', 0.12], ['Head', 0.18]]; + var AIM_Y = [['spine_01', 0.18], ['spine_02', 0.22], ['spine_03', 0.3], ['neck_01', 0.12], ['Head', 0.18]]; + AP._applyAim = function () { + var rq = worldQuat(this.root, new T.Quaternion()); + var left = new T.Vector3(1, 0, 0).applyQuaternion(rq), up = new T.Vector3(0, 1, 0).applyQuaternion(rq); + var q = new T.Quaternion(); + // prone: the body lies on its elbows, so the aim can only tilt a little (the clip already holds the rifle level); + // a camera looking down must not bend the lying spine and point the gun into the ground + var pr = this._stW ? this._stW.prone : 0, aY = this.aimY * (1 - 0.6 * pr); + var aP = this.aimP * (1 - pr) + Math.max(-0.2, Math.min(0.25, this.aimP)) * 0.5 * pr; + for (var i = 0; i < AIM_Y.length; i++) { + var b = this.bones[AIM_Y[i][0]]; if (!b) continue; + q.setFromAxisAngle(up, aY * AIM_Y[i][1]); rotWorld(b, q); + } + for (i = 0; i < AIM_P.length; i++) { + b = this.bones[AIM_P[i][0]]; if (!b) continue; + // pitch about the character's current left axis (after yaw) + var l2 = left.clone().applyAxisAngle(up, aY * 0.7); + q.setFromAxisAngle(l2, -aP * AIM_P[i][1]); rotWorld(b, q); + } + }; + AP.dispose = function () { + if (this.fb) return FB.dispose(this); + this.mixer.stopAllAction(); this.mixer.uncacheRoot(this.model); + if (this.root.parent) this.root.parent.remove(this.root); + }; + + IV.spawn = function (kind, opts) { + if (!(kind in KINDS)) kind = 'rifleman'; + var a = new Actor(kind); + if (opts && opts.face != null && !a.fb) a.setFace(opts.face); + return a; + }; + + // ===================================================================================== + // Fallback: a code-made skinned human (lofted limbs on the same 22-bone layout) with procedural motion. + // Used only when the GLB files cannot be loaded, so the game never shows nothing. + // ===================================================================================== + var FB = IV._fallback = (function () { + var J = { // bind-pose joint positions (three.js frame: +X left, +Y up, +Z forward) + pelvis: [0, 1.0, 0.007], spine_01: [0, 1.09, 0.031], spine_02: [0, 1.16, 0.039], spine_03: [0, 1.22, 0.037], neck_01: [0, 1.57, 0.12], + Head: [0, 1.68, 0.14], clavicle_l: [0.024, 1.5, 0.124], upperarm_l: [0.188, 1.5, 0.027], lowerarm_l: [0.456, 1.5, 0.022], + hand_l: [0.728, 1.5, 0.027], thigh_l: [0.113, 1.0, -0.005], calf_l: [0.113, 0.54, -0.009], foot_l: [0.113, 0.086, -0.045], ball_l: [0.113, 0.01, 0.083] + }; + ['clavicle', 'upperarm', 'lowerarm', 'hand', 'thigh', 'calf', 'foot', 'ball'].forEach(function (n) { + var p = J[n + '_l']; J[n + '_r'] = [-p[0], p[1], p[2]]; + }); + var PARENT = { pelvis: null, spine_01: 'pelvis', spine_02: 'spine_01', spine_03: 'spine_02', neck_01: 'spine_03', Head: 'neck_01' }; + ['l', 'r'].forEach(function (s) { + PARENT['clavicle_' + s] = 'spine_03'; PARENT['upperarm_' + s] = 'clavicle_' + s; PARENT['lowerarm_' + s] = 'upperarm_' + s; + PARENT['hand_' + s] = 'lowerarm_' + s; PARENT['thigh_' + s] = 'pelvis'; PARENT['calf_' + s] = 'thigh_' + s; PARENT['foot_' + s] = 'calf_' + s; PARENT['ball_' + s] = 'foot_' + s; + }); + PARENT.weapon_r = 'hand_r'; J.weapon_r = J.hand_r; + var NAMES = Object.keys(PARENT); + // limb segments: [bone, from joint, to joint, radius at start, radius at end] + var SEG = [ + ['pelvis', [0, 0.92, 0.0], [0, 1.1, 0.0], 0.16, 0.15], ['spine_02', [0, 1.1, 0.0], [0, 1.3, 0.0], 0.15, 0.17], + ['spine_03', [0, 1.3, 0.0], [0, 1.52, 0.0], 0.18, 0.15], ['neck_01', [0, 1.52, 0.03], [0, 1.66, 0.05], 0.06, 0.055], + ['Head', [0, 1.62, 0.06], [0, 1.82, 0.06], 0.085, 0.07] + ]; + ['l', 'r'].forEach(function (s) { + var m = s === 'l' ? 1 : -1; + SEG.push(['upperarm_' + s, [m * 0.17, 1.47, 0.02], [m * 0.456, 1.5, 0.022], 0.065, 0.048]); + SEG.push(['lowerarm_' + s, [m * 0.456, 1.5, 0.022], [m * 0.728, 1.5, 0.027], 0.045, 0.034]); + SEG.push(['hand_' + s, [m * 0.728, 1.5, 0.027], [m * 0.85, 1.5, 0.03], 0.033, 0.028]); + SEG.push(['thigh_' + s, [m * 0.11, 1.0, 0.0], [m * 0.113, 0.54, -0.009], 0.095, 0.06]); + SEG.push(['calf_' + s, [m * 0.113, 0.54, -0.009], [m * 0.113, 0.1, -0.04], 0.058, 0.04]); + SEG.push(['foot_' + s, [m * 0.113, 0.06, -0.06], [m * 0.113, 0.03, 0.17], 0.045, 0.04]); + }); + var geo = null, matCache = {}; + function buildGeo() { + var pos = [], nrm = [], idx = [], si = [], sw = [], col = []; + var RING = 12, ROWS = 6; + SEG.forEach(function (s) { + var bi = NAMES.indexOf(s[0]), pi = NAMES.indexOf(PARENT[s[0]] || s[0]); + var a = new T.Vector3().fromArray(s[1]), b = new T.Vector3().fromArray(s[2]); + var ax = b.clone().sub(a), len = ax.length(); ax.normalize(); + var u = Math.abs(ax.y) > 0.9 ? new T.Vector3(1, 0, 0) : new T.Vector3(0, 1, 0); + var v1 = new T.Vector3().crossVectors(ax, u).normalize(), v2 = new T.Vector3().crossVectors(ax, v1).normalize(); + var base = pos.length / 3; + for (var r = 0; r <= ROWS; r++) { + var f = r / ROWS, rad = s[3] + (s[4] - s[3]) * f; + rad *= Math.sin(Math.PI * (0.12 + 0.76 * f)) * 0.25 + 0.8; // rounded ends + var c = a.clone().addScaledVector(ax, len * f); + for (var k = 0; k < RING; k++) { + var th = k / RING * Math.PI * 2, n = v1.clone().multiplyScalar(Math.cos(th)).addScaledVector(v2, Math.sin(th)); + var p = c.clone().addScaledVector(n, rad); + pos.push(p.x, p.y, p.z); nrm.push(n.x, n.y, n.z); + // blend into the parent bone over the first third + var wp = Math.max(0, 0.5 - f * 1.6); + si.push(bi, pi, 0, 0); sw.push(1 - wp, wp, 0, 0); + } + } + for (r = 0; r < ROWS; r++) for (k = 0; k < RING; k++) { + var i0 = base + r * RING + k, i1 = base + r * RING + (k + 1) % RING; + idx.push(i0, i1, i0 + RING, i1, i1 + RING, i0 + RING); + } + }); + var g = new T.BufferGeometry(); + g.setAttribute('position', new T.Float32BufferAttribute(pos, 3)); + g.setAttribute('normal', new T.Float32BufferAttribute(nrm, 3)); + g.setAttribute('skinIndex', new T.Uint16BufferAttribute(si, 4)); + g.setAttribute('skinWeight', new T.Float32BufferAttribute(sw, 4)); + g.setIndex(idx); g.computeVertexNormals(); + g.boundingSphere = new T.Sphere(new T.Vector3(0, 0.9, 0), 1.45); + return g; + } + var COL = { hero: 0x67664a, ally: 0x6a6a4c, rifleman: 0x5f6352, officer: 0x56594c, sniper: 0x65684e, gunner: 0x5f6352 }; + var api = { tris: 0 }; + api.init = function (a, kind) { + if (!geo) { geo = buildGeo(); api.tris = geo.index.count / 3; } + var mat = matCache[kind] || (matCache[kind] = new T.MeshStandardMaterial({ color: new T.Color(COL[kind] || 0x666655).convertSRGBToLinear(), roughness: 0.85, skinning: true })); + var bones = {}, list = []; + NAMES.forEach(function (n) { var b = new T.Bone(); b.name = n; bones[n] = b; list.push(b); }); + NAMES.forEach(function (n) { + var p = PARENT[n], b = bones[n], jp = new T.Vector3().fromArray(J[n]); + if (p) { bones[p].add(b); jp.sub(new T.Vector3().fromArray(J[p])); } + b.position.copy(jp); + }); + var mesh = new T.SkinnedMesh(geo, mat); mesh.castShadow = true; + var root = new T.Group(); root.name = 'IV_' + kind + '_fallback'; + root.add(mesh); mesh.add(bones.pelvis); root.updateMatrixWorld(true); + mesh.bind(new T.Skeleton(list)); + a.root = root; a.bones = bones; a.meshes = [mesh]; a.lods = []; a.t = 0; a.state = 'idle'; a.upperName = null; + a.aimP = a.aimY = 0; a.attached = []; a.height = 1.8; a.speed = 1; a.once = false; a.stateT = 0; + a.rest = {}; NAMES.forEach(function (n) { a.rest[n] = bones[n].quaternion.clone(); }); + }; + api.play = function (a, name, o) { o = o || {}; if (a.state !== name) a.stateT = 0; a.state = name; a.speed = o.speed == null ? 1 : o.speed; a.once = !!(o.once || o.loop === false); return a; }; + api.setUpper = function (a, name) { a.upperName = name; return a; }; + api.bone = function (a, n) { return a.bones[n] || null; }; + var q = new T.Quaternion(), e = new T.Euler(); + function rot(a, n, x, y, z) { var b = a.bones[n]; if (!b) return; e.set(x, y, z); b.quaternion.copy(a.rest[n]).multiply(q.setFromEuler(e)); } + api.update = function (a, dt) { + a.t += dt * a.speed; a.stateT += dt; + var s = a.state, t = a.t, k; + var gait = { walk: [1.9, 0.45], run: [2.8, 0.75], sprint: [3.4, 0.95], crouchWalk: [1.6, 0.4], aimWalk: [1.9, 0.4], limp: [1.5, 0.35] }[s]; + for (var n in a.rest) a.bones[n].quaternion.copy(a.rest[n]); + a.bones.pelvis.position.set(0, 1.0, 0.007); + // arms down from the T bind pose + rot(a, 'upperarm_l', 0, 0, -1.25); rot(a, 'upperarm_r', 0, 0, 1.25); + if (gait) { + var ph = t * gait[0] * Math.PI, amp = gait[1]; + rot(a, 'thigh_l', Math.sin(ph) * amp, 0, 0); rot(a, 'thigh_r', -Math.sin(ph) * amp, 0, 0); + rot(a, 'calf_l', Math.max(0, -Math.cos(ph)) * amp * 1.3, 0, 0); rot(a, 'calf_r', Math.max(0, Math.cos(ph)) * amp * 1.3, 0, 0); + rot(a, 'upperarm_l', -Math.sin(ph) * amp * 0.6, 0, -1.25); rot(a, 'upperarm_r', Math.sin(ph) * amp * 0.6, 0, 1.25); + rot(a, 'pelvis', 0, Math.sin(ph) * 0.08, Math.sin(ph) * 0.04); + a.bones.pelvis.position.y = 1.0 - Math.abs(Math.cos(ph)) * 0.03 * amp - (s === 'crouchWalk' ? 0.3 : 0); + } + if (/crouch/.test(s)) { a.bones.pelvis.position.y = 0.7; rot(a, 'thigh_l', -1.2, 0, 0); rot(a, 'thigh_r', -1.0, 0, 0); rot(a, 'calf_l', 1.9, 0, 0); rot(a, 'calf_r', 1.7, 0, 0); } + if (/prone/.test(s)) { a.bones.pelvis.position.y = 0.15; rot(a, 'pelvis', 1.5, 0, 0); } + if (/death/.test(s)) { k = Math.min(1, a.stateT / 0.9); a.bones.pelvis.position.y = 1.0 - k * 0.85; rot(a, 'pelvis', (s === 'deathBack' ? -1 : 1) * 1.45 * k * k, 0, 0); } + if (/aim|fire|hold/.test(s) || (a.upperName && /aim|fire|hold/.test(a.upperName))) { + rot(a, 'upperarm_r', -1.2, 0.3, 0.3); rot(a, 'lowerarm_r', 0, -1.2, 0); rot(a, 'upperarm_l', -1.2, -0.6, -0.2); rot(a, 'lowerarm_l', 0, 0.6, 0); + } + rot(a, 'spine_02', -a.aimP * 0.5, a.aimY * 0.5, 0); + a.root.updateMatrixWorld(true); + return a; + }; + api.dispose = function (a) { if (a.root.parent) a.root.parent.remove(a.root); }; + api.weapon = function (kind) { + var L = { rifleScoped: 1.1, smg: 0.75, pistol: 0.2, enemyRifle: 1.1, enemySmg: 0.6, mg: 1.2, knife: 0.3, binoculars: 0.15, grenade: 0.1 }[kind] || 0.5; + var g = new T.BoxGeometry(0.04, 0.06, L); g.translate(0, 0, L * 0.4); + var m = new T.Mesh(g, new T.MeshStandardMaterial({ color: new T.Color(0x2a2620).convertSRGBToLinear(), roughness: 0.6 })); + var mz = new T.Object3D(); mz.name = kind + '_muzzle'; mz.position.set(0, 0, L * 0.9); m.add(mz); + m.userData.muzzle = mz; m.userData.grip = { r: null, l: null }; m.userData.kind = kind; + return m; + }; + return api; + })(); +})(); diff --git a/e63334287a3deaa3/ironveil/env-test.html b/e63334287a3deaa3/ironveil/env-test.html new file mode 100644 index 00000000..da7ed10c --- /dev/null +++ b/e63334287a3deaa3/ironveil/env-test.html @@ -0,0 +1,327 @@ + + + + + + +Midnight Ops: environment test + + + + +
Making textures…
+
+ + +
+
Drag to look, WASD / arrows to fly, Q/E down/up, Shift fast. Touch: drag to look, two fingers to move.
+
+ + + + + + + + + + + + + + + + diff --git a/e63334287a3deaa3/ironveil/env/atmosphere.js b/e63334287a3deaa3/ironveil/env/atmosphere.js new file mode 100644 index 00000000..a926d92b --- /dev/null +++ b/e63334287a3deaa3/ironveil/env/atmosphere.js @@ -0,0 +1,425 @@ +/* Midnight Ops environment: atmosphere. Sky dome (gradient, stars, moon, moving cloud, dithered so it does not band), + moon/sun light with shadows, hemisphere fill, exponential fog plus low ground mist that pools in hollows, an + environment map rendered from the sky (reflections in puddles and glass), exposure, wetness and rain. + IVEnv.atmosphere(scene, renderer, preset, opts) -> { sun, hemi, update(dt, camera), set(preset), preset } + Ground mist works by extending three's fog shader chunks (every material with fog: true gets it). The mist settings + ride in the fog object's near/far uniforms: IVEnv uses an object that is both FogExp2 (for the define) and Fog + (so three uploads near = density, far = packed mist base height and amount). */ +(function () { + 'use strict'; + const E = window.IVEnv; + + // sRGB hex helper -> linear THREE.Color + const L = (h) => E.lin(h); + E.PRESETS = { + night_moon: { + skyTop: 0x070a12, skyHor: 0x26303f, ground: 0x0e1014, fog: 0x1d2531, fogD: 0.0105, mist: 0.55, mistTop: 1.8, + sunDir: [-0.5, 0.74, 0.45], sunCol: 0xb4c6ea, sunI: 3.9, sunShadow: true, moon: 1, stars: 1, cloud: 0.4, cloudCol: 0x2b3442, + hemiSky: 0x5f7298, hemiGround: 0x48433a, hemiI: 0.84, env: 0.6, exposure: 0.9, wind: 0.35, wet: 0.15, rain: 0, grade: 'night' + }, + night_overcast: { + skyTop: 0x080a0d, skyHor: 0x1b1f25, ground: 0x0b0c0d, fog: 0x171b20, fogD: 0.0135, mist: 0.7, mistTop: 2.2, + sunDir: [-0.3, 0.8, 0.4], sunCol: 0x8a96aa, sunI: 0.16, sunShadow: false, moon: 0.15, stars: 0, cloud: 1.0, cloudCol: 0x1d2128, + hemiSky: 0x6a7488, hemiGround: 0x34322e, hemiI: 1.0, env: 0.6, exposure: 1.1, wind: 0.5, wet: 0.3, rain: 0, grade: 'night' + }, + dawn_mist: { + skyTop: 0x3c4e66, skyHor: 0xb39a86, ground: 0x2a2a28, fog: 0x8c8e8e, fogD: 0.016, mist: 1.0, mistTop: 3.2, + sunDir: [0.85, 0.12, 0.3], sunCol: 0xffc690, sunI: 0.9, sunShadow: true, moon: 0, stars: 0, cloud: 0.55, cloudCol: 0x9a8f88, + hemiSky: 0x8f9cb0, hemiGround: 0x3c3a34, hemiI: 0.5, env: 0.7, exposure: 0.95, wind: 0.2, wet: 0.35, rain: 0, grade: 'dawn' + }, + night_rain: { + skyTop: 0x06080b, skyHor: 0x1a1e24, ground: 0x0b0c0d, fog: 0x161a1f, fogD: 0.016, mist: 0.6, mistTop: 2.0, + sunDir: [-0.5, 0.74, 0.45], sunCol: 0x8a96aa, sunI: 0.5, sunShadow: false, moon: 0, stars: 0, cloud: 1.0, cloudCol: 0x1a1d22, + hemiSky: 0x5a6476, hemiGround: 0x2a2826, hemiI: 1.0, env: 0.5, exposure: 1.1, wind: 1.1, wet: 1.0, rain: 1, grade: 'rain' + }, + dusty: { + skyTop: 0x9a9284, skyHor: 0xc8b89c, ground: 0x6a5c48, fog: 0xb8a78a, fogD: 0.012, mist: 0.0, mistTop: 1.0, + sunDir: [0.5, 0.55, 0.3], sunCol: 0xf0d8b0, sunI: 1.6, sunShadow: true, moon: 0, stars: 0, cloud: 0.4, cloudCol: 0xb0a490, + hemiSky: 0xc8b8a0, hemiGround: 0x6a5a44, hemiI: 0.7, env: 0.9, exposure: 0.9, wind: 0.9, wet: 0.0, rain: 0, grade: 'day' + }, + dusk_rain: { + skyTop: 0x1a1f28, skyHor: 0x4a4c50, ground: 0x151617, fog: 0x34383d, fogD: 0.017, mist: 0.6, mistTop: 2.0, + sunDir: [-0.85, 0.22, -0.2], sunCol: 0xb79a88, sunI: 0.55, sunShadow: true, moon: 0, stars: 0, cloud: 1.0, cloudCol: 0x2c3036, + hemiSky: 0x7a8494, hemiGround: 0x2e2c2a, hemiI: 0.85, env: 0.8, exposure: 1.0, wind: 1.3, wet: 1.0, rain: 1, grade: 'rain' + }, + day_overcast: { + skyTop: 0x7f8c99, skyHor: 0xb3b7b6, ground: 0x4b4a44, fog: 0xa4a9aa, fogD: 0.0042, mist: 0.0, mistTop: 1.0, + sunDir: [0.4, 0.7, 0.35], sunCol: 0xe8e2d6, sunI: 1.1, sunShadow: true, moon: 0, stars: 0, cloud: 0.85, cloudCol: 0x9ea2a4, + hemiSky: 0xb6c0cc, hemiGround: 0x5a5448, hemiI: 0.75, env: 0.9, exposure: 0.9, wind: 0.6, wet: 0.0, rain: 0, grade: 'day' + } + }; + + // ------------------------------------------------------------------ fog + mist chunks (installed once) + let chunksDone = false; + function installFogChunks() { + if (chunksDone) return; chunksDone = true; + const C = THREE.ShaderChunk; + C.fog_pars_vertex = '#ifdef USE_FOG\n varying float fogDepth;\n varying vec3 vFogW;\n#endif'; + C.fog_vertex = `#ifdef USE_FOG + fogDepth = - mvPosition.z; + { vec3 vt = mvPosition.xyz - viewMatrix[3].xyz; vFogW = vec3(dot(viewMatrix[0].xyz, vt), dot(viewMatrix[1].xyz, vt), dot(viewMatrix[2].xyz, vt)); } + #endif`; + C.fog_pars_fragment = `#ifdef USE_FOG + uniform vec3 fogColor; varying float fogDepth; varying vec3 vFogW; + #ifdef FOG_EXP2 + uniform float fogDensity; + #endif + uniform float fogNear; uniform float fogFar; + float ivFogH(vec2 p){ p = fract(p * vec2(0.1031, 0.1030)); p += dot(p, p.yx + 33.33); return fract((p.x + p.y) * p.x); } + float ivFogN(vec2 p){ vec2 i = floor(p), f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f); + return mix(mix(ivFogH(i), ivFogH(i + vec2(1.0, 0.0)), u.x), mix(ivFogH(i + vec2(0.0, 1.0)), ivFogH(i + vec2(1.0, 1.0)), u.x), u.y); } + #endif`; + C.fog_fragment = `#ifdef USE_FOG + #ifdef FOG_EXP2 + bool ivMine = fogNear < 0.5; float fd = ivMine ? fogNear : fogDensity; + float fogFactor = 1.0 - exp( - fd * fd * fogDepth * fogDepth ); + if (ivMine && fract(fogFar) > 0.001) { + // ground mist: density falls off with height above a base; integrated along the view ray + float mAmt = fract(fogFar), mBase = floor(fogFar) / 10.0 - 500.0, Hm = 1.4; + float h1 = max(cameraPosition.y - mBase, 0.0), h2 = max(vFogW.y - mBase, 0.0); + float dist = length(vFogW - cameraPosition), dh = h2 - h1; + float e1 = exp(-h1 / Hm), e2 = exp(-h2 / Hm); + float integ = abs(dh) > 0.05 ? (e1 - e2) * Hm / dh : e1; + float pocket = 0.45 + 0.9 * ivFogN(vFogW.xz * 0.045 + 3.1) * ivFogN(vFogW.xz * 0.11); + float mist = 1.0 - exp(-integ * dist * 0.05 * mAmt * pocket); + fogFactor = 1.0 - (1.0 - fogFactor) * (1.0 - mist * 0.9); + } + #else + float fogFactor = smoothstep( fogNear, fogFar, fogDepth ); + #endif + gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); + #endif`; + } + function makeFog() { + const f = new THREE.FogExp2(0x000000, 0.01); + f.isFog = true; f.near = 0.01; f.far = 0; // near = density, far = mist pack (see above) + return f; + } + function packMist(base, amt) { return Math.floor((base + 500) * 10) + Math.min(0.99, Math.max(0, amt)); } + + // ------------------------------------------------------------------ sky + const SKY_VS = 'varying vec3 vD; void main(){ vD = normalize(position); vec4 p = projectionMatrix * modelViewMatrix * vec4(position,1.0); gl_Position = p.xyww; }'; + const SKY_FS = E.GLSL.noise + ` + uniform vec3 top, hor, gnd, moonDir, moonCol, cloudCol; uniform float moonAmt, starAmt, cloud, time, bright; + varying vec3 vD; + float fbm3(vec2 p){ float s = 0.0, a = 0.5; for (int i = 0; i < 5; i++){ s += a * ivN(p); p = p * 2.03 + 7.1; a *= 0.5; } return s; } + void main(){ + vec3 d = normalize(vD); + float h = d.y; + vec3 c = mix(hor, top, pow(clamp(h, 0.0, 1.0), 0.5)); + c = mix(c, gnd, smoothstep(0.0, -0.08, h)); + float md = max(dot(d, moonDir), 0.0); + // stars: hashed cells on the sphere, small, twinkling a little + if (starAmt > 0.0 && h > 0.0) { + vec2 sp = vec2(atan(d.z, d.x) * 180.0, asin(clamp(h, -1.0, 1.0)) * 180.0); + vec2 ci = floor(sp), cf = fract(sp) - 0.5; + float r = ivH(ci), b = ivH(ci + 17.3); + float star = step(0.985, r) * smoothstep(0.12, 0.0, length(cf - (vec2(b, ivH(ci + 3.1)) - 0.5) * 0.6)); + star *= (0.5 + 0.5 * b) * (0.8 + 0.2 * sin(time * (2.0 + b * 3.0) + r * 40.0)); + c += vec3(0.55, 0.6, 0.75) * star * starAmt * smoothstep(0.0, 0.25, h); + } + // moon: disc with soft halo + if (moonAmt > 0.0) { + float disc = smoothstep(0.99955, 0.99975, md); + float mare = 0.8 + 0.2 * ivN(d.xy * 900.0); + c = mix(c, moonCol * 2.2 * mare, disc * moonAmt); + c += moonCol * (pow(md, 60.0) * 0.12 + pow(md, 8.0) * 0.035) * moonAmt; + } + // clouds: a slab seen from below, lit from the moon side, drifting + if (h > 0.0 && cloud > 0.0) { + vec2 cp = d.xz / (h + 0.08) * 1.6 + vec2(time * 0.012, time * 0.005); + float n = fbm3(cp * 0.8); + float cov = smoothstep(1.0 - cloud * 0.85 - 0.12, 1.0 - cloud * 0.85 + 0.25, n + cloud * 0.35); + float lit = 0.6 + 0.6 * pow(md, 4.0) * moonAmt + 0.25 * fbm3(cp * 1.7 + 3.0); + vec3 cc = cloudCol * lit; + // structure: slow darker bands of heavier cloud base, and (by day) a brighter thin patch toward the hidden sun + float band = fbm3(cp * 0.33 + vec2(7.0, 1.3)); + cc *= mix(0.68, 1.12, smoothstep(0.32, 0.68, band)); + cc += cloudCol * (1.0 - moonAmt) * (0.45 * pow(max(md, 0.0), 5.0) + 0.12 * smoothstep(0.55, 0.8, band)); + c = mix(c, cc, cov * smoothstep(0.0, 0.12, h)); + } + c *= bright; + // dither against banding (one 8-bit step) + c += (ivH(gl_FragCoord.xy + fract(time) * 61.0) - 0.5) / 255.0; + gl_FragColor = vec4(c, 1.0); + }`; + function skyMaterial() { + return new THREE.ShaderMaterial({ + uniforms: { + top: { value: new THREE.Color() }, hor: { value: new THREE.Color() }, gnd: { value: new THREE.Color() }, moonDir: { value: new THREE.Vector3(0, 1, 0) }, + moonCol: { value: new THREE.Color(0xdde6ff) }, cloudCol: { value: new THREE.Color() }, moonAmt: { value: 1 }, starAmt: { value: 1 }, cloud: { value: 0.4 }, time: { value: 0 }, bright: { value: 1 } + }, + vertexShader: SKY_VS, fragmentShader: SKY_FS, side: THREE.BackSide, depthWrite: false, depthTest: true, fog: false, toneMapped: true + }); + } + + // ------------------------------------------------------------------ rain + // Rain: line streaks in a box that wraps round the camera, all motion in the vertex shader. Nearly invisible in + // the dark, they flare inside lamp light (the four nearest point lights are passed in each frame). + function makeRain(n) { + const g = new THREE.BufferGeometry(), p = new Float32Array(n * 6), e = new Float32Array(n * 2), R = E.rng(5); + for (let i = 0; i < n; i++) { const x = R(), y = R(), z = R(); p.set([x, y, z, x, y, z], i * 6); e[i * 2] = 0; e[i * 2 + 1] = 1; } + g.setAttribute('position', new THREE.BufferAttribute(p, 3)); g.setAttribute('aEnd', new THREE.BufferAttribute(e, 1)); + const m = new THREE.ShaderMaterial({ + uniforms: { uTime: E.U.uTime, uWind: E.U.uWind, uAmt: { value: 1 }, uLamp: { value: [0, 1, 2, 3].map(() => new THREE.Vector4()) }, uLampC: { value: [0, 1, 2, 3].map(() => new THREE.Color()) }, uFlash: { value: 0 } }, + vertexShader: `uniform float uTime, uAmt, uFlash; uniform vec3 uWind; uniform vec4 uLamp[4]; uniform vec3 uLampC[4]; attribute float aEnd; varying vec3 vC; varying float vA; + void main(){ + vec3 B = vec3(26.0, 16.0, 26.0); + vec3 vel = vec3(uWind.x * uWind.z * 2.2, -9.5 - position.x * 2.5, uWind.y * uWind.z * 2.2); + vec3 p = position * B + vel * uTime; + p = mod(p - cameraPosition + 0.5 * B, B) - 0.5 * B + cameraPosition; + p -= normalize(vel) * aEnd * 0.3; + vec3 c = vec3(0.32, 0.36, 0.42) * 0.25; float a = 0.07; + for (int i = 0; i < 4; i++) { float d = length(p - uLamp[i].xyz); float gl = uLamp[i].w * smoothstep(9.0, 0.5, d); c += uLampC[i] * gl * 0.9; a += gl * 0.5; } + c += vec3(0.6, 0.65, 0.8) * uFlash; a += uFlash * 0.3; + float dc = length(p - cameraPosition); + vA = a * step(position.y, uAmt) * smoothstep(0.4, 1.5, dc) * smoothstep(13.0, 7.0, dc); + vC = c; + gl_Position = projectionMatrix * viewMatrix * vec4(p, 1.0); + }`, + fragmentShader: 'varying vec3 vC; varying float vA; void main(){ gl_FragColor = vec4(vC * vA, vA); }', + transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, fog: false + }); + const ls = new THREE.LineSegments(g, m); ls.frustumCulled = false; ls.renderOrder = 5; + return ls; + } + + // ------------------------------------------------------------------ the atmosphere object + E.atmosphere = function (scene, renderer, preset, opts) { + opts = opts || {}; + installFogChunks(); + const A = { flashes: opts.flashes !== false, scene, renderer, sun: null, hemi: null, mistBase: opts.mistBase != null ? opts.mistBase : 0, shadowR: opts.shadowRadius || (E.Q.name === 'low' ? 24 : 32) }; + const sun = A.sun = new THREE.DirectionalLight(0xffffff, 1); + const hemi = A.hemi = new THREE.HemisphereLight(0xffffff, 0x000000, 0.3); + scene.add(sun); scene.add(sun.target); scene.add(hemi); + const Q = E.Q; + if (opts.shadows !== false) { + const sz = opts.shadowMapSize || (Q.name === 'high' ? 2048 : Q.name === 'medium' ? 1536 : 1024); + sun.castShadow = true; sun.shadow.mapSize.set(sz, sz); + const s = A.shadowR; Object.assign(sun.shadow.camera, { left: -s, right: s, top: s, bottom: -s, near: 1, far: 260 }); + sun.shadow.bias = -0.0004; sun.shadow.normalBias = 0.035; sun.shadow.radius = 2; + sun.shadow.camera.updateProjectionMatrix(); + } + const sky = A.skyMat = skyMaterial(); + const dome = A.dome = new THREE.Mesh(new THREE.SphereGeometry(800, 48, 24), sky); + dome.frustumCulled = false; dome.renderOrder = -10; scene.add(dome); + const fog = A.fog = makeFog(); scene.fog = fog; + const rain = A.rain = makeRain(Q.name === 'low' ? 1200 : 3000); rain.visible = false; scene.add(rain); + // environment map from a copy of the sky + const envScene = new THREE.Scene(), envDome = new THREE.Mesh(new THREE.SphereGeometry(100, 32, 16), sky.clone()); + envScene.add(envDome); + // A small cube render of the sky with mipmaps (PMREM float targets proved unreliable on software GL). + const cubeRT = new THREE.WebGLCubeRenderTarget(64, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter, magFilter: THREE.LinearFilter, type: THREE.UnsignedByteType }); + const cubeCam = new THREE.CubeCamera(0.1, 200, cubeRT); envScene.add(cubeCam); + A.dir = new THREE.Vector3(); + + // one weather state: A.set(name) at once, A.blendTo(name, seconds) eased; sky, sun/moon, fill, fog and mist, + // exposure, wetness, wind, rain and the environment map all follow the same blended values + A.blendTo = function (name, secs) { const to = E.PRESETS[name]; if (!to) return A; A.blend = { from: Object.assign({}, A.P), to, name, t: 0, T: Math.max(0.1, secs || 30), envT: 0 }; return A; }; + const mixP = (a, b, k) => { const o = {}; for (const key in b) { const x = a[key], y = b[key]; if (typeof y === 'number' && typeof x === 'number') { if (/(sky|Hor|ground|fog$|Col|hemi(Sky|Ground)|cloudCol)/.test(key) && y > 2) { o[key] = new THREE.Color(x).lerp(new THREE.Color(y), k).getHex(); } else o[key] = x + (y - x) * k; } else if (Array.isArray(y) && Array.isArray(x)) o[key] = y.map((v, i) => x[i] + (v - x[i]) * k); else o[key] = k < 0.5 ? x : y; } o.rain = k > 0.35 ? b.rain : a.rain; o.grade = k < 0.5 ? a.grade : b.grade; return o; }; + A.stepBlend = function (dt) { const B = A.blend; if (!B) return; B.t += dt; const u = Math.min(1, B.t / B.T), k = u * u * (3 - 2 * u); B.envT -= dt; const refresh = B.envT <= 0 || u >= 1; if (refresh) B.envT = 1; A.apply(mixP(B.from, B.to, k), B.name, !refresh); if (u >= 1) { A.blend = null; A.preset = B.name; A.P = B.to; } }; + A.set = function (name) { A.blend = null; return A.apply(E.PRESETS[name] || E.PRESETS.night_moon, name); }; + A.apply = function (P, name, skipEnv) { + A.preset = name; A.P = P; + A.dir.set(P.sunDir[0], P.sunDir[1], P.sunDir[2]).normalize(); + const u = sky.uniforms; + u.top.value.copy(L(P.skyTop)); u.hor.value.copy(L(P.skyHor)); u.gnd.value.copy(L(P.ground)); u.moonDir.value.copy(A.dir); + u.moonAmt.value = P.moon; u.starAmt.value = P.stars; u.cloud.value = P.cloud; u.cloudCol.value.copy(L(P.cloudCol)); + if (!P.moon) u.moonCol.value.copy(L(P.sunCol)); else u.moonCol.value.set(0xdde6ff).convertSRGBToLinear(); + sun.color.copy(L(P.sunCol)); sun.intensity = P.sunI; sun.castShadow = opts.shadows !== false && P.sunShadow; + hemi.color.copy(L(P.hemiSky)); hemi.groundColor.copy(L(P.hemiGround)); hemi.intensity = P.hemiI; + fog.color.copy(L(P.fog)); fog.near = P.fogD * (opts.fogMul || 1); fog.far = packMist(A.mistBase + P.mistTop - 1.8, P.mist * 0.99); + scene.background = null; + renderer.toneMappingExposure = P.exposure * (A.brightness || 1) * (E.Q.post ? 1 : 1.45); // Low has no grade/lift pass + E.U.uWet.value = P.wet; E.U.uRain.value = P.rain ? 1 : 0; E.U.uDust.value = P.rain ? 0 : P.grade === 'day' ? 0.5 : 0.35; E.U.uNight.value = P.grade === 'night' || P.grade === 'rain' ? 1 : 0; + E.setWind(E.U.uWind.value.x, E.U.uWind.value.y, P.wind); + rain.visible = !!P.rain && Q.name !== 'low' || (!!P.rain && opts.rainOnLow); + // environment map: the sky (no stars, no sun disc glare) scaled by env + if (skipEnv) return A; + const eu = envDome.material.uniforms; for (const k in u) if (eu[k]) eu[k].value = u[k].value && u[k].value.clone ? u[k].value.clone() : u[k].value; + eu.starAmt.value = 0; eu.bright.value = P.env; eu.moonAmt.value = P.moon * 0.6; + const tm = renderer.toneMapping; renderer.toneMapping = THREE.NoToneMapping; + envDome.material.uniforms.bright.value = P.env; + cubeCam.update(renderer, envScene); + renderer.toneMapping = tm; + scene.environment = cubeRT.texture; + return A; + }; + // brightness setting for players (multiplies exposure) + A.setBrightness = function (b) { A.brightness = b; renderer.toneMappingExposure = A.P.exposure * b * (E.Q.post ? 1 : 1.45); }; + A.setFlashes = function (on) { A.flashes = !!on; if (!on) A.flashAge = 99; }; // reduced-effects setting + A.update = function (dt, camera) { + if (A.blend) A.stepBlend(dt); + sky.uniforms.time.value += dt; + dome.position.copy(camera.position); + // shadow camera follows the camera, snapped to texels so shadows do not swim + if (sun.castShadow) { + const s = A.shadowR, texel = (2 * s) / sun.shadow.mapSize.x; + const fwd = new THREE.Vector3(); camera.getWorldDirection(fwd); fwd.y = 0; if (fwd.lengthSq() > 0) fwd.normalize(); + const fx = Math.round((camera.position.x + fwd.x * s * 0.5) / texel) * texel, fz = Math.round((camera.position.z + fwd.z * s * 0.5) / texel) * texel; + const fy = Math.round(camera.position.y); + sun.target.position.set(fx, fy, fz); sun.position.set(fx + A.dir.x * 120, fy + A.dir.y * 120, fz + A.dir.z * 120); + } else { sun.position.copy(A.dir).multiplyScalar(100); sun.target.position.set(0, 0, 0); } + if (rain.visible) { + const U = rain.material.uniforms, cp = camera.position; let k = 0; + const ls = []; scene.traverse(o => { if (o.isPointLight && o.intensity > 0 && o.visible) ls.push(o); }); + ls.sort((a, b) => a.position.distanceToSquared(cp) - b.position.distanceToSquared(cp)); + for (; k < 4; k++) { const l = ls[k]; if (l) { U.uLamp.value[k].set(l.position.x, l.position.y, l.position.z, Math.min(1.5, l.intensity * 0.5)); U.uLampC.value[k].copy(l.color); } else U.uLamp.value[k].w = 0; } + // lightning: a double flicker every 12-25 s, cool white, on the hemisphere light and the rain + A.flashT = (A.flashT == null ? 8 : A.flashT) - dt; + if (A.flashT < 0) { A.flashT = 12 + Math.random() * 13; A.flashAge = A.flashes ? 0 : 99; const dist = 600 + Math.random() * 2400; if (E.onAmbience) E.onAmbience({ kind: 'thunder', delay: dist / 343, dist }); } // thunder arrives after the sound delay + A.flashAge = (A.flashAge == null ? 99 : A.flashAge + dt); + const f = A.flashAge < 0.07 ? 1 : A.flashAge < 0.16 ? 0 : A.flashAge < 0.24 ? 0.55 : Math.max(0, 0.55 - (A.flashAge - 0.24) * 2.5); + hemi.intensity = A.P.hemiI * (1 + f * 2.5); U.uFlash.value = f; + } + }; + A.set(preset || 'night_moon'); + E.atmo = A; + return A; + }; + + E.setWind = function (dx, dz, strength) { + const l = Math.hypot(dx, dz) || 1; E.U.uWind.value.set(dx / l, dz / l, strength == null ? E.U.uWind.value.z : strength); + }; + E.setPushers = function (list) { + const v = E.U.uPush.value; + for (let i = 0; i < 8; i++) { const p = list && list[i]; if (p) v[i].set(p.x, p.z, p.r || 0.8, p.s == null ? 1 : p.s); else v[i].set(0, 0, 0, 0); } + }; + + // ------------------------------------------------------------------ background activity (not gameplay) + // IVEnv.backdrop(scene, spec) -> { group, info() }: far-off life that is cheap and never reads as an enemy. + // spec.searchlights: [[x, z]] sites far away, beams sweeping the sky + // spec.flak: [[x, z]] sites: shell bursts high up and slow tracer streams climbing + // spec.planes: true -> dark aircraft crossing high (an 'ambience' event 'drone' while one is overhead) + // spec.chutes: [[x, z]] a few distant parachutes drifting down during the first minute + // spec.bombing: [[x, z]] flashes beyond the hills ('ambience' 'rumble' after the sound delay) + // spec.fires: [[x, z, scale]] a burning place on the horizon: glow and a lit smoke column + // spec.flares: [[x, z]] areas where flares rise, hang and drift down + // spec.smoke: [[x, y, z, dark]] chimney smoke; spec.birds: [[x, z, r, h]] flocks wheeling; spec.bats: [[x, z]] + // spec.squalls: [[x, z]] rain curtains hanging over far hills; spec.truck: { path: [[x, z]], heightAt, speed } + // spec.pennant: { x, y, z } a plain camp pennant flying from a mast (no emblem) + // spec.sounds: [{ kind, every: [a, b], x, z }] 'ambience' events for the game's audio (dog, bell, rifle, owl) + // opts.reduced (Reduced motion) slows and thins everything and turns off flashes; Low quality halves the counts. + let softTex = null; + function soft() { if (softTex) return softTex; const c = document.createElement('canvas'); c.width = c.height = 64; const g = c.getContext('2d'), gr = g.createRadialGradient(32, 32, 0, 32, 32, 32); gr.addColorStop(0, 'rgba(255,255,255,1)'); gr.addColorStop(0.45, 'rgba(255,255,255,0.45)'); gr.addColorStop(1, 'rgba(255,255,255,0)'); g.fillStyle = gr; g.fillRect(0, 0, 64, 64); softTex = new THREE.CanvasTexture(c); return softTex; } + E.backdrop = function (scene, spec, opts) { + opts = opts || {}; spec = spec || {}; + const red = !!opts.reduced, low = E.Q.name === 'low', k = (low ? 0.5 : 1) * (red ? 0.5 : 1), R = E.rng(4242), group = new THREE.Group(); group.name = 'IVEnv.backdrop'; + const parts = [], emit = opts.emit || (() => {}); + // every soft particle (flak, tracer, smoke, flares, birds, leaves, glows) is one instance of one of two batched + // billboard meshes (additive and normal blend): two draw calls in all, however many there are + const pools = { add: [], norm: [] }; + const sprite = (col, add, op) => { const o = { position: new THREE.Vector3(), scale: new THREE.Vector3(1, 1, 1), material: { opacity: op == null ? 1 : op, color: new THREE.Color(col), rotation: 0 }, visible: true }; pools[add ? 'add' : 'norm'].push(o); return o; }; + const batch = (list, add) => { + if (!list.length) return null; + const n = list.length, g = new THREE.InstancedBufferGeometry(); g.copy(new THREE.PlaneGeometry(1, 1)); g.instanceCount = n; + const P = new THREE.InstancedBufferAttribute(new Float32Array(n * 3), 3), Sc = new THREE.InstancedBufferAttribute(new Float32Array(n * 3), 3), C = new THREE.InstancedBufferAttribute(new Float32Array(n * 4), 4); + P.setUsage(THREE.DynamicDrawUsage); Sc.setUsage(THREE.DynamicDrawUsage); C.setUsage(THREE.DynamicDrawUsage); g.setAttribute('iPos', P); g.setAttribute('iScale', Sc); g.setAttribute('iCol', C); + const m = new THREE.ShaderMaterial({ uniforms: THREE.UniformsUtils.merge([THREE.UniformsLib.fog, { map: { value: soft() } }]), transparent: true, depthWrite: false, fog: !add, blending: add ? THREE.AdditiveBlending : THREE.NormalBlending, + vertexShader: 'attribute vec3 iPos; attribute vec3 iScale; attribute vec4 iCol; varying vec2 vUv; varying vec4 vCol;\n#include \nvoid main(){ vUv = uv; vCol = iCol; vec4 mvPosition = viewMatrix * vec4(iPos, 1.0); float c = cos(iScale.z), s = sin(iScale.z); vec2 q = position.xy * iScale.xy; mvPosition.xy += vec2(c * q.x - s * q.y, s * q.x + c * q.y); gl_Position = projectionMatrix * mvPosition;\n#include \n}', + fragmentShader: 'uniform sampler2D map; varying vec2 vUv; varying vec4 vCol;\n#include \nvoid main(){ float a = texture2D(map, vUv).a * vCol.a; if (a < 0.003) discard; gl_FragColor = vec4(vCol.rgb, a);\n#include \n}' }); + m.customProgramCacheKey = () => 'ivbackdrop' + (add ? 'A' : 'N'); + const mesh = new THREE.Mesh(g, m); mesh.frustumCulled = false; mesh.userData.dynamic = true; mesh.renderOrder = add ? 3 : 2; group.add(mesh); + return () => { for (let i = 0; i < n; i++) { const o = list[i], v = o.visible === false ? 0 : o.material.opacity; P.array[i * 3] = o.position.x; P.array[i * 3 + 1] = o.position.y; P.array[i * 3 + 2] = o.position.z; Sc.array[i * 3] = o.scale.x; Sc.array[i * 3 + 1] = o.scale.y; Sc.array[i * 3 + 2] = o.material.rotation || 0; C.array[i * 4] = o.material.color.r; C.array[i * 4 + 1] = o.material.color.g; C.array[i * 4 + 2] = o.material.color.b; C.array[i * 4 + 3] = v; } P.needsUpdate = Sc.needsUpdate = C.needsUpdate = true; }; + }; + // searchlights: long thin additive cones from the ground; each wanders over the sky and lights a soft pool on the + // cloud base; now and then two or three cone on the same point and hold it + const beams = [], up = new THREE.Vector3(0, 1, 0), dv = new THREE.Vector3(); let cone = { t: 25, hold: 0, x: 0, z: 0 }; + for (const [x, z] of spec.searchlights || []) { + const g = new THREE.CylinderGeometry(4, 0.4, 1, 10, 1, true); g.translate(0, 0.5, 0); + const m = new THREE.MeshBasicMaterial({ color: 0x8090a8, transparent: true, opacity: 0.06, blending: THREE.AdditiveBlending, depthWrite: false, side: THREE.DoubleSide, fog: false }); + const bm = new THREE.Mesh(g, m), y = opts.heightAt ? opts.heightAt(x, z) : 0; bm.position.set(x, y, z); bm.userData.dynamic = true; group.add(bm); + const pool = sprite(0x6a7890, true, 0.12); pool.scale.set(70, 70, 1); + beams.push({ bm, pool, x, y, z, ph: R() * 6.28, sp: 0.05 + R() * 0.05 }); + } + if (beams.length) parts.push((t, dt) => { + cone.t -= dt; if (cone.t < 0) { cone.hold = 9; cone.t = 35 + R() * 30; cone.x = R.range(-300, 300); cone.z = R.range(-300, 300); } + cone.hold = Math.max(0, cone.hold - dt); + for (const b of beams) { + const wx = b.x + Math.sin(t * b.sp + b.ph) * 380, wz = b.z + Math.cos(t * b.sp * 0.8 + b.ph * 2) * 380, k = cone.hold > 0 ? Math.min(1, cone.hold) : 0; + const tx = wx * (1 - k) + cone.x * k, tz = wz * (1 - k) + cone.z * k, ty = 380; + dv.set(tx - b.x, ty - b.y, tz - b.z); const L = dv.length(); dv.normalize(); b.bm.quaternion.setFromUnitVectors(up, dv); b.bm.scale.set(1, L, 1); + b.pool.position.set(tx, ty, tz); + } + }); + // flak: a brief hard flash, then a small dark puff that drifts and thins; tracer as strings of points climbing on an + // arc and burning out + if ((spec.flak || []).length) { + const bursts = []; for (let i = 0; i < Math.round(9 * k); i++) { const f = sprite(0xfff0d0, true, 0), p = sprite(0x2a2826, false, 0); f.scale.set(5, 5, 1); bursts.push({ f, p, t: -R() * 6, life: 99 }); } + const streams = []; for (let i = 0; i < Math.round(5 * k); i++) { const dots = []; for (let q = 0; q < 7; q++) { const d = sprite(0xffa860, true, 0); d.scale.set(1.4, 1.4, 1); dots.push(d); } streams.push({ dots, t: R() * 5, site: spec.flak[i % spec.flak.length], a: R() * 6.28, sp: 75 + R() * 30, tilt: 0.3 + R() * 0.4 }); } + parts.push((t, dt) => { + for (const b of bursts) { b.t -= dt; b.life += dt; if (b.t < 0) { const st = spec.flak[(R() * spec.flak.length) | 0]; const x = st[0] + R.range(-110, 110), y = 170 + R() * 170, z = st[1] + R.range(-110, 110); b.f.position.set(x, y, z); b.p.position.set(x, y, z); b.t = (red ? 4 : 1.4) + R() * 4; b.life = 0; b.dx = R.range(-2, 2); } + b.f.material.opacity = red ? 0 : (b.life < 0.07 ? 1 : 0); b.p.material.opacity = b.life < 0.07 ? 0 : Math.max(0, 0.55 * (1 - b.life / 5)); b.p.scale.setScalar(4 + b.life * 3); b.p.position.x += b.dx * dt; b.p.position.y += 0.6 * dt; } + for (const q of streams) { q.t += dt; if (q.t > 5.5) { q.t = 0; q.a = R() * 6.28; } for (let n = 0; n < q.dots.length; n++) { const tt = q.t - n * 0.09; const d = q.dots[n]; if (tt < 0 || tt > 4.2) { d.material.opacity = 0; continue; } const h = tt * q.sp - 4 * tt * tt; d.position.set(q.site[0] + Math.cos(q.a) * tt * q.sp * q.tilt, 20 + h, q.site[1] + Math.sin(q.a) * tt * q.sp * q.tilt); d.material.opacity = tt > 3.6 ? (4.2 - tt) * 1.6 : 0.95; } } + }); + } + // falling leaves near the camera (a box that wraps the camera), when trees are about + if (spec.leaves && !red) { + const lv = []; for (let i = 0; i < Math.round(50 * k * 2); i++) { const p = sprite(spec.leaves === 'day' ? 0x6a5a30 : 0x2a2618, false, 0.9); p.scale.set(0.09, 0.06, 1); lv.push({ p, x: R.range(-12, 12), y: R.range(0, 9), z: R.range(-12, 12), ph: R() * 6 }); } + parts.push((t, dt, cam) => { const w = E.windDir ? E.windDir : { x: 1, z: 0.3 }; for (const q of lv) { q.y -= dt * (0.6 + 0.3 * Math.sin(t + q.ph)); q.x += dt * (0.5 * w.x + 0.3 * Math.sin(t * 1.7 + q.ph)); q.z += dt * 0.5 * (w.z || 0); if (q.y < -1) { q.y = 9; q.x = R.range(-12, 12); q.z = R.range(-12, 12); } let rx = ((q.x % 24) + 36) % 24 - 12, rz = ((q.z % 24) + 36) % 24 - 12; q.p.position.set(cam.position.x + rx, cam.position.y - 1.6 + q.y, cam.position.z + rz); q.p.material.rotation = t * 3 + q.ph; } }); + } + // aircraft: dark cross shapes crossing high, a drone event while overhead + if (spec.planes) { + const shape = new THREE.Group(); const mm = new THREE.MeshBasicMaterial({ color: 0x07080b, fog: false }); + shape.add(new THREE.Mesh(new THREE.BoxGeometry(14, 1.6, 1.8), mm)); const wing = new THREE.Mesh(new THREE.BoxGeometry(2.6, 0.35, 26), mm); wing.position.x = 1.5; shape.add(wing); const tail = new THREE.Mesh(new THREE.BoxGeometry(1.4, 0.3, 8), mm); tail.position.x = -6.2; shape.add(tail); + const planes = []; for (let i = 0; i < Math.round(3 * k + 1); i++) { const p = shape.clone(); p.userData.dynamic = true; group.add(p); planes.push({ p, t: R() * 40, z0: R.range(-500, 500), y: 260 + R() * 160, sp: 55 + R() * 20, dir: R() < 0.5 ? 1 : -1, said: false }); } + parts.push((t, dt, cam) => { for (const q of planes) { q.t += dt; const L = 2400, x = -1200 + ((q.t * q.sp) % L); q.p.position.set(x * q.dir, q.y, q.z0 + x * 0.25); q.p.rotation.y = q.dir > 0 ? -0.245 : Math.PI - 0.245; const near = Math.abs(q.p.position.x - cam.position.x) < 300; if (near && !q.said) { q.said = true; emit({ kind: 'drone', x: q.p.position.x, z: q.p.position.z }); } if (!near) q.said = false; } }); + } + // distant parachutes in the first minute + for (const [x, z] of spec.chutes || []) for (let i = 0; i < 3; i++) { + const c = new THREE.Mesh(new THREE.SphereGeometry(3, 8, 4, 0, 6.28, 0, 1.4), new THREE.MeshBasicMaterial({ color: 0x9a9890, fog: true })); c.userData.dynamic = true; group.add(c); + const ox = x + R.range(-40, 40), oz = z + R.range(-40, 40), y0 = 120 + R() * 60, d = R() * 8; parts.push((t) => { const tt = Math.max(0, t - d); c.position.set(ox + tt * 0.8, Math.max(-20, y0 - tt * 4.5), oz + Math.sin(tt * 0.4) * 4); c.visible = t < 70; }); + } + // bombing beyond the hills: an orange flash low on the horizon, rumble after the sound delay + if ((spec.bombing || []).length) { + const f = sprite(0xff9a50, true, 0); f.scale.set(160, 60, 1); let next = 4, life = 9; + parts.push((t, dt, cam) => { next -= dt; life += dt; if (next < 0) { const st = spec.bombing[(R() * spec.bombing.length) | 0]; f.position.set(st[0] + R.range(-60, 60), 25, st[1] + R.range(-60, 60)); life = 0; next = 6 + R() * 14; const dd = Math.hypot(f.position.x - cam.position.x, f.position.z - cam.position.z); emit({ kind: 'rumble', delay: dd / 343, x: f.position.x, z: f.position.z }); } + f.material.opacity = red ? 0.12 * Math.max(0, 1 - life / 2) : (life < 0.15 ? 0.6 : life < 0.3 ? 0.25 : life < 0.45 ? 0.5 : Math.max(0, 0.5 - (life - 0.45) * 0.6)); }); + } + // fires on the horizon: a glow and a smoke column lit from below + for (const [x, z, sc] of spec.fires || []) { + const y = opts.heightAt ? opts.heightAt(x, z) : 0, s0 = sc || 1, glow = sprite(0xff7a30, true, 0.55); glow.position.set(x, y + 6 * s0, z); glow.scale.set(40 * s0, 18 * s0, 1); + const puffs = []; for (let i = 0; i < Math.round(14 * k + 4); i++) { const p = sprite(0x1a1714, false, 0.5); puffs.push({ p, t: i / 14 * 30 }); } + parts.push((t, dt) => { glow.material.opacity = 0.45 + 0.15 * Math.sin(t * 7.3) * Math.sin(t * 3.1); for (const q of puffs) { q.t = (q.t + dt * (red ? 0.5 : 1)) % 30; const u = q.t / 30; q.p.position.set(x + u * 60 * s0, y + 8 * s0 + u * 140 * s0, z + Math.sin(u * 5) * 6); q.p.scale.setScalar((10 + u * 50) * s0); q.p.material.opacity = 0.55 * (1 - u) * Math.min(1, q.t * 2); q.p.material.color.setRGB(0.1 + 0.5 * Math.max(0, 0.25 - u) * 4 * 0.25, 0.09 + 0.15 * Math.max(0, 0.25 - u), 0.08); } }); + } + // flares: rise, hang, drift down burning, a pause, again + for (const [x, z] of spec.flares || []) { + const f = sprite(0xfff0d0, true, 0); f.scale.set(6, 6, 1); let t0 = R() * 20, ox = x, oz = z; + parts.push((t, dt) => { t0 += dt; const T = 26, u = t0 % T; if (u < dt) { ox = x + R.range(-80, 80); oz = z + R.range(-80, 80); } const y = u < 3 ? u * 45 : 135 - (u - 3) * 4; f.position.set(ox + (u > 3 ? (u - 3) * 1.2 : 0), y, oz); f.material.opacity = u < 3 ? 0.4 : u < 18 ? (red ? 0.4 : 0.85 + 0.15 * Math.sin(t * 23)) : 0; }); + } + // chimney smoke + for (const [x, y, z, dark] of spec.smoke || []) { + const puffs = []; for (let i = 0; i < Math.round(6 * k + 2); i++) puffs.push({ p: sprite(dark ? 0x3a3836 : 0x8a8a88, false, 0), t: i / 6 * 9 }); + parts.push((t, dt) => { for (const q of puffs) { q.t = (q.t + dt) % 9; const u = q.t / 9; q.p.position.set(x + u * 5, y + u * 9, z + Math.sin(u * 4 + x) * 0.8); q.p.scale.setScalar(0.8 + u * 4.5); q.p.material.opacity = 0.35 * (1 - u) * Math.min(1, q.t * 3); } }); + } + // birds and bats: dark specks wheeling + for (const [x, z, r, h, n] of (spec.birds || []).concat((spec.bats || []).map(b => [b[0], b[1], 14, 9, 5]))) { + const fl = []; for (let i = 0; i < Math.round((n || 12) * k); i++) { const p = sprite(0x0c0c0c, false, 0.9); p.scale.set(0.9, 0.35, 1); fl.push({ p, a: R() * 6.28, rr: r * (0.6 + R() * 0.5), hh: h + R() * 6, sp: 0.15 + R() * 0.2 }); } + parts.push((t) => { for (const q of fl) { const a = q.a + t * q.sp; q.p.position.set(x + Math.cos(a) * q.rr, q.hh + Math.sin(t * 2 + q.a) * 1.5, z + Math.sin(a * 1.3) * q.rr); q.p.scale.y = 0.2 + 0.25 * Math.abs(Math.sin(t * 9 + q.a)); } }); + } + // rain squalls on the far hills: tall soft grey curtains drifting + for (const [x, z] of spec.squalls || []) { + const m = new THREE.MeshBasicMaterial({ map: soft(), color: 0x5a6068, transparent: true, opacity: 0.32, depthWrite: false, side: THREE.DoubleSide, fog: false }); + const q = new THREE.Mesh(new THREE.PlaneGeometry(220, 140), m); q.position.set(x, 50, z); q.userData.dynamic = true; group.add(q); + parts.push((t, dt, cam) => { q.position.x = x + Math.sin(t * 0.01) * 60; q.lookAt(cam.position.x, 50, cam.position.z); }); + } + // a lorry on the far road + if (spec.truck && E.prop) { + const tr = E.prop('truck', 77).group; tr.userData.dynamic = true; group.add(tr); const P = spec.truck.path, L = []; let tot = 0; for (let i = 0; i < P.length - 1; i++) { const l = Math.hypot(P[i + 1][0] - P[i][0], P[i + 1][1] - P[i][1]); L.push(l); tot += l; } + parts.push((t) => { let d = (t * (spec.truck.speed || 6)) % (tot * 2); if (d > tot) d = 2 * tot - d; let i = 0; while (i < L.length - 1 && d > L[i]) { d -= L[i]; i++; } const a = P[i], b = P[i + 1], u = Math.min(1, d / L[i]), x = a[0] + (b[0] - a[0]) * u, z = a[1] + (b[1] - a[1]) * u; tr.position.set(x, spec.truck.heightAt ? spec.truck.heightAt(x, z) : 0, z); tr.rotation.y = Math.atan2(-(b[1] - a[1]), b[0] - a[0]); }); + } + // a plain pennant on the mast + if (spec.pennant) { + const g = new THREE.PlaneGeometry(1.8, 0.9, 10, 2); g.translate(0.9, 0, 0); const base = g.attributes.position.array.slice(); + const fl = new THREE.Mesh(g, new THREE.MeshStandardMaterial({ color: 0x3c4a34, side: THREE.DoubleSide, roughness: 0.9 })); fl.position.set(spec.pennant.x, spec.pennant.y, spec.pennant.z); fl.userData.dynamic = true; group.add(fl); + parts.push((t) => { const a = g.attributes.position.array; for (let i = 0; i < a.length; i += 3) { const u = base[i] / 1.8; a[i + 2] = Math.sin(t * (red ? 2 : 5) - u * 6) * 0.18 * u; a[i + 1] = base[i + 1] - u * 0.1; } g.attributes.position.needsUpdate = true; g.computeVertexNormals(); }); + } + // sound hooks for the game's audio + for (const sd of spec.sounds || []) { let next = sd.every[0] + R() * (sd.every[1] - sd.every[0]); parts.push((t, dt) => { next -= dt; if (next < 0) { next = sd.every[0] + R() * (sd.every[1] - sd.every[0]); emit({ kind: sd.kind, x: sd.x, z: sd.z }); } }); } + const upA = batch(pools.add, true), upN = batch(pools.norm, false); + scene.add(group); + let T = 0; + (E._updaters = E._updaters || []).push((dt, cam) => { if (!group.parent) return; T += dt; for (const f of parts) f(T, dt, cam); if (upA) upA(); if (upN) upN(); }); + return { group, info: () => ({ parts: parts.length, objects: group.children.length }) }; + }; +})(); diff --git a/e63334287a3deaa3/ironveil/env/build.js b/e63334287a3deaa3/ironveil/env/build.js new file mode 100644 index 00000000..957b7859 --- /dev/null +++ b/e63334287a3deaa3/ironveil/env/build.js @@ -0,0 +1,1212 @@ +/* Midnight Ops environment: buildings, field walls and fences. + IVEnv.building(spec) -> { group, colliders, doors, windows, lights } + spec = { kind, w, d, floors, seed, damage (0..1), lit (0..1 share of lit windows), roof ('tile'|'slate') } + kinds: farmhouse, barn, shed, cottage, office (long low camp hut), church, shoprow, ruin, bunker (alias pillbox) + Local space: origin on the ground at the centre of the footprint, front door faces +Z, Y up, metres. + colliders: [{ x, z, hx, hz, y0, y1, rot, surf, kind }] boxes in local space (rot about Y). + doors: [{ pivot (Object3D, rotate .rotation.y to open), width, x, z, open(angle) }] + windows: [{ x, y, z, nx, nz, w, h, lit }] ; lights: [{ x, y, z, color, r, power }] for lit windows and lamps. + IVEnv.wall(points, { type: 'stone'|'brick', h, t, gaps: [[from, to] metres along], brokenStart, brokenEnd, seed, + heightFn }) -> { group, colliders } (points are [x, z] in world or parent space) + IVEnv.fence(points, kind, { heightFn, seed }) -> { group, colliders } kinds: rail, picket, barbed, hurdle + Everything is built brick by brick where the outline shows it: arches, sills, quoins, ridge tiles, eaves, slipped + and missing tiles, broken wall tops with loose bricks, rubble. Wear decals are placed where wear happens. */ +(function () { + 'use strict'; + const E = window.IVEnv; + const TAU = Math.PI * 2; + + // ------------------------------------------------------------------ rocks / rubble geometry (cached) + const rockCache = {}; + E.rockGeo = function (seed, detail) { + const k = seed + ':' + (detail == null ? 1 : detail); if (rockCache[k]) return rockCache[k]; + const g = new THREE.IcosahedronGeometry(1, detail == null ? 1 : detail), p = g.attributes.position, R = E.rng(seed); + const sx = R.range(0.8, 1.3), sy = R.range(0.45, 0.8), sz = R.range(0.75, 1.2), o = [R() * 9, R() * 9, R() * 9]; + for (let i = 0; i < p.count; i++) { + const x = p.getX(i), y = p.getY(i), z = p.getZ(i), n = 0.78 + 0.35 * E.vnoise(x * 1.7 + o[0], z * 1.7 + y * 1.3 + o[1], seed) + 0.12 * E.vnoise(x * 4 + o[2], y * 4, seed + 1); + p.setXYZ(i, x * sx * n, Math.max(y * sy * n, -0.25 * sy), z * sz * n); + } + g.computeVertexNormals(); rockCache[k] = g; return g; + }; + const _M = new THREE.Matrix4(), _Q = new THREE.Quaternion(), _Eu = new THREE.Euler(), _P = new THREE.Vector3(), _S = new THREE.Vector3(); + function placeRock(B, mat, x, y, z, s, seed, rot, tint) { + _Eu.set(rot ? rot[0] : 0, rot ? rot[1] : 0, rot ? rot[2] : 0); _Q.setFromEuler(_Eu); _P.set(x, y, z); _S.set(s, s, s); + B.geo(mat, E.rockGeo(seed % 23, s > 0.35 ? 1 : 0), _M.compose(_P, _Q, _S), { tint }); + } + // a loose brick (or any small block) lying at a random angle + function looseBlock(B, mat, x, y, z, R, sx, sy, sz, tint) { + if (E.Q.name === 'low') { R(); R(); R(); return; } + B.det(2, () => B.box(mat, x, y, z, sx || 0.32, sy || 0.1, sz || 0.155, R() * TAU, { rx: R.range(-0.4, 0.4), rz: R.range(-0.4, 0.4), tint })); + } + E.looseBlock = looseBlock; + // rubble pile: bricks, stone lumps and dust, a low mound + function rubble(B, x, z, r, R, mats, n, y0) { + y0 = y0 || 0; + for (let i = 0; i < n; i++) { + const a = R() * TAU, d = Math.sqrt(R()) * r, hx = x + Math.cos(a) * d, hz = z + Math.sin(a) * d, hy = y0 + (1 - d / r) * r * 0.35 * R(); + if (R() < 0.6) looseBlock(B, mats.brick || 'brick_red', hx, hy, hz, R, null, null, null, tintJ(R, 0.12)); + else { const rs = R.range(0.08, 0.22), sd = (R() * 1000) | 0, rr = [R() * 3, R() * 3, R() * 3]; B.det(2, () => placeRock(B, mats.stone || 'fieldstone', hx, hy, hz, rs, sd, rr)); } + } + // the mound under it + placeRock(B, 'mud', x, y0 - r * 0.15, z, r * 0.8, (R() * 1000) | 0, [0, R() * 3, 0]); + } + const tintJ = (R, v, base) => { const k = 1 + R.range(-v, v); const c = new THREE.Color(base || 0xffffff); return new THREE.Color(c.r * k, c.g * k * (1 + R.range(-0.03, 0.03)), c.b * k); }; + + // ------------------------------------------------------------------ walls with openings + // A straight wall: from local point (x0, z0) along unit dir (dx, dz) for length L; outward normal (nx, nz) = right of dir. + // ops: openings [{ a0, a1, y0, y1 }]; mats: { out, in }; uStart: perimeter u for the outer face (bricks wrap corners). + function wallRun(B, W) { + const { x0, z0, dx, dz, L, T, H, y0 = 0, ops = [], mats, uStart = 0 } = W; + const nx = -dz, nz = dx; // outward (left of the direction of travel) + const xs = new Set([0, L]), ys = new Set([y0, y0 + H]); + for (const o of ops) { xs.add(Math.max(0, Math.min(L, o.a0))); xs.add(Math.max(0, Math.min(L, o.a1))); ys.add(Math.max(y0, Math.min(y0 + H, o.y0))); ys.add(Math.max(y0, Math.min(y0 + H, o.y1))); } + const X = [...xs].sort((a, b) => a - b), Y = [...ys].sort((a, b) => a - b); + const isOpen = (a, y) => ops.some(o => a > o.a0 && a < o.a1 && y > o.y0 && y < o.y1); + const P = (a, y, side) => [x0 + dx * a + nx * side * T / 2, y, z0 + dz * a + nz * side * T / 2]; + const top = W.topAt; // optional broken top profile: topAt(a) -> y + for (let j = 0; j < Y.length - 1; j++) for (let i = 0; i < X.length - 1; i++) { + const a0 = X[i], a1 = X[i + 1], ya = Y[j], yb = Y[j + 1], am = (a0 + a1) / 2, ym = (ya + yb) / 2; + if (isOpen(am, ym) || a1 - a0 < 1e-4 || yb - ya < 1e-4) continue; + // outer face + B.quad(mats.out, P(a0, ya, 1), P(a1, ya, 1), P(a1, yb, 1), P(a0, yb, 1), [[uStart + a0, ya], [uStart + a1, ya], [uStart + a1, yb], [uStart + a0, yb]], W.tint, 0); + if (mats.in) B.quad(mats.in, P(a1, ya, -1), P(a0, ya, -1), P(a0, yb, -1), P(a1, yb, -1), [[L - a1, ya], [L - a0, ya], [L - a0, yb], [L - a1, yb]], null, W.inFoot != null ? W.inFoot : 0); + // reveals next to openings (and wall ends) + const rev = (aa, flip) => B.quad(mats.out, flip ? P(aa, ya, -1) : P(aa, ya, 1), flip ? P(aa, ya, 1) : P(aa, ya, -1), flip ? P(aa, yb, 1) : P(aa, yb, -1), flip ? P(aa, yb, -1) : P(aa, yb, 1), [[0, ya], [T, ya], [T, yb], [0, yb]], W.tint, 0); + if ((i > 0 && isOpen(a0 - 1e-3, ym)) || (i === 0 && W.capStart)) rev(a0, true); + if ((i < X.length - 2 && isOpen(a1 + 1e-3, ym)) || (i === X.length - 2 && W.capEnd)) rev(a1, false); + const hz = (yy, down) => { const p0 = P(a0, yy, 1), p1 = P(a1, yy, 1), p2 = P(a1, yy, -1), p3 = P(a0, yy, -1); if (down) B.quad(mats.out, p3, p2, p1, p0, [[a0, 0], [a1, 0], [a1, T], [a0, T]], W.tint, 0); else B.quad(mats.out, p0, p1, p2, p3, [[a0, 0], [a1, 0], [a1, T], [a0, T]], W.tint, 0); }; + if (j < Y.length - 2 && isOpen(am, yb + 1e-3)) hz(yb, true); // soffit over an opening + if (j > 0 && isOpen(am, ya - 1e-3)) hz(ya, false); // sill bed under a window + if (j === Y.length - 2 && W.capTop !== false) hz(yb, false); + } + // colliders: one box per run of solid columns at full height, and lintel/sill boxes around openings + const cx = (a) => x0 + dx * a, cz = (a) => z0 + dz * a, rot = Math.atan2(-dz, dx); + for (let i = 0; i < X.length - 1; i++) { + const a0 = X[i], a1 = X[i + 1], am = (a0 + a1) / 2; + const segs = []; let cur = null; + for (let j = 0; j < Y.length - 1; j++) { const solid = !isOpen(am, (Y[j] + Y[j + 1]) / 2); if (solid) { if (!cur) cur = [Y[j], Y[j + 1]]; else cur[1] = Y[j + 1]; } else if (cur) { segs.push(cur); cur = null; } } + if (cur) segs.push(cur); + for (const s of segs) B.col(cx(am), cz(am), a1 - a0, T, s[0], s[1], rot, W.surf || 'stone', 'wall'); + } + } + E._wallRun = wallRun; + + // ------------------------------------------------------------------ window and door dressing + // frame + glazing bars + glass + sill + head (brick arch, stone lintel or timber lintel) + optional shutters + function dressWindow(B, S, o) { + // o: { cx, cz (centre of the opening on the wall line), dx, dz, T, w, y0, y1, head: 'arch'|'lintel'|'timber'|'pointed', sill, shutters, lit, broken } + const R = S.R, nx = -o.dz, nz = o.dx, rot = Math.atan2(-o.dz, o.dx); + const out = (d) => [o.cx + nx * d, o.cz + nz * d]; + const inset = Math.min(0.12, o.T * 0.35), fp = out(o.T / 2 - inset - 0.03); + // frame (four bars) and glazing bars + const fw = 0.06, fd = 0.07, wood = 'wood_painted', tint = S.paintTint; + B.box(wood, fp[0], o.y0, fp[1], o.w, fw, fd, rot, { tint }); + B.box(wood, fp[0], o.y1 - fw, fp[1], o.w, fw, fd, rot, { tint }); + for (const s of [-1, 1]) { const q = [fp[0] + o.dx * s * (o.w / 2 - fw / 2), fp[1] + o.dz * s * (o.w / 2 - fw / 2)]; B.box(wood, q[0], o.y0, q[1], fw, o.y1 - o.y0, fd, rot, { tint }); } + const mid = (o.y0 + o.y1) / 2; + B.det(1, () => { B.box(wood, fp[0], mid - 0.02, fp[1], o.w, 0.035, 0.04, rot, { tint }); B.box(wood, fp[0], o.y0, fp[1], 0.035, o.y1 - o.y0, 0.04, rot, { tint }); }); + // glass panes (four), some broken out when damaged + const gp = out(o.T / 2 - inset - 0.03 - 0.01), hw = o.w / 2 - fw, panes = [[-1, 0], [1, 0], [-1, 1], [1, 1]]; + for (const [sx, sy] of panes) { + const broken = o.broken && R() < 0.5; + if (broken) continue; + const ax = sx < 0 ? -hw : 0.02, bx = sx < 0 ? -0.02 : hw, ya = sy ? mid + 0.015 : o.y0 + fw, yb = sy ? o.y1 - fw : mid - 0.02; + const P = (a, y) => [gp[0] + o.dx * a, y, gp[1] + o.dz * a]; + B.quad(o.lit ? 'glass_lit' : 'glass', P(ax, ya), P(bx, ya), P(bx, yb), P(ax, yb), [[ax, ya], [bx, ya], [bx, yb], [ax, yb]], null, null); + } + // boarded up: planks nailed across the frame at odd angles (empty or shot-up houses) + if (!o.lit && (o.boarded || (S.damage > 0.3 && R() < 0.35))) { const bp = out(o.T / 2 + 0.03); for (let k = 0; k < 3 + R.int(2); k++) { const yy = o.y0 + (o.y1 - o.y0) * (0.12 + 0.25 * k) + R.range(-0.05, 0.05); B.box('planks', bp[0] + nx * 0.01 * k, yy, bp[1] + nz * 0.01 * k, o.w + R.range(0.15, 0.35), R.range(0.13, 0.2), 0.025, rot, { rz: R.range(-0.25, 0.25), tint: tintJ(R, 0.15, 0xc8bca8) }); } } + // a dark backing so an unlit window does not show the sky through the building + if (!o.lit && !S.interior) { const bp = out(o.T / 2 - inset - 0.2), P = (a, y) => [bp[0] + o.dx * a, y, bp[1] + o.dz * a]; B.quad('timber', P(-o.w / 2, o.y0), P(o.w / 2, o.y0), P(o.w / 2, o.y1), P(-o.w / 2, o.y1), [[0, 0], [1, 0], [1, 1], [0, 1]], new THREE.Color(0.08, 0.08, 0.08), null); } + // sill: dressed stone, proud of the wall and wider than the opening, with a drip and a stain under it + const sp = out(o.T / 2 + 0.03); + if (o.sill !== false) { + B.box(o.sillMat || 'ashlar', sp[0] - nx * 0.06, o.y0 - 0.07, sp[1] - nz * 0.06, o.w + 0.16, 0.07, 0.2, rot, { tint: tintJ(R, 0.08) }); + B.decal('waterstain', [sp[0] + nx * 0.0, o.y0 - 0.32, sp[1] + nz * 0.0], [nx, 0, nz], o.w * 0.9, 0.45, 0); + } + // head + const hp = out(o.T / 2); + if (o.head === 'arch' || o.head === 'pointed') { + // a segmental (or pointed) arch of individual bricks / voussoirs, rising over the opening + const span = o.w + 0.02, rise = o.head === 'pointed' ? span * 0.55 : span * 0.16, mat = o.head === 'pointed' ? 'ashlar' : S.brickMat || 'brick_red'; + const rad = o.head === 'pointed' ? span * 0.8 : (span * span / 4 + rise * rise) / (2 * rise), depth = o.head === 'pointed' ? 0.3 : 0.32; + const n = Math.max(7, Math.round((span + rise) / (o.head === 'pointed' ? 0.22 : 0.108))); + const cy = o.y1 + rise - rad; + if (E.Q.name === 'low') B.box(mat, hp[0] + nx * 0.02, o.y1, hp[1] + nz * 0.02, span + 0.1, o.head === 'pointed' ? rise * 0.7 : 0.24, 0.06, rot, {}); + B.det(2, () => { for (let i = 0; i < n; i++) { + const t = (i + 0.5) / n; + let ang, cxo; + if (o.head === 'pointed') { const side = t < 0.5 ? -1 : 1, tt = t < 0.5 ? t * 2 : (1 - t) * 2; const a0 = Math.acos((rad - span / 2) / rad); ang = Math.PI / 2 + side * (a0 * (1 - tt)); cxo = -side * (rad - span / 2); ang = side < 0 ? Math.PI - (a0 * (1 - tt)) : a0 * (1 - tt); } + const half = Math.asin(Math.min(1, span / 2 / rad)); + if (o.head !== 'pointed') ang = Math.PI / 2 + half - t * 2 * half; + let px, py; + if (o.head === 'pointed') { const side = t < 0.5 ? -1 : 1; const ccx = side < 0 ? span / 2 - rad : -span / 2 + rad; px = ccx + Math.cos(ang) * (rad + depth / 2); py = o.y1 + Math.sin(ang) * (rad + depth / 2); } + else { px = Math.cos(ang) * (rad + depth / 2); py = cy + Math.sin(ang) * (rad + depth / 2); } + const tang = ang - Math.PI / 2; + const wx = hp[0] + o.dx * px, wz = hp[1] + o.dz * px; + // each voussoir is a box turned in the wall plane: rotate about the wall normal + const bw = o.head === 'pointed' ? 0.2 : 0.098; + const g = new THREE.BoxGeometry(bw, depth, 0.1 + (o.head === 'pointed' ? 0.02 : 0)); + _Eu.set(0, rot, 0); _Q.setFromEuler(_Eu); + const q2 = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 0, 1), tang); + _Q.multiply(q2); _P.set(wx + nx * 0.035, py, wz + nz * 0.035); _S.set(1, 1, 1); + B.geo(mat, g, _M.compose(_P, _Q, _S), { tint: tintJ(R, 0.14) }); + } }); + } else if (o.head === 'lintel') { + // some lintels have dropped at one end: tilted, with a crack running up from the low end + const drop = S.old && R() < 0.35 ? R.range(0.03, 0.07) * (R() < 0.5 ? -1 : 1) : 0; + B.box('ashlar', hp[0] + nx * 0.015, o.y1 - Math.abs(drop) * 0.25, hp[1] + nz * 0.015, o.w + 0.36, 0.24, 0.12, rot, { tint: tintJ(R, 0.08), rz: drop }); + if (drop) B.decal('crack', [hp[0] + nx * 0.006 - o.dx * Math.sign(drop) * (o.w / 2 + 0.1), o.y1 + 0.5, hp[1] + nz * 0.006 - o.dz * Math.sign(drop) * (o.w / 2 + 0.1)], [nx, 0, nz], 0.45, 0.8, R.range(-0.3, 0.3)); + } else if (o.head === 'timber') { + B.box('timber', hp[0] + nx * 0.02, o.y1, hp[1] + nz * 0.02, o.w + 0.4, 0.18, 0.16, rot, { grain: 'long' }); + } + // shutters: open against the wall, one sometimes hanging off a hinge + if (o.shutters) for (const s of [-1, 1]) { + const hang = (S.damage > 0.3 && R() < S.damage * 0.5) || (S.old && R() < 0.12), sw = o.w / 2 + 0.02; + const q = [hp[0] + nx * 0.03 + o.dx * s * (o.w / 2 + sw / 2 + 0.02), hp[1] + nz * 0.03 + o.dz * s * (o.w / 2 + sw / 2 + 0.02)]; + B.box(wood, q[0], o.y0 + (hang ? -0.15 : 0), q[1], sw, o.y1 - o.y0, 0.035, rot, { rz: hang ? s * 0.35 : 0, tint }); + // ledges on the shutter + for (const yy of [0.15, 0.5, 0.85]) B.det(1, () => B.box(wood, q[0] + nx * 0.025, o.y0 + (o.y1 - o.y0) * yy + (hang ? -0.15 : 0), q[1] + nz * 0.025, sw * 0.9, 0.08, 0.02, rot, { rz: hang ? s * 0.35 : 0, tint })); + if (R() < 0.6) B.decal('chipped', [q[0] + nx * 0.05, o.y0 + (o.y1 - o.y0) * 0.4, q[1] + nz * 0.05], [nx, 0, nz], sw * 0.8, 0.5, R() * 3); + } + // soot streak over a lit / once-burnt window, crack from a corner + if (S.damage > 0.2 && R() < S.damage) B.decal('soot', [hp[0] + nx * 0.005, o.y1 + 0.45, hp[1] + nz * 0.005], [nx, 0, nz], o.w * 1.2, 0.9, 0); + if (R() < 0.35 + S.damage * 0.4) B.decal('crack', [hp[0] + nx * 0.005 + o.dx * (R() < 0.5 ? -1 : 1) * o.w * 0.55, o.y1 + 0.25, hp[1] + nz * 0.005], [nx, 0, nz], 0.5, 0.6, R.range(-0.4, 0.4)); + S.windows.push({ x: hp[0], y: (o.y0 + o.y1) / 2, z: hp[1], nx, nz, w: o.w, h: o.y1 - o.y0, lit: !!o.lit }); + if (o.lit) S.lights.push({ x: hp[0] - nx * 0.8, y: (o.y0 + o.y1) / 2, z: hp[1] - nz * 0.8, color: 0xffb060, r: 7, power: 0.9 }); + } + // door: frame, threshold stone, a hinged plank door (its own little group so it can swing), wear decals + function dressDoor(B, S, o, group) { + const R = S.R, nx = -o.dz, nz = o.dx, rot = Math.atan2(-o.dz, o.dx); + const fp = [o.cx + nx * (o.T / 2 - 0.1), o.cz + nz * (o.T / 2 - 0.1)]; + const tint = S.paintTint; + for (const s of [-1, 1]) B.box('timber', fp[0] + o.dx * s * (o.w / 2 - 0.05), 0, fp[1] + o.dz * s * (o.w / 2 - 0.05), 0.1, o.h, 0.12, rot, { grain: 'long' }); + B.box('timber', fp[0], o.h - 0.1, fp[1], o.w, 0.1, 0.12, rot, { grain: 'long' }); + const tp = [o.cx + nx * (o.T / 2), o.cz + nz * (o.T / 2)]; + if (o.threshold !== false) B.box('ashlar', tp[0] - nx * (o.T / 2 - 0.12), -0.02, tp[1] - nz * (o.T / 2 - 0.12), o.w + 0.2, 0.1, o.T + 0.24, rot, { tint: tintJ(R, 0.06, 0xb8b0a0) }); + B.decal('mud', [tp[0] + nx * 0.25, 0.09, tp[1] + nz * 0.25], [0, 1, 0], o.w * 1.1, 0.7, R() * 0.4); + B.decal('grime', [tp[0] + o.dx * (o.w / 2 + 0.1), 0.95, tp[1] + o.dz * (o.w / 2 + 0.1)], [nx, 0, nz], 0.35, 0.8, 0); + if (o.leaf !== false) { + // the door leaf: boards, ledges and braces, iron latch; built in its own builder, hinged at one side + const D = E.builder(S.seed + 77 + S.doors.length), lw = o.w - 0.12, lh = o.h - 0.12, th = 0.05; + D.box('wood_painted', lw / 2, 0, 0, lw, lh, th, 0, { tint }); + for (const yy of [0.12, 0.5, 0.86]) D.box('wood_painted', lw / 2, lh * yy - 0.06, -th / 2 - 0.012, lw - 0.06, 0.12, 0.025, 0, { tint }); + D.box('wood_painted', lw / 2, lh * 0.18, -th / 2 - 0.012, 0.1, lh * 0.66, 0.022, 0, { rz: Math.atan2(lw * 0.85, lh * 0.66) * 0.6, tint }); + D.box('metal_rust', lw - 0.12, lh * 0.48, th / 2 + 0.01, 0.03, 0.12, 0.03, 0, { noFoot: true }); + D.box('metal_rust', lw - 0.2, lh * 0.53, th / 2 + 0.01, 0.16, 0.025, 0.02, 0, { noFoot: true }); + D.decal('scratches', [lw - 0.12, lh * 0.5, th / 2 + 0.002], [0, 0, 1], 0.3, 0.35, R() * 3); + D.decal('chipped', [lw * 0.5, 0.25, th / 2 + 0.002], [0, 0, 1], lw * 0.9, 0.45, 0); + D.decal('scratches', [lw * 0.5, 0.18, th / 2 + 0.002], [0, 0, 1], lw * 0.9, 0.3, Math.PI / 2); + const leaf = D.finish(); const pivot = new THREE.Group(); + const hx = o.cx - o.dx * (lw / 2) + nx * (o.T / 2 - 0.12), hz = o.cz - o.dz * (lw / 2) + nz * (o.T / 2 - 0.12); + pivot.position.set(hx, 0.06, hz); pivot.rotation.y = rot; pivot.add(leaf); pivot.userData.dynamic = true; group.add(pivot); + const door = { pivot, width: lw, x: o.cx, z: o.cz, closedY: rot, open(a) { pivot.rotation.y = rot - a; } }; + if (o.ajar) door.open(o.ajar); + if (S.damage > 0.4 && R() < 0.6) { door.hang = true; door.open(R.range(0.9, 1.5)); leaf.rotation.z = R.range(0.08, 0.16); leaf.position.y = -0.04; } // torn off the top hinge + S.doors.push(door); + } + } + + // ------------------------------------------------------------------ roofs + // Gable roof over a rectangle centred on the origin: ridge along X. eave: wall top height; pitch in radians. + function gableRoof(B, S, P) { + const R = S.R, ov = P.over || 0.35, gov = P.gable || 0.25, w = P.w, d = P.d, eave = P.eave, pitch = P.pitch || 0.72, mat = P.mat, th = 0.07; + const run = d / 2 + ov, rise = run * Math.tan(pitch), ridge = eave + (d / 2) * Math.tan(pitch); + const x0 = -w / 2 - gov, x1 = w / 2 + gov, L = x1 - x0, slope = Math.hypot(run, rise); + const sag = (x) => -P.sag * Math.sin(Math.PI * (x - x0) / L), eaveW = (x, side) => (P.eaveWander != null ? P.eaveWander : 0.035) * Math.sin(x * 1.3 + side * 2.1) * Math.sin(x * 0.37 + 1.0); + const holes = new Set(); + const fine = S.damage >= 0.45 && !P.noShell, NX = Math.max(2, Math.round(L / (fine ? 0.45 : 1.0))), NS = Math.max(2, Math.round(slope / (fine ? 0.42 : 0.9))); + if (S.damage > 0.25) { const nh = Math.round(S.damage * S.damage * NX * NS * 0.12); for (let k = 0; k < nh; k++) holes.add(((1 + R.int(NX - 2)) + ':' + (R.int(NS - 1)) + ':' + (R() < 0.5 ? 1 : -1))); } + // a shell hole: a ragged opening through tiles and boards, rafters snapped and hanging into it (damage >= 0.45) + const shell = S.damage >= 0.45 && !P.noShell ? { x: R.range(x0 + 1.6, x1 - 1.6), t: R.range(0.3, 0.65), side: R() < 0.5 ? 1 : -1, r: R.range(1.0, 1.7) } : null; + const inShell = (x, t, side) => shell && side === shell.side && Math.hypot(x - shell.x, (t - shell.t) * slope) < shell.r * (0.75 + 0.5 * E.vnoise(x * 2.1, t * 6, 7)); + for (const side of [1, -1]) { + for (let i = 0; i < NX; i++) for (let j = 0; j < NS; j++) { + const xa = x0 + L * i / NX, xb = x0 + L * (i + 1) / NX, ta = j / NS, tb = (j + 1) / NS; + const yE = eave - (ov * Math.tan(pitch)); + const pt = (x, t, off) => { const z = side * (run - t * run), y = yE + t * (ridge - yE) + sag(x) * t + (1 - t) * eaveW(x, side) + off; return [x, y, z]; }; + const nOff = (p, k) => [p[0], p[1] + k * Math.cos(pitch), p[2] + side * k * Math.sin(pitch)]; + const hole = holes.has(i + ':' + j + ':' + side) || inShell((xa + xb) / 2, (ta + tb) / 2, side); + const a = pt(xa, ta, 0), b = pt(xb, ta, 0), c = pt(xb, tb, 0), dd = pt(xa, tb, 0); + const sa = slope * ta, sb = slope * tb; + if (!hole) { + const A = nOff(a, th), Bp = nOff(b, th), C = nOff(c, th), D = nOff(dd, th); + if (side > 0) B.quad(mat, A, Bp, C, D, [[xa, sa], [xb, sa], [xb, sb], [xa, sb]], null, null); + else B.quad(mat, Bp, A, D, C, [[-xb, sa], [-xa, sa], [-xa, sb], [-xb, sb]], null, null); + // underside: roof boards + if (side > 0) B.quad('planks', b, a, dd, c, [[xb, sa], [xa, sa], [xa, sb], [xb, sb]], new THREE.Color(0.7, 0.66, 0.6), null); + else B.quad('planks', a, b, c, dd, [[xa, sa], [xb, sa], [xb, sb], [xa, sb]], new THREE.Color(0.7, 0.66, 0.6), null); + } else { + // missing tiles: battens across the hole, a few broken tiles hanging at the edge + for (let k = 0; k < 4; k++) { const t = ta + (tb - ta) * (k + 0.5) / 4, p = pt((xa + xb) / 2, t, -0.01); B.box('timber', p[0], p[1] - 0.012, p[2], xb - xa, 0.025, 0.05, 0, { rx: side * pitch, noFoot: true }); } + for (let k = 0; k < 3; k++) { const p = pt(xa + (xb - xa) * R(), ta + (tb - ta) * R() * 0.3, th); looseBlock(B, mat, p[0], p[1], p[2], R, 0.165, 0.014, 0.26); } + } + // eave edge (the tile thickness shows as a fascia board) at j == 0; gable verge at the ends + if (j === 0) { const A = nOff(a, th), Bp = nOff(b, th); B.quad('timber', side > 0 ? a : b, side > 0 ? b : a, side > 0 ? Bp : A, side > 0 ? A : Bp, [[0, 0], [1, 0], [1, 0.1], [0, 0.1]], null, null); } + } + // rafters' ends and barge boards along the gable edges + for (const ex of [x0, x1]) { + const a = [ex, eave - ov * Math.tan(pitch), side * run], c = [ex, ridge + sag(ex), 0], len = Math.hypot(c[1] - a[1], c[2] - a[2]); + B.box('timber', ex - Math.sign(ex) * 0.02, (a[1] + c[1]) / 2 - 0.11, (a[2] + c[2]) / 2, 0.05, 0.22, len, 0, { rx: side * pitch, grain: 'long', noFoot: true }); + } + // a fascia board under the tiles along the eave + B.box('timber', 0, eave - ov * Math.tan(pitch) - 0.16, side * (run - 0.03), L, 0.18, 0.04, 0, { grain: 'long', noFoot: true }); + // slipped tiles lying on the roof + for (let k = 0; k < Math.round(1 + S.damage * 6); k++) { + const t = R.range(0.1, 0.8), x = R.range(x0 + 0.5, x1 - 0.5), y = eave - ov * Math.tan(pitch) + t * (ridge - eave + ov * Math.tan(pitch)) + th + 0.02, z = side * (run - t * run); + B.box(mat, x, y, z, 0.17, 0.014, 0.27, R.range(-0.4, 0.4), { rx: side * pitch + R.range(-0.15, 0.15), noFoot: true }); + } + } + if (shell) { + // rafters every 0.45 m under the hole: the ones crossing it are snapped, the stubs splintered and the free ends + // hanging down into the room; charred boards round the edge + const yE = eave - ov * Math.tan(pitch), side = shell.side, P3 = (x, t) => [x, yE + t * (ridge - yE) + sag(x) * t - 0.08, side * (run - t * run)]; + for (let x = shell.x - shell.r - 0.2; x <= shell.x + shell.r + 0.2; x += 0.45) { + const dx = Math.abs(x - shell.x); if (dx > shell.r) continue; + const half = Math.sqrt(shell.r * shell.r - dx * dx) / slope, t0 = shell.t - half, t1 = shell.t + half; + for (const [ta, tb, dir] of [[Math.max(0, t0 - 0.25), t0 + R.range(0.02, 0.12), 1], [t1 - R.range(0.02, 0.12), Math.min(1, t1 + 0.25), -1]]) { + const a = P3(x, ta), b = P3(x, tb), len = Math.hypot(b[1] - a[1], b[2] - a[2]); + B.box('timber', x, (a[1] + b[1]) / 2 - 0.08, (a[2] + b[2]) / 2, 0.07, 0.16, len, 0, { rx: side * pitch, grain: 'long', noFoot: true, tint: new THREE.Color(0.55, 0.5, 0.45) }); + // splinters at the broken end + const e = dir > 0 ? b : a; for (let k = 0; k < 3; k++) B.box('timber', x + R.range(-0.03, 0.03), e[1] - 0.12, e[2], 0.02, 0.03, R.range(0.12, 0.3), R.range(-0.5, 0.5), { rx: side * pitch + R.range(-0.6, 0.6), noFoot: true, tint: new THREE.Color(0.7, 0.62, 0.5) }); + } + if (R() < 0.5) { const m = P3(x, shell.t); B.box('timber', x, m[1] - 1.2, m[2], 0.07, 0.16, R.range(1.2, 2.0), R.range(-0.3, 0.3), { rx: side * pitch + R.range(0.7, 1.1) * -side, grain: 'long', noFoot: true, tint: new THREE.Color(0.5, 0.45, 0.4) }); } + } + const c = P3(shell.x, shell.t); B.decal('soot', [c[0], c[1] + 0.2, c[2] + side * 0.05], [0, Math.cos(pitch), side * Math.sin(pitch)], shell.r * 3, shell.r * 2.6, R() * 3); + S.shellHole = { x: shell.x, y: c[1], z: c[2] }; + } + // ridge: a row of half-round ridge tiles, each a little out of line + const rN = Math.ceil(L / 0.42); + { const nr = Math.max(2, Math.round(L / 1.2)); for (let i = 0; i < nr; i++) { const xa = x0 + L * i / nr, xb = x0 + L * (i + 1) / nr, ya = ridge + sag(xa), yb = ridge + sag(xb); B.box(P.ridgeMat || 'roof_tile', (xa + xb) / 2, (ya + yb) / 2 + th - 0.04, 0, xb - xa + 0.02, 0.16, 0.22, 0, { noFoot: true, rz: Math.atan2(yb - ya, xb - xa) }); } } // plain ridge (all qualities), following the sag + B.det(2, () => { for (let i = 0; i < rN; i++) { + const x = x0 + (i + 0.5) * L / rN, g = new THREE.CylinderGeometry(0.13, 0.13, L / rN + 0.01, 8, 1, false, 0, Math.PI); + _Eu.set(R.range(-0.03, 0.03), 0, Math.PI / 2 + R.range(-0.02, 0.02)); _Q.setFromEuler(_Eu); + // cylinder axis is Y; turned to X, opening downward + const q2 = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(1, 0, 0), -Math.PI / 2); + _Q.multiply(q2); + _P.set(x, ridge + sag(x) + th + 0.02, R.range(-0.01, 0.01)); _S.set(1, 1, 1); + B.geo(P.ridgeMat || 'roof_tile', g, _M.compose(_P, _Q, _S), { tint: tintJ(R, 0.1), noFoot: true }); + } }); + return { ridge, eave, x0, x1, run }; + } + // the triangular gable wall above the eaves (outer + inner faces), local x = +-w/2 + function gableWall(B, S, P, xSide) { + const x = xSide * P.w / 2, T = P.T, eave = P.eave, ridge = P.ridge, d = P.d; + for (const side of [1, -1]) { + const xx = x + xSide * side * T / 2 * (side > 0 ? 1 : 1) * 0 + (side > 0 ? xSide * T / 2 : -xSide * T / 2); + const mat = side > 0 ? P.out : P.in; if (!mat) continue; + const A = [xx, eave, -d / 2], Bp = [xx, eave, d / 2], C = [xx, ridge, 0]; + const fwd = (xSide > 0) === (side > 0); + const uA = P.uStart != null ? P.uStart : 0; + if (fwd) B.tri(mat, A, C, Bp, [[uA, eave], [uA + d / 2, ridge], [uA + d, eave]], null, 0); + else B.tri(mat, Bp, C, A, [[uA + d, eave], [uA + d / 2, ridge], [uA, eave]], null, 0); + } + } + // corner quoins: alternating long and short dressed stones, slightly proud + function quoins(B, S, w, d, H, T) { B.det(2, () => quoins0(B, S, w, d, H, T)); } + // brick corners: alternate stretchers and headers sit 1-2.5 cm proud, chipped (a little turned), a few missing, so the + // outline of a brick corner is stepped, not a ruler line with a picture wrapped round it + function brickCorners(B, S, w, d, H, mat) { B.det(2, () => { const R = S.R, C = 0.105; for (let y = 0, k = 0; y < H - 0.05; y += C, k++) for (const [sx, sz] of [[1, 1], [-1, 1], [1, -1], [-1, -1]]) { + if (R() < 0.07) continue; const o = R.range(0.008, 0.025), la = k % 2 ? 0.32 : 0.16, lb = k % 2 ? 0.16 : 0.32, t = tintJ(R, 0.12); + B.box(mat, sx * (w / 2 - la / 2 + o), y + 0.005, sz * (d / 2 + o / 2), la, C - 0.014, o + 0.01, R.range(-0.02, 0.02), { tint: t, uvOff: [R() * 7, y] }); + B.box(mat, sx * (w / 2 + o / 2), y + 0.005, sz * (d / 2 - lb / 2 + o), o + 0.01, C - 0.014, lb, R.range(-0.02, 0.02), { tint: t, uvOff: [R() * 7, y] }); } }); } + // brick jambs at an opening: headers proud by 1-2 cm every other course up both sides + function brickJambs(B, S, o, mat) { B.det(2, () => { const R = S.R, C = 0.105, nx = -o.dz, nz = o.dx, rot = Math.atan2(-o.dz, o.dx); for (const sd of [-1, 1]) for (let y = o.y0, k = 0; y < o.y1 - 0.05; y += C, k++) { if (k % 2 || R() < 0.1) continue; + const pr = R.range(0.008, 0.02), a = sd * (o.w / 2 + 0.08), px = o.cx + o.dx * a + nx * (o.T / 2 + pr / 2), pz = o.cz + o.dz * a + nz * (o.T / 2 + pr / 2); B.box(mat, px, y + 0.005, pz, 0.16, C - 0.014, pr + 0.01, rot + R.range(-0.03, 0.03), { tint: tintJ(R, 0.12), uvOff: [R() * 7, y] }); } }); } + function quoins0(B, S, w, d, H, T) { + const R = S.R; let y = 0, k = 0; + while (y < H - 0.1) { + const h = Math.min(0.3, H - y), long = k % 2 === 0; + for (const [sx, sz] of [[1, 1], [-1, 1], [1, -1], [-1, -1]]) { + const tint = tintJ(R, 0.1, 0xb0aaa0), la = long ? 0.42 : 0.24, lb = long ? 0.24 : 0.42; + B.box('ashlar', sx * (w / 2 - la / 2 + 0.015), y, sz * (d / 2 + 0.015) - sz * 0.0, la + 0.03, h - 0.012, 0.03 + 0.001, 0, { tint }); + B.box('ashlar', sx * (w / 2 + 0.015) - sx * 0.0, y, sz * (d / 2 - lb / 2 + 0.015), 0.03 + 0.001, h - 0.012, lb + 0.03, 0, { tint }); + } + y += h; k++; + } + } + function chimney(B, S, x, z, base, top, sooty) { + const R = S.R, mat = sooty ? 'brick_sooty' : 'brick_red'; + B.box(mat, x, base, z, 0.62, top - base, 0.5, 0, { noFoot: true }); + B.box(mat, x, top - 0.12, z, 0.72, 0.14, 0.6, 0, { noFoot: true }); + for (const s of [-0.13, 0.15]) B.det(2, () => { const g = new THREE.CylinderGeometry(0.075, 0.09, 0.32 + R() * 0.1, 10); B.geo('roof_tile', g, _M.compose(_P.set(x + s, top + 0.16, z), _Q.identity(), _S.set(1, 1, 1)), { noFoot: true, tint: tintJ(R, 0.1) }); }); + B.decal('soot', [x, top - 0.45, z + 0.252], [0, 0, 1], 0.6, 0.9, 0); B.decal('soot', [x, top - 0.45, z - 0.252], [0, 0, -1], 0.6, 0.9, 0); + B.decal('soot', [x + 0.312, top - 0.45, z], [1, 0, 0], 0.5, 0.9, 0); B.decal('soot', [x - 0.312, top - 0.45, z], [-1, 0, 0], 0.5, 0.9, 0); + } + + // ------------------------------------------------------------------ interiors + function furn(B, S, kind, x, z, rot) { B.det(1, () => furn0(B, S, kind, x, z, rot)); } + function furn0(B, S, kind, x, z, rot) { + const R = S.R, c = Math.cos(rot || 0), s = Math.sin(rot || 0), L = (lx, lz) => [x + lx * c + lz * s, z - lx * s + lz * c]; + const add = (mat, lx, y0, lz, sx, sy, sz, o) => { const p = L(lx, lz); B.box(mat, p[0], y0 + (S.fy || 0), p[1], sx, sy, sz, rot || 0, Object.assign({ grain: 'long', foot: S.fy || 0 }, o || {})); }; + const col = (sx, sz, h) => B.col(x, z, sx, sz, S.fy || 0, (S.fy || 0) + h, rot || 0, 'wood', 'furniture'); + if (kind === 'table') { add('timber', 0, 0.72, 0, 1.6, 0.06, 0.85); for (const [a, b] of [[-0.7, -0.35], [0.7, -0.35], [-0.7, 0.35], [0.7, 0.35]]) add('timber', a, 0, b, 0.07, 0.72, 0.07); add('timber', 0, 0.55, 0, 1.4, 0.08, 0.04); B.decal('scratches', [x, (S.fy || 0) + 0.783, z], [0, 1, 0], 0.8, 0.5, rot || 0); col(1.6, 0.85, 0.78); } + else if (kind === 'chair') { add('timber', 0, 0.44, 0, 0.42, 0.04, 0.42); for (const [a, b] of [[-0.18, -0.18], [0.18, -0.18], [-0.18, 0.18], [0.18, 0.18]]) add('timber', a, 0, b, 0.04, 0.44, 0.04); for (const a of [-0.18, 0.18]) add('timber', a, 0.44, -0.19, 0.04, 0.5, 0.04); add('timber', 0, 0.8, -0.19, 0.4, 0.08, 0.03); } + else if (kind === 'dresser') { add('planks', 0, 0, 0, 1.4, 0.9, 0.5, { tint: new THREE.Color(0.8, 0.7, 0.6) }); add('timber', 0, 0.9, 0, 1.46, 0.04, 0.54); add('planks', 0, 0.94, -0.2, 1.4, 1.0, 0.04, { tint: new THREE.Color(0.8, 0.7, 0.6) }); for (const yy of [1.2, 1.5]) add('timber', 0, yy, -0.1, 1.36, 0.03, 0.22); for (let k = 0; k < 5; k++) { const p = L(-0.5 + k * 0.25, -0.08); B.geo('roof_tile', new THREE.CylinderGeometry(0.06, 0.05, 0.12, 10), _M.compose(_P.set(p[0], (S.fy || 0) + 1.29, p[1]), _Q.identity(), _S.set(1, 1, 1)), { tint: new THREE.Color(0.9, 0.9, 0.85) }); } col(1.46, 0.54, 1.94); } + else if (kind === 'cupboard') { add('wood_painted', 0, 0, 0, 1.0, 1.9, 0.55, { tint: S.paintTint }); add('timber', 0, 1.9, 0, 1.06, 0.06, 0.6); B.decal('chipped', L(0, 0.28).concat([]).length ? [L(0, 0.28)[0], (S.fy || 0) + 0.6, L(0, 0.28)[1]] : [0, 0, 0], [s, 0, c], 0.8, 0.8, 0); col(1.06, 0.6, 1.96); } + else if (kind === 'bed') { add('timber', 0, 0, 0, 1.0, 0.4, 2.0); add('canvas', 0, 0.4, 0.05, 0.94, 0.14, 1.9, { tint: new THREE.Color(0.9, 0.88, 0.8) }); add('timber', 0, 0, -1.0, 1.06, 0.9, 0.06); col(1.0, 2.0, 0.55); } + else if (kind === 'desk') { add('timber', 0, 0.74, 0, 1.3, 0.05, 0.7); add('timber', -0.45, 0, 0, 0.4, 0.74, 0.66); add('timber', 0.6, 0, 0, 0.05, 0.74, 0.66); add('canvas', 0.1, 0.79, 0.05, 0.5, 0.004, 0.35, { tint: new THREE.Color(1.2, 1.15, 1.0) }); add('canvas', -0.2, 0.795, -0.1, 0.3, 0.004, 0.22, { tint: new THREE.Color(1.1, 1.05, 0.9), rz: 0 }); col(1.3, 0.7, 0.8); } + else if (kind === 'bench') { add('timber', 0, 0.42, 0, 1.6, 0.05, 0.3); for (const a of [-0.65, 0.65]) add('timber', a, 0, 0, 0.06, 0.42, 0.26); } + else if (kind === 'stove') { add('metal_rust', 0, 0, 0, 0.8, 0.75, 0.6, { noFoot: true }); add('metal_painted', 0, 0.75, 0, 0.84, 0.04, 0.64, { tint: new THREE.Color(0.25, 0.25, 0.25), noFoot: true }); const g = new THREE.CylinderGeometry(0.07, 0.07, 1.8, 10); const p = L(0.25, -0.2); B.geo('metal_rust', g, _M.compose(_P.set(p[0], (S.fy || 0) + 1.7, p[1]), _Q.identity(), _S.set(1, 1, 1)), { noFoot: true }); col(0.8, 0.6, 0.8); } + else if (kind === 'barrel') { const g = new THREE.CylinderGeometry(0.28, 0.28, 0.85, 14); g.attributes.position.array.forEach((v, i, a) => { if (i % 3 === 0 || i % 3 === 2) { const y = a[i - (i % 3) + 1]; a[i] = v * (1 + 0.12 * (1 - (y / 0.425) ** 2)); } }); g.computeVertexNormals(); B.geo('planks', g, _M.compose(_P.set(x, (S.fy || 0) + 0.425, z), _Q.identity(), _S.set(1, 1, 1)), { keepUv: true, uvW: 1.8, uvH: 0.85 }); for (const yy of [0.12, 0.73]) B.geo('metal_rust', new THREE.CylinderGeometry(0.315, 0.315, 0.04, 14, 1, true), _M.compose(_P.set(x, (S.fy || 0) + yy, z), _Q.identity(), _S.set(1, 1, 1)), {}); col(0.6, 0.6, 0.85); } + } + function fireplace(B, S, x, z, rot) { + const c = Math.cos(rot), s = Math.sin(rot), L = (lx, lz) => [x + lx * c + lz * s, z - lx * s + lz * c]; + const a = (mat, lx, y, lz, sx, sy, sz, o) => { const p = L(lx, lz); B.box(mat, p[0], y + (S.fy || 0), p[1], sx, sy, sz, rot, o); }; + a('fieldstone', -0.75, 0, 0.1, 0.4, 1.3, 0.55); a('fieldstone', 0.75, 0, 0.1, 0.4, 1.3, 0.55); + a('timber', 0, 1.3, 0.12, 1.95, 0.25, 0.6, { grain: 'long' }); + a('brick_sooty', 0, 0, -0.12, 1.1, 1.3, 0.1); + a('ashlar', 0, -0.02, 0.25, 2.0, 0.06, 0.8, { tint: new THREE.Color(0.55, 0.52, 0.48) }); + const p = L(0, 0.0); B.decal('scorch', [p[0], (S.fy || 0) + 0.06, p[1]], [0, 1, 0], 1.0, 0.7, rot); + const ps = L(0, 0.41); B.decal('soot', [ps[0], (S.fy || 0) + 1.75, ps[1]], [s, 0, c], 1.6, 0.9, 0); + for (let k = 0; k < 3; k++) { const q = L(-0.2 + k * 0.2, 0.05); B.box('bark_oak', q[0], (S.fy || 0) + 0.08 + k * 0.03, q[1], 0.6, 0.1, 0.1, rot + 0.3 * k, { noFoot: true, tint: new THREE.Color(0.5, 0.45, 0.4) }); } + B.col(x, z, 2.0, 0.8, S.fy || 0, (S.fy || 0) + 1.55, rot, 'stone', 'fireplace'); + } + function floorDeck(B, S, w, d, y, T, mat, hole) { + // boards on joists; hole = { x0, x1, z0, z1 } left open for the stairs + const iw = w - 2 * T, id = d - 2 * T; + const pieces = hole ? [[-iw / 2, hole.x0, -id / 2, id / 2], [hole.x1, iw / 2, -id / 2, id / 2], [hole.x0, hole.x1, -id / 2, hole.z0], [hole.x0, hole.x1, hole.z1, id / 2]] : [[-iw / 2, iw / 2, -id / 2, id / 2]]; + for (const [xa, xb, za, zb] of pieces) if (xb - xa > 0.01 && zb - za > 0.01) { B.box(mat, (xa + xb) / 2, y - 0.03, (za + zb) / 2, xb - xa, 0.03, zb - za, 0, { grain: 'long', noFoot: true }); B.col((xa + xb) / 2, (za + zb) / 2, xb - xa, zb - za, y - 0.25, y, 0, 'wood', 'floor'); } + // joists across the depth, seen from the room below + B.det(1, () => { for (let x = -iw / 2 + 0.3; x < iw / 2 - 0.1; x += 0.6) { if (hole && x > hole.x0 && x < hole.x1) continue; B.box('timber', x, y - 0.23, 0, 0.12, 0.2, id, 0, { grain: 'long', noFoot: true }); } }); + B.box('timber', 0, y - 0.3, 0, iw, 0.26, 0.24, 0, { grain: 'long', noFoot: true }); // the main beam + } + function stairs(B, S, x0, z0, dirX, y0, y1, width) { + const n = Math.round((y1 - y0) / 0.2), rise = (y1 - y0) / n, run = 0.25; + for (let i = 0; i < n; i++) { + const x = x0 + dirX * (i + 0.5) * run; + B.box('floorboards', x, y0 + i * rise + rise - 0.035, z0, run + 0.02, 0.035, width, 0, { noFoot: true }); + B.box('planks', x + dirX * run * 0.45, y0 + i * rise, z0, 0.02, rise, width, 0, { noFoot: true, tint: new THREE.Color(0.7, 0.65, 0.6) }); + B.col(x, z0, run, width, y0, y0 + i * rise + rise, 0, 'wood', 'stairs'); + } + for (const s of [-1, 1]) { const len = Math.hypot(n * run, y1 - y0); B.box('timber', x0 + dirX * n * run / 2, y0 + (y1 - y0) / 2 - 0.15, z0 + s * (width / 2 + 0.03), len, 0.25, 0.05, 0, { rz: -dirX * Math.atan2(y1 - y0, n * run), grain: 'long', noFoot: true }); } + } + + // ------------------------------------------------------------------ house-like buildings + // Shared by farmhouse, cottage, shop units, church nave: four walls with openings, gable roof, details. + function house(B, S, H) { + const { w, d, T, floors, storey } = H, R = S.R, wallH = floors * storey + (H.knee || 0); + const mats = { out: H.out, in: H.in }; + // plinth course + if (H.plinth) { B.box(H.plinth, 0, -0.3, 0, w + 0.08, 0.6, d + 0.08, 0, { tint: tintJ(R, 0.05) }); } + // openings per side from the layout + const sides = [ + { name: 'front', x0: -w / 2, z0: d / 2, dx: 1, dz: 0, L: w, ops: H.front || [] }, + { name: 'right', x0: w / 2, z0: d / 2, dx: 0, dz: -1, L: d, ops: H.right || [] }, + { name: 'back', x0: w / 2, z0: -d / 2, dx: -1, dz: 0, L: w, ops: H.back || [] }, + { name: 'left', x0: -w / 2, z0: -d / 2, dx: 0, dz: 1, L: d, ops: H.left || [] } + ]; + let u = 0; + for (const sd of sides) { + // walls on the sides are inset by the thickness so the corners overlap cleanly + const along = sd.name === 'front' || sd.name === 'back'; + const W = { + x0: sd.x0 + sd.dz * (T / 2) * 0 - sd.dz * 0, z0: sd.z0, dx: sd.dx, dz: sd.dz, L: sd.L, T, H: wallH, ops: sd.ops, mats, uStart: u, surf: H.surf, + capStart: false, capEnd: false + }; + // shift the wall inward by T/2 (its centre line) + const nx = -sd.dz, nz = sd.dx; W.x0 -= nx * T / 2; W.z0 -= nz * T / 2; + if (!along) { W.x0 += sd.dx * T; W.z0 += sd.dz * T; W.L -= 2 * T; } + wallRun(B, W); + // dress the openings + for (const o of sd.ops) { + const am = (o.a0 + o.a1) / 2 - (along ? 0 : T), cx = W.x0 + sd.dx * am, cz = W.z0 + sd.dz * am; + if (o.door) dressDoor(B, S, { cx, cz, dx: sd.dx, dz: sd.dz, T, w: o.a1 - o.a0, h: o.y1 - o.y0, ajar: o.ajar, leaf: o.leaf, threshold: o.threshold }, S.group); + else dressWindow(B, S, { cx, cz, dx: sd.dx, dz: sd.dz, T, w: o.a1 - o.a0, y0: o.y0, y1: o.y1, head: o.head || H.head, shutters: o.shutters != null ? o.shutters : H.shutters, lit: o.lit, broken: o.broken, sill: H.sill, sillMat: H.sillMat }); + if (o.door && H.head && H.head !== 'none') dressWindow; // (door heads use the same dressing below) + if (o.door && H.doorHead) { const nn = [-sd.dz, sd.dx], hp = [cx + nn[0] * T / 2, cz + nn[1] * T / 2]; if (H.doorHead === 'lintel') B.box('ashlar', hp[0] + nn[0] * 0.015, o.y1, hp[1] + nn[1] * 0.015, o.a1 - o.a0 + 0.4, 0.26, 0.12, Math.atan2(-sd.dz, sd.dx), { tint: tintJ(R, 0.06) }); else if (H.doorHead === 'timber') B.box('timber', hp[0] + nn[0] * 0.02, o.y1, hp[1] + nn[1] * 0.02, o.a1 - o.a0 + 0.4, 0.2, 0.16, Math.atan2(-sd.dz, sd.dx), { grain: 'long' }); } + } + // wear along the foot of the wall and the odd bullet pock + for (let k = 0; k < Math.round(sd.L / 3); k++) { + const a = R.range(0.3, sd.L - 0.3), p = [W.x0 + sd.dx * a + nx * (T / 2 + 0.001), W.z0 + sd.dz * a + nz * (T / 2 + 0.001)]; + if (sd.ops.some(o => a > o.a0 - 0.2 && a < o.a1 + 0.2 && o.door)) continue; + B.decal(R() < 0.5 ? 'moss' : 'mud', [p[0], R.range(0.1, 0.3), p[1]], [nx, 0, nz], R.range(0.6, 1.4), R.range(0.3, 0.6), 0); + if (R() < 0.3) B.decal('waterstain', [p[0], R.range(0.5, wallH - 0.5), p[1]], [nx, 0, nz], R.range(0.8, 1.6), R.range(0.8, 1.6), R() * 3); + } + // bursts: a machine-gun burst walks across a wall in a tight cluster; blast chips low down from a grenade + if (S.damage > 0.2) for (let k = 0; k < Math.round(S.damage * sd.L / 4); k++) { const ca = R.range(0.8, sd.L - 0.8), cy = R.range(0.6, Math.min(2.4, wallH - 0.3)); for (let q = 0; q < 6 + R.int(9); q++) { const a = ca + R.range(-0.55, 0.55) + q * 0.04, p = [W.x0 + sd.dx * a + nx * (T / 2), W.z0 + sd.dz * a + nz * (T / 2)]; B.decal(R() < 0.6 ? 'bullethole' : 'pocks', [p[0], cy + R.range(-0.3, 0.3), p[1]], [nx, 0, nz], R.range(0.12, 0.3), null, R() * 6); } + if (R() < 0.4) { const a = R.range(0.6, sd.L - 0.6), p = [W.x0 + sd.dx * a + nx * (T / 2), W.z0 + sd.dz * a + nz * (T / 2)]; B.decal('chipped', [p[0], 0.5, p[1]], [nx, 0, nz], R.range(1.0, 1.8), 1.0, R() * 6); B.decal('scorch', [p[0], 0.35, p[1]], [nx, 0, nz], 1.6, 0.9, 0); } } + const pocks = Math.round(S.damage * sd.L * 0.6); + for (let k = 0; k < pocks; k++) { const a = R.range(0.3, sd.L - 0.3), p = [W.x0 + sd.dx * a + nx * (T / 2), W.z0 + sd.dz * a + nz * (T / 2)]; B.decal(R() < 0.7 ? 'pocks' : 'bullethole', [p[0], R.range(0.4, wallH - 0.3), p[1]], [nx, 0, nz], R.range(0.25, 0.6), null, R() * 6); } + u += sd.L; + } + if (H.quoins) quoins(B, S, w, d, wallH, T); + else if (/brick/.test(H.out)) { brickCorners(B, S, w, d, wallH, H.out); for (const sd of sides) { const nx = -sd.dz, nz = sd.dx; for (const o of sd.ops) { const along = sd.name === 'front' || sd.name === 'back', am = (o.a0 + o.a1) / 2 - (along ? 0 : T), wx0 = sd.x0 - nx * T / 2 + (along ? 0 : sd.dx * T), wz0 = sd.z0 - nz * T / 2 + (along ? 0 : sd.dz * T); brickJambs(B, S, { cx: wx0 + sd.dx * am, cz: wz0 + sd.dz * am, dx: sd.dx, dz: sd.dz, T, w: o.a1 - o.a0, y0: o.y0, y1: o.y1 }, H.out); } } } + // roof and gables + const old = !H.trim, roof = gableRoof(B, S, { w, d, eave: wallH, pitch: H.pitch || 0.75, mat: H.roof, sag: H.sag != null ? H.sag : old ? 0.09 + S.damage * 0.12 + S.R() * 0.08 : 0.04 + S.R() * 0.03, over: H.over, gable: H.gableOver, ridgeMat: H.ridgeMat, eaveWander: old ? 0.09 : 0.03 }); + for (const xs of [1, -1]) gableWall(B, S, { w: w - T, d: d - 0.001, T, eave: wallH, ridge: roof.ridge - 0.05, out: H.out, in: H.in, uStart: 0 }, xs); + B.col(-w / 2 + T / 2, 0, T, d, wallH, roof.ridge, 0, H.surf || 'stone', 'gable'); B.col(w / 2 - T / 2, 0, T, d, wallH, roof.ridge, 0, H.surf || 'stone', 'gable'); + S.roofTop = roof.ridge; S.eaveH = wallH; S.footX = w; S.footZ = d; S.outMat = H.out; + return { wallH, ridge: roof.ridge }; + } + // window / door layout along a wall of length L for n bays + function bays(L, n, y0, y1, extra) { const out = []; for (let i = 0; i < n; i++) { const c = L * (i + 0.5) / n, w = (extra && extra.w) || 0.9; out.push(Object.assign({ a0: c - w / 2, a1: c + w / 2, y0, y1 }, extra || {})); } return out; } + + // ------------------------------------------------------------------ the kinds + const KINDS = {}; + KINDS.farmhouse = function (B, S, sp) { + const w = sp.w || 12, d = sp.d || 7.5, floors = sp.floors || 2, storey = 2.8, T = 0.5, R = S.R; + const litW = (i) => R() < (sp.lit || 0); + const front = []; + const nb = Math.max(3, Math.round(w / 3)), mid = Math.floor(nb / 2); + for (let f = 0; f < floors; f++) for (let i = 0; i < nb; i++) { + const c = w * (i + 0.5) / nb; + if (f === 0 && i === mid) front.push({ a0: c - 0.55, a1: c + 0.55, y0: 0, y1: 2.15, door: true, ajar: sp.doorAjar || 0 }); + else front.push({ a0: c - 0.5, a1: c + 0.5, y0: f * storey + 0.9, y1: f * storey + 2.25 - (f ? 0.15 : 0), lit: litW(), broken: R() < sp.damage * 0.6, shutters: true }); + } + const back = []; for (let f = 0; f < floors; f++) for (let i = 0; i < nb - 1; i++) { const c = w * (i + 0.5) / (nb - 1); if (f === 0 && i === 0) back.push({ a0: c - 0.45, a1: c + 0.45, y0: 0, y1: 2.05, door: true }); else back.push({ a0: c - 0.45, a1: c + 0.45, y0: f * storey + 0.95, y1: f * storey + 2.15, lit: litW(), broken: R() < sp.damage * 0.6, shutters: true }); } + const right = [{ a0: d / 2 - 0.4 - 0.5, a1: d / 2 - 0.4 + 0.5, y0: storey + 0.95, y1: storey + 2.1, lit: litW() }]; + const H = { w, d, T, floors, storey, out: sp.out || 'fieldstone', in: 'plaster_interior', roof: sp.roof === 'slate' ? 'slate' : 'roof_tile', head: 'lintel', doorHead: 'lintel', shutters: true, quoins: true, front, back, right, left: [], pitch: 0.78, surf: 'stone' }; + const r = house(B, S, H); + chimney(B, S, -w / 2 + T + 0.31, -0.3, 0, r.ridge + 0.9, true); + if (w > 10) chimney(B, S, w / 2 - T - 0.31, 0.4, 0, r.ridge + 0.75, false); + // interior: ground floor flags, upper floor, stairs, a partition with a doorway, fireplace, furniture + B.box('ashlar', 0, -0.05, 0, w - 2 * T, 0.06, d - 2 * T, 0, { tint: new THREE.Color(0.62, 0.6, 0.56), noFoot: true }); + const sx0 = w / 2 - T - 0.35 - 3.8, hole = { x0: sx0, x1: w / 2 - T, z0: -d / 2 + T, z1: -d / 2 + T + 1.0 }; + for (let f = 1; f < floors; f++) floorDeck(B, S, w, d, f * storey, T, 'floorboards', f === 1 ? hole : null); + stairs(B, S, w / 2 - T - 0.2, -d / 2 + T + 0.5, -1, 0, storey, 0.9); + // partition wall (plaster both sides) with a doorway, splitting off the office at the right end + const px = w / 2 - T - 3.6; + wallRun(B, { x0: px, z0: d / 2 - T, dx: 0, dz: -1, L: d - 2 * T - 1.2, T: 0.14, H: storey - 0.32, ops: [{ a0: 0.6, a1: 1.5, y0: 0, y1: 2.0 }], mats: { out: 'plaster_interior', in: 'plaster_interior' }, surf: 'stone', capStart: true, capEnd: true }); + fireplace(B, S, -w / 2 + T + 0.45, -0.3, Math.PI / 2); + S.fy = 0; + furn(B, S, 'table', -1.2, 0.6, 0); furn(B, S, 'chair', -1.6, 1.25, Math.PI); furn(B, S, 'chair', -0.6, 0.0, 0.2); furn(B, S, 'bench', -1.2, -0.2, 0); + furn(B, S, 'dresser', -2.2, -d / 2 + T + 0.3, 0); furn(B, S, 'stove', 0.9, -d / 2 + T + 0.4, 0); + furn(B, S, 'desk', w / 2 - T - 1.0, d / 2 - T - 0.8, Math.PI); furn(B, S, 'chair', w / 2 - T - 1.0, d / 2 - T - 1.4, 0.3); furn(B, S, 'cupboard', px + 0.45, -d / 2 + T + 1.6, -Math.PI / 2); + furn(B, S, 'barrel', -w / 2 + T + 1.6, d / 2 - T - 0.5); + if (floors > 1) { S.fy = storey; furn(B, S, 'bed', -w / 2 + T + 2.0, -d / 2 + T + 1.1, 0); furn(B, S, 'bed', -0.5, -d / 2 + T + 1.1, 0); furn(B, S, 'cupboard', 1.8, d / 2 - T - 0.35, Math.PI); furn(B, S, 'chair', -2.5, 1.5, 1.0); S.fy = 0; } + S.lights.push({ x: -1.2, y: 2.1, z: 0.6, color: 0xffa860, r: 10, power: sp.lit ? 2.4 : 0, interior: true }); if (sp.lit) lantern(B, -1.2, 0.78, 0.6); + }; + KINDS.cottage = function (B, S, sp) { + const w = sp.w || 8, d = sp.d || 6, T = 0.3, storey = 2.6, R = S.R, floors = sp.floors || 1; + const front = [{ a0: w / 2 - 0.5, a1: w / 2 + 0.5, y0: 0, y1: 2.05, door: true }, ...bays(w, 2, 0.9, 2.05, { w: 0.9 }).map((o, i) => Object.assign(o, { a0: i ? w * 0.8 - 0.45 : w * 0.2 - 0.45, a1: i ? w * 0.8 + 0.45 : w * 0.2 + 0.45, lit: R() < (sp.lit || 0), broken: R() < sp.damage * 0.6 }))]; + const back = bays(w, 2, 0.95, 2.0, { w: 0.8 }).map(o => Object.assign(o, { lit: R() < (sp.lit || 0) })); + const r = house(B, S, { w, d, T, floors, storey, knee: floors === 1 ? 0.4 : 0, out: sp.out || 'brick_red', in: 'plaster_interior', roof: sp.roof === 'tile' ? 'roof_tile' : 'slate', head: 'arch', doorHead: 'timber', shutters: false, quoins: false, front, back, right: [{ a0: d / 2 - 0.4, a1: d / 2 + 0.4, y0: storey * floors - 0.2, y1: storey * floors + 0.8 }], left: [], pitch: 0.8, plinth: 'brick_sooty', sill: true, surf: 'stone' }); + chimney(B, S, w / 2 - T - 0.31, 0, 0, r.ridge + 0.8, true); + B.box('floorboards', 0, -0.03, 0, w - 2 * T, 0.03, d - 2 * T, 0, { noFoot: true }); + }; + // a long, low camp office hut: brick walls (sp.out for another wall material) on a sooty plinth, a shallow slate roof, a row of sash windows, a short stack + KINDS.office = function (B, S, sp) { + const w = sp.w || 14, d = sp.d || 7, T = 0.25, storey = 2.7, R = S.R; + // sp.doorEnd: the door is in the +X gable end (local), not the middle of the front + const nf = Math.max(2, Math.round(w / 3.2)), front = sp.doorEnd ? [] : [{ a0: w / 2 - 0.55, a1: w / 2 + 0.55, y0: 0, y1: 2.1, door: true }]; + for (let i = 0; i < nf; i++) { const c = w * (i + 0.5) / nf; if (sp.doorEnd || Math.abs(c - w / 2) > 1.4) front.push({ a0: c - 0.55, a1: c + 0.55, y0: 0.95, y1: 2.25, lit: R() < (sp.lit || 0) }); } + const back = bays(w, nf, 0.95, 2.25, { w: 1.1 }).map(o => Object.assign(o, { lit: R() < (sp.lit || 0) })); + const end = [{ a0: d / 2 - 0.5, a1: d / 2 + 0.5, y0: 0.95, y1: 2.25 }], dEnd = [{ a0: d / 2 - 0.6, a1: d / 2 + 0.6, y0: 0, y1: 2.1, door: true }]; + const r = house(B, S, { w, d, T, floors: 1, storey, out: sp.out || 'brick_red', in: 'plaster_interior', plinth: 'brick_sooty', roof: 'slate', pitch: 0.3, over: 0.45, head: 'lintel', doorHead: 'timber', shutters: false, quoins: false, front, back, right: sp.doorEnd ? dEnd : end, left: end }); + chimney(B, S, -w / 2 + 2.2, 0, 0, r.ridge + 0.6, true); + // door step, a boot scraper, the stains rain makes under the sills and along the plinth + if (sp.doorEnd) { B.box('concrete', w / 2 + 0.35, 0, 0, 0.6, 0.16, 1.6, 0, { tint: new THREE.Color(0.85, 0.83, 0.8) }); B.box('metal_rust', w / 2 + 0.5, 0.16, 1.0, 0.05, 0.12, 0.35, 0, { noFoot: true }); } + else { B.box('concrete', 0, 0, d / 2 + 0.35, 1.5, 0.16, 0.6, 0, { tint: new THREE.Color(0.85, 0.83, 0.8) }); B.box('metal_rust', 0.95, 0.16, d / 2 + 0.5, 0.35, 0.12, 0.05, 0, { noFoot: true }); } + for (const z of [d / 2 + 0.01, -d / 2 - 0.01]) { B.decal('waterstain', [0, 0.45, z], [0, 0, Math.sign(z)], w * 0.95, 0.9, 0); B.decal(R() < 0.5 ? 'moss' : 'grime', [R.range(-w / 3, w / 3), 0.25, z], [0, 0, Math.sign(z)], 2.5, 0.5, 0); } + B.box('floorboards', 0, -0.03, 0, w - 2 * T, 0.03, d - 2 * T, 0, { noFoot: true }); + }; + KINDS.shoprow = function (B, S, sp) { + const n = sp.units || 3, uw = sp.w ? sp.w / n : 5.4, d = sp.d || 8, R = S.R, T = 0.3, storey = 3.0; + const NAMES = ['BOULANGERIE', 'EPICERIE', 'QUINCAILLERIE', 'CAFE DU PONT', 'MERCERIE', 'TABAC', 'BOUCHERIE', 'HORLOGERIE']; + for (let i = 0; i < n; i++) { + const ox = (i - (n - 1) / 2) * uw, Bu = E.builder(S.seed + i * 13), floors = 2 + (R() < 0.3 ? 1 : 0); + const Su = Object.assign({}, S, { R: E.rng(S.seed + i * 13), windows: [], lights: [], doors: [], group: new THREE.Group() }); + const plaster = R() < 0.35; + const front = [{ a0: uw * 0.72 - 0.5, a1: uw * 0.72 + 0.5, y0: 0, y1: 2.3, door: true }, { a0: 0.45, a1: uw * 0.55, y0: 0.6, y1: 2.5, lit: R() < (sp.lit || 0), broken: R() < sp.damage * 0.7, head: 'timber' }]; + for (let f = 1; f < floors; f++) for (const c of [uw * 0.27, uw * 0.73]) front.push({ a0: c - 0.45, a1: c + 0.45, y0: f * storey + 0.9, y1: f * storey + 2.2, lit: R() < (sp.lit || 0) * 0.6, broken: R() < sp.damage * 0.5, shutters: plaster }); + const r = house(Bu, Su, { w: uw, d, T, floors, storey, out: plaster ? 'plaster' : (R() < 0.3 ? 'brick_sooty' : 'brick_red'), in: 'plaster_interior', roof: R() < 0.6 ? 'slate' : 'roof_tile', head: plaster ? 'lintel' : 'arch', doorHead: 'timber', front, back: bays(uw, 2, storey + 0.9, storey + 2.1, { w: 0.8 }), left: [], right: [], pitch: 0.7 + R() * 0.15, quoins: plaster, sag: 0.03 + R() * 0.05, gableOver: 0.02, over: 0.3 }); + // fascia sign with a painted name (invented shop words only) + const sign = signMesh(NAMES[(S.seed + i * 3) % NAMES.length], uw - 0.5, 0.58, Su.R); + sign.position.set(ox, 2.6, d / 2 + 0.06); S.group.add(sign); + Bu.box('timber', 0, 2.55, d / 2 + 0.02, uw - 0.4, 0.62, 0.06, 0, { grain: 'long', tint: new THREE.Color(0.55, 0.5, 0.45) }); + chimney(Bu, Su, uw / 2 - 0.35, -1, r.wallH - 1, r.ridge + 1.0, true); + const g = Bu.finish(); g.position.x = ox; S.group.add(g); + Su.colliders = Bu.colliders.map(c => Object.assign(c, { x: c.x + ox })); S.extraCols.push(...Su.colliders); + for (const wv of Su.windows) S.windows.push(Object.assign(wv, { x: wv.x + ox })); for (const l of Su.lights) S.lights.push(Object.assign(l, { x: l.x + ox })); + for (const dr of Su.doors) { dr.pivot.parent.remove(dr.pivot); dr.pivot.position.x += ox; S.group.add(dr.pivot); S.doors.push(dr); } + for (const c of Su.group.children.slice()) { c.position.x += ox; S.group.add(c); } + } + }; + function signMesh(text, w, h, R) { + const c = document.createElement('canvas'); c.width = 512; c.height = Math.round(512 * h / w); + const g = c.getContext('2d'); g.fillStyle = '#2c3a33'; g.fillRect(0, 0, c.width, c.height); + g.font = 'bold ' + Math.round(c.height * 0.72) + 'px Georgia, "Times New Roman", serif'; g.textAlign = 'center'; g.textBaseline = 'middle'; g.fillStyle = '#e8dcb4'; g.fillText(text, c.width / 2, c.height * 0.55, c.width * 0.92); g.strokeStyle = '#bba873'; g.lineWidth = 2; g.strokeRect(6, 6, c.width - 12, c.height - 12); + // weathering: flaked paint and grime + for (let i = 0; i < 160; i++) { g.fillStyle = `rgba(${R() < 0.5 ? '20,18,14' : '90,80,64'},${R() * 0.25})`; g.fillRect(R() * c.width, R() * c.height, R() * 5, R() * 2); } + const t = new THREE.CanvasTexture(c); t.encoding = THREE.sRGBEncoding; t.anisotropy = 4; + const m = new THREE.MeshStandardMaterial({ map: t, roughness: 0.85, emissive: 0xffffff, emissiveMap: t, emissiveIntensity: 0.12 }); m.userData.linear = true; + const mesh = new THREE.Mesh(new THREE.PlaneGeometry(w, h), m); mesh.receiveShadow = true; return mesh; + } + KINDS.barn = function (B, S, sp) { + const w = sp.w || 10, d = sp.d || 16, R = S.R, T = 0.45, base = 1.1, eave = 4.6; + // a stone plinth wall, then vertical boards on a timber frame; the long side faces +Z (big doors) + // here the ridge runs along the barn's length: we build it rotated so the length is local X + const L = d, Wd = w; + const dw = 3.4, dh = 3.6; + // stone lower walls + const sides = [ + { x0: -L / 2, z0: Wd / 2, dx: 1, dz: 0, len: L, ops: [{ a0: L / 2 - dw / 2, a1: L / 2 + dw / 2, y0: 0, y1: 3.0 }] }, + { x0: L / 2, z0: Wd / 2, dx: 0, dz: -1, len: Wd, ops: [{ a0: Wd / 2 - 0.5, a1: Wd / 2 + 0.5, y0: 0, y1: 2.0 }] }, + { x0: L / 2, z0: -Wd / 2, dx: -1, dz: 0, len: L, ops: [] }, + { x0: -L / 2, z0: -Wd / 2, dx: 0, dz: 1, len: Wd, ops: [] } + ]; + let u = 0; + for (const sd of sides) { + const nx = -sd.dz, nz = sd.dx, along = sd.dx !== 0; + const W = { x0: sd.x0 - nx * T / 2, z0: sd.z0 - nz * T / 2, dx: sd.dx, dz: sd.dz, L: sd.len, T, H: base, ops: sd.ops.map(o => Object.assign({}, o, { y1: Math.min(o.y1, base + 0.01) })), mats: { out: 'fieldstone', in: 'fieldstone' }, uStart: u, surf: 'stone' }; + if (!along) { W.x0 += sd.dx * T; W.z0 += sd.dz * T; W.L -= 2 * T; } + wallRun(B, W); + // boarded upper walls: vertical planks on the outside of a timber frame + const bt = 0.04, H2 = eave - base, plankMat = sp.lit ? 'planks|gaplit' : 'planks'; + const W2 = { x0: sd.x0 - nx * bt / 2, z0: sd.z0 - nz * bt / 2, dx: sd.dx, dz: sd.dz, L: sd.len, T: bt, H: H2, y0: base, ops: sd.ops.concat(along && sd.z0 > 0 ? [{ a0: L * 0.2 - 0.6, a1: L * 0.2 + 0.6, y0: 3.0, y1: 4.1 }] : []).map(o => Object.assign({}, o)), mats: { out: plankMat, in: 'planks' }, uStart: u, surf: 'wood', capTop: true }; + wallRun(B, W2); + // posts of the frame inside, every 2.5 m, and a wall plate + for (let a = 0; a <= sd.len + 0.01; a += sd.len / Math.round(sd.len / 2.5)) { + if (sd.ops.some(o => a > o.a0 - 0.1 && a < o.a1 + 0.1)) continue; + const px = sd.x0 + sd.dx * a - nx * (bt + 0.1), pz = sd.z0 + sd.dz * a - nz * (bt + 0.1); + B.box('timber', px, base, pz, 0.2, H2, 0.2, 0, { grain: 'long', noFoot: true }); + } + B.box('timber', sd.x0 + sd.dx * sd.len / 2 - nx * (bt + 0.1), eave - 0.22, sd.z0 + sd.dz * sd.len / 2 - nz * (bt + 0.1), along ? sd.len : 0.22, 0.22, along ? 0.22 : sd.len, 0, { grain: 'long', noFoot: true }); + // wear on the lower boards + for (let k = 0; k < Math.round(sd.len / 2); k++) B.decal(R() < 0.5 ? 'mud' : 'grime', [sd.x0 + sd.dx * R.range(0.5, sd.len - 0.5) + nx * 0.025, base + R.range(0.2, 0.6), sd.z0 + sd.dz * R.range(0.5, sd.len - 0.5) + nz * 0.025], [nx, 0, nz], R.range(0.6, 1.4), 0.5, 0); + u += sd.len; + } + // big doors: two leaves hung open, frame, and the loft hatch + for (const s of [-1, 1]) { + const D = E.builder(S.seed + 40 + s), lw = dw / 2 - 0.05; + D.box('planks', lw / 2, 0, 0, lw, dh - 0.05, 0.05, 0, {}); + for (const yy of [0.15, 0.5, 0.85]) D.box('timber', lw / 2, (dh - 0.05) * yy - 0.08, 0.04, lw - 0.05, 0.16, 0.04, 0, { grain: 'long' }); + D.box('timber', lw / 2, 0.4, 0.04, 0.14, dh - 0.9, 0.035, 0, { rz: s * 0.62, grain: 'long' }); + D.decal('mud', [lw / 2, 0.25, 0.03], [0, 0, 1], lw * 0.9, 0.5, 0); D.decal('scratches', [lw / 2, 1.0, 0.03], [0, 0, 1], lw * 0.7, 0.6, 0.3); + const leaf = D.finish(), pv = new THREE.Group(); pv.add(leaf); pv.userData.dynamic = true; + if (s < 0) { pv.position.set(-dw / 2, 0.02, Wd / 2 + 0.03); } else { pv.position.set(dw / 2, 0.02, Wd / 2 + 0.03); pv.scale.x = -1; } + S.group.add(pv); + const door = { pivot: pv, width: lw, x: s * dw / 4, z: Wd / 2, open(a) { pv.rotation.y = -s * a; } }; + door.open(sp.doorOpen != null ? sp.doorOpen : 1.4 + R() * 0.3); S.doors.push(door); + } + B.box('timber', 0, dh, Wd / 2 + 0.02, dw + 0.5, 0.25, 0.25, 0, { grain: 'long' }); + // interior: posts, tie beams, half loft with ladder, hay, stalls + for (let x = -L / 2 + 2.5; x < L / 2 - 1; x += 2.5) { + for (const z of [-Wd / 2 + 2.2, Wd / 2 - 2.2]) { B.box('timber', x, 0, z, 0.24, eave - 0.2, 0.24, 0, { grain: 'long' }); B.col(x, z, 0.26, 0.26, 0, eave, 0, 'wood', 'post'); B.decal('scratches', [x, 0.9, z + 0.121], [0, 0, 1], 0.2, 0.5, Math.PI / 2); } + B.box('timber', x, eave - 0.25, 0, 0.22, 0.26, Wd - 0.2, 0, { grain: 'long', noFoot: true }); + } + const loftX0 = 1.0, loftY = 2.7; + B.box('floorboards', (loftX0 + L / 2 - T) / 2, loftY, 0, L / 2 - T - loftX0, 0.05, Wd - 0.2, 0, { noFoot: true, grain: 'long' }); + B.col((loftX0 + L / 2 - T) / 2, 0, L / 2 - T - loftX0, Wd - 0.2, loftY - 0.2, loftY + 0.05, 0, 'wood', 'floor'); + for (let z = -Wd / 2 + 0.6; z < Wd / 2 - 0.3; z += 0.6) B.box('timber', (loftX0 + L / 2 - T) / 2, loftY - 0.2, z, L / 2 - T - loftX0, 0.2, 0.12, 0, { grain: 'long', noFoot: true }); + // ladder up to the loft + const lx = loftX0 - 0.05, lz = 1.0; + for (const s of [-0.22, 0.22]) B.box('timber', lx - 0.45, 0, lz + s, 0.06, 3.0, 0.06, 0, { rz: 0.28, grain: 'long', noFoot: true }); + for (let k = 1; k < 10; k++) B.box('timber', lx - 0.45 + k * 0.08, k * 0.29, lz, 0.04, 0.04, 0.5, 0, { noFoot: true }); + // hay in the loft and on the floor, a stall partition, a cart wheel against the wall + for (let k = 0; k < 14; k++) { const x = R.range(loftX0 + 0.8, L / 2 - T - 0.7), z = R.range(-Wd / 2 + 0.8, Wd / 2 - 0.8); E.hayBale(B, x, loftY + 0.05 + (k > 9 ? 0.4 : 0), z, R.range(-0.2, 0.2) + (R() < 0.5 ? 0 : Math.PI / 2), R); } + for (let k = 0; k < 5; k++) E.hayBale(B, -L / 2 + T + 0.8 + (k % 2) * 0.95, (k > 2 ? 0.4 : 0), -Wd / 2 + T + 0.6 + Math.floor(k / 2) * 0.0, 0, R); + B.decal('leaves', [-1.5, 0.01, 0.5], [0, 1, 0], 3.5, 2.5, 0.3); B.decal('mud', [0, 0.01, Wd / 2 - 0.8], [0, 1, 0], 3.2, 1.6, 0); + for (let k = 0; k < 4; k++) B.box('planks', -L / 2 + T + 3.2 + k * 0.0, 0, -Wd / 2 + T + 1.3, 0.05, 1.3, 2.4, 0, { noFoot: true }); + // straw on the floor + B.box('earth', 0, -0.04, 0, L - 2 * T, 0.05, Wd - 2 * T, 0, { noFoot: true, tint: new THREE.Color(0.7, 0.65, 0.55) }); + // roof along the barn's length (local X) + const roof = gableRoof(B, S, { w: L, d: Wd, eave, pitch: 0.82, mat: sp.roof === 'tile' ? 'roof_tile' : 'slate', sag: 0.12 + S.damage * 0.12 + R() * 0.08, over: 0.4, gable: 0.3, eaveWander: 0.08 }); + // boarded gables + for (const xs of [1, -1]) gableWall(B, S, { w: L - 0.04, d: Wd, T: 0.04, eave, ridge: roof.ridge - 0.05, out: 'planks', in: 'planks' }, xs); + S.lights.push({ x: -2.5, y: 2.2, z: 0.8, color: 0xffa050, r: 13, power: sp.lit ? 2.8 : 0, interior: true }); if (sp.lit) lantern(B, -2.5, 1.9, 0.8, true); + S.roofTop = roof.ridge; S.eaveH = eave; S.footX = L; S.footZ = Wd; S.outMat = 'fieldstone'; + }; + KINDS.shed = function (B, S, sp) { + const w = sp.w || 4, d = sp.d || 3, R = S.R, h1 = 2.4, h2 = 1.9, bt = 0.04; + const sides = [ + { x0: -w / 2, z0: d / 2, dx: 1, dz: 0, len: w, ops: [{ a0: w * 0.3, a1: w * 0.3 + 0.9, y0: 0, y1: 1.95 }], h: h1 }, + { x0: w / 2, z0: d / 2, dx: 0, dz: -1, len: d, ops: [{ a0: d / 2 - 0.3, a1: d / 2 + 0.3, y0: 1.1, y1: 1.6 }], h: h2 }, + { x0: w / 2, z0: -d / 2, dx: -1, dz: 0, len: w, ops: [], h: h2 }, + { x0: -w / 2, z0: -d / 2, dx: 0, dz: 1, len: d, ops: [], h: h2 } + ]; + let u = 0; + for (const sd of sides) { const nx = -sd.dz, nz = sd.dx; wallRun(B, { x0: sd.x0 - nx * bt / 2, z0: sd.z0 - nz * bt / 2, dx: sd.dx, dz: sd.dz, L: sd.len, T: bt, H: sd.h, ops: sd.ops, mats: { out: 'planks', in: 'planks' }, uStart: u, surf: 'wood' }); u += sd.len; } + // gaps up the sides between front (taller) and back: triangles of boards + for (const xs of [-1, 1]) for (const io of [1, -1]) { const x = xs * w / 2 + xs * io * 0.0; const A = [x, h2, -d / 2], Bq = [x, h2, d / 2], C = [x, h1, d / 2]; const uz = (z) => xs > 0 ? w + (d / 2 - z) : 2 * w + d + (z + d / 2); // the same u the wall run below uses, so boards continue + if ((xs > 0) === (io > 0)) B.tri('planks', A, C, Bq, [[uz(-d / 2), h2], [uz(d / 2), h1], [uz(d / 2), h2]], null, 0); else B.tri('planks', A, Bq, C, [[uz(-d / 2), h2], [uz(d / 2), h2], [uz(d / 2), h1]], null, 0); } + // posts in the corners, a mono-pitch roof of slates (corrugated sheets would need a new material) + for (const [a, b] of [[-1, -1], [1, -1], [-1, 1], [1, 1]]) B.box('timber', a * (w / 2 - 0.06), 0, b * (d / 2 - 0.06), 0.1, b > 0 ? h1 : h2, 0.1, 0, { grain: 'long' }); + const pitch = Math.atan2(h1 - h2, d), len = Math.hypot(d + 0.5, h1 - h2); + B.box(sp.roof === 'tile' ? 'roof_tile' : 'slate', 0, (h1 + h2) / 2 + 0.02, 0, w + 0.4, 0.05, len, 0, { rx: -pitch, noFoot: true }); + B.box('planks', 0, (h1 + h2) / 2 - 0.01, 0, w + 0.3, 0.025, len - 0.05, 0, { rx: -pitch, noFoot: true, tint: new THREE.Color(0.6, 0.55, 0.5) }); + for (let k = 0; k < 3; k++) B.box('timber', -w / 2 + 0.2 + k * (w - 0.4) / 2, (h1 + h2) / 2 - 0.12, 0, 0.08, 0.1, len - 0.1, 0, { rx: -pitch, noFoot: true }); + // door leaf + dressDoor(B, S, { cx: -w / 2 + w * 0.3 + 0.45, cz: d / 2 - bt / 2, dx: 1, dz: 0, T: bt, w: 0.9, h: 1.95, ajar: 0.5, threshold: false }, S.group); + E.prop && null; + for (let k = 0; k < 3; k++) B.decal(R() < 0.5 ? 'mud' : 'moss', [R.range(-w / 2 + 0.3, w / 2 - 0.3), 0.2, d / 2 + 0.003], [0, 0, 1], 0.8, 0.35, 0); + S.roofTop = h1 + 0.1; + }; + KINDS.church = function (B, S, sp) { + const w = sp.w || 16, d = sp.d || 8, R = S.R, T = 0.7, nave = 5.6; + const side = []; for (let i = 0; i < 4; i++) { const c = w * (i + 0.5) / 4; side.push({ a0: c - 0.45, a1: c + 0.45, y0: 1.8, y1: 4.4, head: 'pointed', lit: R() < (sp.lit || 0) * 0.5, broken: R() < sp.damage * 0.6 }); } + const r = house(B, S, { w, d, T, floors: 1, storey: nave, out: 'fieldstone', in: 'plaster_interior', roof: 'slate', head: 'pointed', shutters: false, quoins: true, front: side, back: side.map(o => Object.assign({}, o, { lit: false })), right: [{ a0: d / 2 - 0.9, a1: d / 2 + 0.9, y0: 2.0, y1: 4.8, head: 'pointed' }], left: [], pitch: 0.95, sag: 0.03 + S.damage * 0.1, plinth: 'ashlar', sillMat: 'ashlar' }); + // stepped buttresses between the nave windows, with sloped weatherings + for (let i = 0; i <= 4; i++) { const x = -w / 2 + i * w / 4; for (const sz of [-1, 1]) { const z = sz * (d / 2 + 0.35); B.box('fieldstone', x, 0, z, 0.75, 2.6, 0.7, 0, {}); B.box('fieldstone', x, 2.6, sz * (d / 2 + 0.22), 0.65, 1.6, 0.45, 0, {}); B.box('ashlar', x, 4.1, sz * (d / 2 + 0.2), 0.7, 0.12, 0.5, 0, { rx: -sz * 0.6, noFoot: true }); B.col(x, z, 0.75, 0.7, 0, 3.5, 0, 'stone', 'buttress'); } } + // the tower at the west end (local -X), with a pointed door, louvred belfry openings and a pyramid spire + const tw = 4.4, th = 15, tx = -w / 2 - tw / 2 + 0.2, Tt = 0.8; + const T2 = E.builder(S.seed + 9), S2 = Object.assign({}, S, { R: E.rng(S.seed + 9), windows: S.windows, lights: S.lights, doors: S.doors }); + const bell = (o) => Object.assign({ y0: th - 3.4, y1: th - 1.2, head: 'pointed', a0: tw / 2 - 0.5, a1: tw / 2 + 0.5 }, o || {}); + const sidesT = [ + { x0: -tw / 2, z0: tw / 2, dx: 1, dz: 0, ops: [{ a0: tw / 2 - 0.7, a1: tw / 2 + 0.7, y0: 0, y1: 2.8, door: true }, bell()] }, + { x0: tw / 2, z0: tw / 2, dx: 0, dz: -1, ops: [bell()] }, + { x0: tw / 2, z0: -tw / 2, dx: -1, dz: 0, ops: [bell()] }, + { x0: -tw / 2, z0: -tw / 2, dx: 0, dz: 1, ops: [bell(), { a0: tw / 2 - 0.3, a1: tw / 2 + 0.3, y0: 6, y1: 7.6 }] } + ]; + let u = 0; + for (const sd of sidesT) { + const nx = -sd.dz, nz = sd.dx, along = sd.dx !== 0, Wt = { x0: sd.x0 - nx * Tt / 2, z0: sd.z0 - nz * Tt / 2, dx: sd.dx, dz: sd.dz, L: tw, T: Tt, H: th, ops: sd.ops, mats: { out: 'fieldstone', in: 'fieldstone' }, uStart: u, surf: 'stone' }; + if (!along) { Wt.x0 += sd.dx * Tt; Wt.z0 += sd.dz * Tt; Wt.L -= 2 * Tt; } + wallRun(T2, Wt); + for (const o of sd.ops) { + const am = (o.a0 + o.a1) / 2 - (along ? 0 : Tt), cx = Wt.x0 + sd.dx * am, cz = Wt.z0 + sd.dz * am; + if (o.door) dressDoor(T2, S2, { cx, cz, dx: sd.dx, dz: sd.dz, T: Tt, w: 1.4, h: 2.8 }, S.group); + else if (o.y0 > 10) { // belfry: louvre boards instead of glass + const nn = [-sd.dz, sd.dx], hp = [cx + nn[0] * (Tt / 2 - 0.2), cz + nn[1] * (Tt / 2 - 0.2)]; + for (let k = 0; k < 7; k++) T2.box('planks', hp[0], o.y0 + 0.15 + k * 0.28, hp[1], 0.95, 0.03, 0.22, Math.atan2(-sd.dz, sd.dx), { rx: 0.6, noFoot: true, tint: new THREE.Color(0.5, 0.48, 0.45) }); + dressWindow(T2, S2, { cx, cz, dx: sd.dx, dz: sd.dz, T: Tt, w: 1.0, y0: o.y0, y1: o.y1, head: 'pointed', sill: true, shutters: false, lit: false, broken: true }); + } else dressWindow(T2, S2, { cx, cz, dx: sd.dx, dz: sd.dz, T: Tt, w: o.a1 - o.a0, y0: o.y0, y1: o.y1, head: 'lintel', sill: true }); + } + u += tw; + } + quoins(T2, S2, tw, tw, th, Tt); + // string course and a parapet-less pyramid spire of slate + T2.box('ashlar', 0, th - 0.2, 0, tw + 0.12, 0.2, tw + 0.12, 0, { noFoot: true }); + const sh = 6.5, cone = new THREE.ConeGeometry((tw + 0.4) * 0.707, sh, 4, 3); cone.rotateY(Math.PI / 4); + T2.geo('slate', cone, _M.compose(_P.set(0, th + sh / 2, 0), _Q.identity(), _S.set(1, 1, 1)), { noFoot: true }); + T2.box('metal_rust', 0, th + sh - 0.1, 0, 0.05, 1.4, 0.05, 0, { noFoot: true }); T2.box('metal_rust', 0, th + sh + 0.8, 0, 0.5, 0.05, 0.05, 0, { noFoot: true }); + // a weathervane arrow, a clock face on the tower (plain numerals, no maker's name) + T2.box('metal_rust', 0.35, th + sh + 0.86, 0, 0.32, 0.18, 0.015, 0, { noFoot: true, rz: 0.78 }); + { const cy = th - 4.6, cz = tw / 2 + 0.03; T2.geo('wood_painted', new THREE.CircleGeometry(0.62, 20), _M.compose(_P.set(0, cy, cz), _Q.identity(), _S.set(1, 1, 1)), { noFoot: true, tint: new THREE.Color(1.5, 1.45, 1.35) }); + T2.geo('metal_rust', new THREE.TorusGeometry(0.64, 0.035, 4, 24), _M.compose(_P.set(0, cy, cz + 0.01), _Q.identity(), _S.set(1, 1, 1)), { noFoot: true }); + for (let k = 0; k < 12; k++) { const a = k / 12 * TAU; T2.box('metal_painted', Math.cos(a) * 0.5, cy + Math.sin(a) * 0.5 - 0.04, cz + 0.02, 0.03, 0.08, 0.01, 0, { noFoot: true, rz: a, tint: new THREE.Color(0.15, 0.15, 0.15) }); } + T2.box('metal_painted', 0.12, cy - 0.02, cz + 0.03, 0.32, 0.04, 0.01, 0, { noFoot: true, rz: 0.5, tint: new THREE.Color(0.1, 0.1, 0.1) }); T2.box('metal_painted', 0, cy - 0.02, cz + 0.035, 0.03, 0.46, 0.01, 0, { noFoot: true, rz: -0.3, tint: new THREE.Color(0.1, 0.1, 0.1) }); } + // a gabled porch on the tower door + { const pz = tw / 2 + 1.1; for (const sx of [-1, 1]) T2.box('fieldstone', sx * 1.15, 0, pz, 0.35, 2.3, 2.2, 0, {}); T2.box('timber', 0, 2.3, pz + 1.0, 2.7, 0.2, 0.2, 0, { noFoot: true }); + const pr = new THREE.ConeGeometry(1.0, 1, 4, 1).rotateY(Math.PI / 4); T2.geo('slate', pr, _M.compose(_P.set(0, 2.85, pz), _Q.identity(), _S.set(2.1, 1.1, 1.75)), { noFoot: true }); + T2.col(-1.15, pz, 0.35, 2.2, 0, 2.3, 0, 'stone', 'porch'); T2.col(1.15, pz, 0.35, 2.2, 0, 2.3, 0, 'stone', 'porch'); } + const g2 = T2.finish(); g2.position.x = tx; S.group.add(g2); + for (const c of T2.colliders) S.extraCols.push(Object.assign(c, { x: c.x + tx })); + for (const dr of S.doors) if (dr.pivot.parent === S.group && !dr._moved && dr.x < 0) { } + S.roofTop = th + sh; + }; + KINDS.ruin = function (B, S, sp) { + // a burnt-out brick house: walls with stepped broken tops and loose bricks, no roof, charred beams, rubble + const w = sp.w || 9, d = sp.d || 7, R = S.R, T = 0.33, H = 5.4, dmg = Math.max(0.5, S.damage); + const sides = [ + { x0: -w / 2, z0: d / 2, dx: 1, dz: 0, L: w, ops: [{ a0: w / 2 - 0.5, a1: w / 2 + 0.5, y0: 0, y1: 2.1 }, { a0: 1.0, a1: 1.9, y0: 0.9, y1: 2.1 }, { a0: w - 1.9, a1: w - 1.0, y0: 0.9, y1: 2.1 }, { a0: 1.0, a1: 1.9, y0: 3.4, y1: 4.5 }] }, + { x0: w / 2, z0: d / 2, dx: 0, dz: -1, L: d, ops: [{ a0: d / 2 - 0.45, a1: d / 2 + 0.45, y0: 0.9, y1: 2.1 }] }, + { x0: w / 2, z0: -d / 2, dx: -1, dz: 0, L: w, ops: [{ a0: 2.0, a1: 2.9, y0: 0.9, y1: 2.1 }] }, + { x0: -w / 2, z0: -d / 2, dx: 0, dz: 1, L: d, ops: [] } + ]; + let u = 0; const course = 0.105, bw = 0.33; + for (let si = 0; si < 4; si++) { + const sd = sides[si], nx = -sd.dz, nz = sd.dx, along = sd.dx !== 0; + // broken top profile: a smooth random line, quantised to brick courses and half-bricks, with a deep bite + const prof = (a) => { const n = E.fbm2(a * 0.35 + si * 7, si * 3.1, 900 + S.seed, 3); const bite = Math.exp(-((a - sd.L * (0.3 + 0.4 * E.hash(si, 1, S.seed))) ** 2) / 2.5) * 2.5 * dmg; return Math.max(0.6, H * (1 - dmg * 0.55 * n) - bite); }; + let x0 = sd.x0 - nx * T / 2, z0 = sd.z0 - nz * T / 2, L = sd.L; if (!along) { x0 += sd.dx * T; z0 += sd.dz * T; L -= 2 * T; } + // split the wall into columns of one brick length; each column has its own height, rounded to courses + for (let a = 0; a < L - 1e-3; a += bw) { + const a1 = Math.min(L, a + bw), top = Math.floor(prof(a + bw / 2) / course) * course; + const ops = sd.ops.map(o => ({ a0: o.a0 - a, a1: o.a1 - a, y0: o.y0, y1: o.y1 })).filter(o => o.a1 > 0 && o.a0 < a1 - a); + wallRun(B, { x0: x0 + sd.dx * a, z0: z0 + sd.dz * a, dx: sd.dx, dz: sd.dz, L: a1 - a, T, H: top, ops, mats: { out: 'brick_red', in: 'brick_sooty' }, uStart: u + a, surf: 'stone' }); + // ragged course on top: some bricks of the next course still sitting there, half-bricks proud + if (R() < 0.6) B.det(2, () => B.box('brick_red', x0 + sd.dx * (a + bw / 2) + R.range(-0.02, 0.02), top, z0 + sd.dz * (a + bw / 2), along ? 0.32 : T * 0.9, 0.1, along ? T * 0.9 : 0.32, R.range(-0.08, 0.08), { tint: tintJ(R, 0.12), uvOff: [R() * 3, R() * 3] })); + if (R() < 0.25) looseBlock(B, 'brick_red', x0 + sd.dx * (a + bw / 2) + nx * R.range(-0.1, 0.1), top + 0.07, z0 + sd.dz * (a + bw / 2) + nz * R.range(-0.1, 0.1), R, null, null, null, tintJ(R, 0.12)); + } + // soot above the openings, scorch, pocks, a big crack + for (const o of sd.ops) { const am = (o.a0 + o.a1) / 2 - (along ? 0 : T); B.decal('soot', [x0 + sd.dx * am + nx * (T / 2 + 0.003), o.y1 + 0.6, z0 + sd.dz * am + nz * (T / 2 + 0.003)], [nx, 0, nz], 1.4, 1.4, 0); B.decal('soot', [x0 + sd.dx * am - nx * (T / 2 + 0.003), o.y1 + 0.6, z0 + sd.dz * am - nz * (T / 2 + 0.003)], [-nx, 0, -nz], 1.4, 1.6, 0); } + for (let k = 0; k < Math.round(L * 0.8); k++) { const a = R.range(0.3, L - 0.3); B.decal(R() < 0.6 ? 'pocks' : 'bullethole', [x0 + sd.dx * a + nx * (T / 2 + 0.002), R.range(0.5, 2.5), z0 + sd.dz * a + nz * (T / 2 + 0.002)], [nx, 0, nz], R.range(0.25, 0.5), null, R() * 6); } + B.decal('crack', [x0 + sd.dx * L * 0.6 + nx * (T / 2 + 0.002), 1.6, z0 + sd.dz * L * 0.6 + nz * (T / 2 + 0.002)], [nx, 0, nz], 1.2, 1.6, 0.2); + B.decal('scorch', [x0 + sd.dx * L * 0.4 - nx * (T / 2 + 0.002), 1.2, z0 + sd.dz * L * 0.4 - nz * (T / 2 + 0.002)], [-nx, 0, -nz], 2.4, 2.4, 0); + // loose bricks fallen at the foot, both sides + for (let k = 0; k < Math.round(L * 2.5); k++) { const a = R.range(0, L), side = R() < 0.5 ? 1 : -1; looseBlock(B, 'brick_red', x0 + sd.dx * a + nx * side * R.range(0.25, 1.4), 0.03, z0 + sd.dz * a + nz * side * R.range(0.25, 1.4), R, null, null, null, tintJ(R, 0.14)); } + u += sd.L; + } + // rubble piles inside, charred beams fallen across, a burnt floor + rubble(B, -w * 0.15, -d * 0.1, 1.8, R, {}, 70); rubble(B, w * 0.25, d * 0.15, 1.3, R, {}, 40); + for (let k = 0; k < 3; k++) B.box('timber', R.range(-w / 4, w / 4), 0.2 + k * 0.25, R.range(-d / 4, d / 4), w * 0.7, 0.22, 0.24, R.range(-0.6, 0.6), { rz: R.range(-0.35, 0.35), tint: new THREE.Color(0.18, 0.16, 0.15), grain: 'long', noFoot: true }); + B.box('timber', -w / 2 + 0.6, 2.4, 0, 0.24, 0.24, d * 0.8, 0, { rx: 0.35, tint: new THREE.Color(0.15, 0.13, 0.12), grain: 'long', noFoot: true }); + B.decal('scorch', [0, 0.02, 0], [0, 1, 0], Math.min(w, d) * 0.8, Math.min(w, d) * 0.8, 0); + B.box('earth', 0, -0.04, 0, w - 2 * T, 0.05, d - 2 * T, 0, { tint: new THREE.Color(0.45, 0.42, 0.4), noFoot: true }); + S.roofTop = H; + }; + KINDS.bunker = function (B, S, sp) { + // a concrete pillbox with board-marked walls, a firing slit on each face, a thick roof slab, sandbags and earth + const w = sp.w || 5, d = sp.d || 5, R = S.R, T = 0.9, H = 2.2; + const slit = (L) => [{ a0: L / 2 - 0.7, a1: L / 2 + 0.7, y0: 1.15, y1: 1.45 }]; + const sides = [ + { x0: -w / 2, z0: d / 2, dx: 1, dz: 0, L: w, ops: slit(w) }, { x0: w / 2, z0: d / 2, dx: 0, dz: -1, L: d, ops: slit(d) }, + { x0: w / 2, z0: -d / 2, dx: -1, dz: 0, L: w, ops: [{ a0: w / 2 - 0.45, a1: w / 2 + 0.45, y0: 0, y1: 1.9 }] }, { x0: -w / 2, z0: -d / 2, dx: 0, dz: 1, L: d, ops: slit(d) } + ]; + let u = 0; + for (const sd of sides) { + const nx = -sd.dz, nz = sd.dx, along = sd.dx !== 0, W = { x0: sd.x0 - nx * T / 2, z0: sd.z0 - nz * T / 2, dx: sd.dx, dz: sd.dz, L: sd.L, T, H, ops: sd.ops, mats: { out: 'concrete', in: 'concrete' }, uStart: u, surf: 'stone' }; + if (!along) { W.x0 += sd.dx * T; W.z0 += sd.dz * T; W.L -= 2 * T; } + wallRun(B, W); + for (let k = 0; k < Math.round(sd.L * 1.2 * (0.3 + S.damage)); k++) { const a = R.range(0.3, sd.L - 0.3); B.decal(R() < 0.7 ? 'pocks' : 'gouges', [W.x0 + sd.dx * a + nx * (T / 2 + 0.002), R.range(0.6, H - 0.2), W.z0 + sd.dz * a + nz * (T / 2 + 0.002)], [nx, 0, nz], R.range(0.3, 0.7), null, R() * 6); } + const am = sd.L / 2; B.decal('scorch', [W.x0 + sd.dx * am + nx * (T / 2 + 0.003), 1.3, W.z0 + sd.dz * am + nz * (T / 2 + 0.003)], [nx, 0, nz], 1.8, 1.2, 0); + B.decal('waterstain', [W.x0 + sd.dx * am * 0.6 + nx * (T / 2 + 0.002), H - 0.5, W.z0 + sd.dz * am * 0.6 + nz * (T / 2 + 0.002)], [nx, 0, nz], 1.5, 1.2, 0); + u += sd.L; + } + B.box('concrete', 0, H, 0, w + 0.6, 0.6, d + 0.6, 0, { noFoot: true }); B.col(0, 0, w + 0.6, d + 0.6, H, H + 0.6, 0, 'stone', 'roof'); + // earth and grass sods on the roof, sandbags round the entrance + placeRock(B, 'mud', 0, H + 0.45, 0, Math.min(w, d) * 0.45, 77, [0, 0.4, 0]); + for (let k = 0; k < 2; k++) for (let i = 0; i < 6; i++) E.sandbag(B, -1.4 + i * 0.5 + (k % 2) * 0.25, k * 0.17, -d / 2 - 1.3, (k ? 0.1 : -0.1), R); + B.box('concrete', 0, -0.05, 0, w - 2 * T, 0.06, d - 2 * T, 0, { noFoot: true, tint: new THREE.Color(0.7, 0.7, 0.7) }); + S.roofTop = H + 1; + }; + KINDS.pillbox = KINDS.bunker; + + // small helpers other files use too + E.hayBale = function (B, x, y, z, rot, R) { + B.box('straw', x, y, z, 0.9, 0.4, 0.48, rot, { noFoot: true, tint: tintJ(R, 0.12) }); + for (const s of [-0.25, 0.25]) { const c = Math.cos(rot), sn = Math.sin(rot); B.box('canvas', x + c * s, y - 0.001, z - sn * s, 0.012, 0.402, 0.482, rot, { noFoot: true, tint: new THREE.Color(0.7, 0.62, 0.45) }); } + B.col(x, z, 0.9, 0.48, y, y + 0.4, rot, 'wood', 'hay'); + }; + E.sandbag = function (B, x, y, z, rot, R) { + const g = new THREE.SphereGeometry(0.5, E.Q.name === 'low' ? 6 : 8, E.Q.name === 'low' ? 3 : 4); const p = g.attributes.position; + for (let i = 0; i < p.count; i++) { const X = p.getX(i), Y = p.getY(i), Z = p.getZ(i); p.setXYZ(i, Math.sign(X) * Math.pow(Math.abs(X) * 2, 0.45) / 2, Y * (Y < 0 ? 0.7 : 1), Math.sign(Z) * Math.pow(Math.abs(Z) * 2, 0.6) / 2); } + g.computeVertexNormals(); + _Eu.set(R.range(-0.05, 0.05), rot + R.range(-0.08, 0.08), R.range(-0.04, 0.04)); _Q.setFromEuler(_Eu); _P.set(x, y + 0.085, z); _S.set(0.56, 0.17, 0.32); + B.geo('sandbag', g, _M.compose(_P, _Q, _S), { tint: tintJ(R, 0.1), uvOff: [R() * 5, R() * 5] }); + B.col(x, z, 0.55, 0.33, y, y + 0.17, rot, 'cloth', 'sandbag'); + }; + E.placeRock = placeRock; E.rubble = rubble; E.tintJ = tintJ; + // a hanging oil lantern (lit glass, iron frame) at an interior light + function lantern(B, x, y, z, hook) { B.box('metal_rust', x, y, z, 0.16, 0.03, 0.16, 0, { noFoot: true }); B.geo('glass_lit', new THREE.CylinderGeometry(0.06, 0.06, 0.16, 10), _M.compose(_P.set(x, y + 0.11, z), _Q.identity(), _S.set(1, 1, 1)), { noFoot: true }); B.box('metal_rust', x, y + 0.19, z, 0.14, 0.04, 0.14, 0, { noFoot: true }); if (hook) B.box('metal_rust', x, y + 0.23, z, 0.01, 0.6, 0.01, 0, { noFoot: true }); } + // ivy climbing one end wall: leaf cards flat against the stone, ragged top, thicker at the foot + function ivy(spec, R, kind) { + const w = spec.w || 10, d = spec.d || 8, x = (kind === 'church' ? 1 : -1) * (w / 2 + 0.03), z0 = R.range(-d / 2 + 0.6, 0), wd = R.range(1.8, 3.2), top = R.range(2.6, 4.2); + const P = [], N = [], U = [], C = [], Wd = [], I = [], cu = 0.0, cv = 0.5; + for (let k = 0; k < 220; k++) { + const zz = z0 + R() * wd, yy = Math.pow(R(), 1.4) * top * (0.7 + 0.3 * Math.sin(zz * 3.1)), s = R.range(0.35, 0.6), base = P.length / 3, a = R() * 6.283, ca = Math.cos(a), sa = Math.sin(a); + for (const [i, j] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) { P.push(x + Math.sign(x) * R.range(0, 0.06), yy + (i * sa + j * ca) * s / 2, zz + (i * ca - j * sa) * s / 2); N.push(Math.sign(x), 0.3, 0); U.push(0.0 + (i * 0.5 + 0.5) * 0.25, 0.5 + (j * 0.5 + 0.5) * 0.5); const sh = 0.55 + 0.4 * R(); C.push(sh * 0.9, sh, sh * 0.85); Wd.push(R() * 6, 0.1, 0.4, 0.2); } + I.push(base, base + 1, base + 2, base, base + 2, base + 3); + } + const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.Float32BufferAttribute(P, 3)); g.setAttribute('normal', new THREE.Float32BufferAttribute(N, 3)); g.setAttribute('uv', new THREE.Float32BufferAttribute(U, 2)); g.setAttribute('color', new THREE.Float32BufferAttribute(C, 3)); g.setAttribute('aWind', new THREE.Float32BufferAttribute(Wd, 4)); g.setIndex(I); + const m = new THREE.Mesh(g, E.leafMaterial('ivy', { stiff: 0.05, trans: 0.6 })); m.receiveShadow = true; m.name = 'ivy'; E.registerDetail(m, 60); return m; + } + + // ------------------------------------------------------------------ the public building call + // ------------------------------------------------------------------ rugged, grown-over-time buildings + // Old country buildings were added to for a century: a wing at the back (L or T plan) in another material, a lean-to + // or outshot with a rusty sheet roof, a porch, outside stone steps to a loft door, a doorway bricked up in odd brick, + // patches of repair, render fallen off the foot of the wall, buttresses and tie plates where a wall moved. + // spec.rugged (0..1, default 0 = none; IVEnv.settle passes opts.rugged) picks how many. Extra footprints are returned + // as building.extraFoot [{ x, z, hx, hz, h }] (local) so a settlement gives them colliders and shells. + function mergeB(B, B2, x, z, rot, y) { + const c = Math.cos(rot), s = Math.sin(rot); y = y || 0; + for (const k in B2.buckets) { + const src = B2.buckets[k], dst = B.buckets[k] || (B.buckets[k] = { p: [], n: [], u: [], a: [], i: [] }), base = dst.p.length / 3; + for (let i = 0; i < src.p.length; i += 3) { const px = src.p[i], pz = src.p[i + 2], nx = src.n[i], nz = src.n[i + 2]; dst.p.push(x + px * c + pz * s, src.p[i + 1] + y, z - px * s + pz * c); dst.n.push(nx * c + nz * s, src.n[i + 1], -nx * s + nz * c); } + for (let i = 0; i < src.u.length; i++) dst.u.push(src.u[i]); + for (let i = 0; i < src.a.length; i += 4) dst.a.push(src.a[i], src.a[i + 1], src.a[i + 2], src.a[i + 3] ? src.a[i + 3] + y : 0); + for (let i = 0; i < src.i.length; i++) dst.i.push(src.i[i] + base); + } + for (const d of B2.decals) { const p = d.p, n = d.n; B.decals.push(Object.assign({}, d, { p: [x + p[0] * c + p[2] * s, p[1] + y, z - p[0] * s + p[2] * c], n: [n[0] * c + n[2] * s, n[1], -n[0] * s + n[2] * c] })); } + for (const k of B2.colliders) B.colliders.push(Object.assign({}, k, { x: x + k.x * c + k.z * s, z: z - k.x * s + k.z * c, rot: (k.rot || 0) + rot, y0: k.y0 + y, y1: k.y1 + y })); + } + E._mergeB = mergeB; + const OTHER = { fieldstone: ['brick_red', 'planks', 'brick_sooty'], plaster: ['fieldstone', 'brick_red', 'planks'], brick_red: ['fieldstone', 'planks', 'plaster'], brick_sooty: ['fieldstone', 'planks', 'brick_red'], planks: ['fieldstone', 'brick_red'] }; + // a frame on one side of the footprint: a along the wall, b outward from it; r0 = box rotation, sg = which way box z points + function sideFrame(side, X, Z) { + if (side === 'back') return { P: (a, b) => [a, -Z / 2 - b], r0: 0, sg: -1, len: X }; + if (side === 'right') return { P: (a, b) => [X / 2 + b, -a], r0: Math.PI / 2, sg: 1, len: Z }; + if (side === 'left') return { P: (a, b) => [-X / 2 - b, a], r0: -Math.PI / 2, sg: 1, len: Z }; + return { P: (a, b) => [a, Z / 2 + b], r0: Math.PI, sg: -1, len: X }; + } + function leanTo(B, S, side, X, Z, eave, mat, foot) { + const R = S.R, F = sideFrame(side, X, Z), Lt = Math.min(F.len - 0.6, F.len * R.range(0.38, 0.72)), oa = R.range(-1, 1) * (F.len - Lt) / 2; + const Dt = R.range(2.0, 3.0), hi = Math.min(eave - 0.25, R.range(2.7, 3.3)), lo = Math.max(1.85, hi - Dt * R.range(0.32, 0.45)), t = mat === 'planks' ? 0.06 : 0.24; + const yAt = (b) => hi + (lo - hi) * b / Dt; + // outer wall and two end walls built in vertical strips that follow the slope (planks: boards; masonry: stepped) + const P0 = F.P(oa, Dt - t / 2); B.box(mat, P0[0], 0, P0[1], Lt, lo, t, F.r0, { tint: tintJ(R, 0.06) }); + const open = R() < 0.5 ? 1 : -1; + for (const e of [-1, 1]) { + const step = mat === 'planks' ? 0.22 : 0.3; + for (let b = 0; b < Dt - t; b += step) { + if (e === open && b < Dt * 0.55) continue; // one end open for a door or a woodpile + const bb = Math.min(step, Dt - t - b), hh = yAt(b + bb * (mat === 'planks' ? 0.5 : 0)), p = F.P(oa + e * (Lt / 2 - t / 2), b + bb / 2); + B.box(mat, p[0], 0, p[1], t, hh + (mat === 'planks' ? R.range(-0.04, 0.03) : 0), bb + 0.002, F.r0, { tint: tintJ(R, 0.05) }); + } + } + // the roof: a rusty sheet or old slates on rafters, a little bent + const pitch = Math.atan2(hi - lo, Dt), len = Math.hypot(Dt + 0.35, hi - lo), pc = F.P(oa, Dt / 2 + 0.1), roofMat = R() < 0.55 ? 'metal_rust' : 'slate'; + B.box(roofMat, pc[0], (hi + lo) / 2 + 0.02, pc[1], Lt + 0.3, 0.035, len, F.r0, { rx: F.sg * pitch, rz: R.range(-0.025, 0.025), noFoot: true, tint: roofMat === 'metal_rust' ? tintJ(R, 0.12, 0x9a8a7a) : null }); + for (let k = 0; k < 3; k++) { const p = F.P(oa - Lt / 2 + 0.15 + k * (Lt - 0.3) / 2, Dt / 2); B.box('timber', p[0], (hi + lo) / 2 - 0.1, p[1], 0.08, 0.1, len - 0.1, F.r0, { rx: F.sg * pitch, noFoot: true }); } + // a wall plate on the main wall and the flashing stain where the roof meets it + const pw = F.P(oa, 0.06); B.box('timber', pw[0], hi - 0.12, pw[1], Lt + 0.2, 0.12, 0.1, F.r0, { grain: 'long', noFoot: true }); + const nn = sideFrame(side, X, Z), pn = nn.P(oa, 0.005), dn = nn.P(0, 1), d0 = nn.P(0, 0), N = [dn[0] - d0[0], 0, dn[1] - d0[1]]; + B.decal('waterstain', [pn[0], hi + 0.25, pn[1]], N, Lt * 0.9, 0.6, 0); + const c = F.P(oa, Dt / 2); foot.push({ x: c[0], z: c[1], hx: side === 'back' || side === 'front' ? Lt / 2 : Dt / 2, hz: side === 'back' || side === 'front' ? Dt / 2 : Lt / 2, h: hi }); + } + function porch(B, S, door) { + const R = S.R, ang = door.closedY != null ? door.closedY : 0, dx = Math.cos(ang), dz = -Math.sin(ang), nx = -dz, nz = dx; + const w = R.range(1.7, 2.3), dp = R.range(1.0, 1.3), y = R.range(2.45, 2.7), rot = Math.atan2(-dz, dx); + for (const s of [-1, 1]) { const px = door.x + dx * s * (w / 2 - 0.08) + nx * (dp - 0.08), pz = door.z + dz * s * (w / 2 - 0.08) + nz * (dp - 0.08); B.box('timber', px, 0, pz, 0.12, y - 0.05 + R.range(-0.04, 0), 0.12, rot, { grain: 'long', rz: R.range(-0.03, 0.03) }); } + const pc = [door.x + nx * dp / 2, door.z + nz * dp / 2]; + B.box(R() < 0.5 ? 'roof_tile' : 'slate', pc[0], y + 0.12, pc[1], w + 0.3, 0.05, dp + 0.35, rot, { rx: -0.32, rz: R.range(-0.04, 0.04), noFoot: true }); + B.box('timber', pc[0] + nx * (dp / 2 - 0.08), y - 0.05, pc[1] + nz * (dp / 2 - 0.08), w, 0.14, 0.12, rot, { grain: 'long', noFoot: true }); + B.box('ashlar', pc[0], -0.05, pc[1], w - 0.1, 0.12, dp, rot, { tint: tintJ(R, 0.06, 0xa8a090) }); + } + function outsideStairs(B, S, X, Z, eave, foot) { + // stone steps up a gable end to a loft door: no rail, worn treads, a dark door at the top + const R = S.R, xs = R() < 0.5 ? 1 : -1, rise = Math.min(eave - 0.6, 3.0), n = Math.round(rise / 0.24), run = n * 0.3, wdt = 0.9, z0 = R.range(-Z / 2 + run / 2 + 0.3, Z / 2 - run / 2 - 0.3) - run / 2; + for (let k = 0; k < n; k++) B.box('fieldstone', xs * (X / 2 + wdt / 2 + 0.02), 0, z0 + k * 0.3 + 0.15 + R.range(-0.02, 0.02), wdt + R.range(-0.06, 0.06), (k + 1) * 0.24, 0.32, R.range(-0.03, 0.03), { tint: tintJ(R, 0.08) }); + B.box('fieldstone', xs * (X / 2 + wdt / 2 + 0.02), 0, z0 + run + 0.45, wdt + 0.1, rise, 0.9, 0, { tint: tintJ(R, 0.06) }); // the landing + B.box('wood_painted', xs * (X / 2 + 0.03), rise, z0 + run + 0.45, 0.06, 1.85, 0.85, 0, { tint: S.paintTint }); + B.box('timber', xs * (X / 2 + 0.04), rise + 1.85, z0 + run + 0.45, 0.08, 0.14, 1.15, 0, { grain: 'long' }); + B.decal('moss', [xs * (X / 2 + wdt + 0.03), 0.3, z0 + run / 2], [xs, 0, 0], 1.6, 0.5, 0); + foot.push({ x: xs * (X / 2 + wdt / 2 + 0.02), z: z0 + (run + 0.9) / 2, hx: wdt / 2 + 0.05, hz: (run + 0.9) / 2, h: rise }); + } + // a patch of different brick or stone set into a wall face, with a ragged stepped edge (repairs, a bricked-up door) + function patch(B, S, side, X, Z, a, y0, w, h, mat, lintel) { + const R = S.R, F = sideFrame(side, X, Z), rows = Math.max(2, Math.round(h / 0.3)); + for (let r = 0; r < rows; r++) { + const jag = lintel ? 0 : R.range(-0.2, 0.2), ww = w + (lintel ? 0 : R.range(-0.25, 0.15)), p = F.P(a + jag * 0.5, 0.012); + B.box(mat, p[0], y0 + r * h / rows, p[1], Math.max(0.3, ww), h / rows + 0.004, 0.03, F.r0, { tint: tintJ(R, 0.07), uvOff: [R() * 5, 0] }); + } + if (lintel) { const p = F.P(a, 0.03), dr = R() < 0.5 ? R.range(-0.06, 0.06) : 0; B.box('ashlar', p[0], y0 + h, p[1], w + 0.36, 0.24, 0.1, F.r0, { tint: tintJ(R, 0.08), rz: dr }); B.box('ashlar', p[0], -0.02, p[1], w + 0.2, 0.08, 0.2, F.r0, { tint: tintJ(R, 0.06) }); } + const pn = F.P(a, 0.05), q0 = F.P(a, 0), N = [pn[0] - q0[0], 0, pn[1] - q0[1]], l = Math.hypot(N[0], N[2]); N[0] /= l; N[2] /= l; + B.decal(R() < 0.5 ? 'grime' : 'damp', [pn[0] - N[0] * 0.03, y0 + h * 0.4, pn[1] - N[2] * 0.03], N, w * 1.3, h * 0.9, 0); + } + // render fallen off a wall low down: the stone underneath shows through in a soft-edged blotch (overlapping panes, + // the outer ones smaller and set back, with a damp stain over the edge so there is no hard outline) + function renderLoss(B, S, side, X, Z, a, w, h) { + const R = S.R, F = sideFrame(side, X, Z), q0 = F.P(a, 0), q1 = F.P(a, 1), N = [q1[0] - q0[0], 0, q1[1] - q0[1]]; + for (let k = 0; k < 7; k++) { const ww = w * R.range(0.35, 0.8), hh = h * R.range(0.3, 0.75), aa = a + R.range(-0.5, 0.5) * (w - ww), yy = R.range(0, h - hh) * (k < 3 ? 0.2 : 1), p = F.P(aa, 0.006 + k * 0.0006); + B.box('fieldstone', p[0], yy, p[1], ww, hh, 0.012, F.r0, { tint: tintJ(R, 0.05, 0xc8c0b4), uvOff: [aa * 0.37, 0] }); } + B.decal('damp', [q0[0] + N[0] * 0.02, h * 0.55, q0[1] + N[2] * 0.02], N, w * 1.25, h * 1.1, 0); + B.decal('mud', [q0[0] + N[0] * 0.02, 0.2, q0[1] + N[2] * 0.02], N, w * 1.1, 0.5, 0); + } + function buttress(B, S, side, X, Z, a, h, mat) { + const R = S.R, F = sideFrame(side, X, Z), dep = R.range(0.7, 1.0), p = F.P(a, dep / 2 - 0.05); + B.box(mat, p[0], 0, p[1], 0.6, h * 0.55, dep, F.r0, { tint: tintJ(R, 0.05) }); + const p2 = F.P(a, dep * 0.3); B.box(mat, p2[0], h * 0.5, p2[1], 0.56, h * 0.32, dep * 0.6, F.r0, { tint: tintJ(R, 0.05), rx: -F.sg * 0.22 }); + } + function tiePlates(B, S, side, X, Z, y, n) { + const R = S.R, F = sideFrame(side, X, Z); + for (let k = 0; k < n; k++) { const a = (k - (n - 1) / 2) * F.len / (n + 0.4) + R.range(-0.2, 0.2), p = F.P(a, 0.025); const g = new THREE.CylinderGeometry(0.13, 0.13, 0.03, 10).rotateX(Math.PI / 2); + _Eu.set(0, F.r0, 0); _Q.setFromEuler(_Eu); B.geo('metal_rust', g, _M.compose(_P.set(p[0], y + R.range(-0.08, 0.08), p[1]), _Q, _S.set(1, 1, 1)), { noFoot: true }); + const q = F.P(a, 0.0); B.decal('rust', [q[0], y - 0.35, q[1]], (() => { const o = F.P(a, 1), z = F.P(a, 0); return [o[0] - z[0], 0, o[1] - z[1]]; })(), 0.3, 0.7, 0); } + } + function rugged(B, S, sp, kind) { + const R = E.rng(sp.seed * 13 + 5), k = sp.rugged, X = S.footX, Z = S.footZ, eave = S.eaveH || 3, out = S.outMat || 'fieldstone', foot = S.extraFoot = []; + if (!X || !Z) return; + const S2 = Object.assign({}, S, { R }); + const alt = (OTHER[out] || OTHER.fieldstone)[R.int(3) % (OTHER[out] || OTHER.fieldstone).length]; + const used = {}, free = sp.free || ['back', 'left', 'right']; // sides that may grow outward (a street row: only the back) + // a wing behind (L or T plan) for houses big enough to have grown + if ((kind === 'farmhouse' || kind === 'cottage') && R() < 0.55 * k && !sp.noWing && free.includes('back')) { + const Lw = R.range(4.5, sp.wingMax || 7.5), dw = R.range(4.0, Math.min(5.4, X * 0.6)), tee = R() < 0.3, ox = tee ? R.range(-0.6, 0.6) : (R() < 0.5 ? -1 : 1) * (X / 2 - dw / 2 - R.range(0, 0.6)); + const W2 = buildParts({ kind: 'cottage', w: Lw, d: dw, floors: 1, seed: sp.seed + 101, out: alt === 'planks' ? 'brick_red' : alt, roof: R() < 0.5 ? 'tile' : 'slate', damage: sp.damage * 0.6, lit: 0 }); + mergeB(B, W2.B, ox, -Z / 2 - Lw / 2 + 0.25, Math.PI / 2, 0); + foot.push({ x: ox, z: -Z / 2 - Lw / 2 + 0.25, hx: dw / 2, hz: Lw / 2, h: W2.S.eaveH || 3, roof: W2.S.roofTop, wall: alt === 'planks' ? 'brick_red' : alt, axis: 'z' }); + used.back = true; + } + // lean-tos and outshots: at the back, or on a gable end + { const opts = free.filter(sd => !used[sd]); if (kind !== 'church' && kind !== 'shoprow' && opts.length && R() < 0.75 * k) { const side = opts.includes('back') && R() < 0.6 ? 'back' : opts[R.int(opts.length)]; leanTo(B, S2, side, X, Z, eave, R() < 0.5 ? 'planks' : alt, foot); used[side] = true; } } + // a porch over the front door + if ((kind === 'cottage' || kind === 'farmhouse') && S.doors[0] && R() < 0.4 * k) porch(B, S2, S.doors[0]); + // outside stairs to a loft door (barns, farmhouses) on a free gable + if ((kind === 'barn' || kind === 'farmhouse') && R() < 0.5 * k && free.includes('left') && free.includes('right') && !(used.left || used.right)) outsideStairs(B, S2, X, Z, eave, foot); + // a bricked-up doorway on a side or back wall, repairs in odd brick or stone, render fallen off low down + const sides = ['back', 'left', 'right'].filter(s => !used[s]); + if (sides.length && R() < 0.6 * k) { const sd = sides[R.int(sides.length)], F = sideFrame(sd, X, Z); patch(B, S2, sd, X, Z, R.range(-0.3, 0.3) * F.len, 0, 1.0, 2.05, out === 'brick_red' ? 'brick_sooty' : 'brick_red', true); } + for (let n = 0; n < Math.round(R.range(1, 3) * k); n++) { const sd = ['front', 'back', 'left', 'right'][R.int(4)], F = sideFrame(sd, X, Z); if (used[sd]) continue; patch(B, S2, sd, X, Z, R.range(-0.38, 0.38) * F.len, R.range(0.3, Math.max(0.4, eave - 1.6)), R.range(0.7, 1.6), R.range(0.5, 1.1), out === 'brick_red' ? 'brick_sooty' : out === 'fieldstone' ? 'brick_red' : 'brick_red', false); } + if (out === 'plaster') for (let n = 0; n < 2 + R.int(3); n++) { const sd = ['front', 'back', 'left', 'right'][R.int(4)], F = sideFrame(sd, X, Z); if (used[sd] && sd !== 'front') continue; renderLoss(B, S2, sd, X, Z, R.range(-0.4, 0.4) * F.len, R.range(1.0, 2.4), R.range(0.6, 1.3)); } + // a wall that moved: buttresses and tie plates (barns and long houses) + if ((kind === 'barn' || X > 10) && R() < 0.45 * k) { const sd = used.back ? 'front' : 'back', F = sideFrame(sd, X, Z); if (sd !== 'front') for (const a of [-0.3, 0.3]) buttress(B, S2, sd, X, Z, a * F.len + R.range(-0.4, 0.4), Math.min(eave, 3.2), kind === 'barn' ? 'fieldstone' : out === 'plaster' ? 'fieldstone' : out); } + if (kind !== 'shed' && R() < 0.5 * k && eave > 3.5) tiePlates(B, S2, R() < 0.5 ? 'left' : 'right', X, Z, eave - 2.6 > 1 ? 2.75 : eave - 0.4, 2); + } + + // ------------------------------------------------------------------ the camp hut (Boot Camp barrack hut) + // A timber barrack hut on a brick plinth: ridge along local X (sp.w long), the door in the +X gable end with a framed, + // set-back doorway, two concrete steps and a number board; a stove pipe through the roof; fire buckets on a board. + KINDS.hut = function (B, S, sp) { + const w = sp.w || 10, d = sp.d || 6, R = S.R, T = 0.14, storey = 2.5, lift = 0.45; + const B2 = E.builder(sp.seed + 3), S2 = Object.assign({}, S, { doors: [], windows: [], lights: [], group: new THREE.Group() }); + const nf = Math.max(2, Math.round(w / 2.6)), sideW = []; for (let i = 0; i < nf; i++) { const c = w * (i + 0.5) / nf; sideW.push({ a0: c - 0.5, a1: c + 0.5, y0: 0.95, y1: 2.05, lit: R() < (sp.lit || 0) }); } + const door = [{ a0: d / 2 - 0.5, a1: d / 2 + 0.5, y0: 0, y1: 2.0, door: true, leaf: false, threshold: false }], end = [{ a0: d / 2 - 0.4, a1: d / 2 + 0.4, y0: 1.0, y1: 1.9 }]; + house(B2, S2, { w, d, T, floors: 1, storey, out: 'planks', in: 'plaster_interior', roof: 'slate', ridgeMat: 'slate', pitch: 0.42, over: 0.4, gableOver: 0.3, head: 'timber', doorHead: 'timber', shutters: false, quoins: false, front: sideW, back: sideW.map(o => Object.assign({}, o)), right: door, left: end, sill: false, trim: true, sag: 0.03 }); + mergeB(B, B2, 0, 0, 0, lift); + S.windows.push(...S2.windows.map(o => Object.assign({}, o, { y: o.y + lift }))); + // plinth with air bricks, and the floor + B.box('brick_red', 0, -0.25, 0, w + 0.06, lift + 0.25, d + 0.06, 0, { tint: tintJ(R, 0.05) }); + for (let i = 0; i < 4; i++) for (const s of [-1, 1]) B.box('metal_rust', -w / 2 + (i + 0.5) * w / 4, 0.18, s * (d / 2 + 0.035), 0.22, 0.07, 0.01, 0, { noFoot: true, tint: new THREE.Color(0.4, 0.4, 0.4) }); + B.box('floorboards', 0, lift - 0.02, 0, w - 2 * T, 0.03, d - 2 * T, 0, { noFoot: true }); + // the doorway: a deep timber surround proud of the wall, the door set back in it, a little canopy, steps + const ex = w / 2, dy = lift; + for (const s of [-1, 1]) B.box('timber', ex + 0.09, dy, s * 0.62, 0.2, 2.15, 0.16, 0, { grain: 'long' }); + B.box('timber', ex + 0.09, dy + 2.1, 0, 0.2, 0.16, 1.4, 0, { grain: 'long' }); + B.box('wood_painted', ex - 0.12, dy, 0, 0.05, 1.98, 0.98, 0, { tint: S.paintTint }); + for (const yy of [0.25, 1.0, 1.7]) B.box('wood_painted', ex - 0.09, dy + yy, 0, 0.03, 0.1, 0.9, 0, { tint: S.paintTint }); + B.box('metal_rust', ex - 0.07, dy + 0.98, -0.36, 0.03, 0.03, 0.14, 0, { noFoot: true }); + B.box('slate', ex + 0.45, dy + 2.35, 0, 0.9, 0.04, 1.6, 0, { rz: 0.3, noFoot: true }); + for (const s of [-1, 1]) B.box('timber', ex + 0.55, dy + 1.95, s * 0.6, 0.6, 0.08, 0.08, 0, { rz: -0.6, noFoot: true }); + B.box('concrete', ex + 0.35, 0, 0, 0.7, 0.3, 1.5, 0, { tint: tintJ(R, 0.05, 0xb8b4ac) }); + B.box('concrete', ex + 0.85, 0, 0, 0.36, 0.15, 1.4, 0, { tint: tintJ(R, 0.05, 0xb0aca4) }); + B.decal('mud', [ex + 0.7, 0.31, 0], [0, 1, 0], 0.8, 1.1, 0); B.decal('chipped', [ex + 1.03, 0.08, 0], [1, 0, 0], 1.2, 0.2, 0); + // number board beside the door + if (sp.num != null) { try { const sg = signMesh(String(sp.num), 0.42, 0.32, R); sg.position.set(ex + 0.2, dy + 1.65, 0.95); sg.rotation.y = Math.PI / 2; S.group.add(sg); B.box('timber', ex + 0.18, dy + 1.47, 0.95, 0.02, 0.38, 0.48, 0, {}); } catch (e) {} } + // stove pipe through the roof (with a collar and a cap), soot on the roof round it + const rise = d / 2 * Math.tan(0.42), sx = -w / 2 + 2.0 + R() * 1.0, sz = R() < 0.5 ? -0.8 : 0.8; + const py = lift + storey + rise * (1 - Math.abs(sz) / (d / 2)) - 0.1; + B.geo('metal_rust', new THREE.CylinderGeometry(0.08, 0.08, 1.5, 10), _M.compose(_P.set(sx, py + 0.6, sz), _Q.identity(), _S.set(1, 1, 1)), { noFoot: true }); + B.geo('metal_rust', new THREE.ConeGeometry(0.2, 0.16, 10), _M.compose(_P.set(sx, py + 1.45, sz), _Q.identity(), _S.set(1, 1, 1)), { noFoot: true }); + B.geo('metal_rust', new THREE.CylinderGeometry(0.16, 0.2, 0.12, 10), _M.compose(_P.set(sx, py + 0.02, sz), _Q.identity(), _S.set(1, 1, 1)), { noFoot: true }); + B.decal('soot', [sx, py + 0.08, sz], [0, 1, 0], 0.8, 0.8, 0); + // fire buckets on a board on the gable + const bz = -d / 2 + 0.9; B.box('timber', ex + 0.04, dy + 0.9, bz, 0.04, 0.5, 1.1, 0, {}); + for (let i = 0; i < 3; i++) { const z = bz - 0.36 + i * 0.36; B.geo('metal_painted', new THREE.CylinderGeometry(0.13, 0.1, 0.28, 10), _M.compose(_P.set(ex + 0.2, dy + 0.85, z), _Q.identity(), _S.set(1, 1, 1)), { noFoot: true, tint: new THREE.Color(1.6, 0.42, 0.3) }); B.box('metal_rust', ex + 0.08, dy + 1.03, z, 0.06, 0.03, 0.03, 0, { noFoot: true }); } + B.geo('metal_painted', new THREE.CylinderGeometry(0.17, 0.15, 0.32, 10), _M.compose(_P.set(ex + 0.35, 0.16, -d / 2 + 0.4), _Q.identity(), _S.set(1, 1, 1)), { tint: new THREE.Color(1.5, 0.45, 0.32) }); + // rain stains under the eaves, mud splash on the plinth + for (const z of [d / 2 + 0.01, -d / 2 - 0.01]) { B.decal('waterstain', [0, lift + 0.4, z + Math.sign(z) * 0.04], [0, 0, Math.sign(z)], w * 0.9, 0.7, 0); B.decal('mud', [R.range(-w / 3, w / 3), 0.25, z + Math.sign(z) * 0.035], [0, 0, Math.sign(z)], 3, 0.4, 0); } + S.roofTop = lift + storey + rise; S.eaveH = lift + storey; S.footX = w; S.footZ = d; S.outMat = 'planks'; + }; + function buildParts(spec) { + spec = Object.assign({ kind: 'farmhouse', seed: 1, damage: 0, lit: 0 }, spec || {}); + const kind = spec.kind === 'church with tower' ? 'church' : spec.kind === 'village shop row' || spec.kind === 'shop' ? 'shoprow' : spec.kind === 'ruined shell' || spec.kind === 'ruined' ? 'ruin' : spec.kind; + const fn = KINDS[kind]; if (!fn) throw new Error('IVEnv.building: unknown kind ' + spec.kind); + const B = E.builder(spec.seed), group = new THREE.Group(); + const R = E.rng(spec.seed * 7 + 3); + const paints = [0x5a6b5c, 0x4d5a66, 0x6b4a3e, 0x6a6a5a, 0x3e4a40]; + const S = { R, seed: spec.seed, damage: spec.damage || 0, group, windows: [], lights: [], doors: [], extraCols: [], paintTint: new THREE.Color(paints[spec.seed % paints.length]).multiplyScalar(1 / 0.36), interior: kind === 'farmhouse' || kind === 'barn', old: kind !== 'office' && kind !== 'hut' && kind !== 'bunker' }; + // paint tint is relative to the texture's own paint (about 0.36 of white): keep it near 1 + S.paintTint.r = E.clamp(S.paintTint.r * 0.36 / 0.3, 0.6, 1.5); S.paintTint.g = E.clamp(S.paintTint.g * 0.36 / 0.36, 0.6, 1.5); S.paintTint.b = E.clamp(S.paintTint.b * 0.36 / 0.32, 0.6, 1.5); + fn(B, S, spec); + if (kind !== 'shed' && kind !== 'bunker' && kind !== 'hut') E.ageMesh(B, { w: S.footX || spec.w || 10, d: S.footZ || spec.d || 8, eave: S.eaveH || (S.roofTop || 6) * 0.62, ridge: S.roofTop, seed: spec.seed, amount: spec.age != null ? spec.age : (kind === 'office' ? 0.4 : 1) }); + // old walls are not true: a slight lean and a bulge at mid height on the long walls (house-like kinds) + if (kind === 'farmhouse' || kind === 'cottage' || kind === 'church' || kind === 'barn') { + const lx = R.range(-0.008, 0.008), lz = R.range(-0.006, 0.006), bul = R.range(0.02, 0.045), H = Math.max(2, (S.roofTop || 6) * 0.7), w = spec.w || 10, d = spec.d || 8; + const D2 = kind === 'barn' ? w / 2 : d / 2, W2 = kind === 'barn' ? d / 2 : w / 2; + for (const k in B.buckets) { const p = B.buckets[k].p; for (let i = 0; i < p.length; i += 3) { const y = p[i + 1]; if (y <= 0.05) continue; p[i] += lx * y; p[i + 2] += lz * y; if (Math.abs(Math.abs(p[i + 2]) - D2) < 0.8 && y < H) p[i + 2] += Math.sign(p[i + 2]) * bul * Math.sin(Math.PI * y / H) * Math.cos(Math.PI * 0.5 * E.clamp(p[i] / W2, -1, 1)); } } + } + if (spec.rugged && kind !== 'church' && kind !== 'ruin' && kind !== 'bunker' && kind !== 'hut' && kind !== 'office') rugged(B, S, spec, kind); + if (kind === 'farmhouse' || kind === 'cottage' || kind === 'church') group.add(ivy(spec, R, kind)); + return { B, S, kind, group, spec, R }; + } + E.building = function (spec0) { + const { B, S, kind, group } = buildParts(spec0); + // a settled building is one closed box (no interior to walk into): drop the inner faces, floors and furniture + if (spec0 && spec0.closed) for (const k in B.buckets) if (/^(plaster_interior|floorboards|straw)(#d)?$/.test(k) || (k.endsWith('#d') && /^(wood_painted|timber|planks)#d$/.test(k) && S.interior)) delete B.buckets[k]; + const g = B.finish(); group.add(g); + group.name = 'IVEnv.building:' + kind; group.userData.kind = kind; + const colliders = B.colliders.concat(S.extraCols); + return { group, colliders, doors: S.doors, windows: S.windows, lights: S.lights, height: S.roofTop || 0, extraFoot: S.extraFoot || [] }; + }; + + // ------------------------------------------------------------------ age: nothing old is true + // IVEnv.ageMesh(builder, { w, d, eave, seed, amount, cx, cz }) bends the drawn mesh of one building (colliders are not + // touched): walls a little out of plumb with a slow wobble, a bulge mid-height, wall tops that wander, a swaybacked + // roof that sags between the gables and droops at one end. Coordinates are relative to (cx, cz) (default 0, 0). + E.ageMesh = function (B, o) { + const R = E.rng((o.seed || 1) * 31 + 7), a = o.amount == null ? 1 : o.amount, cx = o.cx || 0, cz = o.cz || 0, rot = o.rot || 0, c = Math.cos(rot), s = Math.sin(rot); + const lx = R.range(-0.024, 0.024) * a, lz = R.range(-0.018, 0.018) * a, ph = R() * 9, sag = R.range(0.08, 0.18) * a, droop = R.range(-0.14, 0.14) * a, ridge = o.ridge || 1e9, cl = R.range(-0.09, 0.09) * a, cl2 = R.range(-0.07, 0.07) * a, W2 = Math.max(o.w || 8, o.d || 6) / 2, eave = o.eave || 4, base = o.y0 || 0; + for (const k in B.buckets) { + const p = B.buckets[k].p; + for (let i = 0; i < p.length; i += 3) { + const X = p[i] - cx, Z = p[i + 2] - cz, y = p[i + 1] - base; if (y <= 0.05) continue; + const u = X * c - Z * s, v = X * s + Z * c; // building-local: u along the ridge + let dx = lx * y + 0.04 * a * Math.sin(y * 0.9 + v * 0.6 + ph) * Math.min(1, y / 2), dz = lz * y + 0.04 * a * Math.sin(y * 0.8 + u * 0.5 + ph * 1.7) * Math.min(1, y / 2); + if (y > ridge - 0.6) { dx += cl * (y - ridge + 0.6); dz += cl2 * (y - ridge + 0.6); } // stacks lean on their own + let dy = 0.08 * a * Math.sin(u * 0.45 + ph) * Math.min(1, y / eave); // tops wander + if (y > eave * 0.9) { const t = IVc(u / W2); dy -= sag * (1 - t * t) * Math.min(1, (y - eave * 0.9) / 1.5 + 0.4) + droop * Math.max(0, t) * 0.5; } // swayback, one end drooping + p[i] += dx * c + dz * s; p[i + 1] += dy; p[i + 2] += -dx * s + dz * c; + } + } + }; + const IVc = (v) => v < -1 ? -1 : v > 1 ? 1 : v; + + // ------------------------------------------------------------------ settlements: many buildings, cheap at range + // IVEnv.settle(specs, { heightFn, near, shellOnly, seed }) -> { group, colliders, lights, chimneys } + // spec = { kind, x, z, rot, w, d, floors, seed, damage, lit (0..1), roof, units, y, shellOnly, solid, eave, pitch } + // Every building gets a SHELL: its walls set 12 cm inside the real walls, a roof just under the real roof, and its + // windows as dark or lit panes, all merged into a handful of meshes for the whole settlement and always drawn. A + // building the player can reach also gets the full IVEnv building, merged per 40 m cell and drawn only within `near` + // metres; up close it hides the shell, and through its windows you see the shell's closed interior. Doors are shut + // and the colliders are one closed box per footprint (no interiors). Lights: lit windows, for practical lights. + function shellDims(sp) { + const k = sp.kind, f = sp.floors || (k === 'farmhouse' ? 2 : 1); + if (k === 'barn') return { X: sp.d || 16, Z: sp.w || 10, eave: 4.6, rise: (sp.w || 10) / 2 * 0.9, wall: 'planks', roof: 'roof_tile', win: 0 }; + if (k === 'church') return { X: sp.w || 16, Z: sp.d || 8, eave: 5.6, rise: (sp.d || 8) / 2 * 1.0, wall: 'fieldstone', roof: 'slate', win: 0.2, tower: true }; + if (k === 'shoprow') { const n = sp.units || 3; return { X: n * (sp.w ? sp.w / n : 5.4), Z: sp.d || 8, eave: 3.0 * 2 + 0.2, rise: (sp.d || 8) / 2 * 0.75, wall: 'plaster', roof: 'slate', win: 1, floors: 2 }; } + if (k === 'hut') return { X: sp.w || 10, Z: sp.d || 6, eave: 2.95, rise: (sp.d || 6) / 2 * Math.tan(0.42), wall: 'planks', roof: 'slate', win: 1, floors: 1 }; + if (k === 'shed') return { X: sp.w || 4, Z: sp.d || 3, eave: 2.1, rise: 0.4, wall: 'planks', roof: 'slate', win: 0 }; + if (k === 'ruin') return { X: sp.w || 9, Z: sp.d || 7, eave: 3.2, rise: 0, wall: 'brick_sooty', roof: null, win: 0 }; + if (k === 'office') return { X: sp.w || 14, Z: sp.d || 7, eave: 2.7, rise: (sp.d || 7) / 2 * Math.tan(0.3), wall: sp.out || 'brick_red', roof: 'slate', win: 1, floors: 1 }; + if (k === 'farmhouse') return { X: sp.w || 12, Z: sp.d || 7.5, eave: f * 2.8, rise: (sp.d || 7.5) / 2 * 0.85, wall: 'fieldstone', roof: sp.roof === 'tile' ? 'roof_tile' : 'slate', win: 1, floors: f }; + return { X: sp.w || 8, Z: sp.d || 6, eave: f * 2.6 + (f === 1 ? 0.4 : 0), rise: (sp.d || 6) / 2 * 0.88, wall: 'brick_red', roof: sp.roof === 'tile' ? 'roof_tile' : 'slate', win: 1, floors: f }; + } + const prismGeo = (() => { const g = new THREE.BufferGeometry(); const P = [-0.5, 0, -0.5, 0.5, 0, -0.5, 0.5, 1, 0, -0.5, 1, 0, -0.5, 0, 0.5, 0.5, 0, 0.5, 0.5, 1, 0, -0.5, 1, 0, -0.5, 0, -0.5, -0.5, 1, 0, -0.5, 0, 0.5, 0.5, 0, -0.5, 0.5, 0, 0.5, 0.5, 1, 0]; + g.setAttribute('position', new THREE.Float32BufferAttribute(P, 3)); g.setIndex([0, 3, 2, 0, 2, 1, 4, 5, 6, 4, 6, 7, 8, 10, 9, 11, 13, 12]); g.computeVertexNormals(); return g; })(); + // warm light spilling from lit windows and doorways onto the ground in front: one additive mesh of soft pools draped + // on the terrain (cheap: no extra lights), faded by fog. list: [[x, z, nx, nz, r, k]] (nx, nz: outward from the wall) + let poolTex = null; + E.glowPools = function (list, hf) { + if (!poolTex) { const c = document.createElement('canvas'); c.width = c.height = 64; const g = c.getContext('2d'), gr = g.createRadialGradient(32, 32, 0, 32, 32, 32); gr.addColorStop(0, 'rgba(255,255,255,1)'); gr.addColorStop(0.35, 'rgba(255,255,255,0.5)'); gr.addColorStop(1, 'rgba(255,255,255,0)'); g.fillStyle = gr; g.fillRect(0, 0, 64, 64); poolTex = new THREE.CanvasTexture(c); } + const P = [], U = [], C = [], I = [], N = 4; + for (const [x, z, nx, nz, r, k] of list) { + const cx = x + nx * r * 0.55, cz = z + nz * r * 0.55, base = P.length / 3, tx = -nz, tz = nx; + for (let j = 0; j <= N; j++) for (let i = 0; i <= N; i++) { const u = i / N - 0.5, v = j / N - 0.5, px = cx + tx * u * r * 1.6 + nx * v * r * 1.3, pz = cz + tz * u * r * 1.6 + nz * v * r * 1.3; P.push(px, hf(px, pz) + 0.04, pz); U.push(i / N, j / N); C.push(k, k * 0.62, k * 0.3); } + for (let j = 0; j < N; j++) for (let i = 0; i < N; i++) { const a = base + j * (N + 1) + i; I.push(a, a + N + 1, a + 1, a + 1, a + N + 1, a + N + 2); } + } + const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.Float32BufferAttribute(P, 3)); g.setAttribute('uv', new THREE.Float32BufferAttribute(U, 2)); g.setAttribute('color', new THREE.Float32BufferAttribute(C, 3)); g.setIndex(I); g.computeBoundingSphere(); + const m = new THREE.MeshBasicMaterial({ map: poolTex, vertexColors: true, transparent: true, blending: THREE.AdditiveBlending, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -4, fog: true }); + m.userData.linear = true; const mesh = new THREE.Mesh(g, m); mesh.name = 'glow-pools'; mesh.renderOrder = 2; return mesh; + }; + E.settle = function (specs, opts) { + opts = opts || {}; + const Q = E.Q.name, near = opts.near || (Q === 'low' ? 26 : Q === 'high' ? 55 : 34), hf = opts.heightFn || (() => 0); + const SB = E.builder(opts.seed || 77), detailRoot = new THREE.Group(), group = new THREE.Group(); group.name = 'IVEnv.settlement'; + const colliders = [], lights = [], chimneys = [], RR = E.rng((opts.seed || 77) * 3 + 1); + for (const sp0 of specs) { + const sp = Object.assign({ seed: 1 + ((sp0.x * 13 + sp0.z * 7) | 0) % 997, rot: 0 }, sp0), D = shellDims(sp), rot = sp.rot; + const y = sp.y != null ? sp.y : Math.min(hf(sp.x, sp.z), hf(sp.x + D.X / 2, sp.z), hf(sp.x - D.X / 2, sp.z), hf(sp.x, sp.z + D.Z / 2), hf(sp.x, sp.z - D.Z / 2)); + const c = Math.cos(rot), s = Math.sin(rot), W = (lx, lz) => [sp.x + lx * c + lz * s, sp.z - lx * s + lz * c]; + const eave = sp.eave || D.eave, X = D.X - 0.24, Z = D.Z - 0.24, tint = E.tintJ(RR, 0.06); + // shell: walls (sunk into the ground on slopes), roof prism, windows + SB.box(sp.out || sp.wall || D.wall, sp.x, y - 0.8, sp.z, X, eave + 0.8 - 0.05, Z, rot, { tint, uvOff: [RR() * 9, 0] }); + if (D.roof && !(sp.damage > 0.85)) { const m = new THREE.Matrix4().compose(new THREE.Vector3(sp.x, y + eave - 0.42, sp.z), new THREE.Quaternion().setFromEuler(new THREE.Euler(0, rot, 0)), new THREE.Vector3(X + 0.75, Math.max(0.3, (sp.rise || D.rise) - 0.2), Z + 1.1)); SB.geo(D.roof, prismGeo, m, { noFoot: true, tint: E.tintJ(RR, 0.05) }); + // eaves read as a dark line under the roof edge (fascia and shadow), a plinth band at the foot + for (const sd of [-1, 1]) { const p = W(0, sd * (Z / 2 + 0.06)); SB.box('timber', p[0], y + eave - 0.5, p[1], X + 0.3, 0.2, 0.1, rot, { noFoot: true, tint: new THREE.Color(0.25, 0.23, 0.21) }); } } + if (D.win || sp.kind === 'barn' || sp.kind === 'shed') { // a door recess on the front, framed, with a step + const dw = sp.kind === 'barn' ? 3.2 : 1.0, dh = sp.kind === 'barn' ? 3.4 : 2.05, p = W(sp.kind === 'barn' ? 0 : X * 0.12, Z / 2 + 0.015); + SB.box('timber', p[0], y, p[1], dw, dh, 0.05, rot, { noFoot: true, tint: new THREE.Color(0.1, 0.09, 0.085) }); + const q = W(sp.kind === 'barn' ? 0 : X * 0.12, Z / 2 + 0.04); SB.box('timber', q[0], y + dh, q[1], dw + 0.3, 0.16, 0.07, rot, { noFoot: true }); +} + if (D.tower) { const p = W(-X / 2 - 2.0, 0); SB.box('fieldstone', p[0], y - 0.5, p[1], 4.2, 15.5, 4.2, rot, { tint }); const m = new THREE.Matrix4().compose(new THREE.Vector3(p[0], y + 15, p[1]), new THREE.Quaternion().setFromEuler(new THREE.Euler(0, rot + Math.PI / 4, 0)), new THREE.Vector3(3.2, 6.5, 3.2)); SB.geo('slate', new THREE.ConeGeometry(1, 1, 4, 1).translate(0, 0.5, 0), m, { noFoot: true }); } + if (D.win) { + const fl = D.floors || 1, nW = Math.max(1, Math.floor(X / 2.8)); + for (const side of [-1, 1]) for (let f = 0; f < fl; f++) for (let i = 0; i < nW; i++) { + const lx = -X / 2 + (i + 0.5) * X / nW, lit = RR() < (sp.lit || 0) * (side > 0 ? 1 : 0.6), p = W(lx, side * (Z / 2 + 0.01)); + SB.box(lit ? 'glass_lit' : 'timber', p[0], y + 0.95 + f * 2.7, p[1], 0.85, 1.25, 0.03, rot, { noFoot: true, tint: lit ? null : new THREE.Color(0.06, 0.06, 0.06) }); + { const q = W(lx, side * (Z / 2 + 0.04)); SB.box('ashlar', q[0], y + 0.86 + f * 2.7, q[1], 1.05, 0.09, 0.07, rot, { noFoot: true, tint: new THREE.Color(0.75, 0.73, 0.68) }); SB.box('ashlar', q[0], y + 2.2 + f * 2.7, q[1], 1.15, 0.16, 0.08, rot, { noFoot: true, tint: new THREE.Color(0.7, 0.68, 0.64) }); } // sill and lintel + if (lit) lights.push({ x: p[0] + s * side * 1.0, y: y + 1.4 + f * 2.7, z: p[1] + c * side * 1.0, wx: p[0], wz: p[1], nx: s * side, nz: c * side, f }); + } + } + if (sp.lit && D.win && D.roof) { const p = W(X * 0.3, 0); chimneys.push({ x: p[0], y: y + eave + (sp.rise || D.rise) + 0.8, z: p[1] }); } + // the full building near the player + if (!opts.shellOnly && !sp.shellOnly) { + try { + const b = E.building(Object.assign({ rugged: opts.rugged || 0 }, sp, { lit: sp.lit || 0, closed: true })); + for (const f of b.extraFoot) { // wings, lean-tos and stairs: a collider and a shell each + const p = W(f.x, f.z); + if (sp.solid !== false) colliders.push({ x: p[0], z: p[1], hx: f.hx, hz: f.hz, y0: y - 1, y1: y + f.h, rot, kind: 'building' }); + if (f.roof) { SB.box(f.wall || 'brick_red', p[0], y - 0.8, p[1], f.hx * 2 - 0.24, f.h + 0.75, f.hz * 2 - 0.24, rot, { tint: E.tintJ(RR, 0.06) }); const m = new THREE.Matrix4().compose(new THREE.Vector3(p[0], y + f.h - 0.3, p[1]), new THREE.Quaternion().setFromEuler(new THREE.Euler(0, rot + Math.PI / 2, 0)), new THREE.Vector3(f.hz * 2 + 0.1, Math.max(0.3, f.roof - f.h - 0.35), f.hx * 2 + 0.3)); SB.geo('slate', prismGeo, m, { noFoot: true }); } + } + for (const d of b.doors) { try { if (d.open && !d.hang) d.open(0); } catch (e) {} } + b.group.traverse(o => { o.userData.dynamic = false; }); + b.group.position.set(sp.x, y, sp.z); b.group.rotation.y = rot; detailRoot.add(b.group); + } catch (e) { console.warn('IVEnv.settle building', sp.kind, e); } + } + if (sp.solid !== false) colliders.push({ x: sp.x, z: sp.z, hx: D.X / 2, hz: D.Z / 2, y0: y - 1, y1: y + eave + 0.3, rot, kind: 'building' }); + } + let shells = SB.finish({ castShadow: false }); shells.name = 'IVEnv.shells'; + // shell-only settlements (far skylines) in one plain vertex-coloured mesh: one draw call instead of one per material + if (opts.shellOnly && E.mergeStatic && E.Q.name !== 'high') { const wrap = new THREE.Group(); wrap.add(shells); const m = E.mergeStatic(wrap, { flat: true }); m.traverse(o => { if (o.isMesh) o.castShadow = false; }); shells = m; shells.name = 'IVEnv.shells'; } + group.add(shells); + if (opts.pools !== false && lights.length) { try { group.add(E.glowPools(lights.filter(l => l.nx != null && l.f === 0).map(l => [l.wx, l.wz, l.nx, l.nz, 3.4, 0.16]), hf)); } catch (e) { console.warn('pools', e); } } + if (detailRoot.children.length) { + const merged = E.mergeStatic ? E.mergeStatic(detailRoot, { cell: 80 }) : detailRoot; merged.name = 'IVEnv.settlement-detail'; group.add(merged); + // only walls and roofs cast shadows (Low and Medium): frames, glass, doors, metal and timber trim each cost a + // shadow draw call per cell for shadows nobody reads at night + if (E.Q.name !== 'high') { const BIG = { fieldstone: 1, brick_red: 1, brick_sooty: 1, plaster: 1, roof_tile: 1, slate: 1, planks: 1, ashlar: 0 }; merged.traverse(o => { if (o.isMesh && o.material && o.material.userData && !BIG[o.material.userData.ivenv]) o.castShadow = false; }); } + if (merged !== detailRoot && detailRoot.children.length) group.add(detailRoot); // anything that could not merge + const list = []; merged.traverse(o => { if (o.isMesh) { if (!o.geometry.boundingSphere) o.geometry.computeBoundingSphere(); list.push(o); } }); + const v = new THREE.Vector3(); + (E._updaters = E._updaters || []).push((dt, cam) => { if (!group.parent) return; for (const o of list) { const bs = o.geometry.boundingSphere; v.copy(bs.center).applyMatrix4(o.matrixWorld); o.visible = v.distanceTo(cam.position) < near + bs.radius * 0.5; } }); + } + return { group, colliders, lights, chimneys }; + }; + + // ------------------------------------------------------------------ field walls + E.wall = function (points, opts) { + opts = Object.assign({ type: 'stone', h: 1.2, t: 0.55, gaps: [], seed: 11 }, opts || {}); + const B = E.builder(opts.seed), R = E.rng(opts.seed * 3 + 1), hf = opts.heightFn || (() => 0), stone = opts.type !== 'brick'; + const mat = stone ? 'fieldstone' : 'brick_red'; + let total = 0; const segs = []; + for (let i = 0; i < points.length - 1; i++) { const a = points[i], b = points[i + 1], L = Math.hypot(b[0] - a[0], b[1] - a[1]); segs.push({ a, b, L, s0: total }); total += L; } + const inGap = (s) => opts.gaps.some(g => s > g[0] && s < g[1]); + const STEP = 1.2; + for (const sg of segs) { + const dx = (sg.b[0] - sg.a[0]) / sg.L, dz = (sg.b[1] - sg.a[1]) / sg.L, rot = Math.atan2(-dz, dx), n = Math.max(1, Math.round(sg.L / STEP)); + for (let k = 0; k < n; k++) { + const s0 = sg.s0 + sg.L * k / n, s1 = sg.s0 + sg.L * (k + 1) / n, sm = (s0 + s1) / 2; if (inGap(sm)) continue; + // height falls off toward broken ends and gap edges in steps + let h = opts.h * (0.92 + 0.16 * E.vnoise(sm * 0.4, 3, opts.seed)); + const dEnd = Math.min(opts.brokenStart ? sm : 1e9, opts.brokenEnd ? total - sm : 1e9, ...opts.gaps.map(g => sm < g[0] ? g[0] - sm : sm > g[1] ? sm - g[1] : 1e9)); + if (dEnd < 3) h *= E.clamp(0.25 + dEnd / 3, 0.25, 1); + const len = (s1 - s0) + 0.02, cx = sg.a[0] + dx * (sm - sg.s0), cz = sg.a[1] + dz * (sm - sg.s0), y = Math.min(hf(sg.a[0] + dx * (s0 - sg.s0), sg.a[1] + dz * (s0 - sg.s0)), hf(sg.a[0] + dx * (s1 - sg.s0), sg.a[1] + dz * (s1 - sg.s0)), hf(cx, cz)); + // coping as separate weathered slabs 0.45-0.9 m long, grey, each sitting a little askew, the odd one missing + // or slipped (one long plank-like box read as boards from the lane) + const copingSlabs = (ccx, cy, ccz, L, t, fy) => { let a = -L / 2; while (a < L / 2 - 0.05) { const sl = Math.min(L / 2 - a, R.range(0.45, 0.9)), mid = a + sl / 2; a += sl; if (R() < 0.04) continue; + const slip = R() < 0.06 ? R.range(0.04, 0.1) : 0; B.box('ashlar', ccx + dx * mid - dz * slip, cy + R.range(-0.012, 0.012), ccz + dz * mid + dx * slip, sl - 0.012, R.range(0.11, 0.15), t + R.range(0, 0.04), rot, { foot: fy, tint: tintJ(R, 0.1, 0x9c9a94), rx: R.range(-0.04, 0.04), rz: R.range(-0.025, 0.025) + (slip ? 0.08 : 0), uvOff: [R() * 9, R() * 9] }); } }; + // battered wall: wide base course, narrower body, coping + B.box(mat, cx, y - 0.25, cz, len, h * 0.45 + 0.25, opts.t, rot, { foot: y, uvOff: [sm, 0] }); + B.box(mat, cx, y + h * 0.45, cz, len, h * 0.45, opts.t * 0.82, rot, { foot: y, uvOff: [sm, 0] }); + B.col(cx, cz, len, opts.t, y - 0.2, y + h * 0.9, rot, 'stone', 'wall'); + if (stone) { // coping: stones set on edge ("cock and hen"), each tilted a little; a plain cap on Low + if (opts.coping !== 'cock') copingSlabs(cx, y + h * 0.9 - 0.02, cz, len, opts.t * 1.05, y); // dressed coping slabs (churchyards, garden walls) + else if (E.Q.name === 'low') B.box('fieldstone', cx, y + h * 0.9 - 0.02, cz, len, 0.22, opts.t * 0.8, rot, { foot: y }); + else for (let c = 0; c < Math.round(len / 0.16); c++) { + const off = -len / 2 + (c + 0.5) * len / Math.round(len / 0.16), px = cx + dx * off, pz = cz + dz * off, tall = R() < 0.35; + B.box('fieldstone', px, y + h * 0.9 - 0.02, pz, R.range(0.09, 0.15), tall ? R.range(0.26, 0.34) : R.range(0.17, 0.24), opts.t * R.range(0.7, 0.9), rot, { rz: R.range(-0.15, 0.15), tint: tintJ(R, 0.14), foot: y, uvOff: [R() * 9, R() * 9] }); + } + } else copingSlabs(cx, y + h * 0.9, cz, len, opts.t * 0.95, y); + // moss and damp along the foot, a pock or two + if (R() < 0.5) B.decal('moss', [cx + dz * (opts.t / 2 + 0.003), y + 0.2, cz - dx * (opts.t / 2 + 0.003)], [dz, 0, -dx], len * 0.9, 0.4, 0); + if (R() < 0.3) B.decal('moss', [cx - dz * (opts.t / 2 + 0.003), y + 0.25, cz + dx * (opts.t / 2 + 0.003)], [-dz, 0, dx], len * 0.8, 0.45, 0); + // fallen stones at broken ends + if (dEnd < 3) for (let r = 0; r < 6; r++) placeRock(B, mat === 'brick_red' ? 'brick_red' : 'fieldstone', cx + dz * R.range(-1, 1) * 0.9 + dx * R.range(-0.5, 0.5), y + 0.02, cz - dx * R.range(-1, 1) * 0.9 + dz * R.range(-0.5, 0.5), R.range(0.1, 0.2), (R() * 999) | 0, [R() * 3, R() * 3, R() * 3], tintJ(R, 0.12)); + } + } + const g = B.finish(); g.name = 'IVEnv.wall'; + return { group: g, colliders: B.colliders }; + }; + + // ------------------------------------------------------------------ fences + E.fence = function (points, kind, opts) { + opts = Object.assign({ seed: 5 }, opts || {}); kind = kind || 'rail'; + const B = E.builder(opts.seed), R = E.rng(opts.seed * 5 + 2), hf = opts.heightFn || (() => 0); + const wires = []; + for (let i = 0; i < points.length - 1; i++) { + const a = points[i], b = points[i + 1], L = Math.hypot(b[0] - a[0], b[1] - a[1]), dx = (b[0] - a[0]) / L, dz = (b[1] - a[1]) / L, rot = Math.atan2(-dz, dx); + const sp = kind === 'picket' ? 2.0 : kind === 'barbed' ? 3.0 : 2.4, n = Math.max(1, Math.round(L / sp)); + for (let k = 0; k <= n; k++) { + if (k === n && i < points.length - 2) continue; + const px = a[0] + dx * L * k / n, pz = a[1] + dz * L * k / n, y = hf(px, pz), lean = R.range(-0.06, 0.06); + const ph = kind === 'picket' ? 1.1 : kind === 'barbed' ? 1.25 : 1.3; + B.box('timber', px, y - 0.3, pz, 0.11, ph + 0.3, 0.11, rot + R.range(-0.2, 0.2), { rz: lean, rx: R.range(-0.04, 0.04), foot: y, grain: 'long', tint: tintJ(R, 0.15, 0xc0b8b0) }); + B.col(px, pz, 0.12, 0.12, y, y + ph, 0, 'wood', 'post'); + if (R() < 0.4) B.decal('moss', [px + dz * 0.056, y + 0.2, pz - dx * 0.056], [dz, 0, -dx], 0.1, 0.3, 0); + if (k < n) { + const qx = a[0] + dx * L * (k + 1) / n, qz = a[1] + dz * L * (k + 1) / n, y2 = hf(qx, qz), len = L / n, mx = (px + qx) / 2, mz = (pz + qz) / 2, ym = (y + y2) / 2, slope = Math.atan2(y2 - y, len); + if (kind === 'rail') for (const hh of [0.45, 1.0]) { const broken = R() < (opts.damage || 0) * 0.5; B.box('timber', mx, ym + hh + (broken ? -0.35 : 0), mz, len + 0.15, 0.1, 0.05, rot, { rz: slope + (broken ? R.range(-0.4, 0.4) : 0), foot: ym, grain: 'long', tint: tintJ(R, 0.15, 0xc0b8b0) }); } + if (kind === 'picket') { B.box('timber', mx, ym + 0.25, mz, len, 0.07, 0.04, rot, { rz: slope, grain: 'long' }); B.box('timber', mx, ym + 0.85, mz, len, 0.07, 0.04, rot, { rz: slope, grain: 'long' }); for (let p = 0; p < Math.round(len / 0.14); p++) { if (R() < (opts.damage || 0) * 0.3) continue; const o = -len / 2 + (p + 0.5) * len / Math.round(len / 0.14), x = mx + dx * o, z = mz + dz * o; B.box('wood_painted', x + dz * 0.03, hf(x, z) + 0.05, z - dx * 0.03, 0.08, 1.0 + R.range(-0.03, 0.03), 0.02, rot, { rz: R.range(-0.03, 0.03), tint: new THREE.Color(1.5, 1.5, 1.45) }); } } + if (kind === 'hurdle') { for (let p = 0; p < 8; p++) B.box('bark_oak', mx, ym + 0.15 + p * 0.12, mz, len, 0.05, 0.05, rot, { rz: slope, grain: 'long', tint: new THREE.Color(0.75, 0.7, 0.62) }); } + if (kind === 'barbed') for (const hh of [0.4, 0.75, 1.1]) wires.push([px, y + hh, pz, qx, y2 + hh, qz]); + B.col(mx, mz, len, 0.1, ym, ym + 1.0, rot, 'wood', 'fence'); + } + } + } + const g = B.finish(); g.name = 'IVEnv.fence:' + kind; + if (wires.length) g.add(E.wireMesh(wires, 0.004, 0.08)); + return { group: g, colliders: B.colliders }; + }; + // sagging wires (telegraph, barbed): thin tubes, each sagging between its ends + E.wireMesh = function (list, radius, sag) { + // fine wire (barbed, under 1 cm) is drawn as lines: a 6 mm tube is under a pixel past a few metres, and a perimeter + // of tubes cost ~75k triangles. Thicker wire (telegraph) stays a tube, 6 segments per span. + if ((radius || 0.006) < 0.01) { + const P = []; for (const w of list) { let prev = null; for (let i = 0; i <= 8; i++) { const t = i / 8, p = [w[0] + (w[3] - w[0]) * t, w[1] + (w[4] - w[1]) * t - Math.sin(Math.PI * t) * (sag != null ? sag : 0.3), w[2] + (w[5] - w[2]) * t]; if (prev) P.push(...prev, ...p); prev = p; } } + const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.Float32BufferAttribute(P, 3)); g.computeBoundingSphere(); + const m = new THREE.LineSegments(g, new THREE.LineBasicMaterial({ color: 0x1a1714, transparent: true, opacity: 0.85 })); m.material.userData.linear = true; m.name = 'wires'; + const grp = new THREE.Group(); grp.add(m); return grp; + } + const B = E.builder(3); + for (const w of list) { + const pts = []; for (let i = 0; i <= 10; i++) { const t = i / 10; pts.push(new THREE.Vector3(w[0] + (w[3] - w[0]) * t, w[1] + (w[4] - w[1]) * t - Math.sin(Math.PI * t) * (sag != null ? sag : 0.3), w[2] + (w[5] - w[2]) * t)); } + const g = new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts), 6, radius || 0.006, 3, false); + B.geo('metal_rust', g, new THREE.Matrix4(), { noFoot: true }); + } + return B.finish({ castShadow: false }); + }; +})(); diff --git a/e63334287a3deaa3/ironveil/env/builder.js b/e63334287a3deaa3/ironveil/env/builder.js new file mode 100644 index 00000000..0e5b290a --- /dev/null +++ b/e63334287a3deaa3/ironveil/env/builder.js @@ -0,0 +1,256 @@ +/* Midnight Ops environment: geometry builder shared by buildings, walls, fences and props. + Everything is merged into one mesh per material (UVs in metres so texel density is the same everywhere; per-piece + UV offsets so no two planks or stones line up). Wear decals from the atlas are merged in the same way. + const B = IVEnv.builder(seed); B.box('brick_red', cx, y0, cz, sx, sy, sz, rotY, opts); ... const g = B.finish(); + opts: { tint: THREE.Color, foot: ground y for damp (default 0 = the builder's local ground), grain: 'long' (wood + grain along the longest side), uvOff: [u, v], rx, rz (extra rotations), noFoot, sides: {top:false, ...} } */ +(function () { + 'use strict'; + const E = window.IVEnv; + const _m = new THREE.Matrix4(), _n = new THREE.Matrix3(), _q = new THREE.Quaternion(), _e = new THREE.Euler(), _p = new THREE.Vector3(), _s = new THREE.Vector3(), _v = new THREE.Vector3(), _w = new THREE.Vector3(); + // unit cube faces: normal, then 4 corners (counter-clockwise seen from outside), u axis, v axis + const FACES = [ + { n: [1, 0, 0], c: [[0.5, -0.5, 0.5], [0.5, -0.5, -0.5], [0.5, 0.5, -0.5], [0.5, 0.5, 0.5]], k: 'px' }, + { n: [-1, 0, 0], c: [[-0.5, -0.5, -0.5], [-0.5, -0.5, 0.5], [-0.5, 0.5, 0.5], [-0.5, 0.5, -0.5]], k: 'nx' }, + { n: [0, 1, 0], c: [[-0.5, 0.5, 0.5], [0.5, 0.5, 0.5], [0.5, 0.5, -0.5], [-0.5, 0.5, -0.5]], k: 'top' }, + { n: [0, -1, 0], c: [[-0.5, -0.5, -0.5], [0.5, -0.5, -0.5], [0.5, -0.5, 0.5], [-0.5, -0.5, 0.5]], k: 'bottom' }, + { n: [0, 0, 1], c: [[-0.5, -0.5, 0.5], [0.5, -0.5, 0.5], [0.5, 0.5, 0.5], [-0.5, 0.5, 0.5]], k: 'pz' }, + { n: [0, 0, -1], c: [[0.5, -0.5, -0.5], [-0.5, -0.5, -0.5], [-0.5, 0.5, -0.5], [0.5, 0.5, -0.5]], k: 'nz' } + ]; + + function Builder(seed) { + this.R = E.rng(seed || 1); this.buckets = {}; this.colliders = []; this.decals = []; + } + const P = Builder.prototype; + // Detail pieces (arch voussoirs, quoins, loose bricks, ridge tiles, glazing bars, furniture...) go into separate + // meshes that IVEnv.update hides beyond Q.detailDist. detail 2 = also left out entirely on Low. + P.bucket = function (mat) { if (this.detail) mat += '#d'; return this.buckets[mat] || (this.buckets[mat] = { p: [], n: [], u: [], a: [], i: [] }); }; + P.det = function (level, fn) { const prev = this.detail; if (level === 2 && E.Q.name === 'low') return; this.detail = level; try { fn(); } finally { this.detail = prev; } }; + // push one vertex + function vtx(B, x, y, z, nx, ny, nz, u, v, t, foot) { + B.p.push(x, y, z); B.n.push(nx, ny, nz); B.u.push(u, v); + B.a.push(t ? t.r : 0, t ? t.g : 0, t ? t.b : 0, foot == null ? 0 : 1 + Math.max(0, y - foot)); + } + // A quad from 4 world points (counter-clockwise), uv per corner, normal computed. + P.quad = function (mat, a, b, c, d, uv, tint, foot) { + const B = this.bucket(mat), base = B.p.length / 3; + _v.set(b[0] - a[0], b[1] - a[1], b[2] - a[2]); _w.set(d[0] - a[0], d[1] - a[1], d[2] - a[2]); const n = _v.clone().cross(_w).normalize(); + [a, b, c, d].forEach((p, k) => vtx(B, p[0], p[1], p[2], n.x, n.y, n.z, uv[k][0], uv[k][1], tint, foot)); + B.i.push(base, base + 1, base + 2, base, base + 2, base + 3); + }; + P.tri = function (mat, a, b, c, uv, tint, foot) { + const B = this.bucket(mat), base = B.p.length / 3; + _v.set(b[0] - a[0], b[1] - a[1], b[2] - a[2]); _w.set(c[0] - a[0], c[1] - a[1], c[2] - a[2]); const n = _v.clone().cross(_w).normalize(); + [a, b, c].forEach((p, k) => vtx(B, p[0], p[1], p[2], n.x, n.y, n.z, uv[k][0], uv[k][1], tint, foot)); + B.i.push(base, base + 1, base + 2); + }; + // Box: centre x, bottom y0, centre z, sizes, rotation about Y (plus optional rx, rz). UVs in metres per face. + P.box = function (mat, cx, y0, cz, sx, sy, sz, ry, o) { + o = o || {}; + if (!mat) return; + const B = this.bucket(mat); + _e.set(o.rx || 0, ry || 0, o.rz || 0, 'YXZ'); _q.setFromEuler(_e); _p.set(cx, y0 + sy / 2, cz); _s.set(sx, sy, sz); + _m.compose(_p, _q, _s); _n.getNormalMatrix(_m); + const e = _m.elements, ne = _n.elements, tint = o.tint || null, foot = o.noFoot ? null : (o.foot != null ? o.foot : 0); + const uo = o.uvOff || [this.R() * 7, this.R() * 7], long = o.grain === 'long'; + for (const F of FACES) { + if (o.sides && o.sides[F.k] === false) continue; + const base = B.p.length / 3; + const nx = ne[0] * F.n[0] + ne[3] * F.n[1] + ne[6] * F.n[2], ny = ne[1] * F.n[0] + ne[4] * F.n[1] + ne[7] * F.n[2], nz = ne[2] * F.n[0] + ne[5] * F.n[1] + ne[8] * F.n[2]; + const nl = Math.hypot(nx, ny, nz) || 1; + for (const c of F.c) { + const x = c[0], y = c[1], z = c[2]; + const wx = e[0] * x + e[4] * y + e[8] * z + e[12], wy = e[1] * x + e[5] * y + e[9] * z + e[13], wz = e[2] * x + e[6] * y + e[10] * z + e[14]; + // face-local metric UVs: u along the face's horizontal axis, v along its vertical (or depth for top/bottom) + let u, v; + if (F.k === 'px' || F.k === 'nx') { u = (F.k === 'px' ? -z : z) * sz; v = y * sy; if (long && sz > sy) { const t = u; u = v; v = t; } } + else if (F.k === 'pz' || F.k === 'nz') { u = (F.k === 'pz' ? x : -x) * sx; v = y * sy; if (long && sx > sy) { const t = u; u = v; v = t; } } + else { u = x * sx; v = (F.k === 'top' ? -z : z) * sz; if (long && sx > sz) { const t = u; u = v; v = t; } } + vtx(B, wx, wy, wz, nx / nl, ny / nl, nz / nl, u + uo[0], v + uo[1], tint, foot); + } + B.i.push(base, base + 1, base + 2, base, base + 2, base + 3); + } + }; + // Any three.js geometry, transformed; UVs box-projected in metres from the transformed positions. + P.geo = function (mat, geo, matrix, o) { + o = o || {}; + const B = this.bucket(mat), g = geo.index ? geo.toNonIndexed() : geo, pa = g.attributes.position, na = g.attributes.normal; + _n.getNormalMatrix(matrix); const e = matrix.elements, ne = _n.elements, tint = o.tint || null, foot = o.noFoot ? null : (o.foot != null ? o.foot : 0); + const uo = o.uvOff || [this.R() * 7, this.R() * 7], keepUv = o.keepUv && g.attributes.uv, uva = g.attributes.uv, us = o.uvScale || 1; + const base = B.p.length / 3; + for (let i = 0; i < pa.count; i++) { + const x = pa.getX(i), y = pa.getY(i), z = pa.getZ(i); + const wx = e[0] * x + e[4] * y + e[8] * z + e[12], wy = e[1] * x + e[5] * y + e[9] * z + e[13], wz = e[2] * x + e[6] * y + e[10] * z + e[14]; + let nx = ne[0] * na.getX(i) + ne[3] * na.getY(i) + ne[6] * na.getZ(i), ny = ne[1] * na.getX(i) + ne[4] * na.getY(i) + ne[7] * na.getZ(i), nz = ne[2] * na.getX(i) + ne[5] * na.getY(i) + ne[8] * na.getZ(i); + const l = Math.hypot(nx, ny, nz) || 1; nx /= l; ny /= l; nz /= l; + let u, v; + if (keepUv) { u = uva.getX(i) * (o.uvW || 1) * us; v = uva.getY(i) * (o.uvH || 1) * us; } + else { const ax = Math.abs(nx), ay = Math.abs(ny), az = Math.abs(nz); if (ay >= ax && ay >= az) { u = wx; v = wz; } else if (ax >= az) { u = wz; v = wy; } else { u = wx; v = wy; } } + vtx(B, wx, wy, wz, nx, ny, nz, u + uo[0], v + uo[1], tint, foot); + B.i.push(base + i); + } + }; + // Axis-aligned or oriented collider box in the group's local space (same layout the game uses for W.addBox). + P.col = function (x, z, sx, sz, y0, y1, rot, surf, kind) { this.colliders.push({ x, z, hx: sx / 2, hz: sz / 2, y0, y1, rot: rot || 0, surf: surf || 'stone', kind: kind || '' }); }; + // A wear decal from the atlas, laid flat on a surface: centre p, outward normal n, size w x h, rotation in plane. + P.decal = function (type, p, n, w, h, rot) { this.decals.push({ type, p, n, w, h: h || w, rot: rot || 0 }); }; + + // Merge into meshes. Decals go into one extra mesh with the atlas material. + P.finish = function (o) { + o = o || {}; + const g = new THREE.Group(); + for (const mat in this.buckets) { + const B = this.buckets[mat]; if (!B.i.length) continue; + const geo = new THREE.BufferGeometry(); + geo.setAttribute('position', new THREE.Float32BufferAttribute(B.p, 3)); geo.setAttribute('normal', new THREE.Float32BufferAttribute(B.n, 3)); + geo.setAttribute('uv', new THREE.Float32BufferAttribute(B.u, 2)); geo.setAttribute('aEnv', new THREE.Float32BufferAttribute(B.a, 4)); + geo.setIndex(B.p.length / 3 > 65535 ? new THREE.Uint32BufferAttribute(B.i, 1) : new THREE.Uint16BufferAttribute(B.i, 1)); + geo.computeBoundingSphere(); + const det = mat.endsWith('#d'), mn = det ? mat.slice(0, -2) : mat; + const mv = mn.split('|'), m = new THREE.Mesh(geo, mn === 'glass_lit' ? E.mat('glass', 'lit') : E.mat(mv[0], mv[1])); + m.castShadow = o.castShadow !== false && !det && mn !== 'glass' && mn !== 'glass_lit'; m.receiveShadow = true; m.name = mn; + if (det) E.registerDetail(m); + g.add(m); + } + if (this.decals.length) { const dm = E.decalMesh(this.decals); E.registerDetail(dm, 40); g.add(dm); } + return g; + }; + E.builder = (seed) => new Builder(seed); + E._detail = []; + E.registerDetail = function (mesh, dist) { mesh.userData.detail = dist || true; E._detail.push(mesh); }; + const _c = new THREE.Vector3(); let _last = 0; + E._updaters = E._updaters || []; + E._updaters.push(function (dt, cam) { + const now = performance.now(); if (now - _last < 200) return; _last = now; + const D = E.Q.detailDist || 25, list = E._detail; + for (let i = list.length - 1; i >= 0; i--) { + const m = list[i]; if (!m.parent) { if (m.userData.dead) list.splice(i, 1); continue; } + if (!m.geometry.boundingSphere) m.geometry.computeBoundingSphere(); + _c.copy(m.geometry.boundingSphere.center).applyMatrix4(m.matrixWorld); + const d2 = _c.distanceToSquared(cam.position); + if (m.userData.shadowNear) { const sl = m.userData.shadowNear + m.geometry.boundingSphere.radius; m.castShadow = d2 < sl * sl; if (!m.userData.detail) continue; } + const lim = (m.userData.detail === true ? D : m.userData.detail) + m.geometry.boundingSphere.radius; + m.visible = d2 < lim * lim; + } + }); + E.Builder = Builder; + + // ------------------------------------------------------------------ static decal mesh (atlas, merged) + // Atlas cells (4 x 4, row 0 at v = 0): see texgen.js G.decals. + E.DECALS = { scratches: 0, gouges: 1, chipped: 2, pocks: 3, scorch: 4, soot: 5, damp: 6, moss: 7, rust: 8, mud: 9, crack: 10, bullethole: 11, leaves: 12, waterstain: 13, chalk: 14, grime: 15 }; + let decalMat = null; + E.decalMaterial = function () { + if (decalMat) return decalMat; + const T = E.tex.decals; + const m = new THREE.MeshStandardMaterial({ map: T.alb, normalMap: T.nri, transparent: true, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -4, roughness: 1, metalness: 0, alphaTest: 0.02 }); + m.customProgramCacheKey = () => 'ivdecalsatlas'; + m.onBeforeCompile = function (sh) { + sh.fragmentShader = sh.fragmentShader.replace('#include ', 'float roughnessFactor = texture2D(normalMap, vUv).b;') + .replace('#include ', `vec4 dn = texture2D(normalMap, vUv); vec3 mapN = vec3(dn.xy * 2.0 - 1.0, 0.0); mapN.z = sqrt(max(0.05, 1.0 - dot(mapN.xy, mapN.xy))); + normal = perturbNormal2Arb(-vViewPosition, normal, mapN, faceDirection);`); + }; + m.userData.linear = true; decalMat = m; return m; + }; + E.decalMesh = function (list) { + const p = [], n = [], u = [], idx = []; const t = new THREE.Vector3(), b = new THREE.Vector3(), N = new THREE.Vector3(), up = new THREE.Vector3(); + for (const d of list) { + const cell = typeof d.type === 'number' ? d.type : E.DECALS[d.type]; if (cell == null) continue; + N.set(d.n[0], d.n[1], d.n[2]).normalize(); + up.set(0, 1, 0); if (Math.abs(N.y) > 0.9) up.set(0, 0, -1); + t.crossVectors(up, N).normalize(); b.crossVectors(N, t).normalize(); + const c = Math.cos(d.rot), s = Math.sin(d.rot), tx = t.clone().multiplyScalar(c).addScaledVector(b, s), bx = b.clone().multiplyScalar(c).addScaledVector(t, -s); + const ox = (cell % 4) / 4, oy = Math.floor(cell / 4) / 4, inset = 0.004; + const base = p.length / 3; + [[-1, -1], [1, -1], [1, 1], [-1, 1]].forEach(([i, j]) => { + p.push(d.p[0] + tx.x * i * d.w / 2 + bx.x * j * d.h / 2 + N.x * 0.004, d.p[1] + tx.y * i * d.w / 2 + bx.y * j * d.h / 2 + N.y * 0.004, d.p[2] + tx.z * i * d.w / 2 + bx.z * j * d.h / 2 + N.z * 0.004); + n.push(N.x, N.y, N.z); u.push(ox + inset + (i * 0.5 + 0.5) * (0.25 - 2 * inset), oy + inset + (j * 0.5 + 0.5) * (0.25 - 2 * inset)); + }); + idx.push(base, base + 1, base + 2, base, base + 2, base + 3); + } + const g = new THREE.BufferGeometry(); + g.setAttribute('position', new THREE.Float32BufferAttribute(p, 3)); g.setAttribute('normal', new THREE.Float32BufferAttribute(n, 3)); g.setAttribute('uv', new THREE.Float32BufferAttribute(u, 2)); + g.setIndex(idx); g.computeBoundingSphere(); + const m = new THREE.Mesh(g, E.decalMaterial()); m.receiveShadow = true; m.renderOrder = 2; m.name = 'decals'; + return m; + }; +})(); + +/* IVEnv.mergeStatic(root, opts) -> Group: merges every static mesh under root (buildings, walls, fences, props) that + shares a material into one mesh per material, in root's space. Door pivots (objects with userData.dynamic or named + in opts.keep) are left alone. Cuts draw calls from one per material per object to one per material. */ +(function () { + 'use strict'; + const E = window.IVEnv; + // Low: small and minor surfaces share ONE plain material (their texture's mean colour goes into the vertex tint), + // which cuts a draw call per material per cell. Big surfaces (walls, roofs, ground) keep their textures. + const LOW_MINOR = new Set(['metal_rust', 'metal_painted', 'canvas', 'sandbag', 'straw', 'bark_pine', 'ashlar', 'timber', 'wood_painted', 'brick_sooty', 'floorboards', 'concrete', 'cobbles', 'gravel']); + const meanCache = {}; + function meanColour(name) { + if (meanCache[name]) return meanCache[name]; + const R = E.RECIPES[name], T = R && E.tex[R.tex]; const c = new THREE.Color(0.3, 0.3, 0.3); + if (T && T.alb.image && T.alb.image.data) { const d = T.alb.image.data; let r = 0, g = 0, b = 0, n = 0; for (let i = 0; i < d.length; i += 64) { r += d[i]; g += d[i + 1]; b += d[i + 2]; n++; } c.setRGB(r / n / 255, g / n / 255, b / n / 255).convertSRGBToLinear(); } + return meanCache[name] = c; + } + let lowMat = null; + E.lowMinorMaterial = function () { + if (lowMat) return lowMat; + const m = new THREE.MeshStandardMaterial({ roughness: 0.85, metalness: 0 }); + m.onBeforeCompile = (sh) => { + sh.vertexShader = 'attribute vec4 aEnv;\nvarying vec3 vTint;\n' + sh.vertexShader.replace('#include ', '#include \n vTint = aEnv.rgb;'); + sh.fragmentShader = 'varying vec3 vTint;\n' + sh.fragmentShader.replace('#include ', 'diffuseColor.rgb = vTint;'); + }; + m.customProgramCacheKey = () => 'ivlowminor'; m.userData.linear = true; lowMat = m; return m; + }; + E.mergeStatic = function (root, opts) { + opts = opts || {}; + const lowMinor = (E.Q.name === 'low' || opts.flat) && opts.lowMinor !== false; // opts.flat: everything takes the plain material (far shells) + if (E.Q.name === 'low' && opts.cell) opts = Object.assign({}, opts, { cell: Math.max(opts.cell, 160) }); // Low: bigger cells, fewer draw calls + root.updateMatrixWorld(true); + const inv = new THREE.Matrix4().copy(root.matrixWorld).invert(); + const groups = new Map(), victims = []; + const nm = new THREE.Matrix3(), m = new THREE.Matrix4(), v = new THREE.Vector3(); + root.traverse(o => { + if (!o.isMesh || o.isInstancedMesh || o.userData.dynamic || !o.geometry.index) return; + let p = o.parent; while (p && p !== root) { if (p.userData.dynamic) return; p = p.parent; } + const mat = o.material; if (Array.isArray(mat)) return; + // merge per material AND per spatial cell (opts.cell metres), so frustum culling still drops what is out of view + const minor = lowMinor && mat.userData && (opts.flat ? !!mat.userData.ivenv : LOW_MINOR.has(mat.userData.ivenv)) && !o.userData.detail; + let k = (minor ? 'lowminor' : mat.uuid) + (o.userData.detail ? '#d' : ''); + const cellSize = o.userData.detail ? Math.min(opts.cell || 32, 32) : opts.cell; + if (cellSize) { if (!o.geometry.boundingSphere) o.geometry.computeBoundingSphere(); const c = o.geometry.boundingSphere.center.clone().applyMatrix4(o.matrixWorld); k += ':' + Math.floor(c.x / cellSize) + ':' + Math.floor(c.z / cellSize); } + if (!groups.has(k)) groups.set(k, { mat: minor ? E.lowMinorMaterial() : mat, minor, list: [], cast: o.castShadow, order: o.renderOrder, depth: o.customDepthMaterial, detail: o.userData.detail, shadowNear: o.userData.shadowNear }); + groups.get(k).list.push(o); victims.push(o); + }); + const out = new THREE.Group(); out.name = 'IVEnv.merged'; + for (const [, G] of groups) { + let nv = 0, ni = 0; const names = {}; + for (const o of G.list) { nv += o.geometry.attributes.position.count; ni += o.geometry.index.count; for (const k in o.geometry.attributes) names[k] = o.geometry.attributes[k].itemSize; } + const arr = {}; for (const k in names) arr[k] = new Float32Array(nv * names[k]); + const idx = nv > 65535 ? new Uint32Array(ni) : new Uint16Array(ni); + let vo = 0, io = 0; + for (const o of G.list) { + const g = o.geometry, I = g.index, cnt = g.attributes.position.count; + m.multiplyMatrices(inv, o.matrixWorld); nm.getNormalMatrix(m); + for (const k in names) { + const A = g.attributes[k], sz = names[k], out = arr[k]; if (!A) continue; + for (let i = 0; i < cnt; i++) { + if (k === 'position') { v.fromBufferAttribute(A, i).applyMatrix4(m); out[(vo + i) * 3] = v.x; out[(vo + i) * 3 + 1] = v.y; out[(vo + i) * 3 + 2] = v.z; } + else if (k === 'normal') { v.fromBufferAttribute(A, i).applyMatrix3(nm).normalize(); out[(vo + i) * 3] = v.x; out[(vo + i) * 3 + 1] = v.y; out[(vo + i) * 3 + 2] = v.z; } + else if (k === 'aEnv' && G.minor) { const mc = meanColour(o.material.userData.ivenv); for (let c = 0; c < 3; c++) { const t = A.array[i * 4 + c]; out[(vo + i) * 4 + c] = (t > 0 ? t : 1) * (c === 0 ? mc.r : c === 1 ? mc.g : mc.b); } out[(vo + i) * 4 + 3] = A.array[i * 4 + 3]; } + else for (let c = 0; c < sz; c++) out[(vo + i) * sz + c] = A.array[i * sz + c]; + } + } + for (let i = 0; i < I.count; i++) idx[io + i] = I.getX(i) + vo; + vo += cnt; io += I.count; + } + const geo = new THREE.BufferGeometry(); + for (const k in names) geo.setAttribute(k, new THREE.BufferAttribute(arr[k], names[k])); + geo.setIndex(new THREE.BufferAttribute(idx, 1)); + geo.computeBoundingSphere(); + const mesh = new THREE.Mesh(geo, G.mat); mesh.castShadow = G.cast; if (G.depth) mesh.customDepthMaterial = G.depth; if (G.detail) E.registerDetail(mesh, G.detail); if (G.shadowNear && G.cast) { mesh.userData.shadowNear = G.shadowNear; E._detail.push(mesh); } mesh.receiveShadow = true; mesh.renderOrder = G.order; mesh.name = 'merged:' + (G.mat.userData.ivenv || G.mat.type); + out.add(mesh); + } + for (const o of victims) { o.parent.remove(o); o.userData.dead = true; if (opts.dispose !== false) o.geometry.dispose(); } + return out; + }; +})(); diff --git a/e63334287a3deaa3/ironveil/env/core.js b/e63334287a3deaa3/ironveil/env/core.js new file mode 100644 index 00000000..2043a22c --- /dev/null +++ b/e63334287a3deaa3/ironveil/env/core.js @@ -0,0 +1,389 @@ +/* Midnight Ops environment kit: core. Quality levels, texture generation (Web Workers running texgen.js), the shared + material shader, shared uniforms (time, wind, pushers, wetness) and small helpers used by the other env/*.js files. + The public API is documented at the top of env/index.js. Load order: texgen.js, core.js, then the others, index.js last. */ +(function () { + 'use strict'; + const E = window.IVEnv = window.IVEnv || {}; + const BASE = (document.currentScript && document.currentScript.src || '').replace(/[^/]*$/, ''); + E.BASE = BASE; + + // ------------------------------------------------------------------ quality + // tex: hero texture size, texLo: everything else. grass*: see grass.js. post / pom / shadows decided here too. + E.QUALITY = { + low: { name: 'low', tex: 512, texLo: 512, texGround: 512, texMinor: 256, texDecal: 512, pom: false, post: false, aniso: 4, grassNear: 8, grassMid: 22, grassDens: 40, grassMidDens: 5, bladeSegs: 1, seedHeads: false, carpetDens: 110, carpetR: 5, treeLod: 18, plantKinds: ['wheat', 'maize', 'reeds'], detailDist: 18, decals: 64 }, + medium: { name: 'medium', tex: 1024, texLo: 512, texGround: 512, texMinor: 256, texDecal: 512, pom: 6, pomFar: 5.5, pomOnly: /^brick/, post: true, aniso: 8, grassNear: 10, grassMid: 34, grassDens: 40, grassMidDens: 5, bladeSegs: 2, carpetSegs: 1, seedHeads: false, carpetDens: 210, carpetR: 7, treeLod: 26, detailDist: 21, decals: 160 }, + high: { name: 'high', tex: 1024, texLo: 512, texGround: 512, texMinor: 512, texDecal: 1024, pom: 11, pomFar: 9, pomOnly: /^(brick|fieldstone|ashlar)/, post: true, aniso: 16, carpetSegs: 1, grassNear: 14, grassMid: 45, grassDens: 38, grassMidDens: 8, bladeSegs: 3, seedHeads: true, carpetDens: 160, carpetR: 8, treeLod: 45, detailDist: 35, decals: 256 } + }; + E.Q = E.QUALITY.medium; + + // ------------------------------------------------------------------ shared uniforms + const U = E.U = { + uTime: { value: 0 }, + uWind: { value: new THREE.Vector3(0.8, 0.6, 0.35) }, // direction x, z (normalised), strength 0..2 + uPush: { value: [] }, // 8 x vec4 (x, z, radius, strength) + uWet: { value: 0 }, + uRain: { value: 0 }, + uDust: { value: 0.35 }, + uNight: { value: 1 }, + uMacro: { value: null }, + uGrime: { value: 1 } + }; + for (let i = 0; i < 8; i++) U.uPush.value.push(new THREE.Vector4(0, 0, 0, 0)); + + // ------------------------------------------------------------------ helpers + E.rng = function (seed) { return IVEnvTexGen.rng((seed | 0) * 2654435761 + 12345); }; + E.hash = function (i, j, s) { return IVEnvTexGen.hash2(i | 0, j | 0, s | 0); }; + // smooth value noise for JS-side placement (same everywhere it is used, so the game and the test page agree) + E.vnoise = function (x, y, s) { + const xi = Math.floor(x), yi = Math.floor(y), fx = x - xi, fy = y - yi, h = IVEnvTexGen.hash2; + const ux = fx * fx * (3 - 2 * fx), uy = fy * fy * (3 - 2 * fy), a = h(xi, yi, s), b = h(xi + 1, yi, s), c = h(xi, yi + 1, s), d = h(xi + 1, yi + 1, s); + return a + (b - a) * ux + (c - a) * uy + (a - b - c + d) * ux * uy; + }; + E.fbm2 = function (x, y, s, oct) { let t = 0, a = 1, n = 0; for (let o = 0; o < (oct || 3); o++) { t += a * E.vnoise(x, y, s + o * 17); n += a; a *= 0.5; x *= 2.03; y *= 2.03; } return t / n; }; + E.clamp = (v, a, b) => v < a ? a : v > b ? b : v; + E.sstep = (a, b, v) => { const t = E.clamp((v - a) / (b - a), 0, 1); return t * t * (3 - 2 * t); }; + E.lin = (hex) => new THREE.Color(hex).convertSRGBToLinear(); + + // ------------------------------------------------------------------ GLSL shared by every env shader + E.GLSL = {}; + E.GLSL.noise = ` + float ivH(vec2 p){ p = fract(p * vec2(0.1031, 0.1030)); p += dot(p, p.yx + 33.33); return fract((p.x + p.y) * p.x); } + float ivN(vec2 p){ vec2 i = floor(p), f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f); + return mix(mix(ivH(i), ivH(i + vec2(1.0, 0.0)), u.x), mix(ivH(i + vec2(0.0, 1.0)), ivH(i + vec2(1.0, 1.0)), u.x), u.y); } + `; + // One wind field for everything: scrolling noise + slow gust fronts that travel across a field + flutter. + E.GLSL.wind = E.GLSL.noise + ` + uniform float uTime; uniform vec3 uWind; + vec2 ivWind(vec2 p){ + vec2 d = uWind.xy; float s = uWind.z; + float base = ivN(p * 0.045 - d * uTime * 0.22); + float g = sin(dot(p, d) * 0.09 - uTime * 0.85 + ivN(p * 0.02) * 4.0) * 0.5 + 0.5; g = g * g * g; + float fl = ivN(p * 0.6 - d * uTime * 2.1) - 0.5; + return d * s * (0.25 + 0.55 * base + 1.1 * g) + vec2(-d.y, d.x) * fl * 0.35 * s; + } + `; + + // ------------------------------------------------------------------ textures + // name -> { alb, nri } THREE.DataTexture; filled by E.load() + E.tex = {}; + const RAW = {}; + function makeTex(data, S, srgb, aniso) { + const t = new THREE.DataTexture(data, S, S, THREE.RGBAFormat, THREE.UnsignedByteType); + t.wrapS = t.wrapT = THREE.RepeatWrapping; t.magFilter = THREE.LinearFilter; t.minFilter = THREE.LinearMipmapLinearFilter; + t.generateMipmaps = true; t.anisotropy = aniso; t.flipY = false; + if (srgb) t.encoding = THREE.sRGBEncoding; + t.needsUpdate = true; return t; + } + + // Material recipes. tex: generator in texgen.js, size: metres per repeat, hero: gets the big texture size, + // ns: normal strength, id: per-element tint amount, pom: parallax depth in metres (High only), metal / mask. + E.RECIPES = { + brick_red: { tex: 'brick_red', size: 1.35, hero: 1, ns: 1.0, id: 0.04, pom: 0.012, macro: 0.3 }, + brick_sooty: { tex: 'brick_sooty', size: 1.35, hero: 0, hero2: 1, ns: 1.0, id: 0.04, pom: 0.012, macro: 0.32 }, + fieldstone: { tex: 'fieldstone', size: 1.6, hero: 1, ns: 0.65, id: 0.03, pom: 0.016, macro: 0.32 }, + ashlar: { tex: 'ashlar', size: 1.2, hero: 0, minor: 1, ns: 1.0, id: 0.03, macro: 0.26 }, + plaster: { tex: 'plaster', size: 2.5, hero: 0, hero2: 1, ns: 1.0, macro: 0.2 }, + plaster_interior: { tex: 'plaster_interior', size: 2.5, hero: 0, minor: 1, ns: 0.8, macro: 0.14 }, + planks: { tex: 'planks', size: 1.6, hero: 1, ns: 1.0, id: 0.04, macro: 0.28 }, + floorboards: { tex: 'floorboards', size: 2.0, hero: 0, ns: 1.0, id: 0.05, macro: 0.16 }, + wood_painted: { tex: 'wood_painted', size: 1.0, hero: 0, hero2: 1, ns: 1.0, id: 0.03, macro: 0.2 }, + timber: { tex: 'timber', size: 1.0, hero: 0, ns: 1.0, macro: 0.16 }, + roof_tile: { tex: 'roof_tile', size: 1.0, hero: 0, hero2: 1, ns: 1.0, id: 0.06, pom: 0.014, macro: 0.3 }, + slate: { tex: 'slate', size: 1.0, hero: 0, ns: 1.0, id: 0.05, macro: 0.28 }, + cobbles: { tex: 'cobbles', size: 1.5, hero: 0, hero2: 1, ns: 1.0, id: 0.04, pom: 0.025, macro: 0.3 }, + mud: { tex: 'mud', size: 3.0, hero: 0, ground: 1, ns: 1.0, macro: 0.2 }, + grass_ground: { tex: 'grass_ground', size: 2.5, hero: 0, ground: 1, ns: 1.0, macro: 0.2 }, + earth: { tex: 'earth', size: 3.0, hero: 0, ground: 1, ns: 1.0, macro: 0.2 }, + gravel: { tex: 'gravel', size: 1.5, hero: 0, ground: 1, ns: 1.0, macro: 0.16 }, + leaves: { tex: 'leaves', size: 2.0, hero: 0, ground: 1, ns: 1.0, macro: 0.2 }, + bark_oak: { tex: 'bark_oak', size: 1.0, hero: 0, ns: 1.2, macro: 0.12, noFoot: 1 }, + bark_pine: { tex: 'bark_pine', size: 1.0, hero: 0, minor: 1, ns: 1.2, macro: 0.12, noFoot: 1 }, + concrete: { tex: 'concrete', size: 2.4, hero: 0, hero2: 1, ns: 1.0, macro: 0.18 }, + metal_painted: { tex: 'metal_painted', size: 1.0, hero: 0, ns: 1.0, metal: 1, mask: 1, macro: 0.12 }, + metal_rust: { tex: 'metal_rust', size: 1.0, hero: 0, minor: 1, ns: 1.0, metal: 1, mask: 1, macro: 0.16 }, + sandbag: { tex: 'sandbag', size: 0.5, hero: 0, minor: 1, ns: 1.0, macro: 0.16 }, + canvas: { tex: 'canvas', size: 0.8, hero: 0, minor: 1, ns: 1.0, macro: 0.16 }, + glass: { tex: 'glass', size: 1.0, hero: 0, minor: 1, ns: 0.4, macro: 0.1, glass: 1, noFoot: 1 }, + straw: { tex: 'straw', size: 1.0, hero: 0, minor: 1, ns: 1.0, macro: 0.14, noFoot: 1 } + }; + // Scanned sets shipped in env/scans: material -> real size of one repeat in metres (the set's shot size; never smaller) + E.SCANS = {}; + // bricks are drawn about 1.5x real (courses ~10.5 cm, bricks ~32 cm): at game distances true-size brick reads as noise. + // pom: parallax depth in metres for the scans' height maps (mortar recessed ~12 mm, stones up to ~3 cm) + const SCAN_POM = { brick_red: 0.022, brick_sooty: 0.022, fieldstone: 0.04, ashlar: 0.016, roof_tile: 0.03, slate: 0.016, cobbles: 0.03, planks: 0.01 }; + E.useScans = function (table) { Object.assign(E.SCANS, table); for (const k in table) { const r = E.RECIPES[k]; if (r) { r.size = table[k]; r.id = 0; r.scan = 1; r.pom = SCAN_POM[k] || 0; if (/brick|fieldstone|ashlar/.test(k)) r.ns = 1.35; } } }; + E.useScans({ brick_red: 2.1, brick_sooty: 2.2, fieldstone: 2.6, ashlar: 1.9, plaster: 2.5, planks: 2.0, wood_painted: 1.6, timber: 0.5, roof_tile: 4.6, slate: 3.9, cobbles: 1.0, concrete: 3.0, mud: 1.3, earth: 2.0, gravel: 2.0, grass_ground: 3.15, floorboards: 3.0 }); + // Friendly names from the brief map to recipes. + E.ALIASES = { + 'red brick': 'brick_red', brick: 'brick_red', 'sooty brick': 'brick_sooty', 'fieldstone wall': 'fieldstone', stone: 'fieldstone', + 'cracked lime plaster': 'plaster', 'old timber planks': 'planks', 'timber frame': 'timber', 'clay roof tile': 'roof_tile', + tiles: 'roof_tile', cobble: 'cobbles', 'mud lane': 'mud', 'mud lane with ruts': 'mud', grass: 'grass_ground', 'grass ground': 'grass_ground', + 'ploughed earth': 'earth', bark: 'bark_oak', 'bark oak': 'bark_oak', 'bark pine': 'bark_pine', 'bunker concrete': 'concrete', + 'painted metal': 'metal_painted', 'rusty metal': 'metal_rust', 'sandbag cloth': 'sandbag', 'dirty glass': 'glass', hay: 'straw' + }; + + // ------------------------------------------------------------------ init + load + E.init = function (renderer, quality) { + E.renderer = renderer; + E.Q = E.QUALITY[quality] || E.QUALITY.medium; + E.maxAniso = renderer.capabilities.getMaxAnisotropy ? renderer.capabilities.getMaxAnisotropy() : 1; + E.isWebGL2 = !!renderer.capabilities.isWebGL2; + return E; + }; + + // Generates every texture (in up to 4 workers when the page is served over http), reports progress 0..1. + E.load = function (onProgress, only) { + if (E._loading) return E._loading; + const Q = E.Q, t0 = performance.now(), jobs = []; + const want = only || Object.keys(E.RECIPES); + const seen = {}; + for (const n of want) { const r = E.RECIPES[n]; if (!r || seen[r.tex]) continue; seen[r.tex] = 1; jobs.push({ name: r.tex, S: r.hero || (r.hero2 && Q.name === 'high') ? Q.tex : r.ground ? Q.texGround : r.minor ? Q.texMinor : Q.texLo, seed: 1000 + jobs.length * 77 }); } + jobs.push({ name: 'decals', S: Q.texDecal, seed: 4242 }); jobs.push({ name: 'macro', S: 256, seed: 99 }); + // scanned CC0 sets (env/scans, see CREDITS-env.md): fetched as three images (albedo, normal xy + roughness, + // height) and packed into the same layout the generator makes, so every shader layer works on them unchanged + const scanJobs = []; + if (!E.noScans) for (let i = jobs.length - 1; i >= 0; i--) { const j = jobs[i]; if (E.SCANS[j.name]) { scanJobs.push(j); jobs.splice(i, 1); } } + + // the biggest first so the workers finish together + jobs.sort((a, b) => b.S - a.S); jobs.forEach((j, i) => j.job = i); + let done = 0; const total = jobs.length; E.genTimes = {}; + const finishOne = (r) => { + RAW[r.name] = r; E.genTimes[r.name] = r.ms; done++; + if (onProgress) try { onProgress(done / total, r.name); } catch (e) { } + }; + // Generated maps are kept in IndexedDB (keyed by texgen.js contents), so the second visit skips generation. + const idb = () => new Promise((res) => { try { const rq = indexedDB.open('ivenv-textures', 1); rq.onupgradeneeded = () => rq.result.createObjectStore('t'); rq.onsuccess = () => res(rq.result); rq.onerror = () => res(null); } catch (e) { res(null); } }); + const idbGet = (db, k) => new Promise((res) => { try { const r = db.transaction('t').objectStore('t').get(k); r.onsuccess = () => res(r.result || null); r.onerror = () => res(null); } catch (e) { res(null); } }); + const idbPut = (db, k, v) => { try { db.transaction('t', 'readwrite').objectStore('t').put(v, k); } catch (e) { } }; + const version = () => fetch(BASE + 'texgen.js').then(r => r.text()).then(t => { let h = 2166136261; for (let i = 0; i < t.length; i++) { h ^= t.charCodeAt(i); h = Math.imul(h, 16777619); } return (h >>> 0).toString(36); }).catch(() => '0'); + E._loading = Promise.all([E.noCache ? null : idb(), version()]).then(([db, ver]) => new Promise((resolve) => { + const keyOf = (j) => ver + ':' + j.name + ':' + j.S + ':' + j.seed; + E.cacheHits = 0; + const store = (j, r) => { if (db) idbPut(db, keyOf(j), { name: r.name, S: r.S, alb: r.alb, nri: r.nri, ms: r.ms }); }; + const run = (todo) => { + if (!todo.length) { build(); E.genMs = performance.now() - t0; return resolve(E); } + let workers = []; + const nW = Math.max(1, Math.min(4, (navigator.hardwareConcurrency || 2) - 1, todo.length)); + try { if (location.protocol.startsWith('http')) for (let i = 0; i < nW; i++) workers.push(new Worker(BASE + 'texgen.js')); } catch (e) { workers = []; } + let left = todo.length; + const doneOne = (j, r) => { store(j, r); finishOne(r); if (--left === 0) { workers.forEach(w => w.terminate()); build(); E.genMs = performance.now() - t0; resolve(E); } }; + if (!workers.length) { // main thread, yielding between materials so the page can draw a progress bar + let i = 0; const step = () => { if (i >= todo.length) return; const j = todo[i++], s = performance.now(), r = IVEnvTexGen.generate(j.name, j.S, j.seed); r.name = j.name; r.ms = performance.now() - s; doneOne(j, r); setTimeout(step, 0); }; + return step(); + } + let next = 0; + const feed = (w) => { if (next < todo.length) { w.postMessage(todo[next++]); } }; + workers.forEach(w => { w.onmessage = (e) => { doneOne(todo[e.data.job], e.data); feed(w); }; feed(w); }); + }; + if (!db) return run(jobs.map((j, i) => Object.assign(j, { job: i }))); + Promise.all(jobs.map(j => idbGet(db, keyOf(j)))).then(hits => { + const todo = []; + jobs.forEach((j, i) => { const h = hits[i]; if (h && h.alb) { E.cacheHits++; finishOne(h); } else todo.push(j); }); + todo.forEach((j, i) => j.job = i); + run(todo); + }); + })); + if (scanJobs.length) { + const img = (url) => fetch(url).then(r => { if (!r.ok) throw new Error(url); return r.blob(); }).then(b => createImageBitmap(b)); + const px = (bm, S) => { const c = document.createElement('canvas'); c.width = c.height = S; const g = c.getContext('2d'); g.drawImage(bm, 0, 0, S, S); return g.getImageData(0, 0, S, S).data; }; + const scanP = Promise.all(scanJobs.map(j => { + const sfx = E.Q.name === 'low' || j.S <= 512 ? '.512' : '', S = sfx ? 512 : 1024, b = BASE + 'scans/' + j.name + sfx, t1 = performance.now(); + return Promise.all([img(b + '.alb.webp'), img(b + '.nr.webp'), img(b + '.h.webp')]).then(([a, n, h]) => { + const A = px(a, S), N = px(n, S), Hh = px(h, S), alb = new Uint8ClampedArray(S * S * 4), nri = new Uint8ClampedArray(S * S * 4); + for (let i = 0; i < S * S; i++) { const q = i * 4; alb[q] = A[q]; alb[q + 1] = A[q + 1]; alb[q + 2] = A[q + 2]; alb[q + 3] = Hh[q]; nri[q] = N[q]; nri[q + 1] = N[q + 1]; nri[q + 2] = N[q + 2]; nri[q + 3] = 112; } + // rows are stored top-down in the image; the generator's row 0 is v = 0 (bottom): flip + const flip = (arr) => { const row = S * 4, tmp = new Uint8ClampedArray(row); for (let y = 0; y < S / 2; y++) { const a0 = y * row, b0 = (S - 1 - y) * row; tmp.set(arr.subarray(a0, a0 + row)); arr.copyWithin(a0, b0, b0 + row); arr.set(tmp, b0); } }; + flip(alb); flip(nri); + return { name: j.name, S, alb, nri, ms: performance.now() - t1, scan: true }; + }).catch(e => { console.warn('IVEnv scan failed, generating instead:', j.name, e); return IVEnvTexGen.generate(j.name, j.S, j.seed); }); + })).then(list => { for (const r of list) { if (!r.name) continue; RAW[r.name] = r; } }); + const gen = E._loading; E._loading = Promise.all([gen, scanP]).then(() => { for (const k in RAW) if (RAW[k].scan && !E.tex[k]) { build(); break; } return E; }); + } + return E._loading; + }; + function build() { + const a = Math.min(E.Q.aniso, E.maxAniso || 1); + for (const k in RAW) { + const r = RAW[k]; if (E.tex[k]) continue; // (built already: scans arriving after the generated set) + E.tex[k] = { alb: makeTex(r.alb, r.S, k !== 'macro', a), nri: r.nri ? makeTex(r.nri, r.S, false, a) : null, S: r.S }; + } + U.uMacro.value = E.tex.macro.alb; E.tex.macro.alb.encoding = THREE.LinearEncoding; + } + E.texMemory = function () { // bytes on the GPU including mipmaps + let b = 0; for (const k in E.tex) { const t = E.tex[k]; const one = t.S * t.S * 4 * 1.333; b += one * (t.nri ? 2 : 1); } return b + (E.extraTexBytes || 0); + }; + + // ------------------------------------------------------------------ the shared material shader + // Every env material is a MeshStandardMaterial with: + // - UVs in METRES (the kit's geometry is made that way); the recipe size turns metres into repeats; + // - albedo with height in alpha, packed normal/roughness/id texture; + // - large-scale colour variation from world position (no visible repeat), per-element tint that changes in every + // repeat of the tile, damp and moss at the foot of walls (from the aEnv vertex attribute), global wetness; + // - cavity AO from the height, parallax occlusion mapping on High for the recipes that have pom. + // Vertex attribute aEnv (optional, vec4): xyz tint multiplier (0,0,0 = none), w = 1 + height above the ground. + const MATS = {}; + E.mat = function (name, variant) { + name = E.ALIASES[name] || name; + const key = name + (variant ? '|' + variant : ''); + if (MATS[key]) return MATS[key]; + const R = E.RECIPES[name]; + if (!R) throw new Error('IVEnv.mat: unknown material ' + name); + const T = E.tex[R.tex]; + if (!T) throw new Error('IVEnv.mat: textures not loaded yet (call IVEnv.load first)'); + const m = new THREE.MeshStandardMaterial({ map: T.alb.clone(), normalMap: T.nri.clone(), roughness: 1, metalness: R.metal ? 1 : 0, envMapIntensity: 1 }); + m.map.needsUpdate = true; m.normalMap.needsUpdate = true; // clones share the image; repeat differs per material + m.map.repeat.set(1 / R.size, 1 / R.size); m.normalMap.repeat.copy(m.map.repeat); + if (R.glass) { m.transparent = true; m.opacity = 0.62; m.depthWrite = false; } + if (variant === 'gaplit') { m.userData.gapLit = true; } + if (variant === 'lit') { m.emissive = E.lin(0xffb46a); m.emissiveIntensity = 1.6; m.transparent = false; m.opacity = 1; m.depthWrite = true; } + m.shadowSide = THREE.DoubleSide; // walls are open shells: both faces must block the moon + patch(m, R, T.alb.image.width); + m.userData.linear = true; m.userData.ivenv = name; + MATS[key] = m; return m; + }; + E.materials = MATS; + + function patch(m, R, S) { + const defs = {}; + if (R.id) defs.ENV_ID = ''; + if (R.mask) defs.ENV_METALMASK = ''; + // parallax only where it is seen and cheap (owner, 20 Nov): Medium brick walls within ~5 m, High brick and stone + // within ~9 m, never roofs; everything else keeps the normal map and joint occlusion + if (R.pom && E.Q.pom && !R.glass && (!E.Q.pomOnly || E.Q.pomOnly.test(R.tex || ''))) { defs.ENV_POM = ''; defs.ENV_POM_STEPS = (+E.Q.pom).toFixed(1); defs.ENV_POM_FAR = (+(E.Q.pomFar || 8)).toFixed(1); /* GLSL floats: '5.5', never '5.5.0' */ } + if (!R.noFoot) defs.ENV_FOOT = ''; + m.defines = Object.assign(m.defines || {}, defs); + const uni = { + uMacro: U.uMacro, uWet: U.uWet, uGrime: U.uGrime, uDust: U.uDust, uNight: U.uNight, + uIdAmt: { value: R.id || 0 }, uMacroAmt: { value: R.macro || 0.15 }, uTexSize: { value: S }, + uNS: { value: R.ns || 1 }, uPomDepth: { value: R.pom ? R.pom / R.size : 0 }, uAOAmt: { value: R.scan && /brick|fieldstone|ashlar|roof_tile|slate/.test(R.tex) ? 1.0 : 0.85 } + }; + m.userData.uniforms = uni; + m.onBeforeCompile = function (sh) { + Object.assign(sh.uniforms, uni); + sh.vertexShader = 'attribute vec4 aEnv;\nvarying vec4 vEnvA;\nvarying vec3 vEnvW;\n' + sh.vertexShader.replace('#include ', `#include + vec4 envWP = vec4(transformed, 1.0); + #ifdef USE_INSTANCING + envWP = instanceMatrix * envWP; + #endif + vEnvW = (modelMatrix * envWP).xyz; vEnvA = aEnv;`); + sh.fragmentShader = 'uniform sampler2D uMacro; uniform float uDust, uNight; uniform float uWet, uGrime, uIdAmt, uMacroAmt, uTexSize, uNS, uPomDepth, uAOAmt;\nvarying vec4 vEnvA;\nvarying vec3 vEnvW;\n' + + sh.fragmentShader + .replace('#include ', MAP_FRAG) + .replace('#include ', 'float roughnessFactor = clamp(envRough, 0.03, 1.0);') + .replace('#include ', 'float metalnessFactor = metalness;\n#ifdef ENV_METALMASK\nmetalnessFactor *= envN.a;\n#endif') + .replace('#include ', ` + vec3 mapN = vec3((envN.xy * 2.0 - 1.0) * uNS * normalScale, 0.0); + mapN.z = sqrt(max(0.05, 1.0 - dot(mapN.xy, mapN.xy))); + normal = perturbNormal2Arb(-vViewPosition, normal, normalize(mapN), faceDirection);`) + .replace('#include ', '#include \n' + (m.userData.gapLit ? '{ float gx = vUv.x * 8.0; float gd = min(fract(gx), 1.0 - fract(gx)); float gw = max(0.035, fwidth(gx) * 0.9); float on = step(0.62, fract(sin(floor(gx + 0.5) * 12.9898) * 43758.5)) * smoothstep(0.35, 0.65, texture2D(uMacro, vec2(gx * 0.13, vUv.y * 0.6)).g); totalEmissiveRadiance += vec3(1.0, 0.5, 0.18) * 0.38 * uNight * on * smoothstep(gw, 0.0, gd) * (0.6 + 0.4 * smoothstep(0.2, 0.07, envH)); }' : '')) + .replace('#include ', ` + float envAO = mix(1.0, 0.3 + 0.7 * smoothstep(0.05, 0.75, envH), uAOAmt); + reflectedLight.indirectDiffuse *= envAO; reflectedLight.indirectSpecular *= envAO * envAO;`); + }; + m.customProgramCacheKey = () => 'ivenv' + Object.keys(defs).map(k => k + defs[k]).join(',') + (m.userData.gapLit ? 'gap' : ''); + } + const MAP_FRAG = ` + vec2 envUv = vUv; + #ifdef ENV_POM + { + float fd = 1.0 - smoothstep(ENV_POM_FAR * 0.45, ENV_POM_FAR, length(vViewPosition)); + if (fd > 0.0) { + vec3 V = normalize(vViewPosition); + vec3 q0 = dFdx(-vViewPosition), q1 = dFdy(-vViewPosition); vec2 s0 = dFdx(vUv), s1 = dFdy(vUv); + vec3 Nn = normalize(vNormal) * (gl_FrontFacing ? 1.0 : -1.0); + vec3 q1p = cross(q1, Nn), q0p = cross(Nn, q0); + vec3 Tt = q1p * s0.x + q0p * s1.x, Bt = q1p * s0.y + q0p * s1.y; + float dt = max(dot(Tt, Tt), dot(Bt, Bt)); float sc = dt == 0.0 ? 0.0 : inversesqrt(dt); + vec3 Vt = vec3(dot(V, Tt * sc), dot(V, Bt * sc), dot(V, Nn)); + vec2 dir = Vt.xy / max(Vt.z, 0.3) * uPomDepth * fd; + const float STEPS = ENV_POM_STEPS; + float layer = 1.0 / STEPS, cur = 1.0, found = 0.0, prevH = 1.0, prevL = 1.0; vec2 uvc = vUv, prevUv = vUv, hitUv = vUv; + for (float i = 0.0; i < STEPS; i += 1.0) { + float hgt = texture2D(map, uvc, -1.0).a; + float isHit = step(cur, hgt) * (1.0 - found); + float after = cur - hgt, before = prevL - prevH; + float a = clamp(after / min(-1e-4, after - before), 0.0, 1.0); + hitUv = mix(hitUv, mix(uvc, prevUv, a), isHit); + found = max(found, isHit); + prevH = hgt; prevL = cur; prevUv = uvc; cur -= layer; uvc -= dir * layer; + } + envUv = mix(uvc, hitUv, found); + } + } + #endif + vec4 envT = texture2D(map, envUv); vec4 envN = texture2D(normalMap, envUv); + vec3 envAlb = mapTexelToLinear(vec4(envT.rgb, 1.0)).rgb; float envH = envT.a; float envRough = envN.b; + vec3 wp = vEnvW; + float m1 = texture2D(uMacro, (wp.xz + wp.y * vec2(0.71, 0.37)) * 0.035).r; + float m2 = texture2D(uMacro, (wp.xy + wp.zz * vec2(0.83, -0.4)) * 0.11 + 0.37).g; + float mac = m1 * 0.6 + m2 * 0.4; + envAlb *= mix(1.0 - uMacroAmt, 1.0 + uMacroAmt * 0.7, mac); + envRough = clamp(envRough + (m2 - 0.5) * 0.12, 0.03, 1.0); + #ifdef ENV_ID + { + float idb = floor(envN.a * 255.0 + 0.5); float combo = floor(idb / 28.0); float k = idb - combo * 28.0; + vec2 tileC = floor(envUv) + vec2(floor(combo / 3.0) - 1.0, mod(combo, 3.0) - 1.0); + float rid = fract(sin(dot(tileC, vec2(12.9898, 78.233)) + k * 7.31) * 43758.5453); + float rid2 = fract(rid * 13.71 + 0.3); + float idFade = (1.0 - smoothstep(0.7, 2.5, length(fwidth(envUv)) * uTexSize)) * step(0.5, k); + envAlb *= 1.0 + (rid - 0.5) * 2.0 * uIdAmt * idFade; + envAlb *= mix(vec3(1.0), vec3(1.06, 0.98, 0.92), (rid2 - 0.5) * 2.0 * uIdAmt * idFade); + } + #endif + vec3 envTint = (vEnvA.x + vEnvA.y + vEnvA.z) > 0.0 ? vEnvA.xyz : vec3(1.0); + envAlb *= envTint; + #ifdef ENV_FOOT + { + float foot = vEnvA.w > 0.5 ? vEnvA.w - 1.0 : 99.0; + float damp = (1.0 - smoothstep(0.0, 0.25 + 0.7 * m2, foot)) * uGrime; + float moss = damp * smoothstep(0.6, 0.2, envH + m1 * 0.35 - 0.15); + envAlb = mix(envAlb, envAlb * vec3(0.5, 0.5, 0.44), damp * 0.85); + envAlb = mix(envAlb, vec3(0.03, 0.045, 0.015), moss * 0.8); + envRough = mix(envRough, envRough * 0.7, damp); + float splash = (1.0 - smoothstep(0.0, 0.12 + 0.2 * m1, foot)) * uGrime; + envAlb = mix(envAlb, vec3(0.05, 0.04, 0.03), splash * 0.6); + } + #endif + // weathering shared by every material, lined up in world space: rain streaks down walls, sun fading, and dust + // on upward faces (sills, crate tops, ledges) that kills shine and fills the relief; rain washes the dust away + { + vec3 wn = inverseTransformDirection(normalize(vNormal), viewMatrix); + float vert = 1.0 - abs(wn.y); + float streak = texture2D(uMacro, vec2((wp.x + wp.z) * 0.33, wp.y * 0.05)).a; + envAlb *= 1.0 - vert * smoothstep(0.55, 0.9, streak) * 0.22 * uGrime; + // patches that cross many stones or boards (a wall reads as one weathered surface first): lichen and green + // on the lower and middle wall, soot and old dirt in others, a slow 1-3 m scale, on vertical faces only + float pat = texture2D(uMacro, vec2(wp.x + wp.z, wp.y * 1.3) * 0.19 + 0.13).b; + float pat2 = texture2D(uMacro, vec2(wp.x - wp.z, wp.y) * 0.07 + 0.41).r; + float lich = vert * smoothstep(0.6, 0.82, pat) * smoothstep(0.3, 0.7, envH + 0.25) * uGrime; + envAlb = mix(envAlb, envAlb * vec3(0.86, 1.04, 0.66), lich * 0.75); + envAlb *= 1.0 - vert * smoothstep(0.34, 0.1, pat) * 0.32 * uGrime; + envAlb *= mix(0.8, 1.1, pat2 * vert + (1.0 - vert) * 0.7) * mix(vec3(1.0), vec3(1.05, 1.0, 0.92), smoothstep(0.4, 0.8, pat2) * vert); // warmer and cooler areas a few metres across + float lum = dot(envAlb, vec3(0.3, 0.55, 0.15)); + envAlb = mix(envAlb, vec3(lum) * vec3(1.04, 1.0, 0.94), 0.12); + float dustAmt = smoothstep(0.65, 0.95, wn.y) * smoothstep(0.35, 0.7, m2 * 0.6 + m1 * 0.4 + envH * 0.3) * uDust * (1.0 - uWet); + envAlb = mix(envAlb, vec3(0.30, 0.235, 0.155) * (0.8 + 0.4 * m1), dustAmt * 0.7); + envRough = mix(envRough, 1.0, dustAmt); + } + envAlb *= 1.0 - uWet * 0.38 * (0.6 + 0.4 * envH); + envRough = mix(envRough, envRough * 0.4, uWet); + diffuseColor.rgb *= envAlb; + `; + + // ------------------------------------------------------------------ geometry helpers + // Put the aEnv attribute on a geometry: tint (THREE.Color or null) and height above ground taken from y - baseY. + E.setEnvAttr = function (geo, tint, baseY) { + const p = geo.attributes.position, n = p.count, a = new Float32Array(n * 4); + for (let i = 0; i < n; i++) { if (tint) { a[i * 4] = tint.r; a[i * 4 + 1] = tint.g; a[i * 4 + 2] = tint.b; } a[i * 4 + 3] = baseY == null ? 0 : 1 + Math.max(0, p.getY(i) - baseY); } + geo.setAttribute('aEnv', new THREE.BufferAttribute(a, 4)); return geo; + }; + // Box-project UVs in metres (for geometry the game makes itself and then gives an IVEnv material). + E.uvMetres = function (geo) { + const p = geo.attributes.position, nrm = geo.attributes.normal, n = p.count, uv = new Float32Array(n * 2); + for (let i = 0; i < n; i++) { + const x = p.getX(i), y = p.getY(i), z = p.getZ(i), ax = Math.abs(nrm.getX(i)), ay = Math.abs(nrm.getY(i)), az = Math.abs(nrm.getZ(i)); + if (ay >= ax && ay >= az) { uv[i * 2] = x; uv[i * 2 + 1] = z; } else if (ax >= az) { uv[i * 2] = z; uv[i * 2 + 1] = y; } else { uv[i * 2] = x; uv[i * 2 + 1] = y; } + } + geo.setAttribute('uv', new THREE.BufferAttribute(uv, 2)); return geo; + }; +})(); diff --git a/e63334287a3deaa3/ironveil/env/decals.js b/e63334287a3deaa3/ironveil/env/decals.js new file mode 100644 index 00000000..df70a284 --- /dev/null +++ b/e63334287a3deaa3/ironveil/env/decals.js @@ -0,0 +1,53 @@ +/* Midnight Ops environment: runtime decals (impacts, scorch) from one pooled instanced mesh = one draw call. + IVEnv.decal(type, position, normal, size, seed) -> index types: scratches, gouges, chipped, pocks, scorch, soot, + damp, moss, rust, mud, crack, bullethole, leaves, waterstain, chalk, grime (see IVEnv.DECALS). position / normal + are THREE.Vector3 or [x, y, z] in world space. The pool holds IVEnv.Q.decals; the oldest is reused. + IVEnv.impact(surface, position, normal) picks a decal for a bullet hit by surface: 'stone' | 'brick' | 'concrete' | + 'wood' | 'metal' | 'glass' | 'dirt' | 'cloth' (returns the decal index or -1 for surfaces that take none). + IVEnv.clearDecals() empties the pool (level change). Decals are offset 4 mm and use polygon offset (no z-fighting). */ +(function () { + 'use strict'; + const E = window.IVEnv; + let pool = null; + function makePool(scene) { + const n = (E.Q && E.Q.decals) || 128; + const g = new THREE.PlaneGeometry(1, 1); g.translate(0, 0, 0.004); + const cell = new THREE.InstancedBufferAttribute(new Float32Array(n * 2), 2); g.setAttribute('aCell', cell); + const base = E.decalMaterial(), m = base.clone(); + m.onBeforeCompile = function (sh) { + base.onBeforeCompile.call(this, sh); + sh.vertexShader = 'attribute vec2 aCell;\n' + sh.vertexShader.replace('#include ', 'vUv = (uv * (0.25 - 0.008) + 0.004) + aCell;'); + }; + m.customProgramCacheKey = () => 'ivdecalpool'; + const mesh = new THREE.InstancedMesh(g, m, n); mesh.count = 0; mesh.frustumCulled = false; mesh.renderOrder = 3; mesh.receiveShadow = true; mesh.name = 'IVEnv.decals'; + pool = { mesh, cell, n, next: 0, used: 0 }; + (scene || E.atmo && E.atmo.scene).add(mesh); + return pool; + } + const _o = new THREE.Object3D(), _n = new THREE.Vector3(), _p = new THREE.Vector3(); + E.decal = function (type, position, normal, size, seed) { + if (!pool) makePool(); + const c = typeof type === 'number' ? type : E.DECALS[type]; if (c == null) return -1; + _p.set(position.x != null ? position.x : position[0], position.y != null ? position.y : position[1], position.z != null ? position.z : position[2]); + _n.set(normal.x != null ? normal.x : normal[0], normal.y != null ? normal.y : normal[1], normal.z != null ? normal.z : normal[2]).normalize(); + const i = pool.next; pool.next = (pool.next + 1) % pool.n; pool.used = Math.min(pool.n, pool.used + 1); + _o.position.copy(_p); _o.lookAt(_p.x + _n.x, _p.y + _n.y, _p.z + _n.z); + const r = seed != null ? E.hash(seed, 3, 7) : Math.random(); _o.rotateZ(r * Math.PI * 2); + const s = size || 0.3; _o.scale.set(s, s, 1); _o.updateMatrix(); + pool.mesh.setMatrixAt(i, _o.matrix); pool.mesh.instanceMatrix.needsUpdate = true; + pool.cell.setXY(i, (c % 4) / 4, Math.floor(c / 4) / 4); pool.cell.needsUpdate = true; + pool.mesh.count = pool.used; + return i; + }; + E.impact = function (surface, position, normal) { + const s = String(surface || '').toLowerCase(), R = Math.random; + if (s === 'stone' || s === 'brick' || s === 'concrete') return E.decal(R() < 0.65 ? 'bullethole' : 'pocks', position, normal, 0.12 + R() * 0.1); + if (s === 'wood') return E.decal(R() < 0.7 ? 'bullethole' : 'gouges', position, normal, 0.1 + R() * 0.08); + if (s === 'metal') return E.decal('bullethole', position, normal, 0.07 + R() * 0.04); + if (s === 'glass') return E.decal('crack', position, normal, 0.35 + R() * 0.2); + if (s === 'dirt' || s === 'mud' || s === 'grass' || s === 'gravel') return E.decal('mud', position, normal, 0.25 + R() * 0.2); + return -1; + }; + E.clearDecals = function () { if (pool) { pool.used = 0; pool.next = 0; pool.mesh.count = 0; } }; + E.decalPoolMesh = () => pool ? pool.mesh : null; +})(); diff --git a/e63334287a3deaa3/ironveil/env/grass.js b/e63334287a3deaa3/ironveil/env/grass.js new file mode 100644 index 00000000..82d3e91a --- /dev/null +++ b/e63334287a3deaa3/ironveil/env/grass.js @@ -0,0 +1,448 @@ +/* Midnight Ops environment: blade grass. + IVEnv.grass(surfaceAt, heightFn, opts) -> { group, update(camera), info(), dispose() } (also driven by IVEnv.update) + - Real triangle blades bent along a curve in the vertex shader (no camera-facing cards), one instanced mesh per ring. + - Placement is a hash of WORLD coordinates in fixed 8 m tiles: stratified jitter, Voronoi clumps (0.9 m) with their own + height, lean, facing and colour and a pull toward the clump centre; a slow patch noise picks the grass type and + shifts young green toward dry straw. The same field comes out in the game and on the test page. + - Rings: near (all blades, 3 segments on High), mid (a fixed random quarter-ish subset of the SAME blades, fewer + vertices, wider), then nothing: the ground shader carries the colour (see ground.js, which calls IVEnv.grassCarry). + The near ring thins to exactly the mid subset over its last metres, so the hand-over shows no line. + - Lighting: root AO, root colour from the ground, translucency (light from behind comes through, warmer), gloss on + the upper blade only, rounded "V" normal blended to up at the tip and with distance. Receives shadows, casts none. + - One wind field (IVEnv.setWind) with gust fronts; up to 8 pushers (IVEnv.setPushers) bend blades away and down. + surfaceAt(x, z) returns a kind name; kinds with grass: see KINDS below. opts.longAt(x, z) -> 0..1 adds length + (hedge feet, wall bases, fence lines, ditch edges). opts.densityAt(x, z) -> 0..1 multiplies density. + opts.nearMul / opts.carpetMul widen the near ring and the carpet for a world that wants a fuller field (Boot Camp). */ +(function () { + 'use strict'; + const E = window.IVEnv; + const TS = 8; // tile size, metres + + // Kinds: d = density multiplier, h = [min, max] height in metres, long = share of long meadow blades, tus = share of + // tussock, dead = share of dead blades, dry = dryness bias, ground = root colour (sRGB). + const KINDS = E.GRASS_KINDS = { + grass: { d: 0.95, fill: 0.15, h: [0.1, 0.26], long: 0.03, tus: 0.04, dead: 0.06, dry: 0.0, ground: 0x38331f, c: 1.0, ch: 1.0 }, + pasture: { d: 0.7, h: [0.08, 0.2], long: 0.02, tus: 0.03, dead: 0.06, dry: 0.0, ground: 0x38331f, c: 1.0, ch: 0.9 }, + meadow: { d: 1.0, h: [0.3, 0.7], long: 0.5, tus: 0.12, dead: 0.08, dry: 0.04, ground: 0x38331f, c: 0.85, ch: 1.2 }, + tussock: { d: 1.05, h: [0.45, 0.95], long: 0.45, tus: 0.4, dead: 0.2, dry: 0.1, ground: 0x34301e, c: 0.8, ch: 1.3 }, + verge: { d: 1.0, h: [0.25, 0.65], long: 0.35, tus: 0.3, dead: 0.15, dry: 0.06, ground: 0x35301f, c: 0.9, ch: 1.2 }, + lanemid: { d: 0.5, h: [0.08, 0.22], long: 0.03, tus: 0.1, dead: 0.2, dry: 0.1, ground: 0x2a2218, c: 0.7, ch: 0.8 }, + worn: { d: 0.6, h: [0.06, 0.16], long: 0.0, tus: 0.04, dead: 0.25, dry: 0.15, ground: 0x30281c, c: 0.9, ch: 0.75 }, + leaves: { d: 0.15, h: [0.1, 0.25], long: 0.1, tus: 0.0, dead: 0.3, dry: 0.2, ground: 0x2a2016, c: 0.2, ch: 0.8 }, + // lawn: well-kept camp turf, thick and green, a little longer than mown grass (Boot Camp) + lawn: { d: 1.0, fill: 0.3, h: [0.16, 0.36], long: 0.07, tus: 0.05, dead: 0.04, dry: 0.0, ground: 0x4f5a2c, c: 1.05, ch: 1.05 }, + // scorched: round shell holes and burnt ground, short dead stubble flattened outward, dark roots + scorched:{ d: 0.75, fill: 0.2, h: [0.03, 0.1], long: 0.0, tus: 0.0, dead: 0.75, dry: 0.6, ground: 0x1c1915, c: 0.7, ch: 0.45 }, + yardedge:{ d: 0.3, h: [0.06, 0.18], long: 0.0, tus: 0.1, dead: 0.25, dry: 0.15, ground: 0x2e2a22, c: 0.45, ch: 0.7 } + }; + // Blade colours (sRGB) shared by the shader and the ground's far colour + const PAL = E.GRASS_PAL = { young: 0x4f7434, green: 0x3f5a26, olive: 0x575a30, dry: 0x857246, dead: 0x5f5240 }; + + // ------------------------------------------------------------------ the field (JS, deterministic) + const H = (i, j, s) => IVEnvTexGen.hash2(i | 0, j | 0, s | 0); + const F = E.grassField = {}; + F.patch = (x, z) => E.fbm2(x / 11 + 31.7, z / 11 - 7.3, 501, 3); // grass type / dryness patches + F.dens = (x, z) => E.fbm2(x / 4.3 - 2.1, z / 4.3 + 9.4, 502, 2); // bare spots + F.clump = function (x, z, o) { // nearest clump centre on a 0.9 m jittered grid + const C = 0.9, ix = Math.floor(x / C), iz = Math.floor(z / C); let best = 1e9; + for (let j = -1; j <= 1; j++) for (let i = -1; i <= 1; i++) { + const cx = (ix + i + 0.15 + 0.7 * H(ix + i, iz + j, 71)) * C, cz = (iz + j + 0.15 + 0.7 * H(ix + i, iz + j, 72)) * C, d = (cx - x) ** 2 + (cz - z) ** 2; + if (d < best) { best = d; o.x = cx; o.z = cz; o.id = H(ix + i, iz + j, 73); o.d = Math.sqrt(d); } + } + return o; + }; + F.dry = (kind, x, z) => { const K = KINDS[kind] || KINDS.grass; return E.clamp(E.sstep(0.6, 0.85, F.patch(x, z) + K.dry), 0, 1) * 0.8; }; + // average colour of the grass as seen from a distance (linear), for the ground's far ring + const _c1 = new THREE.Color(), _c2 = new THREE.Color(); + F.carry = function (kind, x, z, out) { + const K = KINDS[kind]; if (!K) return out.setRGB(0, 0, 0); + const dry = F.dry(kind, x, z), p = F.patch(x * 1.7, z * 1.7); + out.copy(E.lin(PAL.green)).lerp(_c1.copy(E.lin(PAL.olive)), E.clamp(p, 0, 1) * 0.6); + out.lerp(_c1.copy(E.lin(PAL.dry)), dry * 0.85); + out.lerp(_c2.copy(E.lin(PAL.dead)), K.dead * 0.5); + out.lerp(_c2.copy(E.lin(K.ground)), 0.35); // soil between blades and the dark roots + return out; + }; + + // Generate one tile. Returns { full: Float32Array|null, mid: Float32Array, seed: Float32Array }, 12 floats per blade: + // x, y, z, facing | height, width, lean, type + rnd*0.99 | root r, g, b (linear), dry + const _cl = { x: 0, z: 0, id: 0, d: 0 }, _root = new THREE.Color(); + const rootCache = {}; + // cached surface kinds (0.5 m) and heights (0.25 m, bilinear) for one tile, so surfaceAt/heightFn run a few + // hundred times per tile instead of once per blade + function tileCache(G, x0, z0) { + const SN = TS * 2 + 1, HN = TS * 4 + 1, sk = new Array(SN * SN), hs = new Float32Array(HN * HN); + for (let j = 0; j < SN; j++) for (let i = 0; i < SN; i++) sk[j * SN + i] = G.surfaceAt(x0 + i * 0.5, z0 + j * 0.5); + for (let j = 0; j < HN; j++) for (let i = 0; i < HN; i++) hs[j * HN + i] = G.heightFn(x0 + i * 0.25, z0 + j * 0.25); + return { + kind(x, z) { const i = Math.min(SN - 1, Math.max(0, Math.round((x - x0) * 2))), j = Math.min(SN - 1, Math.max(0, Math.round((z - z0) * 2))); return sk[j * SN + i]; }, + h(x, z) { const fx = Math.min(HN - 1.001, Math.max(0, (x - x0) * 4)), fz = Math.min(HN - 1.001, Math.max(0, (z - z0) * 4)), i = fx | 0, j = fz | 0, u = fx - i, v = fz - j, k = j * HN + i; + return (hs[k] * (1 - u) + hs[k + 1] * u) * (1 - v) + (hs[k + HN] * (1 - u) + hs[k + HN + 1] * u) * v; } + }; + } + function genTile(G, tx, tz, wantFull) { + const Q = E.Q, dens = Q.grassDens, n = Math.ceil(Math.sqrt(dens * TS * TS)), cell = TS / n, midFrac = Math.min(1, Q.grassMidDens * (E._grassMidMul || 1) / Q.grassDens); + const full = wantFull ? [[], [], [], []] : null, mid = [], seed = [], carpet = wantFull ? [[], [], [], []] : null; + const x0 = tx * TS, z0 = tz * TS, TC = tileCache(G, x0, z0); + for (let j = 0; j < n; j++) for (let i = 0; i < n; i++) { + const gi = tx * n + i, gj = tz * n + j; + const rnd = H(gi, gj, 11); + if (!wantFull && rnd >= midFrac) continue; + let x = x0 + (i + H(gi, gj, 12)) * cell, z = z0 + (j + H(gi, gj, 13)) * cell; + const kind = TC.kind(x, z), K = KINDS[kind]; if (!K) continue; + let d = K.d * E.sstep(0.18, 0.45, F.dens(x, z) + 0.12 + (K.fill || 0)); + if (G.densityAt) d *= G.densityAt(x, z); + if (H(gi, gj, 14) > d) continue; + F.clump(x, z, _cl); + const pull = 0.3 + 0.35 * _cl.id; x += (_cl.x - x) * pull; z += (_cl.z - z) * pull; + const y = TC.h(x, z); + const longK = G.longAt ? G.longAt(x, z) : 0; + // grass type: 0 short, 1 long meadow, 2 tussock, 3 dead + const tr = H(gi, gj, 15), pt = F.patch(x, z); + const pLong = E.clamp(K.long + longK * 0.6 + (pt - 0.5) * 0.4, 0, 1), pTus = K.tus + longK * 0.2, pDead = K.dead + (pt > 0.65 ? 0.12 : 0); + let type = 0; + if (tr < pDead) type = 3; else if (tr < pDead + pTus) type = 2; else if (tr < pDead + pTus + pLong) type = 1; + const hm = 0.72 + 0.6 * _cl.id, distC = _cl.d; + let h = (K.h[0] + (K.h[1] - K.h[0]) * Math.pow(H(gi, gj, 16), 0.8)) * hm * (1 + longK * 0.9) * (0.45 + 0.75 * Math.pow(H(gi, gj, 21), 0.6)); + if (type === 1) h *= 1.5; else if (type === 2) h *= 1.25; else if (type === 3) h *= 0.9; + h *= 1 - 0.25 * E.clamp(distC / 0.6, 0, 1); // taller in the middle of a clump + if (H(gi, gj, 22) < (type === 1 ? 0.3 : 0.5)) { h *= 0.22 + 0.3 * H(gi, gj, 23); if (type === 1) type = 0; } // undergrowth: short blades fill the base + const w = (type === 2 ? 0.04 : type === 1 ? 0.03 : type === 3 ? 0.025 : 0.032) * (0.75 + 0.5 * H(gi, gj, 17)) * (H(gi, gj, 24) < 0.15 ? 1.7 : 1); + // facing: blades of a clump fan out from its centre, with some randomness + const fan = Math.atan2(z - _cl.z, x - _cl.x); + const facing = fan + (H(gi, gj, 18) - 0.5) * 2.2 + _cl.id * 3; + const lean = (type === 3 ? 0.6 : type === 2 ? 0.5 : type === 1 ? 0.42 : 0.3) * (0.4 + 0.9 * H(gi, gj, 19)) + 0.3 * E.clamp(distC / 0.6, 0, 1) + (h > 0.5 ? (h - 0.5) * 0.6 : 0); + let rc = rootCache[kind]; if (!rc) rc = rootCache[kind] = E.lin(K.ground); + const dry = E.clamp(F.dry(kind, x, z) + (_cl.id - 0.5) * 0.25 + (type === 3 ? 0.6 : 0), 0, 1); + const rec = [x, y, z, facing, h, w, lean, type + rnd * 0.99, rc.r, rc.g, rc.b, dry]; + if (full) { const qd = (x - x0 >= TS / 2 ? 1 : 0) + (z - z0 >= TS / 2 ? 2 : 0); for (let k = 0; k < 12; k++) full[qd].push(rec[k]); } + if (rnd < midFrac) for (let k = 0; k < 12; k++) mid.push(rec[k]); + if (type === 1 && h > 0.35 && H(gi, gj, 20) < 0.09) for (let k = 0; k < 12; k++) seed.push(rec[k]); + } + // the low carpet: many short broad-ish blades so no bare soil shows near the camera (3 vertices each) + if (carpet) { + const cn = Math.ceil(Math.sqrt(Q.carpetDens * TS * TS)), cc = TS / cn; + for (let j = 0; j < cn; j++) for (let i = 0; i < cn; i++) { + const gi = tx * cn + i, gj = tz * cn + j; + let x = x0 + (i + H(gi, gj, 31)) * cc, z = z0 + (j + H(gi, gj, 32)) * cc; + { const ti = Math.floor(x / 0.42), tj = Math.floor(z / 0.42), tcx = (ti + 0.05 + 0.9 * H(ti, tj, 41)) * 0.42, tcz = (tj + 0.05 + 0.9 * H(ti, tj, 42)) * 0.42; x += (tcx - x) * 0.3; z += (tcz - z) * 0.3; } + const kind = TC.kind(x, z), K = KINDS[kind]; if (!K || !K.c) continue; + if (H(gi, gj, 33) > K.c * E.sstep(0.12, 0.4, F.dens(x, z) + 0.15)) continue; + const rnd = H(gi, gj, 34), y = TC.h(x, z); + const h = (0.05 + 0.11 * Math.pow(H(gi, gj, 35), 0.7)) * K.ch; + const w = 0.014 + 0.014 * H(gi, gj, 36); + let rc = rootCache[kind]; if (!rc) rc = rootCache[kind] = E.lin(K.ground); + const dry = E.clamp(F.dry(kind, x, z) * 0.8 + (H(gi, gj, 37) < 0.12 ? 0.5 : 0), 0, 1); + const rec = [x, y, z, H(gi, gj, 38) * 6.283, h, w, 0.35 + 0.6 * H(gi, gj, 39), 0 + rnd * 0.99, rc.r, rc.g, rc.b, dry]; + const qd = (x - x0 >= TS / 2 ? 1 : 0) + (z - z0 >= TS / 2 ? 2 : 0); for (let k = 0; k < 12; k++) carpet[qd].push(rec[k]); + } + } + // carpet blades sorted by their random value: far quadrants upload only the first 55% (the shader keeps the same ones) + const sortRec = (a) => { const n = a.length / 12, idx = []; for (let i = 0; i < n; i++) idx.push(i); idx.sort((p, q) => (a[p * 12 + 7] % 1) - (a[q * 12 + 7] % 1)); const o = new Float32Array(a.length); idx.forEach((k, i) => { for (let c = 0; c < 12; c++) o[i * 12 + c] = a[k * 12 + c]; }); return o; }; + return { full: full ? full.map(a => new Float32Array(a)) : null, carpet: carpet ? carpet.map(sortRec) : null, mid: new Float32Array(mid), seed: new Float32Array(seed), ymin: 0, ymax: 0 }; + } + + // ------------------------------------------------------------------ blade geometry (per ring) + function bladeGeo(segs) { + // rows packed toward the tip, two vertices per row, one tip vertex + const rows = segs === 3 ? [0, 0.38, 0.7] : segs === 2 ? [0, 0.55] : [0]; + const t = [], s = [], idx = []; + rows.forEach(r => { t.push(r, r); s.push(-1, 1); }); + t.push(1); s.push(0); + for (let i = 0; i < rows.length - 1; i++) { const a = i * 2; idx.push(a, a + 1, a + 2, a + 1, a + 3, a + 2); } + const L = (rows.length - 1) * 2; idx.push(L, L + 1, L + 2); + const g = new THREE.InstancedBufferGeometry(); + g.setAttribute('position', new THREE.Float32BufferAttribute(new Float32Array(t.length * 3), 3)); + g.setAttribute('aT', new THREE.Float32BufferAttribute(t, 1)); g.setAttribute('aS', new THREE.Float32BufferAttribute(s, 1)); + g.setIndex(idx); g.userData.tris = idx.length / 3; + return g; + } + function seedGeo() { // a loose drooping panicle: thin stem tip and narrow spikelets hanging off it + const o = [], idx = []; let v = 0; + const tri = (ax, ay, az, bx, by, bz, cx, cy, cz) => { o.push(ax, ay, az, bx, by, bz, cx, cy, cz); idx.push(v, v + 1, v + 2); v += 3; }; + tri(-0.0015, 0, 0, 0.0015, 0, 0, 0.004, 0.11, 0.002); + for (let k = 0; k < 7; k++) { + const y = 0.02 + k * 0.013, a = k * 2.4, len = 0.035 - k * 0.003, dx = Math.cos(a), dz = Math.sin(a); + const bx = dx * 0.003, bz = dz * 0.003, tx = dx * len * 0.8, tz = dz * len * 0.8, ty = y - len * 0.45; + tri(bx - dz * 0.0025, y, bz + dx * 0.0025, bx + dz * 0.0025, y, bz - dx * 0.0025, tx, ty, tz); + } + const g = new THREE.InstancedBufferGeometry(), n = o.length / 3; + g.setAttribute('position', new THREE.Float32BufferAttribute(o, 3)); + g.setAttribute('aT', new THREE.Float32BufferAttribute(new Array(n).fill(1), 1)); g.setAttribute('aS', new THREE.Float32BufferAttribute(new Array(n).fill(0), 1)); + g.setIndex(idx); g.userData.tris = idx.length / 3; return g; + } + + // ------------------------------------------------------------------ material + const BLADE_VS = ` + attribute float aT; attribute float aS; attribute vec4 iA; attribute vec4 iB; attribute vec4 iC; + uniform vec4 uPush[8]; uniform vec4 uRing; uniform float uWidthFar; + varying float vT; varying float vDry; varying float vType; varying vec3 vRoot; varying float vRnd; varying float vDist; varying float vEdge; varying vec3 vSideW; + ${E.GLSL.wind} + vec3 ivBlade(float t, float side, out vec3 N, out float keep) { + vec3 base = iA.xyz; float face = iA.w; float h = iB.x, w = iB.y, lean = iB.z; float type = floor(iB.w), rnd = fract(iB.w); + vec2 d2 = base.xz - cameraPosition.xz; float dist = length(d2); + // ring ownership + thinning: near ring hands over to the mid subset (rnd < uRing.w) over its last uRing.z metres + float fo = smoothstep(uRing.y - uRing.z, uRing.y, dist); + keep = step(uRing.x, dist) * step(dist, uRing.y); + #ifdef IV_CARPET + // full density right at the lens, thinning to 55% past 4 m; close blades broader, lower, leaning more + keep *= step(rnd, mix(1.0, 0.55, smoothstep(2.5, 4.5, dist))); + float nearK = 1.0 - smoothstep(2.0, 4.0, dist); + float broad = step(fract(rnd * 7.7), 0.35); + w *= 1.0 + nearK * broad * 1.4; h *= 1.0 - nearK * 0.2; lean += nearK * 0.25; + #endif + #ifdef IV_NEAR + keep *= step(rnd, mix(1.0, uRing.w, fo)); + #else + keep *= step(rnd / uRing.w, 1.0 - fo); + h *= 1.0 - fo * 0.85; + #endif + h *= keep; + vec2 fd = vec2(cos(face), sin(face)); + vec2 toCam = dist > 1e-3 ? -d2 / dist : vec2(1.0, 0.0); + float e = dot(fd, toCam); + // nearly edge-on blades twist toward the viewer so they do not vanish + fd = mix(fd, toCam * (e < 0.0 ? -1.0 : 1.0), 0.45 * (1.0 - abs(e))); fd = length(fd) > 1e-4 ? normalize(fd) : vec2(1.0, 0.0); + vec2 sd = vec2(-fd.y, fd.x); + // wind + pushers + the blade's own lean (squared along the blade so the root stays put) + vec2 wv = ivWind(base.xz) * (0.55 + 0.6 * rnd) * (type > 2.5 ? 0.6 : 1.0); + vec2 pv = vec2(0.0); float flat_ = 0.0; + for (int i = 0; i < 8; i++) { + vec4 P = uPush[i]; if (P.z <= 0.0) continue; + vec2 dd = base.xz - P.xy; float l = length(dd); float f = clamp(1.0 - l / P.z, 0.0, 1.0); f = f * f * P.w; + pv += dd / max(l, 1e-3) * f * 1.6; flat_ = max(flat_, f); + } + vec2 off = fd * lean + wv * 0.9 + pv; + float ol = length(off); if (ol > 0.9) off *= 0.9 / ol; ol = min(ol, 0.9); + float tt = t * t; + float y = h * t * sqrt(max(0.05, 1.0 - 0.55 * ol * ol * t)) * (1.0 - flat_ * 0.55 * t); + float fold = step(0.955, fract(rnd * 31.7)) * step(0.15, h) * max(t - 0.55, 0.0); // a few broken blades flop over + vec2 xz = off * h * (0.45 * tt + 0.4 * tt * t); + y -= fold * h * 1.6; xz += fd * fold * h * 1.2; + float wm = 1.0 + (uWidthFar - 1.0) * smoothstep(4.0, 45.0, dist); + float hw = w * wm * 0.5 * (1.0 - pow(t, 1.3)) * (type > 1.5 && type < 2.5 ? 1.2 : 1.0) * keep; + vec3 p = base + vec3(xz.x, y, xz.y) + vec3(sd.x, 0.0, sd.y) * side * hw; + // normal: across-blade rounding ("V"), tangent from the curve, blended to up at the tip and with distance + vec3 T = normalize(vec3(off.x * (0.9 * t + 1.2 * tt), 1.0, off.y * (0.9 * t + 1.2 * tt))); + vec3 S = vec3(sd.x, 0.0, sd.y); + vec3 n = normalize(cross(S, T)); + if (dot(n.xz, toCam) < 0.0) n.xz = -n.xz; + vSideW = S; + n = normalize(mix(n, vec3(0.0, 1.0, 0.0), clamp(0.55 + 0.3 * tt + 0.4 * smoothstep(6.0, 35.0, dist), 0.0, 0.95))); + N = n; + vT = t; vDry = iC.w; vType = type; vRoot = iC.rgb; vRnd = rnd; vDist = dist; vEdge = side; + return p; + } + `; + function bladeMaterial(near, seedHeads, carpet) { + const m = new THREE.MeshStandardMaterial({ side: THREE.DoubleSide, roughness: 0.6, metalness: 0, envMapIntensity: 0.6 }); + m.userData.linear = true; + const uni = { + uTime: E.U.uTime, uWind: E.U.uWind, uPush: E.U.uPush, uWet: E.U.uWet, + uRing: { value: new THREE.Vector4(0, 15, 3, 0.2) }, uWidthFar: { value: 2.6 }, + cYoung: { value: E.lin(PAL.young) }, cGreen: { value: E.lin(PAL.green) }, cOlive: { value: E.lin(PAL.olive) }, cDry: { value: E.lin(PAL.dry) }, cDead: { value: E.lin(PAL.dead) }, + uTrans: { value: 1.0 } + }; + m.userData.uniforms = uni; + m.defines = { IV_GRASS: '' }; if (near) m.defines.IV_NEAR = ''; if (carpet) m.defines.IV_CARPET = ''; if (seedHeads) m.defines.IV_SEED = ''; + m.onBeforeCompile = function (sh) { + Object.assign(sh.uniforms, uni); + sh.vertexShader = BLADE_VS + sh.vertexShader + .replace('#include ', ` + vec3 ivN; float ivKeep; + #ifdef IV_SEED + vec3 ivTip = ivBlade(1.0, 0.0, ivN, ivKeep); + vec3 ivTip2 = ivBlade(0.9, 0.0, ivN, ivKeep); + vec3 ivUp = normalize(ivTip - ivTip2); vec3 ivX = normalize(cross(ivUp, vec3(0.0, 0.0, 1.0) + 0.001)); vec3 ivZ = cross(ivX, ivUp); + vec3 ivP = ivTip + (ivX * position.x + ivUp * position.y + ivZ * position.z) * (0.7 + 0.6 * vRnd) * ivKeep; + ivN = normalize(ivZ + ivUp * 0.3); vT = 1.0; + #else + vec3 ivP = ivBlade(aT, aS, ivN, ivKeep); + #endif + vec3 objectNormal = ivN;`) + .replace('#include ', 'vec3 transformed = ivP;'); + sh.fragmentShader = ` + uniform vec3 cYoung, cGreen, cOlive, cDry, cDead; uniform float uWet, uTrans; + varying float vT; varying float vDry; varying float vType; varying vec3 vRoot; varying float vRnd; varying float vDist; varying float vEdge; varying vec3 vSideW; + vec3 ivTransCol; float ivTransAmt; + ` + sh.fragmentShader + .replace('#include ', THREE.ShaderChunk.lights_physical_pars_fragment.replace( + 'vec3 irradiance = dotNL * directLight.color;', + `vec3 irradiance = dotNL * directLight.color; + { + // light coming through the blade from behind (relative to the viewer): warmer, more saturated + float back = saturate(dot(-geometry.normal, directLight.direction)); + float scat = pow(saturate(dot(-geometry.viewDir, directLight.direction)), 3.0); + vec3 tr = ivTransCol * directLight.color * (back * 0.55 + scat * 0.9) * ivTransAmt; + #ifndef PHYSICALLY_CORRECT_LIGHTS + tr *= PI; + #endif + reflectedLight.directDiffuse += tr * RECIPROCAL_PI; + }`)) + .replace('#include ', ` + float faceDirection = gl_FrontFacing ? 1.0 : -1.0; + vec3 normal = normalize(vNormal); + // folded leaf: each half of the blade tilts away from the midrib, so the highlight shows the crease + vec3 sideV = normalize((viewMatrix * vec4(vSideW, 0.0)).xyz); + float crease = 0.55 * (1.0 - smoothstep(4.0, 14.0, vDist)); + normal = normalize(normal + sideV * clamp(vEdge * 4.0, -1.0, 1.0) * crease); + vec3 geometryNormal = normal;`) + .replace('#include ', ` + vec3 tip = mix(cGreen, cYoung, smoothstep(0.55, 0.95, vRnd)); + tip = mix(tip, cOlive, smoothstep(0.3, 0.7, fract(vRnd * 7.3)) * 0.6); + tip = mix(tip, cDry, vDry * 0.9); + tip = mix(tip, cDead, step(2.5, vType) * 0.7); + tip = mix(tip, cDry * 0.9, smoothstep(0.82, 0.97, vT) * step(0.6, fract(vRnd * 13.1)) * 0.8); + tip *= 0.86 + 0.24 * (1.0 - abs(vEdge)); + tip = mix(tip, tip * 1.25 + vec3(0.012, 0.01, 0.0), smoothstep(0.6, 1.0, vT)); // lighter, slightly yellowed toward the tip + vec3 col = mix(vRoot, tip, smoothstep(0.0, 0.6, vT)); + float ao = mix(0.42, 1.0, pow(clamp(vT, 0.0, 1.0), 0.55)); + col *= ao * (1.0 - uWet * 0.3); + diffuseColor.rgb = col; + ivTransCol = tip * vec3(1.25, 1.4, 0.55) * smoothstep(0.1, 0.7, vT) * (1.0 - vDry * 0.4); + ivTransAmt = uTrans; + `) + .replace('#include ', ` + float roughnessFactor = mix(0.95, 0.5, smoothstep(0.35, 0.85, vT)); + roughnessFactor = mix(roughnessFactor, 0.9, smoothstep(8.0, 30.0, vDist)); + roughnessFactor = mix(roughnessFactor, 0.85, smoothstep(2.0, 0.6, vDist)); // no glare right at the lens + roughnessFactor = mix(roughnessFactor, roughnessFactor * 0.55, uWet);`) + .replace('#include ', 'reflectedLight.indirectDiffuse *= ao; reflectedLight.indirectSpecular *= ao;'); + }; + m.customProgramCacheKey = () => 'ivgrass' + (near ? 'n' : 'm') + (seedHeads ? 's' : '') + (carpet ? 'c' : ''); + return m; + } + + // ------------------------------------------------------------------ the system + function Ring(G, name, segs, cap, near, seed) { + const geo = seed ? seedGeo() : bladeGeo(segs); + const buf = new THREE.InstancedInterleavedBuffer(new Float32Array(cap * 12), 12, 1); + buf.setUsage(THREE.DynamicDrawUsage); + geo.setAttribute('iA', new THREE.InterleavedBufferAttribute(buf, 4, 0)); + geo.setAttribute('iB', new THREE.InterleavedBufferAttribute(buf, 4, 4)); + geo.setAttribute('iC', new THREE.InterleavedBufferAttribute(buf, 4, 8)); + geo.instanceCount = 0; + const mat = bladeMaterial(near, seed, name === 'carpet'); + const mesh = new THREE.Mesh(geo, mat); + mesh.frustumCulled = false; mesh.receiveShadow = true; mesh.castShadow = false; mesh.name = 'grass-' + name; + return { name, geo, buf, cap, mesh, mat, count: 0, key: '' }; + } + + E.grass = function (surfaceAt, heightFn, opts) { + const lowQ = E.Q.name === 'low'; if (lowQ && opts) opts = Object.assign({}, opts, { nearMul: 1, carpetMul: 1, midMul: 1 }); // Low keeps the plain rings + E._grassMidMul = (opts && opts.midMul) || 1; // opts.midMul thickens the mid ring (same blades, a larger share kept) + opts = opts || {}; + const Q = E.Q; + const G = { + surfaceAt, heightFn, longAt: opts.longAt, densityAt: opts.densityAt, + group: new THREE.Group(), tiles: new Map(), pending: [], + rNear: opts.near || Q.grassNear * (opts.nearMul || 1), rMid: opts.mid || Q.grassMid + }; + G.group.name = 'IVEnv.grass'; + const nearCap = Math.ceil(Math.PI * (G.rNear + TS * 1.5) ** 2 * Q.grassDens * 0.9); + const midCap = Math.ceil(Math.PI * (G.rMid + TS * 1.5) ** 2 * Q.grassMidDens * (E._grassMidMul || 1) * 0.9); + G.near = Ring(G, 'near', Q.bladeSegs, nearCap, true, false); + G.rCarpet = Math.min(G.rNear, Q.carpetR * (opts.carpetMul || 1)); + G.carpet = Ring(G, 'carpet', Q.carpetSegs || (Q.name === 'low' ? 1 : 2), Math.ceil(Math.PI * (G.rCarpet + 6) ** 2 * Q.carpetDens * 0.75), true, false); + G.mid = Ring(G, 'mid', 1, midCap, false, false); + G.rings = [G.carpet, G.near, G.mid]; + if (Q.seedHeads) { G.seedN = Ring(G, 'seedNear', 0, Math.ceil(nearCap * 0.15), true, true); G.rings.push(G.seedN); } + const midFrac = Math.min(1, Q.grassMidDens * (E._grassMidMul || 1) / Q.grassDens), fadeN = Math.min(4, G.rNear * 0.3), fadeM = Math.min(10, G.rMid * 0.3); + for (const r of G.rings) { + const u = r.mat.userData.uniforms.uRing.value; + if (r.name === 'carpet') { u.set(0, G.rCarpet, Math.min(3, G.rCarpet * 0.4), 0); G.group.add(r.mesh); continue; } + if (r.name.indexOf('ear') >= 0 || r.name === 'near') u.set(0, G.rNear, fadeN, midFrac); + else u.set(G.rNear, G.rMid, fadeM, midFrac); + u.w = midFrac; + G.group.add(r.mesh); + } + + const frustum = new THREE.Frustum(), pm = new THREE.Matrix4(), box = new THREE.Box3(), v0 = new THREE.Vector3(), v1 = new THREE.Vector3(); + function tileKey(tx, tz) { return tx + ',' + tz; } + function getTile(tx, tz, wantFull) { + const k = tileKey(tx, tz); let t = G.tiles.get(k); + if (t && (!wantFull || t.full)) return t; + return null; + } + function makeTile(tx, tz, wantFull) { + const k = tileKey(tx, tz), t = genTile(G, tx, tz, wantFull); + // vertical bounds for culling + let y0 = 1e9, y1 = -1e9; for (let i = 0; i < 9; i++) { const y = heightFn(tx * TS + (i % 3) * TS / 2, tz * TS + Math.floor(i / 3) * TS / 2); y0 = Math.min(y0, y); y1 = Math.max(y1, y); } + t.ymin = y0 - 0.5; t.ymax = y1 + 1.5; t.tx = tx; t.tz = tz; + G.tiles.set(k, t); return t; + } + G.genMs = 0; + G.update = function (camera, budgetMs) { + const t0 = performance.now(); budgetMs = budgetMs == null ? 6 : budgetMs; + camera.updateMatrixWorld(); pm.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); frustum.setFromProjectionMatrix(pm); + const cx = camera.position.x, cz = camera.position.z; + const lists = { near: [], mid: [] }; + const R = G.rMid + TS, i0 = Math.floor((cx - R) / TS), i1 = Math.floor((cx + R) / TS), j0 = Math.floor((cz - R) / TS), j1 = Math.floor((cz + R) / TS); + for (let tz = j0; tz <= j1; tz++) for (let tx = i0; tx <= i1; tx++) { + // distance from the camera to the tile rectangle + const dx = Math.max(tx * TS - cx, 0, cx - (tx + 1) * TS), dz = Math.max(tz * TS - cz, 0, cz - (tz + 1) * TS), d = Math.hypot(dx, dz); + if (d > G.rMid) continue; + const inNear = d <= G.rNear; + let t = getTile(tx, tz, inNear); + if (!t) { + if (!inNear && performance.now() - t0 > budgetMs && G.warm) { G.pending++; continue; } + t = makeTile(tx, tz, inNear); + } + box.min.set(tx * TS - 1.5, t.ymin, tz * TS - 1.5); box.max.set((tx + 1) * TS + 1.5, t.ymax, (tz + 1) * TS + 1.5); + if (d > 3 && !frustum.intersectsBox(box)) continue; + if (inNear) for (let qd = 0; qd < 4; qd++) { + const qx = tx * TS + (qd & 1) * TS / 2, qz = tz * TS + (qd >> 1) * TS / 2; + const ddx = Math.max(qx - cx, 0, cx - qx - TS / 2), ddz = Math.max(qz - cz, 0, cz - qz - TS / 2), dq = Math.hypot(ddx, ddz); + if (dq > G.rNear) continue; + box.min.set(qx - 1.2, t.ymin, qz - 1.2); box.max.set(qx + TS / 2 + 1.2, t.ymax, qz + TS / 2 + 1.2); + if (dq > 2 && !frustum.intersectsBox(box)) continue; + lists.near.push({ t, qd, dq, tx: t.tx * 2 + (qd & 1), tz: t.tz * 2 + (qd >> 1) }); + } + if (d + TS * 1.5 > G.rNear) lists.mid.push(t); + } + fill(G.near, lists.near, 'full'); + fill(G.carpet, lists.near.filter(e => e.dq <= G.rCarpet), 'carpet'); + lists.nearT = []; { const seen = new Set(); for (const e of lists.near) if (!seen.has(e.t)) { seen.add(e.t); lists.nearT.push(e.t); } } + fill(G.mid, lists.mid, 'mid'); + if (G.seedN) fill(G.seedN, lists.nearT, 'seed'); if (G.seedM) fill(G.seedM, lists.mid, 'seed', 'mid'); + // forget tiles far away + if (G.tiles.size > 600) for (const [k, t] of G.tiles) { if (Math.hypot((t.tx + 0.5) * TS - cx, (t.tz + 0.5) * TS - cz) > G.rMid + 40) G.tiles.delete(k); } + G.warm = true; G.genMs = performance.now() - t0; + }; + function fill(ring, tiles, field, alt) { + const key = field + tiles.map(t => t.tx + ':' + t.tz + (t.qd != null ? 'q' + t.qd + (field === 'carpet' && t.dq > 4.5 ? 'f' : '') : '')).join('|'); + if (key === ring.key) return; ring.key = key; + const arr = ring.buf.array; let n = 0; + const midFrac2 = midFrac; + for (const t of tiles) { + let src = (field === 'full' || field === 'carpet') ? t.t[field][t.qd] : t[field]; + if (field === 'carpet' && t.dq > 4.5) src = src.subarray(0, Math.floor(src.length / 12 * 0.55) * 12); + if (field === 'seed' && alt === 'mid') { // seed heads of mid blades only (rnd < midFrac) + const out = []; for (let i = 0; i < src.length; i += 12) if (src[i + 7] % 1 < midFrac2) for (let k = 0; k < 12; k++) out.push(src[i + k]); src = out; + } + const cnt = Math.min(src.length / 12, ring.cap - n); if (cnt <= 0) break; + if (src.subarray) arr.set(src.subarray(0, cnt * 12), n * 12); else arr.set(src.slice(0, cnt * 12), n * 12); + n += cnt; + } + ring.count = n; ring.geo.instanceCount = n; + ring.buf.updateRange.offset = 0; ring.buf.updateRange.count = n * 12; ring.buf.needsUpdate = true; + } + G.info = function () { + const o = { drawCalls: 0, triangles: 0, rings: {} }; + for (const r of G.rings) { const tris = r.count * r.geo.userData.tris; o.rings[r.name] = { blades: r.count, triangles: tris }; if (r.count) { o.drawCalls++; o.triangles += tris; } } + return o; + }; + G.setVisible = (v) => { G.group.visible = v; }; + // For the game's automatic quality scaling: 0.4..1 shrinks every ring (mid first, carpet last) without a reload. + G.baseR = { near: G.rNear, mid: G.rMid, carpet: G.rCarpet }; + G.setScale = function (k) { + k = E.clamp(k, 0.3, 1); G.scale = k; + G.rMid = G.baseR.mid * k; G.rNear = Math.min(G.baseR.near, G.baseR.near * (0.5 + 0.5 * k)); G.rCarpet = Math.min(G.rNear, G.baseR.carpet * (0.7 + 0.3 * k)); + for (const r of G.rings) { const u = r.mat.userData.uniforms.uRing.value; if (r.name === 'carpet') u.set(0, G.rCarpet, Math.min(3, G.rCarpet * 0.4), 0); else if (r.name === 'near' || r.name === 'seedNear') { u.x = 0; u.y = G.rNear; } else { u.x = G.rNear; u.y = G.rMid; } r.key = ''; } + }; + G.counts = () => ({ near: G.rNear, mid: G.rMid, carpet: G.rCarpet, dens: E.Q.grassDens, midDens: E.Q.grassMidDens, carpetDens: E.Q.carpetDens }); + G.dispose = function () { for (const r of G.rings) { r.geo.dispose(); r.mat.dispose(); } G.tiles.clear(); }; + (E._systems = E._systems || []).push(G); + return G; + }; +})(); diff --git a/e63334287a3deaa3/ironveil/env/ground.js b/e63334287a3deaa3/ironveil/env/ground.js new file mode 100644 index 00000000..6f06d53b --- /dev/null +++ b/e63334287a3deaa3/ironveil/env/ground.js @@ -0,0 +1,285 @@ +/* Midnight Ops environment: the ground. + IVEnv.ground(heightFn, opts) -> { group, material, meshes, heightFn } + opts: { surfaceAt(x,z) -> kind, x0, z0, x1, z1 (or size, centred on 0), step (m, default 1 / 1.5 / 2 by quality), + chunk (m, default 64) } + Kinds: grass, lawn, pasture, meadow, tussock, verge, lanemid, worn, leaves, yardedge (grass kinds, see grass.js) and + lane, mud, yard, road, gravel, cobbles, field, water, floor, none. + Five height-blended layers (turf, mud, ploughed earth, gravel, leaf litter), each sampled at two unrelated scales and + mixed by slow noise so nothing tiles; large-scale colour variation; standing water in low wet spots (ruts, puddles) + that reflects the sky and the lamps; and where there is grass, the far ground takes on the grass colour so the + field does not change where blades end. Normals come from the height function, not the triangles. */ +(function () { + 'use strict'; + const E = window.IVEnv; + // weights: [turf, mud, earth, gravel, leaves, wet] + const W = E.GROUND_KINDS = { + grass: [1, 0.15, 0, 0, 0, 0], lawn: [1, 0.06, 0, 0, 0, 0], pasture: [1, 0.1, 0, 0, 0, 0], meadow: [1, 0.1, 0, 0, 0.05, 0], tussock: [1, 0.2, 0, 0, 0.1, 0.1], verge: [1, 0.25, 0, 0, 0.1, 0.1], + lanemid: [0.6, 0.6, 0, 0.1, 0, 0.2], scorched: [0.3, 0.75, 0.25, 0, 0, 0.25], worn: [0.45, 0.7, 0, 0.1, 0, 0.2], leaves: [0.2, 0.2, 0, 0, 1, 0.1], yardedge: [0.35, 0.6, 0, 0.4, 0, 0.3], + lane: [0, 1, 0, 0.12, 0, 0.85], mud: [0, 1, 0, 0, 0, 0.9], yard: [0.06, 0.8, 0.12, 0.55, 0, 0.6], road: [0, 0.25, 0, 1, 0, 0.35], gravel: [0, 0.2, 0, 1, 0, 0.3], + cobbles: [0, 0.3, 0, 1, 0, 0.4], field: [0, 0.15, 1, 0, 0, 0.1], water: [0, 1, 0, 0.3, 0, 1.0], floor: [0, 0.4, 0, 0.6, 0, 0], none: [0, 0.6, 0, 0.4, 0, 0] + }; + const LAYERS = ['grass_ground', 'mud', 'earth', 'gravel', 'leaves']; + + // average linear luminance (0.3, 0.5, 0.2) of an sRGB DataTexture, sampled sparsely + function meanLum(t) { + const d = t && t.image && t.image.data; if (!d) return 0.045; let s = 0, n = 0; + const L = (v) => { v /= 255; return v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); }; + for (let i = 0; i < d.length; i += 4 * 97) { s += 0.3 * L(d[i]) + 0.5 * L(d[i + 1]) + 0.2 * L(d[i + 2]); n++; } + return Math.max(0.01, s / n); + } + function groundMaterial() { + const T = LAYERS.map(n => E.tex[n]); + const m = new THREE.MeshStandardMaterial({ roughness: 1, metalness: 0, normalMap: T[0].nri, envMapIntensity: 1 }); + m.userData.linear = true; + const uni = { + uMacro: E.U.uMacro, uWet: E.U.uWet, uRain: E.U.uRain, uTime: E.U.uTime, + uA0: { value: T[0].alb }, uA1: { value: T[1].alb }, uA2: { value: T[2].alb }, uA3: { value: T[3].alb }, uA4: { value: T[4].alb }, + uN0: { value: T[0].nri }, uN1: { value: T[1].nri }, uN2: { value: T[2].nri }, uN3: { value: T[3].nri }, uN4: { value: T[4].nri }, + uSz: { value: LAYERS.map((n, i) => 1 / ((E.RECIPES[n] && E.RECIPES[n].size) || [2.5, 3.0, 3.0, 0.85, 2.0][i])) }, // each layer at its real size + uMarks: { value: E.marks.tex() }, uMarksRect: { value: E.marks.rect }, + uCarry: { value: new THREE.Vector2(E.Q.grassNear * 0.45, E.Q.grassMid * 0.95) }, + uTl0: { value: meanLum(T[0].alb) } // the grass layer's own average brightness (scans differ from the generator's) + }; + m.userData.uniforms = uni; + const LOW = E.Q.name === 'low'; + m.onBeforeCompile = function (sh) { + Object.assign(sh.uniforms, uni); + sh.vertexShader = 'attribute vec4 aW0; attribute vec4 aW1; attribute vec4 aGC;\nvarying vec4 vW0; varying vec4 vW1; varying vec4 vGC; varying vec3 vGW;\n' + + sh.vertexShader.replace('#include ', '#include \n vW0 = aW0; vW1 = aW1; vGC = aGC; vGW = (modelMatrix * vec4(transformed, 1.0)).xyz;'); + sh.fragmentShader = ` + uniform sampler2D uMarks; uniform vec4 uMarksRect; + uniform sampler2D uMacro, uA0, uA1, uA2, uA3, uA4, uN0, uN1, uN2, uN3, uN4; uniform float uSz[5]; uniform float uWet, uRain, uTime, uTl0; uniform vec2 uCarry; + vec2 ivRipple(vec2 p, float t) { vec2 cell = floor(p), f = fract(p) - 0.5; float r = fract(sin(dot(cell, vec2(12.9898, 78.233))) * 43758.5453); float ph = fract(t * 1.4 + r * 7.0); + vec2 d = f - (vec2(fract(r * 13.1), fract(r * 27.7)) - 0.5) * 0.5; float dist = length(d); float ring = sin((dist - ph * 0.45) * 45.0) * smoothstep(0.06, 0.0, abs(dist - ph * 0.45)) * (1.0 - ph); return normalize(d + 1e-5) * ring; } + varying vec4 vW0; varying vec4 vW1; varying vec4 vGC; varying vec3 vGW; + void ivLay(sampler2D A, sampler2D N, float s, vec2 p, float m, out vec4 a, out vec4 n) { + vec2 uv = p * s; + a = texture2D(A, uv); n = texture2D(N, uv); + ${LOW ? '' : ` + vec2 uv2 = vec2(p.x * 0.8 - p.y * 0.6, p.x * 0.6 + p.y * 0.8) * s * 0.37 + vec2(0.31, 0.73); + vec4 a2 = texture2D(A, uv2), n2 = texture2D(N, uv2); float t = smoothstep(0.3, 0.7, m); + a = mix(a, a2, t); n = mix(n, n2, t);`} + } + ` + sh.fragmentShader + .replace('#include ', ` + vec2 gp = vGW.xz; + float mA = texture2D(uMacro, gp * 0.012).r, mB = texture2D(uMacro, gp * 0.047 + 0.4).g, mC = texture2D(uMacro, gp * 0.21).b; + vec4 a0, a1, a2, a3, a4, n0, n1, n2, n3, n4; + ivLay(uA0, uN0, uSz[0], gp, mA, a0, n0); ivLay(uA1, uN1, uSz[1], gp, mB, a1, n1); ivLay(uA2, uN2, uSz[2], gp, mA, a2, n2); + ivLay(uA3, uN3, uSz[3], gp, mB, a3, n3); ivLay(uA4, uN4, uSz[4], gp, mA, a4, n4); + // weights wander with noise so borders are ragged, then height-blend (stones and clumps poke through) + vec4 w0 = vW0; float w4 = vW1.x; + w0 += (vec4(mB, 1.0 - mB, mA, mC) - 0.5) * 0.5 * step(0.02, w0); + w4 += (mC - 0.5) * 0.4 * step(0.02, w4); + float b0 = a0.a * 0.6 + w0.x, b1 = a1.a * 0.6 + w0.y, b2 = a2.a * 0.6 + w0.z, b3 = a3.a * 0.6 + w0.w, b4 = a4.a * 0.6 + w4; + float mx = max(max(max(b0, b1), max(b2, b3)), b4) - 0.22; + b0 = max(b0 - mx, 0.0) * step(0.01, w0.x); b1 = max(b1 - mx, 0.0) * step(0.01, w0.y); b2 = max(b2 - mx, 0.0) * step(0.01, w0.z); + b3 = max(b3 - mx, 0.0) * step(0.01, w0.w); b4 = max(b4 - mx, 0.0) * step(0.01, w4); + float bs = max(1e-4, b0 + b1 + b2 + b3 + b4); + // bare soil and mud: dark, cool and less red (the scans are warm; under the moon earth is barely lighter than grass shade) + { float l1 = dot(a1.rgb, vec3(0.3, 0.55, 0.15)), l2 = dot(a2.rgb, vec3(0.3, 0.55, 0.15)); a1.rgb = mix(a1.rgb, vec3(l1) * vec3(0.98, 0.96, 0.95), 0.45) * 0.86; a2.rgb = mix(a2.rgb, vec3(l2) * vec3(0.98, 0.96, 0.94), 0.5) * 0.8; } + vec4 ga = (a0 * b0 + a1 * b1 + a2 * b2 + a3 * b3 + a4 * b4) / bs; + vec4 gn = (n0 * b0 + n1 * b1 + n2 * b2 + n3 * b3 + n4 * b4) / bs; + vec3 galb = sRGBToLinear(vec4(ga.rgb, 1.0)).rgb; + float gh = ga.a, grough = gn.b; + galb *= mix(0.72, 1.18, mA) * mix(0.9, 1.08, mC); + // far grass colour carried by the ground (blades end, colour does not) + float gd = length(vGW - cameraPosition); + float carry = vGC.a * 0.95; + float under = vGC.a * (1.0 - smoothstep(uCarry.x, uCarry.y, gd)); + float tl = dot(sRGBToLinear(vec4(a0.rgb, 1.0)).rgb, vec3(0.3, 0.5, 0.2)); + float clumpN = texture2D(uMacro, gp * 0.9 + 0.17).b; + float midN = texture2D(uMacro, gp * 0.31 + 0.61).g; + vec3 gcol = vGC.rgb * mix(0.7, 1.25, mB) * clamp(tl / uTl0, 0.35, 2.2) * mix(0.45, 1.45, clumpN * clumpN * 1.4) * mix(0.65, 1.3, midN); + // past the blades: stronger patchiness, darker hollows and long wind-combed streaks so the field is not one tint + float farK = carry * smoothstep(uCarry.x, uCarry.x * 2.0 + 6.0, gd); + float streak = texture2D(uMacro, vec2(gp.x * 0.09 + gp.y * 0.03, gp.y * 0.9 - gp.x * 0.2)).g; + gcol *= mix(1.0, mix(0.5, 1.25, smoothstep(0.2, 0.8, mA * 0.55 + midN * 0.45)) * mix(0.82, 1.12, streak), farK); + galb = mix(galb, gcol, carry); + grough = mix(grough, 0.88, carry); + // inside the blade rings the soil between blades is in the blades' shade: dark thatch and roots, never a + // bright flat colour (the blades carry the green there) + galb = mix(galb, galb * vec3(0.3, 0.28, 0.22), under * 0.9); + grough = mix(grough, 1.0, under); + // standing water: wet places, low in the texture height and the slow noise + float wet = vW1.y; + float pud = wet * smoothstep(0.5, 0.36, gh + (mB - 0.5) * 0.45 + (1.0 - wet) * 0.3); + float damp = clamp(wet * 0.8 + uWet * 0.6, 0.0, 1.0); + galb *= 1.0 - damp * 0.3; + grough = mix(grough, grough * 0.55, damp); + galb = mix(galb, galb * 0.32, pud); + grough = mix(grough, 0.04, pud); + float ivPud = pud; + { vec2 mu = (vGW.xz - uMarksRect.xy) / uMarksRect.zw; if (mu.x > 0.0 && mu.y > 0.0 && mu.x < 1.0 && mu.y < 1.0) { vec4 mk = texture2D(uMarks, mu); + galb *= 1.0 - mk.r * 0.38; galb = mix(galb, vec3(0.06, 0.045, 0.03), mk.b * 0.55); grough = mix(grough, 0.25, mk.g); } } // stamped marks: prints in mud, tracked mud, wet ruts + diffuseColor.rgb *= galb;`) + .replace('#include ', 'float roughnessFactor = clamp(grough, 0.03, 1.0);') + .replace('#include ', ` + vec3 mapN = vec3(gn.xy * 2.0 - 1.0, 0.0); + mapN.xy *= (1.0 - ivPud * 0.97) * (1.0 - vGC.a * 0.2) * (1.0 - 0.45 * b3 / bs); + { float fk = vGC.a * smoothstep(uCarry.x, uCarry.x * 2.0 + 6.0, length(vGW - cameraPosition)); float sn = texture2D(uMacro, vec2(vGW.x * 0.35 + vGW.z * 0.1, vGW.z * 1.6 - vGW.x * 0.35)).b - 0.5; mapN.x += sn * 0.6 * fk; mapN.y += (texture2D(uMacro, vGW.xz * 0.6 + 0.3).r - 0.5) * 0.3 * fk; } + mapN.z = sqrt(max(0.05, 1.0 - dot(mapN.xy, mapN.xy))); + normal = perturbNormal2Arb(-vViewPosition, normal, normalize(mapN), faceDirection); + if (uRain > 0.0 && ivPud > 0.01) { vec2 rp = ivRipple(vGW.xz * 3.0, uTime) + ivRipple(vGW.xz * 5.3 + 7.0, uTime * 1.13) * 0.7; normal = normalize(normal + (viewMatrix * vec4(rp.x, 0.0, rp.y, 0.0)).xyz * 0.35 * ivPud * uRain); }`) + .replace('#include ', ` + float gao = 0.45 + 0.55 * smoothstep(0.05, 0.6, gh); + reflectedLight.indirectDiffuse *= gao; reflectedLight.indirectSpecular *= mix(gao, 1.0, ivPud);`); + }; + m.customProgramCacheKey = () => 'ivground' + (LOW ? 'L' : ''); + return m; + } + + // For the game's footsteps and splashes: how wet / muddy the ground is here, 0..1, and its kind. + E.wetnessAt = function (x, z) { const g = E._ground; if (!g) return E.U.uWet.value; const w = W[g.surfaceAt(x, z)] || W.none; return Math.min(1, w[5] + E.U.uWet.value * 0.5); }; + // the ground kind for footsteps, slowdown and cover: the map's kinds, plus 'puddle' where water stands and 'leaves' + // under trees (litter). Mud depth, wetness and puddle amount: IVEnv.groundInfo(x, z). + E.surfaceAt = function (x, z) { const g = E._ground; if (!g) return 'grass'; const i = E.groundInfo(x, z); if (i.puddle > 0.5) return 'puddle'; if (E.GRASS_KINDS[i.kind] && E._treeNear && E._treeNear(x, z, 3.2)) return 'leaves'; return i.kind; }; + E.ground = function (heightFn, opts) { + opts = opts || {}; + const surfaceAt = opts.surfaceAt || (() => 'grass'); + const step = opts.step || (E.Q.name === 'low' ? 3.5 : E.Q.name === 'medium' ? 2.5 : 2); + const half = (opts.size || 200) / 2; + const x0 = opts.x0 != null ? opts.x0 : -half, z0 = opts.z0 != null ? opts.z0 : -half, x1 = opts.x1 != null ? opts.x1 : half, z1 = opts.z1 != null ? opts.z1 : half; + const CH = opts.chunk || (E.Q.name === 'high' ? 64 : E.Q.name === 'medium' ? 96 : 128); + const mat = groundMaterial(); + const group = new THREE.Group(); group.name = 'IVEnv.ground'; + const meshes = [], c = new THREE.Color(), cs = new THREE.Color(); + const e = 0.5; + const weights = (x, z, out) => { // averaged over a small footprint so borders are soft + for (let k = 0; k < 6; k++) out[k] = 0; + const o = step * 0.45, pts = [[0, 0], [o, 0], [-o, 0], [0, o], [0, -o]]; + for (const p of pts) { const w = W[surfaceAt(x + p[0], z + p[1])] || W.none; for (let k = 0; k < 6; k++) out[k] += w[k] / pts.length; } + return out; + }; + const wv = [0, 0, 0, 0, 0, 0]; + const chunk = (cx, cz, step) => { + const ex = Math.min(cx + CH, x1), ez = Math.min(cz + CH, z1); + const nx = Math.round((ex - cx) / step) + 1, nz = Math.round((ez - cz) / step) + 1; + const N = nx * nz, pos = new Float32Array(N * 3), nor = new Float32Array(N * 3), uv = new Float32Array(N * 2), w0 = new Float32Array(N * 4), w1 = new Float32Array(N * 4), gc = new Float32Array(N * 4); + for (let j = 0; j < nz; j++) for (let i = 0; i < nx; i++) { + const k = j * nx + i, x = cx + (ex - cx) * i / (nx - 1), z = cz + (ez - cz) * j / (nz - 1), y = heightFn(x, z); + pos[k * 3] = x; pos[k * 3 + 1] = y; pos[k * 3 + 2] = z; uv[k * 2] = x; uv[k * 2 + 1] = z; + const gx = heightFn(x - e, z) - heightFn(x + e, z), gz = heightFn(x, z - e) - heightFn(x, z + e), l = Math.hypot(gx, 2 * e, gz); + nor[k * 3] = gx / l; nor[k * 3 + 1] = 2 * e / l; nor[k * 3 + 2] = gz / l; + weights(x, z, wv); + w0[k * 4] = wv[0]; w0[k * 4 + 1] = wv[1]; w0[k * 4 + 2] = wv[2]; w0[k * 4 + 3] = wv[3]; w1[k * 4] = wv[4]; w1[k * 4 + 1] = wv[5]; + // grass colour carried far away, weighted by how much grass grows here + const kind = surfaceAt(x, z), K = E.GRASS_KINDS[kind]; + if (K) { E.grassField.carry(kind, x, z, c); const dens = K.d * E.sstep(0.18, 0.45, E.grassField.dens(x, z) + 0.12 + (K.fill || 0)); gc[k * 4] = c.r; gc[k * 4 + 1] = c.g; gc[k * 4 + 2] = c.b; gc[k * 4 + 3] = E.clamp(dens * 1.7 * Math.min(1, 0.45 + K.h[1] * 3), 0, 1); } + } + const idx = new Uint32Array((nx - 1) * (nz - 1) * 6); let q = 0; + for (let j = 0; j < nz - 1; j++) for (let i = 0; i < nx - 1; i++) { + const a = j * nx + i, b = a + 1, cc = a + nx, d = cc + 1; + // split each quad along the diagonal that follows the surface better + const ya = pos[a * 3 + 1], yb = pos[b * 3 + 1], yc = pos[cc * 3 + 1], yd = pos[d * 3 + 1]; + if (Math.abs(ya - yd) < Math.abs(yb - yc)) { idx[q++] = a; idx[q++] = cc; idx[q++] = d; idx[q++] = a; idx[q++] = d; idx[q++] = b; } + else { idx[q++] = a; idx[q++] = cc; idx[q++] = b; idx[q++] = b; idx[q++] = cc; idx[q++] = d; } + } + const g = new THREE.BufferGeometry(); + g.setAttribute('position', new THREE.BufferAttribute(pos, 3)); g.setAttribute('normal', new THREE.BufferAttribute(nor, 3)); g.setAttribute('uv', new THREE.BufferAttribute(uv, 2)); + g.setAttribute('aW0', new THREE.BufferAttribute(w0, 4)); g.setAttribute('aW1', new THREE.BufferAttribute(w1, 4)); g.setAttribute('aGC', new THREE.BufferAttribute(gc, 4)); + g.setIndex(new THREE.BufferAttribute(idx, 1)); g.computeBoundingSphere(); g.computeBoundingBox(); + return g; + }; + // two levels per chunk: the full mesh near the camera, a 2.5x coarser one beyond (swapped in IVEnv.update) + const lods = []; + for (let cz = z0; cz < z1 - 1e-6; cz += CH) for (let cx = x0; cx < x1 - 1e-6; cx += CH) { + const fine = new THREE.Mesh(chunk(cx, cz, step), mat), coarse = new THREE.Mesh(chunk(cx, cz, step * 2.5), mat); + for (const m of [fine, coarse]) { m.receiveShadow = true; m.name = 'ground'; group.add(m); meshes.push(m); } + coarse.visible = false; lods.push({ fine, coarse, x: Math.min(cx + CH / 2, (cx + x1) / 2), z: Math.min(cz + CH / 2, (cz + z1) / 2) }); + } + const near = opts.lodNear || 70; + (E._updaters = E._updaters || []).push((dt, cam) => { for (const L of lods) { const d = Math.hypot(L.x - cam.position.x, L.z - cam.position.z) - CH * 0.71; const f = d < near; L.fine.visible = f; L.coarse.visible = !f; } }); + + E._ground = { surfaceAt }; + return { group, material: mat, meshes, heightFn, surfaceAt }; + }; + + // ------------------------------------------------------------------ ground marks (for the game's code) + // IVEnv.marks.area(x0, z0, size, res) one persistent top-down mark texture over the play area (default the map) + // IVEnv.marks.stamp(x, z, kind, rot, strength) kind 'boot' (a print pressed into mud), 'track' (brown mud carried + // onto hard ground, fades), 'rut' (a wet wheel rut segment, rot = direction); strength 0..1 + // IVEnv.marks.fade(dt) 'track' marks fade over about two minutes (call each frame or now and then) + // channels: R = pressed depth (darkens), G = wetness (glossy), B = tracked mud (brown) + E.marks = (function () { + let S = 512, data = null, tex = null; const rect = new THREE.Vector4(-190, -190, 380, 380); let dirty = false; + const M = { rect, tex() { if (!tex) M.area(rect.x, rect.y, rect.z, S); return tex; }, + area(x0, z0, size, res) { S = res || S; rect.set(x0, z0, size, size); data = new Uint8Array(S * S * 4); if (!tex) { tex = new THREE.DataTexture(data, S, S, THREE.RGBAFormat); tex.magFilter = tex.minFilter = THREE.LinearFilter; } else { tex.image = { data, width: S, height: S }; } tex.needsUpdate = true; return M; }, + stamp(x, z, kind, rot, k) { if (!data) M.area(rect.x, rect.y, rect.z, S); k = k == null ? 1 : k; const px = (x - rect.x) / rect.z * S, pz = (z - rect.y) / rect.w * S, m = S / rect.z, c = Math.cos(rot || 0), s = Math.sin(rot || 0); + const L = kind === 'rut' ? 1.2 : 0.28, Wd = kind === 'rut' ? 0.14 : 0.11, ch = kind === 'boot' ? 0 : kind === 'rut' ? 1 : 2, r = Math.ceil(Math.max(L, Wd) * m) + 1; + for (let j = -r; j <= r; j++) for (let i = -r; i <= r; i++) { const X = Math.round(px + i), Z = Math.round(pz + j); if (X < 0 || Z < 0 || X >= S || Z >= S) continue; const u = (i * c + j * s) / m, v = (-i * s + j * c) / m; const e = (u / L) ** 2 + (v / Wd) ** 2; if (e > 1) continue; const q = (Z * S + X) * 4 + ch, val = Math.round(255 * k * (1 - e * 0.6)); data[q] = Math.max(data[q], val); if (kind === 'rut') data[(Z * S + X) * 4] = Math.max(data[(Z * S + X) * 4], val >> 1); } + dirty = true; }, + fade(dt) { if (!data) return; const f = Math.max(1, Math.round(dt * 2)); for (let i = 2; i < data.length; i += 4) if (data[i]) data[i] = Math.max(0, data[i] - f); dirty = true; }, + update() { if (dirty && tex) { tex.needsUpdate = true; dirty = false; } } + }; + (E._updaters = E._updaters || []).push(() => M.update()); + return M; + })(); + // IVEnv.groundInfo(x, z) -> { kind, mud 0..1 (how deep the mud is), wet 0..1, puddle 0..1 } + E.groundInfo = function (x, z) { const g = E._ground; const kind = g ? g.surfaceAt(x, z) : 'grass', w = W[kind] || W.none; const wet = Math.min(1, w[5] + E.U.uWet.value * 0.5); const n = E.fbm2(x / 3.1, z / 3.1, 909, 2); return { kind, mud: Math.min(1, w[1]), wet, puddle: Math.max(0, (wet - 0.55) * 2.2 * (n - 0.45) * 3) }; }; + + // ------------------------------------------------------------------ the land beyond the map + // IVEnv.skirt(heightFn, { half, outer, hills, woods, seed, day, fogK, landFogK }) -> group + // fogK / landFogK (0..1) thin the scene's fog on the woods / the land beyond ~120 m (1 = same fog as the map) + // A cheap ring of land from the square edge of the playable ground (+-half) out to `outer` metres, rising into + // rolling hills (`hills` metres), with a ring of dark wood masses on it. One mesh for the land, one for the woods, + // no textures, always drawn (not subject to the tree draw range), so from any height the land never stops in a + // straight line: it rolls away into hills and woods and then into fog. + E.skirt = function (heightFn, opts) { + opts = Object.assign({ half: 190, outer: 1400, hills: 30, woods: 1, seed: 5, day: false, fogK: 0.8, landFogK: 1 }, opts || {}); + // the far land sits in thinner fog than the scene's (fogK scales the exp2 density) so its woods and hills keep a + // silhouette against the sky instead of fading to the fog colour + const thinFog = (m, k) => { + if (k >= 0.999) return m; + const k2 = (k * k).toFixed(4); + m.onBeforeCompile = (sh) => { + const ch = THREE.ShaderChunk.fog_fragment.split('fd * fd').join('fd * fd * mix(1.0, ' + k2 + ', smoothstep(120.0, 520.0, fogDepth))').split('fogDensity * fogDensity').join('fogDensity * fogDensity * mix(1.0, ' + k2 + ', smoothstep(120.0, 520.0, fogDepth))'); // IVEnv's fog chunk names the density fd + sh.fragmentShader = sh.fragmentShader.replace('#include ', ch); + }; + m.customProgramCacheKey = () => 'ivskirt' + k2; return m; + }; + const group = new THREE.Group(); group.name = 'IVEnv.skirt'; + const LOWQ = E.Q && E.Q.name === 'low', A = LOWQ ? 64 : 160, NR = LOWQ ? 10 : 22, half = opts.half, P = [], C = [], I = [], col = new THREE.Color(); + const base = opts.day ? [0.055, 0.07, 0.035] : [0.035, 0.042, 0.03]; + const hill = (x, z, t) => opts.hills * t * (0.55 * E.fbm2(x / 420 + 3, z / 420, opts.seed, 4) + 0.45 * E.fbm2(x / 140, z / 140 + 9, opts.seed + 3, 3)) + t * t * opts.hills * 0.25; + const ring = []; + for (let j = 0; j <= NR; j++) { + const t = j / NR, tt = Math.pow(t, 1.8); + for (let i = 0; i < A; i++) { + const a = i / A * Math.PI * 2, ca = Math.cos(a), sa = Math.sin(a), k = 1 / Math.max(Math.abs(ca), Math.abs(sa)); + const ri = half * k - 0.5, r = ri + (opts.outer - ri) * tt, x = ca * r, z = sa * r; + const y0 = heightFn(E.clamp(x, -half, half), E.clamp(z, -half, half)); + const blend = E.sstep(0, 0.08, tt), y = y0 * (1 - blend) + (y0 * 0.3 + hill(x, z, Math.min(1, tt * 3))) * blend - 0.06 - tt * 2; + ring.push([x, y, z]); P.push(x, y, z); + const v = E.fbm2(x / 90, z / 90, opts.seed + 7, 2); + col.setRGB(base[0] * (0.75 + 0.5 * v), base[1] * (0.75 + 0.5 * v), base[2] * (0.8 + 0.4 * v)); C.push(col.r, col.g, col.b); + } + } + for (let j = 0; j < NR; j++) for (let i = 0; i < A; i++) { const a = j * A + i, b = j * A + (i + 1) % A, c = a + A, d = b + A; I.push(a, b, c, b, d, c); } // wound to face up + const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.Float32BufferAttribute(P, 3)); g.setAttribute('color', new THREE.Float32BufferAttribute(C, 3)); g.setIndex(I); g.computeVertexNormals(); + const land = new THREE.Mesh(g, thinFog(new THREE.MeshLambertMaterial({ vertexColors: true }), opts.landFogK)); land.name = 'skirt-land'; land.receiveShadow = false; land.frustumCulled = false; group.add(land); + const sample = (x, z) => { const r = Math.hypot(x, z), a = Math.atan2(z, x), ca = Math.cos(a), sa = Math.sin(a), ri = half / Math.max(Math.abs(ca), Math.abs(sa)); const tt = E.clamp((r - ri) / (opts.outer - ri), 0, 1); const blend = E.sstep(0, 0.08, tt), y0 = heightFn(E.clamp(x, -half, half), E.clamp(z, -half, half)); return y0 * (1 - blend) + (y0 * 0.3 + hill(x, z, Math.min(1, tt * 3))) * blend - 0.06 - tt * 2; }; + E.skirtHeightAt = sample; // the far land's height, for far villages and woods placed by a mission + if (opts.woods && !LOWQ) { // Low: no wood masses (fog hides most of them; saves a draw call and ~10k triangles) + // wood masses: clusters of squashed low-poly blobs on the hills, thicker in a band just outside the map + const R = E.rng(opts.seed + 11), WP = [], WC = [], WI = [], blob = new THREE.IcosahedronGeometry(1, 0), bp = blob.attributes.position, m = new THREE.Matrix4(), v = new THREE.Vector3(); + const bi = blob.index ? blob.index.array : null, wcol = opts.day ? [0.045, 0.06, 0.04] : [0.0035, 0.0045, 0.004]; + const n = Math.round(150 * opts.woods * (LOWQ ? 0.45 : 1)); + for (let k = 0; k < n; k++) { + const a = R() * Math.PI * 2, ca = Math.cos(a), sa = Math.sin(a), ri = half / Math.max(Math.abs(ca), Math.abs(sa)), r = ri + 15 + Math.pow(R(), 1.8) * 300; + if (E.fbm2(ca * 6, sa * 6, opts.seed + 21, 2) < 0.38 && r > ri + 60) continue; // open gaps between the woods + const cx = ca * r, cz = sa * r; + for (let q = 0; q < 6; q++) { + const x = cx + R.range(-16, 16), z = cz + R.range(-16, 16), w = R.range(4, 7), h = R.range(6, 11), y = sample(x, z); + m.compose(v.set(x, y + h * 0.75, z), new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), R() * 6.28), new THREE.Vector3(w, h, w * R.range(0.8, 1.2))); + const b0 = WP.length / 3, sh = R.range(0.8, 1.2); + for (let i = 0; i < bp.count; i++) { v.fromBufferAttribute(bp, i); const top = v.y; v.applyMatrix4(m); WP.push(v.x, v.y, v.z); const s2 = sh * (0.55 + 0.6 * Math.max(0, top)); WC.push(wcol[0] * s2, wcol[1] * s2, wcol[2] * s2); } + if (bi) for (let i = 0; i < bi.length; i++) WI.push(b0 + bi[i]); else for (let i = 0; i < bp.count; i++) WI.push(b0 + i); + } + } + const wg = new THREE.BufferGeometry(); wg.setAttribute('position', new THREE.Float32BufferAttribute(WP, 3)); wg.setAttribute('color', new THREE.Float32BufferAttribute(WC, 3)); wg.setIndex(WI); wg.computeVertexNormals(); + const woods = new THREE.Mesh(wg, thinFog(new THREE.MeshBasicMaterial({ vertexColors: true }), opts.fogK)); // unlit: a dark mass against the sky at any light level woods.name = 'skirt-woods'; woods.frustumCulled = false; group.add(woods); + } + return group; + }; +})(); diff --git a/e63334287a3deaa3/ironveil/env/index.js b/e63334287a3deaa3/ironveil/env/index.js new file mode 100644 index 00000000..c0592a84 --- /dev/null +++ b/e63334287a3deaa3/ironveil/env/index.js @@ -0,0 +1,100 @@ +/* Midnight Ops environment kit: window.IVEnv. Everything the player looks at that is not a person. + Units: metres, Y up. three.js r128 global build. No modules, no build step, no downloads: every texture is made in + code at load time (env/texgen.js, in Web Workers when the page is served over http). + + Load order (plain script tags, after three.min.js): + env/texgen.js env/core.js env/atmosphere.js env/grass.js env/ground.js env/builder.js env/build.js env/nature.js + env/props.js env/decals.js env/post.js env/index.js + Typical frame: IVEnv.update(dt, camera); post ? post.render(dt) : renderer.render(scene, camera); + + ---------------------------------------------------------------- setup + IVEnv.init(renderer, quality) quality 'low' | 'medium' | 'high'. Call once, before load. + IVEnv.load(onProgress) -> Promise makes every texture; onProgress(fraction 0..1, lastName). IVEnv.genMs after. + IVEnv.update(dt, camera) every frame: time, wind, grass rings, tree LOD swaps, atmosphere, decals. + IVEnv.info { drawCalls, triangles, textureMB, genMs, grass:{...} } (refreshed by update + when a renderer was given to init; renderer.info.autoReset must stay true). + + ---------------------------------------------------------------- materials + IVEnv.mat(name) -> shared MeshStandardMaterial with albedo, normal, roughness and AO (cavity from height). + names: brick_red, brick_sooty, fieldstone, ashlar, plaster, plaster_interior, planks, floorboards, wood_painted, + timber, roof_tile, slate, cobbles, mud, grass_ground, earth, gravel, leaves, bark_oak, bark_pine, concrete, + metal_painted, metal_rust, sandbag, canvas, glass, straw (friendly aliases such as 'red brick' also work). + IVEnv.mat('glass', 'lit') is the warm lit-window variant. + Geometry for these materials must have UVs in METRES (IVEnv.uvMetres(geometry) box-projects any geometry). + Optional vertex attribute aEnv (vec4): rgb tint (0 = none), w = 1 + height above ground for damp/moss at the + foot of walls (IVEnv.setEnvAttr(geometry, tint, groundY) fills it). + All IVEnv materials carry userData.linear = true (the game's linearize() must skip them). + + ---------------------------------------------------------------- ground and grass + IVEnv.ground(heightFn, { surfaceAt, x0, z0, x1, z1 | size, step, chunk }) -> { group, material, meshes } + surfaceAt(x, z) -> 'grass' | 'pasture' | 'meadow' | 'tussock' | 'verge' | 'lanemid' | 'worn' | 'leaves' | + 'yardedge' | 'lane' | 'mud' | 'yard' | 'road' | 'gravel' | 'cobbles' | 'field' | 'water' | 'floor' | 'none' + IVEnv.grass(surfaceAt, heightFn, { longAt(x,z)->0..1, densityAt(x,z)->0..1, near, mid }) -> { group, info() } + follows the camera by itself inside IVEnv.update. Add .group to the scene. + IVEnv.setPushers([{ x, z, r, s }]) up to 8 things that flatten grass (r metres, s strength 0..1). + IVEnv.setWind(dirX, dirZ, strength) one wind for grass, crops, hedges and trees. + + ---------------------------------------------------------------- atmosphere and post + IVEnv.atmosphere(scene, renderer, preset, { mistBase, shadows, shadowRadius, fogMul }) -> { sun, hemi, update, + set(preset), setBrightness(k) } presets: night_moon, night_overcast, dawn_mist, dusk_rain, day_overcast. + Sets sky, stars, moon, cloud, fog + ground mist, lights, environment map, exposure, wetness and rain. + IVEnv.post(renderer, scene, camera, quality) -> { render(dt), setSize(w, h) } or null on low. + + grass.setScale(0.3..1) shrinks every ring without a reload (for autores.js: lower grass range first when the + frame time is bad); grass.counts() gives the current radii and densities; grass.info() draw calls / triangles. + IVEnv.setPushers([{ x, z, r, s }]) up to 8 things that flatten grass (r metres, s strength 0..1). + + ---------------------------------------------------------------- buildings, walls, fences (env/build.js) + IVEnv.building({ kind, w, d, floors, seed, damage 0..1, lit 0..1, roof 'tile'|'slate', units (shoprow) }) + -> { group, colliders, doors, windows, lights, height } + kinds: farmhouse, barn, shed, cottage, church (with tower), shoprow, ruin, bunker (= pillbox). Farmhouse and barn + have interiors. Local space: origin on the ground at the footprint centre, front door faces +Z. + colliders: [{ x, z, hx, hz, y0, y1, rot, surf, kind }] (local, rot about Y) ready for the game's W.addBox. + doors: [{ pivot, width, open(angle) }] windows: [{ x, y, z, nx, nz, w, h, lit }] + lights: [{ x, y, z, color, r, power, interior? }] for the game's pooled point lights (power 0 = unlit). + IVEnv.wall(points [[x,z]...], { type 'stone'|'brick', h, t, gaps [[from,to]], brokenStart, brokenEnd, seed, heightFn }) + IVEnv.fence(points, 'rail'|'picket'|'barbed'|'hurdle', { heightFn, seed, damage }) -> { group, colliders } + IVEnv.mergeStatic(root, { cell: 48 }) -> Group: one mesh per material per 48 m cell for everything static under + root (skips objects with userData.dynamic, e.g. door pivots). Call after placing buildings, walls, props, hedges. + Small detail pieces (arch voussoirs, quoins, ridge tiles, loose bricks, glazing bars, furniture, decals, ivy) are + kept in separate meshes (32 m cells) that IVEnv.update hides beyond IVEnv.Q.detailDist (Low 18 m, Medium 25 m, + High 35 m); on Low the purely decorative ones are not built at and a plain ridge / lintel stands in. + IVEnv.wetnessAt(x, z) -> 0..1 and IVEnv.surfaceAt(x, z) -> kind: for footstep sounds and splash effects. + + ---------------------------------------------------------------- nature (env/nature.js) + IVEnv.tree(kind, seed) -> Group kinds: oak, ash, poplar, apple, pine, dead, sapling + IVEnv.trees([{ kind, x, y, z, rot, scale, seed }]) -> { group, colliders, info() } instanced, LOD swaps every 0.25 s + (full mesh, reduced mesh, crossed-quad impostor baked once at load). Needs IVEnv.init(renderer) first. + IVEnv.hedge(points, { h, w, gaps, seed, heightFn }) -> { group, colliders } (colliders: kind 'hedge', sight only) + IVEnv.scatter(kind, areaTest(x,z)->0..1, { heightFn, density, radius, bounds [x0,z0,x1,z1], seed }) + plants that stream round the camera: wheat, reeds, ferns, brambles, nettles, dock, flowers + objects placed once over bounds: rocks, logs, stumps, litter, puddles (-> { group, colliders }) + IVEnv.stream(points, { width, heightFn, waterY(x,z) | level, flow }) -> { group } + IVEnv.puddleMesh([[x, y, z, rx, rz, rot]...]) -> Mesh standing water that reflects lamps and sky. + + ---------------------------------------------------------------- props and decals + IVEnv.prop(kind, seed, opts) -> { group, colliders, lights, door? } kinds: crate, crates, barrel, barrels, drums, + sandbags ({ length, rows }), cart, haybale, haystack, well, trough, telegraph (group.userData.wireTop), lamppost + (lights[0]), gate ({ width, open }), ladder, ammo, truck (no markings), logpile, tarp, bottles. + IVEnv.wireMesh([[x0,y0,z0,x1,y1,z1]...], radius, sag) -> Group wires between telegraph poles, barbed wire. + IVEnv.decal(type, position, normal, size, seed) -> index pooled runtime decals, one draw call. + types: scratches, gouges, chipped, pocks, scorch, soot, damp, moss, rust, mud, crack, bullethole, leaves, + waterstain, chalk, grime. IVEnv.impact(surface, position, normal) picks one per material for a bullet hit. + IVEnv.clearDecals() on level change. +*/ +(function () { + 'use strict'; + const E = window.IVEnv; + E.info = { drawCalls: 0, triangles: 0, textureMB: 0, genMs: 0 }; + E.update = function (dt, camera) { + E.U.uTime.value += dt; + if (E._systems) for (const s of E._systems) if (s.update && s.group.visible !== false) s.update(camera); + if (E._updaters) for (const f of E._updaters) f(dt, camera); + if (E.atmo) E.atmo.update(dt, camera); + const r = E.renderer; + if (E.sceneInfo) { E.info.drawCalls = E.sceneInfo.calls; E.info.triangles = E.sceneInfo.triangles; } + else if (r) { E.info.drawCalls = r.info.render.calls; E.info.triangles = r.info.render.triangles; } + E.info.textureMB = +(E.texMemory() / 1048576).toFixed(1); + E.info.genMs = Math.round(E.genMs || 0); + }; +})(); diff --git a/e63334287a3deaa3/ironveil/env/nature.js b/e63334287a3deaa3/ironveil/env/nature.js new file mode 100644 index 00000000..e5544e35 --- /dev/null +++ b/e63334287a3deaa3/ironveil/env/nature.js @@ -0,0 +1,659 @@ +/* Midnight Ops environment: trees, hedgerows, scattered plants and objects, and the stream. + IVEnv.tree(kind, seed) -> Group (one tree, LOD0; for a hero tree or a single prop) + IVEnv.trees(list) -> { group, update(camera), info() } list: [{ kind, x, y, z, rot, scale, seed }] + kinds: oak, ash, poplar, apple, pine, dead, sapling. Two variants per kind, instanced per kind + variant + LOD + (full mesh near, a reduced mesh in the middle distance, crossed-quad impostors far). LODs swap in IVEnv.update. + IVEnv.hedge(points, { h, w, gaps: [[from, to]], seed, heightFn }) -> { group, colliders } + IVEnv.scatter(kind, areaTest, { heightFn, density, radius, seed }) -> { group, update(camera), info() } + kinds: wheat, maize (standing crop 2.3 m), reeds, ferns, brambles, nettles, dock, flowers, rocks, logs, stumps, litter, puddles. + areaTest(x, z) -> 0..1 (density multiplier). Plants stream around the camera in tiles like the grass; + rocks, logs, stumps, litter and puddles are placed once over opts.bounds [x0, z0, x1, z1]. + IVEnv.stream(points, { width, heightFn, waterY(x, z) | level, flow }) -> { group } + All foliage shares the wind (IVEnv.setWind) with the grass. Leaves are alpha-tested cards (alpha-to-coverage with + MSAA) with coverage-preserving mipmaps, canopy normals, darker interiors and translucency. */ +(function () { + 'use strict'; + const E = window.IVEnv; + const TAU = Math.PI * 2; + const V3 = THREE.Vector3; + + // ------------------------------------------------------------------ leaf atlas (made once, in code) + // 4 x 2 cells of 256 px: 0 oak, 1 ash/apple leaflets, 2 poplar, 3 maize (was pine needles; pines are not used), 4 hawthorn (hedge), 5 fern frond, + // 6 bramble / nettle / dock (big serrated), 7 reed / wheat blades. + let atlas = null; + function leafShape(g, x, y, len, wid, ang, lobed, serr) { + g.save(); g.translate(x, y); g.rotate(ang); g.beginPath(); g.moveTo(0, 0); + const n = 14; + for (let i = 0; i <= n; i++) { const t = i / n, w = Math.sin(Math.PI * Math.pow(t, 0.85)) * wid * (lobed ? 1 + 0.35 * Math.sin(t * 22) : 1) * (serr ? 1 + 0.12 * ((i % 2) ? 1 : -1) : 1); g.lineTo(t * len, -w); } + for (let i = n; i >= 0; i--) { const t = i / n, w = Math.sin(Math.PI * Math.pow(t, 0.85)) * wid * (lobed ? 1 + 0.35 * Math.sin(t * 22 + 1) : 1) * (serr ? 1 + 0.12 * ((i % 2) ? -1 : 1) : 1); g.lineTo(t * len, w); } + g.closePath(); g.fill(); g.restore(); + } + function makeAtlas() { + if (atlas) return atlas; + const W = 1024, H = 512, C = 256, c = document.createElement('canvas'); c.width = W; c.height = H; + const g = c.getContext('2d'), R = E.rng(31); + const col = (h, s, l) => `hsl(${h},${s}%,${l}%)`; + const cell = (i, fn) => { g.save(); g.translate((i % 4) * C, Math.floor(i / 4) * C); g.beginPath(); g.rect(0, 0, C, C); g.clip(); fn(); g.restore(); }; + const twig = (x0, y0, x1, y1, w) => { g.strokeStyle = '#3b3226'; g.lineWidth = w; g.beginPath(); g.moveTo(x0, y0); g.quadraticCurveTo((x0 + x1) / 2 + R.range(-10, 10), (y0 + y1) / 2, x1, y1); g.stroke(); }; + // 0 oak: lobed leaves round a twig + cell(0, () => { twig(128, 250, 128, 40, 4); for (let i = 0; i < 46; i++) { const a = R() * TAU, r = 20 + R() * 95; g.fillStyle = col(78 + R() * 22, 30 + R() * 18, 16 + R() * 14); leafShape(g, 128 + Math.cos(a) * r * 0.7, 140 + Math.sin(a) * r * 0.9, R.range(34, 52), R.range(9, 14), a + R.range(-0.6, 0.6), true, false); } }); + // 1 ash / apple: pinnate leaflets + cell(1, () => { for (let k = 0; k < 6; k++) { const ax = 128 + R.range(-70, 70), ay = 128 + R.range(-70, 70), a = R() * TAU; twig(ax, ay, ax + Math.cos(a) * 90, ay + Math.sin(a) * 90, 2); for (let i = 0; i < 9; i++) { const t = i / 9; g.fillStyle = col(82 + R() * 18, 30 + R() * 20, 18 + R() * 14); for (const s of [-1, 1]) leafShape(g, ax + Math.cos(a) * 90 * t, ay + Math.sin(a) * 90 * t, R.range(18, 26), R.range(5, 7), a + s * 1.0, false, true); } } }); + // 2 poplar: small rounded leaves, dense + cell(2, () => { twig(128, 255, 128, 10, 3); for (let i = 0; i < 90; i++) { const y = R.range(15, 245), x = 128 + R.range(-1, 1) * 70 * Math.sin(Math.PI * y / 255); g.fillStyle = col(75 + R() * 25, 28 + R() * 20, 17 + R() * 15); leafShape(g, x, y, R.range(16, 24), R.range(7, 10), R() * TAU, false, false); } }); + // 3 maize (late summer): three stalks, broad arching leaves yellowing at the tips, a tassel, a cob or two + cell(3, () => { for (let k = 0; k < 3; k++) { const x = 60 + k * 68 + R.range(-12, 12), lean = R.range(-10, 10); + g.strokeStyle = col(58 + R() * 8, 30 + R() * 12, 34 + R() * 8); g.lineWidth = 5; g.beginPath(); g.moveTo(x, 256); g.quadraticCurveTo(x + lean * 0.5, 130, x + lean, 22); g.stroke(); + for (let i = 0; i < 9; i++) { const t = 0.12 + i * 0.09, y = 256 - t * 234, s2 = i % 2 ? 1 : -1, len = R.range(70, 105) * (1 - t * 0.35), a = s2 > 0 ? R.range(-0.6, -0.2) : Math.PI + R.range(0.2, 0.6); + g.fillStyle = col(62 + R() * 18 - t * 20, 30 + R() * 14, 22 + R() * 12 + t * 10); g.save(); g.translate(x + lean * t, y); g.rotate(a); g.beginPath(); g.moveTo(0, 0); + for (let q = 0; q <= 10; q++) { const u = q / 10; g.lineTo(u * len, -Math.sin(Math.PI * Math.min(1, u * 1.15)) * 9 + u * u * 26); } for (let q = 10; q >= 0; q--) { const u = q / 10; g.lineTo(u * len, Math.sin(Math.PI * Math.min(1, u * 1.15)) * 5 + u * u * 26); } g.fill(); g.restore(); } + g.strokeStyle = col(44, 40, 56); g.lineWidth = 1.5; for (let q = 0; q < 7; q++) { g.beginPath(); g.moveTo(x + lean, 24); g.lineTo(x + lean + R.range(-16, 16), R.range(2, 12)); g.stroke(); } + if (R() < 0.8) { g.fillStyle = col(48, 30, 52); g.save(); g.translate(x + lean * 0.5 + 7, 140 + R.range(-15, 15)); g.rotate(0.35); g.beginPath(); g.ellipse(0, 0, 6, 20, 0, 0, 6.29); g.fill(); g.restore(); } } }); + // 4 hawthorn / hedge: small lobed leaves, thorny twigs, very dense + cell(4, () => { for (let k = 0; k < 9; k++) twig(R() * 256, R() * 256, R() * 256, R() * 256, 2); for (let i = 0; i < 140; i++) { const a = R() * TAU, r = Math.sqrt(R()) * 120; g.fillStyle = col(72 + R() * 30, 24 + R() * 20, 13 + R() * 15); leafShape(g, 128 + Math.cos(a) * r, 128 + Math.sin(a) * r, R.range(14, 22), R.range(6, 9), R() * TAU, true, false); } }); + // 5 fern frond + cell(5, () => { g.strokeStyle = '#3c4a26'; g.lineWidth = 3; g.beginPath(); g.moveTo(128, 252); g.quadraticCurveTo(140, 128, 120, 8); g.stroke(); for (let i = 0; i < 30; i++) { const t = i / 30, y = 250 - t * 240, x = 128 + Math.sin(t * 2) * 8, l = 95 * Math.sin(Math.PI * Math.min(1, (1 - t) * 1.1)) + 6; g.fillStyle = col(85 + R() * 15, 30 + R() * 15, 16 + R() * 10); for (const s of [-1, 1]) for (let j = 0; j < 7; j++) leafShape(g, x + s * l * j / 8, y - j * 1.5, l / 8 + 3, 3.5, s > 0 ? -0.3 : Math.PI + 0.3, false, false); } }); + // 6 big serrated leaves (bramble, nettle, dock) + cell(6, () => { for (let i = 0; i < 12; i++) { const a = R() * TAU, r = Math.sqrt(R()) * 80; g.fillStyle = col(85 + R() * 20, 24 + R() * 16, 22 + R() * 14); leafShape(g, 128 + Math.cos(a) * r, 128 + Math.sin(a) * r, R.range(50, 80), R.range(16, 26), R() * TAU, false, true); } }); + // 7 ripe wheat: stalks with ears and awns, a few leaves + cell(7, () => { for (let i = 0; i < 26; i++) { const x = R.range(16, 240), lean = R.range(-18, 18), top = R.range(8, 60), l = 42 + R() * 10; + g.strokeStyle = col(44 + R() * 8, 30 + R() * 15, 40 + R() * 14); g.lineWidth = R.range(2, 3); g.beginPath(); g.moveTo(x, 256); g.quadraticCurveTo(x + lean * 0.3, 150, x + lean, top + l); g.stroke(); + g.fillStyle = col(42 + R() * 8, 38 + R() * 15, 46 + R() * 12); g.save(); g.translate(x + lean, top + l / 2); g.rotate(lean * 0.004); g.beginPath(); g.ellipse(0, 0, 5.5, l / 2, 0, 0, 6.29); g.fill(); + g.strokeStyle = col(45, 35, 58); g.lineWidth = 0.8; for (let k = 0; k < 8; k++) { g.beginPath(); g.moveTo(0, -l / 2 + k * l / 8); g.lineTo((k % 2 ? 1 : -1) * 6, -l / 2 + k * l / 8 - 14); g.stroke(); } g.restore(); } }); + const img = g.getImageData(0, 0, W, H); + // coverage-preserving mipmaps: each level keeps the share of texels above the alpha cut of level 0 + const levels = [{ data: new Uint8Array(img.data.buffer.slice(0)), width: W, height: H }]; + const cover = (d) => { let n = 0; for (let i = 3; i < d.length; i += 4) if (d[i] >= 128) n++; return n / (d.length / 4); }; + const target = cover(levels[0].data); + let w = W, h = H, prev = levels[0].data; + while (w > 1 || h > 1) { + const nw = Math.max(1, w >> 1), nh = Math.max(1, h >> 1), d = new Uint8Array(nw * nh * 4); + for (let y = 0; y < nh; y++) for (let x = 0; x < nw; x++) { + let r = 0, gg = 0, b = 0, a = 0; + for (let j = 0; j < 2; j++) for (let i = 0; i < 2; i++) { const k = (Math.min(h - 1, y * 2 + j) * w + Math.min(w - 1, x * 2 + i)) * 4, al = prev[k + 3] / 255; r += prev[k] * al; gg += prev[k + 1] * al; b += prev[k + 2] * al; a += al; } + const q = (y * nw + x) * 4; d[q] = a ? r / a : 40; d[q + 1] = a ? gg / a : 50; d[q + 2] = a ? b / a : 30; d[q + 3] = a / 4 * 255; + } + // scale alpha so coverage at the 0.5 cut matches level 0 + let lo = 0.5, hi = 4; + for (let it = 0; it < 12; it++) { const m = (lo + hi) / 2; let n = 0; for (let i = 3; i < d.length; i += 4) if (d[i] * m >= 128) n++; if (n / (nw * nh) < target) lo = m; else hi = m; } + const sc = (lo + hi) / 2; for (let i = 3; i < d.length; i += 4) d[i] = Math.min(255, d[i] * sc); + levels.push({ data: d, width: nw, height: nh }); prev = d; w = nw; h = nh; + } + const t = new THREE.DataTexture(levels[0].data, W, H, THREE.RGBAFormat); + t.mipmaps = levels; t.generateMipmaps = false; t.minFilter = THREE.LinearMipmapLinearFilter; t.magFilter = THREE.LinearFilter; + t.flipY = false; t.encoding = THREE.sRGBEncoding; t.anisotropy = 4; t.needsUpdate = true; + E.extraTexBytes = (E.extraTexBytes || 0) + W * H * 4 * 1.33; + atlas = t; return t; + } + E.leafAtlas = makeAtlas; + const cellUV = (i) => [(i % 4) / 4, Math.floor(i / 4) / 2, 0.25, 0.5]; // u0, v0, du, dv (row 0 = v 0, image row 0) + + // ------------------------------------------------------------------ foliage materials (wind, translucency) + const FOL_VS = ` + attribute vec4 aWind; // x: branch phase, y: branch sway weight, z: flutter weight, w: height in the plant (m) + ${E.GLSL.wind} + vec3 ivSway(vec3 p) { + vec3 ip = vec3(0.0); vec3 ax = vec3(1.0, 0.0, 0.0), az = vec3(0.0, 0.0, 1.0); float sc = 1.0; + #ifdef USE_INSTANCING + ip = vec3(instanceMatrix[3][0], instanceMatrix[3][1], instanceMatrix[3][2]); + ax = vec3(instanceMatrix[0][0], instanceMatrix[0][1], instanceMatrix[0][2]); az = vec3(instanceMatrix[2][0], instanceMatrix[2][1], instanceMatrix[2][2]); + sc = length(ax); ax /= sc; az /= length(az); + #else + ip = vec3(modelMatrix[3][0], modelMatrix[3][1], modelMatrix[3][2]); + #endif + vec2 wv = ivWind(ip.xz + p.xz * 0.3); + float hh = max(aWind.w, 0.0) * sc; + vec2 bend = wv * 0.012 * hh * hh * uStiff; // trunk / whole plant + float ph = aWind.x + uTime * 1.6; + bend += wv * aWind.y * (0.06 + 0.05 * sin(ph)) ; // branch sway, own phase + vec3 fl = vec3(sin(uTime * 8.3 + aWind.x * 9.0), sin(uTime * 7.1 + aWind.x * 5.0) * 0.6, cos(uTime * 9.2 + aWind.x * 7.0)) * aWind.z * 0.02 * (0.4 + uWind.z); + // to object space (instance rotation and scale) + vec2 ob = vec2(dot(vec3(bend.x, 0.0, bend.y), ax), dot(vec3(bend.x, 0.0, bend.y), az)) / sc; + return p + vec3(ob.x, -dot(ob, ob) * 0.3, ob.y) + fl / sc; + } + `; + function foliagePatch(m, opts) { + const uni = { uTime: E.U.uTime, uWind: E.U.uWind, uNight: E.U.uNight, uStiff: { value: opts.stiff == null ? 1 : opts.stiff }, uTrans: { value: opts.trans == null ? 1 : opts.trans } }; + m.userData.uniforms = uni; + const leaf = !!opts.leaf; + m.onBeforeCompile = function (sh) { + Object.assign(sh.uniforms, uni); + sh.vertexShader = 'uniform float uStiff;\n' + FOL_VS + sh.vertexShader.replace('#include ', 'vec3 transformed = ivSway(position);'); + if (leaf) { + sh.fragmentShader = 'uniform float uTrans, uNight;\nvec3 ivTransCol; float ivTransAmt;\n' + sh.fragmentShader + .replace('#include ', THREE.ShaderChunk.lights_physical_pars_fragment.replace('vec3 irradiance = dotNL * directLight.color;', `vec3 irradiance = dotNL * directLight.color; + { float back = saturate(dot(-geometry.normal, directLight.direction)); float scat = pow(saturate(dot(-geometry.viewDir, directLight.direction)), 4.0); + vec3 tr = ivTransCol * directLight.color * (back * 0.2 + scat * 0.25) * ivTransAmt; + #ifndef PHYSICALLY_CORRECT_LIGHTS + tr *= PI; + #endif + reflectedLight.directDiffuse += tr * RECIPROCAL_PI; }`)) + .replace('#include ', 'float faceDirection = gl_FrontFacing ? 1.0 : -1.0; vec3 normal = normalize(vNormal); vec3 geometryNormal = normal;') + .replace('#include ', '#include \n { float lm = dot(diffuseColor.rgb, vec3(0.3, 0.59, 0.11)), cap = mix(0.3, 0.15, uNight); if (lm > cap) diffuseColor.rgb *= cap / lm; } ivTransCol = diffuseColor.rgb * vec3(1.1, 1.2, 0.7); ivTransAmt = uTrans;') + .replace('#include ', 'reflectedLight.directSpecular = vec3(0.0); reflectedLight.indirectSpecular = vec3(0.0);'); + sh.fragmentShader = sh.fragmentShader.replace('float dotNL = saturate( dot( geometry.normal, directLight.direction ) );', 'float dotNL = saturate( (dot( geometry.normal, directLight.direction ) + 0.45) / 1.45 ) * 0.85;'); + } + }; + m.customProgramCacheKey = () => 'ivfol' + (leaf ? 'L' : 'B') + (opts.key || ''); + return m; + } + const leafMats = {}, barkMats = {}; + E.leafMaterial = function (key, o) { + if (leafMats[key]) return leafMats[key]; + const m = new THREE.MeshStandardMaterial({ map: makeAtlas(), alphaTest: 0.5, side: THREE.DoubleSide, vertexColors: true, roughness: 0.95, metalness: 0, envMapIntensity: 0.12 }); + m.alphaToCoverage = !!(E.renderer && E.renderer.capabilities.isWebGL2 && E.Q.post); + m.userData.linear = true; + foliagePatch(m, Object.assign({ leaf: true, key }, o || {})); + // shadows of the cards follow their alpha + m.userData.depth = new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking, map: m.map, alphaTest: 0.5, side: THREE.DoubleSide }); + leafMats[key] = m; return m; + }; + E.barkMaterial = function (name, stiff) { + const key = name + ':' + (stiff || 1); if (barkMats[key]) return barkMats[key]; + const base = E.mat(name), m = base.clone(); + m.userData = Object.assign({}, base.userData); + const prev = base.onBeforeCompile; + const uni = { uTime: E.U.uTime, uWind: E.U.uWind, uStiff: { value: stiff || 1 } }; + m.onBeforeCompile = function (sh) { + prev.call(this, sh); Object.assign(sh.uniforms, uni); + sh.vertexShader = 'uniform float uStiff;\n' + FOL_VS + sh.vertexShader.replace('#include ', 'vec3 transformed = ivSway(position);'); + }; + m.customProgramCacheKey = () => 'ivbark' + name; + barkMats[key] = m; return m; + }; + + // ------------------------------------------------------------------ tree generator + const KIND = { + oak: { h: [7, 10], trunkR: 0.32, trunkH: 0.32, limbs: [5, 7], limbAng: [0.75, 1.15], limbLen: 0.55, depth: 3, child: 4, cards: 0.95, cell: 0, bark: 'bark_oak', crown: [0.5, 0.42], spread: 1.0, tint: 0xffffff, droop: 0.15 }, + ash: { h: [10, 14], trunkR: 0.24, trunkH: 0.45, limbs: [5, 6], limbAng: [0.45, 0.75], limbLen: 0.45, depth: 3, child: 3, cards: 0.85, cell: 1, bark: 'bark_oak', crown: [0.62, 0.32], spread: 0.8, tint: 0xc8c6c0, droop: 0.05 }, + poplar: { h: [16, 22], trunkR: 0.26, trunkH: 0.12, limbs: [16, 22], limbAng: [0.18, 0.35], limbLen: 0.16, depth: 2, child: 3, cards: 0.7, cell: 2, bark: 'bark_oak', crown: [0.55, 0.12], spread: 0.3, tint: 0xd0ccc4, droop: 0 }, + apple: { h: [3.5, 5], trunkR: 0.14, trunkH: 0.32, limbs: [4, 5], limbAng: [0.8, 1.2], limbLen: 0.6, depth: 3, child: 3, cards: 0.6, cell: 1, bark: 'bark_oak', crown: [0.6, 0.55], spread: 1.0, tint: 0x9a9088, droop: 0.25 }, + pine: { h: [12, 18], trunkR: 0.25, trunkH: 0.35, limbs: [44, 54], limbAng: [1.5, 1.85], limbLen: 0.28, depth: 2, child: 3, cards: 0.9, cell: 3, bark: 'bark_pine', crown: [0.6, 0.25], spread: 0.5, tint: 0xffffff, droop: 0.2, whorl: true }, + dead: { h: [7, 10], trunkR: 0.3, trunkH: 0.35, limbs: [4, 6], limbAng: [0.7, 1.1], limbLen: 0.5, depth: 3, child: 3, cards: 0, cell: 0, bark: 'bark_oak', crown: [0.5, 0.4], spread: 0.9, tint: 0x8a8580, droop: 0.1, broken: true }, + burnt: { h: [5, 8], trunkR: 0.28, trunkH: 0.4, limbs: [2, 4], limbAng: [0.6, 1.0], limbLen: 0.4, depth: 2, child: 2, cards: 0, cell: 0, bark: 'bark_oak', crown: [0.5, 0.4], spread: 0.7, tint: 0x2c2826, droop: 0.05, broken: true }, + sapling: { h: [2.2, 3.2], trunkR: 0.04, trunkH: 0.25, limbs: [4, 6], limbAng: [0.5, 0.9], limbLen: 0.35, depth: 2, child: 2, cards: 0.45, cell: 1, bark: 'bark_oak', crown: [0.6, 0.3], spread: 0.6, tint: 0xb0a898, droop: 0.05 } + }; + E.TREE_KINDS = KIND; + // Build one tree. lod 0 (full), 1 (reduced). Returns { bark: BufferGeometry, leaves: BufferGeometry|null, height, crown } + function genTree(kind, seed, lod) { + const K = KIND[kind], R = E.rng(seed * 131 + 7), H = R.range(K.h[0], K.h[1]); + const bark = { p: [], n: [], u: [], w: [], i: [] }, leaves = { p: [], n: [], u: [], c: [], w: [], i: [] }; + const crownC = new V3(0, H * K.crown[0] + H * 0.12, 0), crownR = new V3(H * K.crown[1] * K.spread + 1.0, H * (1 - K.crown[0]) * 0.75, H * K.crown[1] * K.spread + 1.0); + const sides = (r) => lod ? (r > 0.15 ? 6 : 4) : (r > 0.15 ? 10 : r > 0.05 ? 6 : 4); + // tube along a list of points with radii + function tube(pts, rad, phase) { + const s = sides(rad[0]), base = bark.p.length / 3; let vlen = 0; + for (let k = 0; k < pts.length; k++) { + const p = pts[k], q = pts[Math.min(pts.length - 1, k + 1)], o = pts[Math.max(0, k - 1)], dir = new V3().subVectors(q, o).normalize(); + if (k > 0) vlen += p.distanceTo(pts[k - 1]); + const up = Math.abs(dir.y) < 0.95 ? new V3(0, 1, 0) : new V3(1, 0, 0), a = new V3().crossVectors(dir, up).normalize(), b = new V3().crossVectors(dir, a).normalize(); + for (let j = 0; j <= s; j++) { + const t = j / s * TAU, nrm = a.clone().multiplyScalar(Math.cos(t)).addScaledVector(b, Math.sin(t)), r = rad[k] * (1 + (k === 0 && pts === trunkPts ? 0 : 0)); + bark.p.push(p.x + nrm.x * r, p.y + nrm.y * r, p.z + nrm.z * r); bark.n.push(nrm.x, nrm.y, nrm.z); + bark.u.push(j / s * TAU * Math.max(0.15, rad[k]) * 1.0, vlen); bark.w.push(phase, Math.min(1, p.distanceTo(new V3(0, p.y, 0)) / 4), 0, p.y); + } + } + for (let k = 0; k < pts.length - 1; k++) for (let j = 0; j < s; j++) { const a = base + k * (s + 1) + j, b = a + s + 1; bark.i.push(a, b, a + 1, a + 1, b, b + 1); } + } + const tips = []; + function quad(c, ax, ay, w, h, cell, cn, shade, phase) { + const base = leaves.p.length / 3, [u0, v0, du, dv] = cellUV(cell), hue = R.range(0.92, 1.06); + for (const [i, j] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) { + const v = c.clone().addScaledVector(ax, i * w / 2).addScaledVector(ay, j * h / 2); + leaves.p.push(v.x, v.y, v.z); leaves.n.push(cn.x, cn.y, cn.z); leaves.u.push(u0 + (i * 0.5 + 0.5) * du, v0 + (j * 0.5 + 0.5) * dv); + leaves.c.push(shade * hue * (kind === 'pine' ? 0.75 : 1), shade * (kind === 'pine' ? 0.92 : 1), shade * (2 - hue) * (kind === 'pine' ? 1.05 : 1)); leaves.w.push(phase, 1, 1, v.y); + } + leaves.i.push(base, base + 1, base + 2, base, base + 2, base + 3); + } + function card(p, size, cell, phase, sway, rotRand, along) { + // a leaf-cluster card facing a random direction, normal pointing out of the crown + const base = leaves.p.length / 3, rel = new V3().subVectors(p, crownC), out = rel.clone().normalize(); + let nrm = new V3(R.range(-1, 1), R.range(-0.4, 1), R.range(-1, 1)).normalize().lerp(out, 0.4).normalize(); + if (along) { const side = new V3().crossVectors(along, new V3(0, 1, 0)).normalize(); nrm = side.multiplyScalar(R() < 0.5 ? 1 : -1).add(new V3(0, R.range(0.2, 0.6), 0)).normalize(); } + const up = Math.abs(nrm.y) > 0.9 ? new V3(1, 0, 0) : new V3(0, 1, 0), tx = new V3().crossVectors(up, nrm).normalize(), ty = new V3().crossVectors(nrm, tx).normalize(); + const ang = rotRand ? R() * TAU : R.range(-0.5, 0.5), ca = Math.cos(ang), sa = Math.sin(ang), ax = tx.clone().multiplyScalar(ca).addScaledVector(ty, sa), ay = ty.clone().multiplyScalar(ca).addScaledVector(tx, -sa); + const [u0, v0, du, dv] = cellUV(cell); + // interior darkening: cards near the crown centre are in the shade of the others + const e = Math.sqrt((rel.x / crownR.x) ** 2 + (rel.y / crownR.y) ** 2 + (rel.z / crownR.z) ** 2), shade = E.clamp(0.35 + 0.7 * e, 0.35, 1.05); + const hue = R.range(0.9, 1.08); + const cn = out.clone().lerp(nrm, 0.25).normalize(); // canopy normal + for (const [i, j] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) { + const v = p.clone().addScaledVector(ax, i * size / 2).addScaledVector(ay, j * size / 2); + leaves.p.push(v.x, v.y, v.z); leaves.n.push(cn.x, cn.y, cn.z); leaves.u.push(u0 + (i * 0.5 + 0.5) * du, v0 + (j * 0.5 + 0.5) * dv); + leaves.c.push(shade * hue, shade, shade * (2 - hue)); leaves.w.push(phase, sway, 1, v.y); + } + leaves.i.push(base, base + 1, base + 2, base, base + 2, base + 3); + } + // the trunk: a slightly wandering line with a flared base + const trunkTop = H * K.trunkH + (K.whorl || kind === 'poplar' ? H * 0.6 : 0); + const trunkPts = [], trunkRad = [], tn = lod ? 4 : 7, lean = kind === 'pine' || kind === 'poplar' ? new V3(R.range(-0.03, 0.03), 0, R.range(-0.03, 0.03)) : new V3(R.range(-0.15, 0.15), 0, R.range(-0.15, 0.15)); + const fullH = K.whorl || kind === 'poplar' ? H * 0.95 : trunkTop; + for (let k = 0; k <= tn; k++) { const t = k / tn; const wob = kind === 'pine' ? 0.01 : 0.04; trunkPts.push(new V3(lean.x * t * t * H * 0.3 + R.range(-wob, wob) * (k > 0), t * fullH, lean.z * t * t * H * 0.3 + R.range(-wob, wob) * (k > 0))); trunkRad.push(K.trunkR * (1 - t * 0.55) * (k === 0 ? 1.45 : k === 1 ? 1.1 : 1)); } + trunkPts[0].y = -0.15; + tube(trunkPts, trunkRad, 0); + // roots: three or four short flares at the base (full LOD only) + if (!lod && K.trunkR > 0.1) for (let r = 0; r < 4; r++) { const a = r / 4 * TAU + R() * 0.8, d = new V3(Math.cos(a), 0, Math.sin(a)); tube([new V3(0, 0.25, 0).addScaledVector(d, K.trunkR * 0.6), new V3(0, 0.02, 0).addScaledVector(d, K.trunkR * 1.6), new V3(0, -0.12, 0).addScaledVector(d, K.trunkR * 2.6)], [K.trunkR * 0.45, K.trunkR * 0.28, K.trunkR * 0.1], 0); } + // branches, recursively + function branch(start, dir, len, rad, depth, phase) { + const n = lod ? 2 : 4, pts = [start.clone()], rads = [rad]; + const d = dir.clone(); + for (let k = 1; k <= n; k++) { + d.y -= K.droop * 0.25 * (depth + 1) / n; d.x += R.range(-0.18, 0.18); d.z += R.range(-0.18, 0.18); d.normalize(); + const p = pts[k - 1].clone().addScaledVector(d, len / n); pts.push(p); rads.push(rad * (1 - k / n * 0.65)); + } + if (K.broken && depth === 1 && R() < 0.4) { pts.length = 2; rads.length = 2; } + tube(pts, rads, phase); + const tip = pts[pts.length - 1]; + if (kind === 'pine' && K.cards > 0) { + // drooping bough: crossed needle fans along the branch, flat fan + a hanging fan + const segs = pts.length - 1; + for (let k = 0; k < segs; k++) { + const p0 = pts[k], p1 = pts[k + 1], c = p0.clone().lerp(p1, 0.5), ax = p1.clone().sub(p0); const L = ax.length(); ax.normalize(); + const side = new V3().crossVectors(ax, new V3(0, 1, 0)).normalize(), hang = new V3().crossVectors(side, ax).normalize(); + const wdt = (1.25 - 0.45 * k / segs) * (lod ? 1.3 : 1), shade = 0.42 + 0.3 * (k / segs); + // two fans hanging in a V under the bough (never a flat disc seen edge-on), plus a top fan + const w2 = wdt * 1.5, cA = Math.cos(0.75), sA = Math.sin(0.75); + for (const sg of [1, -1]) { const fd = side.clone().multiplyScalar(sg * cA).addScaledVector(hang, -sA).normalize(); quad(c.clone().addScaledVector(fd, w2 * 0.45), ax, fd, L + 0.4, w2, 3, side.clone().multiplyScalar(sg).add(new V3(0, 0.9, 0)).normalize(), shade * (0.8 + 0.2 * sg), phase); } + if (!lod) quad(c.clone().addScaledVector(hang, 0.06), ax, side, L + 0.3, wdt, 3, new V3(0, 1, 0).add(side.clone().multiplyScalar(0.3)).normalize(), shade, phase); + } + } + if (depth >= K.depth || rad < 0.02) { if (kind !== 'pine') tips.push(tip.clone()); return; } + const nch = K.child + (lod ? -1 : 0); + for (let c = 0; c < nch; c++) { + const t = R.range(0.35, 1), sp = pts[Math.min(pts.length - 1, Math.round(t * (pts.length - 1)))]; + const nd = d.clone().add(new V3(R.range(-1, 1), R.range(-0.2, 0.7), R.range(-1, 1)).multiplyScalar(0.9)).normalize(); + branch(sp, nd, len * R.range(0.45, 0.7), rad * 0.6, depth + 1, phase + R() * 2); + } + } + const nl = Math.round(R.range(K.limbs[0], K.limbs[1]) * (lod ? 0.75 : 1)); + for (let l = 0; l < nl; l++) { + const t = kind === 'pine' ? 0.22 + 0.76 * Math.pow((l + R() * 0.6) / nl, 0.9) : K.whorl || kind === 'poplar' ? 0.18 + 0.8 * (l + R()) / nl : 0.85 + R() * 0.15; + const sy = (K.whorl || kind === 'poplar') ? fullH * t : trunkTop * t; + const a = l / nl * TAU * 2.4 + R.range(-0.4, 0.4), el = R.range(K.limbAng[0], K.limbAng[1]); + const dir = new V3(Math.cos(a) * Math.sin(el), Math.cos(el), Math.sin(a) * Math.sin(el)).normalize(); + const lenK = (kind === 'pine' ? Math.pow(1 - t, 0.9) * 1.25 + 0.06 : K.whorl ? (1 - t) * 1.2 + 0.15 : 1) * K.limbLen * H * R.range(0.85, 1.1); + branch(new V3(lean.x * t * t * H * 0.3, sy, lean.z * t * t * H * 0.3), dir, lenK, K.trunkR * (K.whorl || kind === 'poplar' ? 0.25 : 0.6) * (1 - t * 0.3), 1, R() * 6); + } + // ---- crown mass: rounded sub-crowns of overlapping leaf clusters around the branch ends (poplar: a column) + if (K.cards > 0 && kind !== 'pine') { + let centres = []; + if (kind === 'poplar') { for (let y = H * 0.14; y < H * 0.98; y += 0.9) centres.push(new V3(R.range(-0.3, 0.3), y, R.range(-0.3, 0.3))); } + else { const mergeD = kind === 'sapling' ? 0.4 : 1.3; for (const t of tips) { if (!centres.some(c => c.distanceTo(t) < mergeD)) centres.push(t.clone().add(new V3(0, 0.35, 0))); } } + const rs0 = { oak: 1.9, ash: 1.6, apple: 1.2, sapling: 0.55, poplar: 1.55, dead: 0, burnt: 0 }[kind] || 1.4; + const per = Math.round((lod ? 10 : 30) * (kind === 'poplar' ? 1.4 : K.cards)), size0 = { sapling: 0.55, apple: 0.95, poplar: 1.3 }[kind] || 1.35; + for (const cc of centres) { + const rs = rs0 * R.range(0.8, 1.2) * (kind === 'poplar' ? (1 - 0.45 * Math.pow(cc.y / H, 3)) : 1); + for (let k = 0; k < per; k++) { + const dir = new V3(R.range(-1, 1), R.range(-0.7, 1), R.range(-1, 1)).normalize(), rr = rs * (0.3 + 0.7 * Math.cbrt(R())); + const p = cc.clone().addScaledVector(dir, rr); if (kind === 'poplar') { p.x = cc.x + (p.x - cc.x) * 0.75; p.z = cc.z + (p.z - cc.z) * 0.75; } + // spherical normals: mostly from the sub-crown centre, a little from the whole crown + const sub = p.clone().sub(cc).normalize(), whole = p.clone().sub(crownC).normalize(), cn = sub.multiplyScalar(0.6).add(whole.multiplyScalar(0.4)).normalize(); + const inner = rr / rs, shade = E.clamp(0.32 + 0.62 * inner + 0.12 * cn.y, 0.3, 0.98); + const fwd = cn.clone().lerp(new V3(R.range(-1, 1), R.range(-1, 1), R.range(-1, 1)).normalize(), 0.55).normalize(); + const up = Math.abs(fwd.y) > 0.9 ? new V3(1, 0, 0) : new V3(0, 1, 0), ax = new V3().crossVectors(up, fwd).normalize(), ay = new V3().crossVectors(fwd, ax).normalize(); + const sz = size0 * (lod ? 1.45 : 1) * R.range(0.8, 1.25); + quad(p, ax, ay, sz, sz, K.cell, cn, shade, R() * 6 + cc.x); + } + } + } + // a few cards hugging the upper trunk of columnar trees + const mk = (A, attrs) => { const g = new THREE.BufferGeometry(); for (const [k, n] of attrs) g.setAttribute(k, new THREE.Float32BufferAttribute(A[n.name], n.size)); g.setIndex(A.i); g.computeBoundingSphere(); return g; }; + const bg = new THREE.BufferGeometry(); + bg.setAttribute('position', new THREE.Float32BufferAttribute(bark.p, 3)); bg.setAttribute('normal', new THREE.Float32BufferAttribute(bark.n, 3)); + bg.setAttribute('uv', new THREE.Float32BufferAttribute(bark.u, 2)); bg.setAttribute('aWind', new THREE.Float32BufferAttribute(bark.w, 4)); + const ae = new Float32Array(bark.p.length / 3 * 4); const tc = new THREE.Color(K.tint); for (let i = 0; i < ae.length / 4; i++) { ae[i * 4] = tc.r; ae[i * 4 + 1] = tc.g; ae[i * 4 + 2] = tc.b; ae[i * 4 + 3] = 1 + Math.max(0, bark.p[i * 3 + 1]); } + bg.setAttribute('aEnv', new THREE.BufferAttribute(ae, 4)); bg.setIndex(bark.i); bg.computeBoundingSphere(); + let lg = null; + if (leaves.i.length) { + lg = new THREE.BufferGeometry(); + lg.setAttribute('position', new THREE.Float32BufferAttribute(leaves.p, 3)); lg.setAttribute('normal', new THREE.Float32BufferAttribute(leaves.n, 3)); + lg.setAttribute('uv', new THREE.Float32BufferAttribute(leaves.u, 2)); lg.setAttribute('color', new THREE.Float32BufferAttribute(leaves.c, 3)); + lg.setAttribute('aWind', new THREE.Float32BufferAttribute(leaves.w, 4)); lg.setIndex(leaves.i); lg.computeBoundingSphere(); + } + return { bark: bg, leaves: lg, height: H, radius: crownR.x, kind }; + } + const treeCache = {}; + function treeGeo(kind, variant, lod) { const k = kind + ':' + variant + ':' + lod; return treeCache[k] || (treeCache[k] = genTree(kind, 1000 + variant * 37 + kind.length * 101, lod)); } + E.tree = function (kind, seed) { + if (!KIND[kind]) throw new Error('IVEnv.tree: unknown kind ' + kind); + const t = genTree(kind, seed || 1, 0), g = new THREE.Group(); g.name = 'IVEnv.tree:' + kind; + const b = new THREE.Mesh(t.bark, E.barkMaterial(KIND[kind].bark)); b.castShadow = true; b.receiveShadow = true; g.add(b); + if (t.leaves) { const lm = E.leafMaterial(kind); const l = new THREE.Mesh(t.leaves, lm); l.castShadow = true; l.receiveShadow = true; l.customDepthMaterial = lm.userData.depth; g.add(l); } + g.userData.height = t.height; return g; + }; + + // impostor: the full tree drawn once from the side into a small texture, shown on two crossed quads + const impCache = {}; + function impostor(kind, variant) { + const k = kind + ':' + variant; if (impCache[k]) return impCache[k]; + const t = treeGeo(kind, variant, 0), r = E.renderer, S = 256; + const rt = new THREE.WebGLRenderTarget(S, S, { minFilter: THREE.LinearMipmapLinearFilter, generateMipmaps: true }); + const sc = new THREE.Scene(); sc.add(new THREE.AmbientLight(0xffffff, 0.55)); + const b = new THREE.Mesh(t.bark, new THREE.MeshLambertMaterial({ color: new THREE.Color(0x4a4038) })); sc.add(b); + if (t.leaves) { const lm = new THREE.MeshLambertMaterial({ map: makeAtlas(), alphaTest: 0.5, side: THREE.DoubleSide, vertexColors: true }); sc.add(new THREE.Mesh(t.leaves, lm)); } + const w = Math.max(t.radius * 1.15, t.height * 0.32) + 0.5, h = t.height * 1.08 + 0.5; + const cam = new THREE.OrthographicCamera(-w, w, h, 0 - 0.2, 0.1, 100); cam.position.set(0, 0, 50); cam.lookAt(0, 0, 0); + const prevT = r.getRenderTarget(), tm = r.toneMapping, cc = r.getClearColor(new THREE.Color()), ca = r.getClearAlpha(); + r.toneMapping = THREE.NoToneMapping; r.setRenderTarget(rt); r.setClearColor(0x2a3020, 0); r.clear(); r.render(sc, cam); + r.setRenderTarget(prevT); r.toneMapping = tm; r.setClearColor(cc, ca); + rt.texture.encoding = THREE.LinearEncoding; + const g = new THREE.BufferGeometry(), P = [], N = [], U = [], I = [], Wd = []; + for (let q = 0; q < 2; q++) { + const a = q * Math.PI / 2, c = Math.cos(a), s = Math.sin(a), base = P.length / 3; + for (const [i, j] of [[-1, 0], [1, 0], [1, 1], [-1, 1]]) { P.push(i * w * c, j * (h + 0.2) - 0.2, i * w * s); N.push(-s * 0.4, 0.9, c * 0.4); U.push(i * 0.5 + 0.5, j); Wd.push(0, 0, 0, j * h); } + I.push(base, base + 1, base + 2, base, base + 2, base + 3); + } + g.setAttribute('position', new THREE.Float32BufferAttribute(P, 3)); g.setAttribute('normal', new THREE.Float32BufferAttribute(N, 3)); g.setAttribute('uv', new THREE.Float32BufferAttribute(U, 2)); g.setAttribute('aWind', new THREE.Float32BufferAttribute(Wd, 4)); g.setIndex(I); + const m = new THREE.MeshStandardMaterial({ map: rt.texture, alphaTest: 0.5, side: THREE.DoubleSide, roughness: 0.9 }); m.userData.linear = true; + foliagePatch(m, { leaf: true, key: 'imp', stiff: 0.6, trans: 0.6 }); + m.alphaToCoverage = !!(r.capabilities.isWebGL2 && E.Q.post); + E.extraTexBytes = (E.extraTexBytes || 0) + S * S * 4 * 1.33; + return impCache[k] = { geo: g, mat: m, depth: new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking, map: rt.texture, alphaTest: 0.5, side: THREE.DoubleSide }) }; + } + + // ------------------------------------------------------------------ instanced forests with LOD swaps + E.trees = function (list) { + const Q = E.Q, group = new THREE.Group(); group.name = 'IVEnv.trees'; + const sets = {}; // kind:variant -> { lod0: [bark, leaves], lod1: [...], imp, items } + const dummy = new THREE.Object3D(); + for (const it of list) { + const kind = KIND[it.kind] ? it.kind : 'oak', variant = (it.seed != null ? it.seed : Math.round(it.x * 7 + it.z * 13)) & 1, key = kind + ':' + variant; + let s = sets[key]; + if (!s) { + s = sets[key] = { kind, variant, items: [], meshes: [] }; + const cap = list.length; + const mkI = (geo, mat, lod, part, depth) => { const m = new THREE.InstancedMesh(geo, mat, cap); m.count = 0; m.castShadow = true; m.receiveShadow = true; m.frustumCulled = false; if (depth) m.customDepthMaterial = depth; m.userData = { lod, part }; group.add(m); s.meshes.push(m); return m; }; + for (const lod of [0, 1]) { + const t = treeGeo(kind, variant, lod); + const bm = mkI(t.bark, E.barkMaterial(KIND[kind].bark), lod, 'bark'); if (lod > 0) bm.castShadow = false; + if (t.leaves) { const lm = E.leafMaterial(kind); const lm2 = mkI(t.leaves, lm, lod, 'leaves', lm.userData.depth); if (E.Q.name === 'low' || lod > 0) lm2.castShadow = false; } + } + const imp = impostor(kind, variant); mkI(imp.geo, imp.mat, 2, 'imp', imp.depth).castShadow = false; + } + s.items.push({ x: it.x, y: it.y || 0, z: it.z, rot: it.rot != null ? it.rot : (it.x * 12.9898 + it.z * 78.233) % TAU, scale: it.scale || 1, lod: -1 }); + } + const T = { group, sets, last: -1, near: Q.treeLod, mid: Q.treeLod * (Q.name === 'low' ? 2 : 3) }; + T.update = function (camera, force) { + const now = performance.now(); if (!force && now - T.last < 250) return; T.last = now; + const cx = camera.position.x, cz = camera.position.z; + for (const k in sets) { + const s = sets[k], counts = [0, 0, 0]; + for (const m of s.meshes) m.count = 0; + for (const it of s.items) { + const d = Math.hypot(it.x - cx, it.z - cz), lod = d < T.near ? 0 : d < T.mid ? 1 : 2; + dummy.position.set(it.x, it.y, it.z); dummy.rotation.set(0, lod === 2 ? Math.atan2(cx - it.x, cz - it.z) : it.rot, 0); dummy.scale.setScalar(it.scale); dummy.updateMatrix(); + for (const m of s.meshes) if (m.userData.lod === lod) m.setMatrixAt(m.count++, dummy.matrix); + counts[lod]++; + } + for (const m of s.meshes) { m.instanceMatrix.needsUpdate = true; m.visible = m.count > 0; } + } + }; + T.info = function () { let tris = 0, calls = 0; for (const k in sets) for (const m of sets[k].meshes) if (m.count) { calls++; tris += m.count * m.geometry.index.count / 3; } return { drawCalls: calls, triangles: tris }; }; + T.colliders = list.map(it => ({ x: it.x, z: it.z, hx: (KIND[it.kind] || KIND.oak).trunkR * (it.scale || 1), hz: (KIND[it.kind] || KIND.oak).trunkR * (it.scale || 1), y0: it.y || 0, y1: (it.y || 0) + 4, rot: 0, surf: 'wood', kind: 'trunk' })); + (E._updaters = E._updaters || []).push((dt, cam) => T.update(cam)); + return T; + }; + + // ------------------------------------------------------------------ hedgerows + E.hedge = function (points, opts) { + opts = Object.assign({ h: 2.4, w: 1.8, gaps: [], seed: 21 }, opts || {}); + const R = E.rng(opts.seed), hf = opts.heightFn || (() => 0), group = new THREE.Group(); group.name = 'IVEnv.hedge'; + const colliders = []; + let total = 0; const segs = []; + for (let i = 0; i < points.length - 1; i++) { const a = points[i], b = points[i + 1], L = Math.hypot(b[0] - a[0], b[1] - a[1]); segs.push({ a, b, L, s0: total }); total += L; } + const inGap = (s) => opts.gaps.some(g => s > g[0] && s < g[1]); + const CH = 16, perM = E.Q.name === 'low' ? 7 : E.Q.name === 'medium' ? 17 : 30, cardK = E.Q.name === 'medium' ? 1.25 : E.Q.name === 'high' ? 1.06 : 1.12; // fewer, larger cards on Medium + const lm = E.leafMaterial('hedge', { stiff: 0.4 }), bm = E.barkMaterial('bark_oak', 0.3); + for (let c0 = 0; c0 < total; c0 += CH) { + const L = { p: [], n: [], u: [], c: [], w: [], i: [] }, Bk = E.builder(opts.seed + c0); + const at = (s) => { for (const sg of segs) if (s <= sg.s0 + sg.L + 1e-6) { const t = (s - sg.s0) / sg.L; return [sg.a[0] + (sg.b[0] - sg.a[0]) * t, sg.a[1] + (sg.b[1] - sg.a[1]) * t, (sg.b[0] - sg.a[0]) / sg.L, (sg.b[1] - sg.a[1]) / sg.L]; } const sg = segs[segs.length - 1]; return [sg.b[0], sg.b[1], (sg.b[0] - sg.a[0]) / sg.L, (sg.b[1] - sg.a[1]) / sg.L]; }; + const c1 = Math.min(total, c0 + CH), n = Math.round((c1 - c0) * perM * (E.Q.name === 'low' ? 1 : 1.08)); // +8%, and a third of all cards go to the lower 2 m (a dense foot) + const ctr = at((c0 + c1) / 2); + for (let k = 0; k < n; k++) { + const s = R.range(c0, c1); if (inGap(s)) continue; + // ragged profile: height and width wander, thinner near gap edges + const gapD = Math.min(...opts.gaps.map(g => s < g[0] ? g[0] - s : s > g[1] ? s - g[1] : 0), 99); + const hk = (0.82 + 0.3 * E.fbm2(s * 0.18, opts.seed, 77, 3)) * Math.min(1, 0.55 + gapD / 1.5), H = opts.h * hk; + const [px, pz, dx, dz] = at(s), side = R.range(-1, 1), y0 = hf(px, pz); + const low = R() < 0.32, u = low ? Math.pow(R(), 1.3) * Math.min(1, 2.0 / Math.max(H, 0.5)) : R(), y = y0 + (low ? u * H : Math.pow(u, 0.8) * H), wk = opts.w * 0.5 * (low ? 0.75 + 0.35 * R() : 0.6 + 0.6 * Math.sin(Math.PI * Math.min(1, u * 1.1 + 0.1))) * (0.8 + 0.4 * E.vnoise(s * 0.5, 3, opts.seed)); + const p = new V3(px - dz * side * wk, y, pz + dx * side * wk), cc = new V3(px, y0 + H * 0.5, pz); + const out = p.clone().sub(cc).normalize(), size = R.range(0.55, 0.95) * cardK; + const nrm = new V3(R.range(-1, 1), R.range(-0.5, 1), R.range(-1, 1)).normalize().lerp(out, 0.4).normalize(); + const up = Math.abs(nrm.y) > 0.9 ? new V3(1, 0, 0) : new V3(0, 1, 0), tx = new V3().crossVectors(up, nrm).normalize(), ty = new V3().crossVectors(nrm, tx).normalize(); + const ang = R() * TAU, ca = Math.cos(ang), sa = Math.sin(ang), ax = tx.clone().multiplyScalar(ca).addScaledVector(ty, sa), ay = ty.clone().multiplyScalar(ca).addScaledVector(tx, -sa); + const cell = R() < 0.75 ? 4 : R() < 0.5 ? 6 : 0, [u0, v0, du, dv] = cellUV(cell); + const shade = E.clamp(0.3 + 0.75 * Math.abs(side) + 0.25 * u, 0.3, 1.05), hue = R.range(0.88, 1.1), base = L.p.length / 3; + const cn = out.clone().lerp(nrm, 0.3).normalize(); + for (const [i, j] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) { const v = p.clone().addScaledVector(ax, i * size / 2).addScaledVector(ay, j * size / 2); L.p.push(v.x, v.y, v.z); L.n.push(cn.x, cn.y, cn.z); L.u.push(u0 + (i * 0.5 + 0.5) * du, v0 + (j * 0.5 + 0.5) * dv); L.c.push(shade * hue * (1 + 0.1 * u), shade * (1 - 0.1 * u), shade * (2 - hue) * (1 + 0.08 * u)); L.w.push(R() * 6, 0.4, 1, v.y - y0); } + L.i.push(base, base + 1, base + 2, base, base + 2, base + 3); + } + // stems and a few thicker hazel/hawthorn trunks seen in the gaps and at the foot + for (let k = 0; k < Math.round((c1 - c0) * 1.2); k++) { + const s = R.range(c0, c1); if (inGap(s)) continue; const [px, pz] = at(s), y0 = hf(px, pz); + const sx = R.range(-0.4, 0.4); Bk.det(1, () => Bk.box('bark_oak', px + sx, y0 - 0.1, pz + R.range(-0.4, 0.4), 0.05, opts.h * R.range(0.4, 0.8), 0.05, R() * TAU, { rx: R.range(-0.35, 0.35), rz: R.range(-0.35, 0.35), noFoot: true, tint: new THREE.Color(0.75, 0.72, 0.68) })); + } + // leaf litter and dead leaves at the foot of the hedge + for (let k = 0; k < Math.round((c1 - c0) / 2); k++) { const s = R.range(c0, c1), [px, pz, dx, dz] = at(s), sd = R.range(-1, 1) * opts.w * 0.7; Bk.decal(R() < 0.8 ? 'grime' : 'leaves', [px - dz * sd, hf(px - dz * sd, pz + dx * sd) + 0.03, pz + dx * sd], [0, 1, 0], R.range(1, 2), R.range(1, 2), R() * 6); } // mostly brown earth, a little litter + if (L.i.length) { + const g = new THREE.BufferGeometry(); + g.setAttribute('position', new THREE.Float32BufferAttribute(L.p, 3)); g.setAttribute('normal', new THREE.Float32BufferAttribute(L.n, 3)); g.setAttribute('uv', new THREE.Float32BufferAttribute(L.u, 2)); + g.setAttribute('color', new THREE.Float32BufferAttribute(L.c, 3)); g.setAttribute('aWind', new THREE.Float32BufferAttribute(L.w, 4)); g.setIndex(L.i); g.computeBoundingSphere(); + const m = new THREE.Mesh(g, lm); m.castShadow = E.Q.name !== 'low'; m.userData.shadowNear = 22; m.receiveShadow = true; m.customDepthMaterial = lm.userData.depth; m.name = 'hedge-leaves'; group.add(m); + } + const st = Bk.finish(); st.traverse(o => { if (o.isMesh && o.material === E.mat('bark_oak')) o.material = bm; }); group.add(st); + // colliders: sight-blocking boxes along the hedge (the game decides flags) + for (let s = c0; s < c1; s += 2) { if (inGap(s + 1)) continue; const [px, pz, dx, dz] = at(Math.min(c1, s + 1)), y0 = hf(px, pz); colliders.push({ x: px, z: pz, hx: 1.0, hz: opts.w * 0.45, y0, y1: y0 + opts.h * 0.9, rot: Math.atan2(-dz, dx), surf: 'foliage', kind: 'hedge' }); } + } + return { group, colliders }; + }; + + // ------------------------------------------------------------------ scatter: plants stream like grass, objects are placed once + function plantGeo(kind) { + // small meshes; aWind.w = height above the root + const P = [], N = [], U = [], C = [], W = [], I = [], R = E.rng(kind.length * 31 + 5); + const card = (cx, cy, cz, w, h, ang, cell, tilt, shade) => { + const [u0, v0, du, dv] = cellUV(cell), base = P.length / 3, ca = Math.cos(ang), sa = Math.sin(ang), tx = Math.sin(tilt || 0); + for (const [i, j] of [[-1, 0], [1, 0], [1, 1], [-1, 1]]) { const x = cx + ca * i * w / 2 + (j ? -sa * tx * h : 0), y = cy + j * h * Math.cos(tilt || 0), z = cz + sa * i * w / 2 + (j ? ca * tx * h : 0); P.push(x, y, z); N.push(-sa * 0.3, 0.9, ca * 0.3); U.push(u0 + (i * 0.5 + 0.5) * du, v0 + j * dv); C.push(shade, shade, shade); W.push(R() * 6, 0, j, y); } + I.push(base, base + 1, base + 2, base, base + 2, base + 3); + }; + const blade = (x, z, h, w, lean, ang, col) => { // a geometric stalk: tapered strip of 3 segments + const base = P.length / 3, ca = Math.cos(ang), sa = Math.sin(ang); + for (let k = 0; k <= 3; k++) { const t = k / 3, ww = w * (1 - t * 0.7), off = lean * t * t * h; for (const s of [-1, 1]) { const px = x + ca * off + -sa * s * ww / 2, pz = z + sa * off + ca * s * ww / 2; P.push(px, t * h, pz); N.push(ca * 0.3, 0.9, sa * 0.3); U.push(0.125 + s * 0.01, 0.95); C.push(col[0], col[1], col[2]); W.push(R() * 6, 0, t, t * h); } } + for (let k = 0; k < 3; k++) { const a = base + k * 2; I.push(a, a + 1, a + 2, a + 1, a + 3, a + 2); } + return [x + ca * lean * h, h, z + sa * lean * h]; + }; + if (kind === 'maize') { + // three crossed cards of standing maize, 2.3 m (6 triangles a clump) + for (let k = 0; k < 3; k++) card(0, 0, 0, 1.1, 2.3, k / 3 * Math.PI + R() * 0.3, 3, 0, 1.0); + } else if (kind === 'wheat') { + // three crossed cards of ripe stalks (6 triangles): cheap enough for a whole field + for (let k = 0; k < 3; k++) card(0, 0, 0, 0.55, 1.0, k / 3 * Math.PI + R() * 0.3, 7, 0, 1.0); + } else if (kind === 'reeds') { for (let k = 0; k < 9; k++) blade(R.range(-0.15, 0.15), R.range(-0.15, 0.15), R.range(1.1, 1.8), 0.02, R.range(0.05, 0.35), R() * TAU, [0.9, 1.0, 0.75]); } + else if (kind === 'ferns') { for (let k = 0; k < 6; k++) { const a = k / 6 * TAU + R() * 0.4; card(Math.cos(a) * 0.12, 0, Math.sin(a) * 0.12, 0.45, 0.75, a + Math.PI / 2, 5, 0.7, 0.9); } } + else if (kind === 'brambles') { for (let k = 0; k < 7; k++) { const a = R() * TAU; card(R.range(-0.3, 0.3), R.range(0, 0.3), R.range(-0.3, 0.3), 0.7, 0.55, a, 6, R.range(0.2, 0.8), R.range(0.6, 1.0)); } for (let k = 0; k < 4; k++) blade(R.range(-0.3, 0.3), R.range(-0.3, 0.3), R.range(0.8, 1.2), 0.012, R.range(0.6, 1.1), R() * TAU, [0.6, 0.45, 0.4]); } + else if (kind === 'nettles') { for (let k = 0; k < 5; k++) { const x = R.range(-0.15, 0.15), z = R.range(-0.15, 0.15), h = R.range(0.6, 1.0); blade(x, z, h, 0.012, 0.05, R() * TAU, [0.7, 0.8, 0.6]); for (let j = 0; j < 3; j++) card(x, h * (0.35 + j * 0.22), z, 0.28 - j * 0.05, 0.22, R() * TAU, 6, 1.2, 0.9); } } + else if (kind === 'dock') { for (let k = 0; k < 6; k++) { const a = k / 6 * TAU; card(0, 0.02, 0, 0.35, 0.55, a, 6, 1.1, 0.85); } blade(0, 0, 0.9, 0.015, 0.05, 0, [0.7, 0.5, 0.4]); } + else if (kind === 'flowers') { for (let k = 0; k < 4; k++) { const tip = blade(R.range(-0.1, 0.1), R.range(-0.1, 0.1), R.range(0.3, 0.55), 0.006, 0.1, R() * TAU, [0.8, 0.9, 0.7]); const base = P.length / 3; for (let s = 0; s < 5; s++) { const a = s / 5 * TAU; P.push(tip[0] + Math.cos(a) * 0.022, tip[1], tip[2] + Math.sin(a) * 0.022); N.push(0, 1, 0); U.push(0.13, 0.96); C.push(3.2, 3.1, 2.6); W.push(0, 0, 1, tip[1]); } P.push(tip[0], tip[1] + 0.005, tip[2]); N.push(0, 1, 0); U.push(0.13, 0.96); C.push(3, 2.6, 0.8); W.push(0, 0, 1, tip[1]); for (let s = 0; s < 5; s++) I.push(base + s, base + 5, base + (s + 1) % 5); } } + const g = new THREE.BufferGeometry(); + g.setAttribute('position', new THREE.Float32BufferAttribute(P, 3)); g.setAttribute('normal', new THREE.Float32BufferAttribute(N, 3)); g.setAttribute('uv', new THREE.Float32BufferAttribute(U, 2)); + g.setAttribute('color', new THREE.Float32BufferAttribute(C, 3)); g.setAttribute('aWind', new THREE.Float32BufferAttribute(W, 4)); g.setIndex(I); g.computeBoundingSphere(); + return g; + } + const PLANTS = { + wheat: { dens: 7, r: [25, 35, 45], scale: [0.7, 1.15], tint: 0xa09070, cell: 7, stiff: 1.4 }, + maize: { dens: 2.2, r: [35, 45, 60], scale: [0.85, 1.15], tint: 0x767c56, cell: 3, stiff: 1.0 }, + reeds: { dens: 3, r: [20, 30, 40], scale: [0.8, 1.2], tint: 0x8a9a5a, stiff: 1.2 }, + ferns: { dens: 1.2, r: [18, 25, 35], scale: [0.7, 1.3], tint: 0x6a8040, stiff: 0.6 }, + brambles: { dens: 0.8, r: [18, 25, 35], scale: [0.8, 1.4], tint: 0x5a6a38, stiff: 0.5 }, + nettles: { dens: 1.5, r: [15, 22, 30], scale: [0.7, 1.2], tint: 0x5f7040, stiff: 0.8 }, + dock: { dens: 0.6, r: [15, 22, 30], scale: [0.7, 1.2], tint: 0x5a6a34, stiff: 0.6 }, + flowers: { dens: 1.5, r: [12, 18, 25], scale: [0.8, 1.2], tint: 0x6a7a48, stiff: 1.2 } + }; + E.scatter = function (kind, areaTest, opts) { + opts = Object.assign({ density: 1, seed: 7 }, opts || {}); + const hf = opts.heightFn || (() => 0), Q = E.Q, qi = Q.name === 'low' ? 0 : Q.name === 'medium' ? 1 : 2; + if (PLANTS[kind]) { + if (Q.plantKinds && Q.plantKinds.indexOf(kind) < 0) { const g = new THREE.Group(); g.name = 'IVEnv.scatter:' + kind + ' (off on ' + Q.name + ')'; return { group: g, update() { }, info() { return { drawCalls: 0, triangles: 0 }; } }; } + return plantField(kind, areaTest, hf, opts, qi); + } + return objectField(kind, areaTest, hf, opts); + }; + const _pm = new THREE.Matrix4(), _fr = new THREE.Frustum(), _bx = new THREE.Box3(); + function plantField(kind, areaTest, hf, opts, qi) { + const P = PLANTS[kind], radius = opts.radius || P.r[qi], dens = P.dens * opts.density * (qi === 0 ? 0.5 : qi === 1 ? 0.75 : 1), TS = 8; + const geo = plantGeo(kind), lm = E.leafMaterial('plant-' + kind, { stiff: P.stiff, trans: 1 }); + const cap = Math.ceil(Math.PI * (radius + 10) ** 2 * dens * 0.9); + const mesh = new THREE.InstancedMesh(geo, lm, cap); mesh.count = 0; mesh.frustumCulled = false; + // The per-instance tint buffer must be made at full capacity here: InstancedMesh.setColorAt sizes it from the + // current count, which is 0 at this point, and every tint then reads as black (the old black cut-out plants). + mesh.instanceColor = new THREE.InstancedBufferAttribute(new Float32Array(cap * 3).fill(1), 3); mesh.receiveShadow = true; mesh.castShadow = kind === 'wheat' || kind === 'maize' ? false : qi === 2; mesh.customDepthMaterial = lm.userData.depth; mesh.name = 'scatter-' + kind; + const tint = new THREE.Color(P.tint).convertSRGBToLinear(); if (kind !== 'wheat' && kind !== 'maize') tint.multiplyScalar(0.6 / Math.max(tint.r, tint.g, tint.b)); // a hue shift, not a darkening (the atlas already carries the colour) + const tiles = new Map(), group = new THREE.Group(); group.add(mesh); group.name = 'IVEnv.scatter:' + kind; + const dummy = new THREE.Object3D(), col = new THREE.Color(); + const gen = (tx, tz) => { + const out = [], n = Math.ceil(Math.sqrt(dens * TS * TS)), cell = TS / n; + for (let j = 0; j < n; j++) for (let i = 0; i < n; i++) { + const gi = tx * n + i, gj = tz * n + j, x = tx * TS + (i + E.hash(gi, gj, 61 + opts.seed)) * cell, z = tz * TS + (j + E.hash(gi, gj, 62 + opts.seed)) * cell; + const a = areaTest(x, z); if (!a || E.hash(gi, gj, 63 + opts.seed) > a) continue; + const patch = E.fbm2(x / 9, z / 9, 66 + opts.seed, 2), s = (P.scale[0] + (P.scale[1] - P.scale[0]) * E.hash(gi, gj, 64)) * (0.85 + 0.3 * E.fbm2(x / 3.5, z / 3.5, 67 + opts.seed, 2)); + out.push(x, hf(x, z) - 0.02, z, E.hash(gi, gj, 65) * TAU, s * (0.85 + 0.3 * patch), patch); + } + return new Float32Array(out); + }; + let key = ''; + const F = { + group, update(camera) { + const cx = camera.position.x, cz = camera.position.z, i0 = Math.floor((cx - radius) / TS), i1 = Math.floor((cx + radius) / TS), j0 = Math.floor((cz - radius) / TS), j1 = Math.floor((cz + radius) / TS); + const fwd = new V3(); camera.getWorldDirection(fwd); const yaw = Math.round(Math.atan2(fwd.x, fwd.z) / 0.26); + const k = i0 + ',' + j0 + ',' + i1 + ',' + j1 + ',' + yaw + ',' + Math.round(camera.position.x / 4) + ',' + Math.round(camera.position.z / 4); if (k === key) return; key = k; + camera.updateMatrixWorld(); _pm.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); _fr.setFromProjectionMatrix(_pm); + let n = 0; + for (let tz = j0; tz <= j1; tz++) for (let tx = i0; tx <= i1; tx++) { + const dxT = Math.max(tx * TS - cx, 0, cx - (tx + 1) * TS), dzT = Math.max(tz * TS - cz, 0, cz - (tz + 1) * TS); + _bx.min.set(tx * TS - 2, camera.position.y - 60, tz * TS - 2); _bx.max.set((tx + 1) * TS + 2, camera.position.y + 60, (tz + 1) * TS + 2); + if (Math.hypot(dxT, dzT) > 4 && !_fr.intersectsBox(_bx)) continue; + const tk = tx + ',' + tz; let t = tiles.get(tk); if (!t) { t = gen(tx, tz); tiles.set(tk, t); } + for (let q = 0; q < t.length && n < mesh.instanceMatrix.count; q += 6) { + const d = Math.hypot(t[q] - cx, t[q + 2] - cz); if (d > radius) continue; + const fade = E.clamp((radius - d) / 6, 0, 1); + dummy.position.set(t[q], t[q + 1], t[q + 2]); dummy.rotation.set(0, t[q + 3], 0); dummy.scale.setScalar(t[q + 4] * (0.3 + 0.7 * fade)); dummy.updateMatrix(); + mesh.setMatrixAt(n, dummy.matrix); + col.copy(tint).multiplyScalar(0.8 + 0.4 * t[q + 5]); mesh.setColorAt(n, col); n++; + } + } + mesh.count = n; mesh.instanceMatrix.needsUpdate = true; if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true; + if (tiles.size > 400) tiles.clear(); + }, + info() { return { drawCalls: mesh.count ? 1 : 0, triangles: mesh.count * geo.index.count / 3, instances: mesh.count }; } + }; + (E._systems = E._systems || []).push(F); + return F; + } + // objects placed once over bounds (rocks, logs, stumps, leaf litter, puddles): merged, not streamed + function objectField(kind, areaTest, hf, opts) { + if (E.Q.name === 'low' && (kind === 'logs' || kind === 'stumps' || kind === 'rocks')) { const g = new THREE.Group(); g.name = 'IVEnv.scatter:' + kind + ' (off on low)'; return { group: g, colliders: [], update() { }, info() { return {}; } }; } + const b = opts.bounds || [-50, -50, 50, 50], R = E.rng(opts.seed * 17 + kind.length), B = E.builder(opts.seed), group = new THREE.Group(); + const area = (b[2] - b[0]) * (b[3] - b[1]), dens = { rocks: 0.006, logs: 0.004, stumps: 0.004, litter: 0.02, puddles: 0.006 }[kind] || 0.01; + const n = Math.round(area * dens * opts.density * (E.Q.name === 'low' && kind !== 'puddles' ? 0.45 : 1)), colliders = []; + const puddles = []; + let placed = 0; + for (let k = 0; k < n * 6 && placed < n; k++) { + const x = R.range(b[0], b[2]), z = R.range(b[1], b[3]), a = areaTest(x, z); if (!a || R() > a) continue; placed++; + const y = hf(x, z); + if (kind === 'rocks') { const s = R.range(0.12, 0.6) * (R() < 0.1 ? 2 : 1); E.placeRock(B, 'fieldstone', x, y - s * 0.35, z, s, (R() * 999) | 0, [R() * 0.4, R() * 6, R() * 0.4], E.tintJ(R, 0.15, 0x8a8680)); if (R() < 0.6) B.decal('moss', [x, y + s * 0.42, z], [0, 1, 0], s * 1.3, s * 1.3, R() * 6); if (s > 0.4) colliders.push({ x, z, hx: s * 0.8, hz: s * 0.8, y0: y, y1: y + s * 0.5, rot: 0, surf: 'stone', kind: 'rock' }); } + else if (kind === 'logs') { const L = R.range(1.5, 4), r = R.range(0.12, 0.3), rot = R() * TAU, g = new THREE.CylinderGeometry(r, r * 1.08, L, 9, 3); g.rotateZ(Math.PI / 2); B.geo('bark_oak', g, new THREE.Matrix4().compose(new V3(x, y + r * 0.8, z), new THREE.Quaternion().setFromEuler(new THREE.Euler(0, rot, R.range(-0.05, 0.05))), new V3(1, 1, 1)), { tint: new THREE.Color(0.7, 0.66, 0.6), foot: y }); for (const s of [-1, 1]) B.geo('timber', new THREE.CircleGeometry(r * 0.96, 9), new THREE.Matrix4().compose(new V3(x + Math.cos(rot) * s * L / 2, y + r * 0.8, z - Math.sin(rot) * s * L / 2), new THREE.Quaternion().setFromEuler(new THREE.Euler(0, rot + s * Math.PI / 2, 0)), new V3(1, 1, 1)), { noFoot: true, tint: new THREE.Color(0.9, 0.75, 0.6) }); B.decal('moss', [x, y + r * 1.75, z], [0, 1, 0], L * 0.6, r * 1.5, rot); colliders.push({ x, z, hx: L / 2, hz: r, y0: y, y1: y + r * 1.6, rot, surf: 'wood', kind: 'log' }); } + else if (kind === 'stumps') { const r = R.range(0.18, 0.45), h = R.range(0.25, 0.6); B.geo('bark_oak', new THREE.CylinderGeometry(r * 0.9, r * 1.25, h, 10, 2), new THREE.Matrix4().compose(new V3(x, y + h / 2 - 0.05, z), new THREE.Quaternion(), new V3(1, 1, 1)), { tint: new THREE.Color(0.7, 0.66, 0.6), foot: y }); B.geo('timber', new THREE.CircleGeometry(r * 0.88, 10).rotateX(-Math.PI / 2), new THREE.Matrix4().makeTranslation(x, y + h - 0.049, z), { noFoot: true, tint: new THREE.Color(0.85, 0.72, 0.6) }); B.decal('moss', [x, y + h - 0.04, z], [0, 1, 0], r * 1.6, r * 1.6, R() * 6); colliders.push({ x, z, hx: r, hz: r, y0: y, y1: y + h, rot: 0, surf: 'wood', kind: 'stump' }); } + else if (kind === 'litter') B.decal('leaves', [x, y + 0.02, z], [0, 1, 0], R.range(1, 2.5), R.range(1, 2.5), R() * 6); + else if (kind === 'puddles') puddles.push([x, y, z, R.range(0.6, 2.2), R.range(0.4, 1.4), R() * TAU]); + } + const g = B.finish({ castShadow: kind === 'logs' }); group.add(g); group.name = 'IVEnv.scatter:' + kind; + if (puddles.length) group.add(E.puddleMesh(puddles)); + return { group, colliders, update() { }, info() { return {}; } }; + } + // standing water discs (ruts, yard): dark mirror with soft edges, rippling when it rains + let pudMat = null; + E.puddleMaterial = function () { + if (pudMat) return pudMat; + const m = new THREE.MeshStandardMaterial({ color: 0x07080a, roughness: 0.06, metalness: 0, transparent: true, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -1, polygonOffsetUnits: -2, envMapIntensity: 0.55 }); m.defines = { USE_UV: '' }; + const uni = { uTime: E.U.uTime, uWet: E.U.uWet }; m.customProgramCacheKey = () => 'ivpuddle'; + m.onBeforeCompile = (sh) => { + Object.assign(sh.uniforms, uni); + sh.fragmentShader = 'uniform float uTime, uWet;\n' + E.GLSL.noise + sh.fragmentShader + .replace('#include ', `{ vec2 p = vUv * 6.0; float rn = uWet; vec2 g = vec2(ivN(p * 3.0 + uTime * 0.7) - ivN(p * 3.0 + vec2(0.37, 0.0) + uTime * 0.7), ivN(p * 3.0 + vec2(0.0, 0.37) - uTime * 0.5) - ivN(p * 3.0 - uTime * 0.5)); normal = normalize(normal + (vec3(g.x, g.y, 0.0)) * (0.05 + 0.3 * rn)); }`) + .replace('#include ', '{ float r = length(vUv - 0.5) * 2.0; diffuseColor.a = smoothstep(1.0, 0.55, r + (ivN(vUv * 9.0) - 0.5) * 0.4); }'); + }; + m.userData.linear = true; pudMat = m; return m; + }; + // opaque brown water (shell holes, ruts in clay): the same ripples, a muddy colour, little reflection + let pudMatB = null; + E.puddleMaterialBrown = function () { + if (pudMatB) return pudMatB; + const m = E.puddleMaterial().clone(); m.color.setHex(0x2a2012); m.roughness = 0.16; m.envMapIntensity = 0.3; m.onBeforeCompile = E.puddleMaterial().onBeforeCompile; m.customProgramCacheKey = () => 'ivpuddle'; + m.userData.linear = true; pudMatB = m; return m; + }; + E.puddleMesh = function (list, opts) { + const B = { p: [], n: [], u: [], i: [] }; + for (const [x, y, z, a, b, r] of list) { + const base = B.p.length / 3, c = Math.cos(r), s = Math.sin(r); + for (const [i, j] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) { B.p.push(x + c * i * a - s * j * b, y + 0.015, z + s * i * a + c * j * b); B.n.push(0, 1, 0); B.u.push(i * 0.5 + 0.5, j * 0.5 + 0.5); } + B.i.push(base, base + 2, base + 1, base, base + 3, base + 2); + } + const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.Float32BufferAttribute(B.p, 3)); g.setAttribute('normal', new THREE.Float32BufferAttribute(B.n, 3)); g.setAttribute('uv', new THREE.Float32BufferAttribute(B.u, 2)); g.setIndex(B.i); + g.computeBoundingSphere(); + const m = new THREE.Mesh(g, opts && opts.brown ? E.puddleMaterialBrown() : E.puddleMaterial()); m.receiveShadow = true; m.renderOrder = 1; m.name = 'puddles'; return m; + }; + + // ------------------------------------------------------------------ the stream + E.stream = function (points, opts) { + opts = Object.assign({ width: 3, flow: 0.35 }, opts || {}); + const hf = opts.heightFn || (() => 0), wy = opts.waterY || ((x, z) => opts.level != null ? opts.level : 0); + const P = [], N = [], U = [], D = [], I = []; + let along = 0; const step = 1.0, across = 6; + const pts = []; + for (let i = 0; i < points.length - 1; i++) { const a = points[i], b = points[i + 1], L = Math.hypot(b[0] - a[0], b[1] - a[1]), n = Math.max(1, Math.round(L / step)); for (let k = 0; k < n; k++) pts.push([a[0] + (b[0] - a[0]) * k / n, a[1] + (b[1] - a[1]) * k / n]); } + pts.push(points[points.length - 1]); + for (let i = 0; i < pts.length; i++) { + const p = pts[i], q = pts[Math.min(pts.length - 1, i + 1)], o = pts[Math.max(0, i - 1)], dx = q[0] - o[0], dz = q[1] - o[1], l = Math.hypot(dx, dz) || 1, nx = -dz / l, nz = dx / l; + if (i > 0) along += Math.hypot(p[0] - pts[i - 1][0], p[1] - pts[i - 1][1]); + const w = opts.width * (0.85 + 0.3 * E.vnoise(along * 0.2, 1, 9)); + for (let k = 0; k <= across; k++) { + const t = k / across - 0.5, x = p[0] + nx * t * w * 1.6, z = p[1] + nz * t * w * 1.6, y = wy(p[0], p[1]); + P.push(x, y, z); N.push(0, 1, 0); U.push(t * w * 1.6, along); D.push(Math.max(0, y - hf(x, z))); + } + } + for (let i = 0; i < pts.length - 1; i++) for (let k = 0; k < across; k++) { const a = i * (across + 1) + k, b = a + across + 1; I.push(a, b, a + 1, a + 1, b, b + 1); } + const g = new THREE.BufferGeometry(); + g.setAttribute('position', new THREE.Float32BufferAttribute(P, 3)); g.setAttribute('normal', new THREE.Float32BufferAttribute(N, 3)); g.setAttribute('uv', new THREE.Float32BufferAttribute(U, 2)); g.setAttribute('aDepth', new THREE.Float32BufferAttribute(D, 1)); + g.setIndex(I); g.computeBoundingSphere(); + // water: Fresnel reflection of the sky (environment map) and lamps, two ripple normals scrolling along the flow, + // body colour from depth (clear at the edge, dark peat-brown green in the middle), lapping foam at the banks + const m = new THREE.MeshStandardMaterial({ color: 0x0b1210, roughness: 0.05, metalness: 0, transparent: true, depthWrite: false, envMapIntensity: 1.2 }); m.defines = { USE_UV: '' }; + const uni = { uTime: E.U.uTime, uWet: E.U.uWet, uFlow: { value: opts.flow }, uMacro: E.U.uMacro }; m.customProgramCacheKey = () => 'ivwater'; + m.onBeforeCompile = (sh) => { + Object.assign(sh.uniforms, uni); + sh.vertexShader = 'attribute float aDepth; varying float vDepth;\n' + sh.vertexShader.replace('#include ', '#include \n vDepth = aDepth;'); + sh.fragmentShader = 'uniform float uTime, uWet, uFlow; uniform sampler2D uMacro; varying float vDepth;\n' + sh.fragmentShader + .replace('#include ', ` + float dep = vDepth; + vec3 shallow = vec3(0.045, 0.05, 0.035), deep = vec3(0.006, 0.012, 0.011); + diffuseColor.rgb = mix(deep, shallow, exp(-dep * 3.0)); + vec2 fuv1 = vUv * vec2(0.35, 0.18) + vec2(0.0, -uTime * uFlow * 0.18), fuv2 = vUv * vec2(0.7, 0.3) + vec2(0.31, -uTime * uFlow * 0.31); + float f1 = texture2D(uMacro, fuv1).b, f2 = texture2D(uMacro, fuv2).g; + float foam = smoothstep(0.12, 0.0, dep + (f1 - 0.5) * 0.12 + sin(uTime * 0.8 + vUv.y * 0.7) * 0.02) * smoothstep(0.35, 0.7, f2); + diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.38, 0.38, 0.34), foam * 0.7); + diffuseColor.a = smoothstep(0.0, 0.12, dep) * (0.86 + 0.14 * foam);`) + .replace('#include ', 'float roughnessFactor = mix(0.04, 0.6, foam);') + .replace('#include ', `{ + float e = 0.02; + float a1 = texture2D(uMacro, fuv1).b, b1 = texture2D(uMacro, fuv1 + vec2(e, 0.0)).b, c1 = texture2D(uMacro, fuv1 + vec2(0.0, e)).b; + float a2 = texture2D(uMacro, fuv2).g, b2 = texture2D(uMacro, fuv2 + vec2(e, 0.0)).g, c2 = texture2D(uMacro, fuv2 + vec2(0.0, e)).g; + vec2 g = vec2(a1 - b1, a1 - c1) * 1.2 + vec2(a2 - b2, a2 - c2) * 0.7; + normal = normalize(normal + (viewMatrix * vec4(g.x, 0.0, g.y, 0.0)).xyz * (0.6 + uWet * 0.6)); + }`); + }; + m.userData.linear = true; + const mesh = new THREE.Mesh(g, m); mesh.receiveShadow = true; mesh.renderOrder = 1; mesh.name = 'stream'; + const group = new THREE.Group(); group.name = 'IVEnv.stream'; group.add(mesh); + return { group, mesh }; + }; +})(); diff --git a/e63334287a3deaa3/ironveil/env/post.js b/e63334287a3deaa3/ironveil/env/post.js new file mode 100644 index 00000000..ffdcbca9 --- /dev/null +++ b/e63334287a3deaa3/ironveil/env/post.js @@ -0,0 +1,106 @@ +/* Midnight Ops environment: post-processing (Medium and High only; Low returns null and renders straight to the screen). + IVEnv.post(renderer, scene, camera, quality) -> { render(dt), setSize(w, h), params } or null + The scene is drawn into a linear HDR target with three's tone mapping switched off; one composite pass then adds a + small bloom (lamps, lit windows, muzzle flashes only: high threshold), tone maps with the same ACES curve as three, + grades (slight shadow lift so nothing goes pure black, desaturation, cool shadows / warm highlights), adds a vignette + and fine film grain (low amplitude, no flicker of the whole frame), then dithers. MSAA on High (WebGL2). + While post is active renderer.toneMapping is NoToneMapping; exposure still comes from renderer.toneMappingExposure. */ +(function () { + 'use strict'; + const E = window.IVEnv; + const VS = 'varying vec2 vUv; void main(){ vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }'; + const BRIGHT = `uniform sampler2D tSrc; uniform float uThr; varying vec2 vUv; + void main(){ vec3 c = texture2D(tSrc, vUv).rgb; float l = max(c.r, max(c.g, c.b)); float k = smoothstep(uThr, uThr * 2.5, l); + gl_FragColor = vec4(min(c * k, vec3(8.0)), 1.0); }`; + const BLUR = `uniform sampler2D tSrc; uniform vec2 uDir; varying vec2 vUv; + void main(){ vec3 s = texture2D(tSrc, vUv).rgb * 0.2270270; + s += (texture2D(tSrc, vUv + uDir * 1.3846153).rgb + texture2D(tSrc, vUv - uDir * 1.3846153).rgb) * 0.3162162; + s += (texture2D(tSrc, vUv + uDir * 3.2307692).rgb + texture2D(tSrc, vUv - uDir * 3.2307692).rgb) * 0.0702703; + gl_FragColor = vec4(s, 1.0); }`; + const COMP = `uniform sampler2D tScene, tB1, tB2; uniform float uExp, uBloom, uGrain, uVig, uTime, uSat, uLift; uniform vec3 uShadowTint, uHighTint; uniform vec2 uRes; + varying vec2 vUv; + vec3 RRTAndODTFit(vec3 v){ vec3 a = v * (v + 0.0245786) - 0.000090537; vec3 b = v * (0.983729 * v + 0.4329510) + 0.238081; return a / b; } + vec3 aces(vec3 color){ + const mat3 ACESInputMat = mat3(vec3(0.59719, 0.07600, 0.02840), vec3(0.35458, 0.90834, 0.13383), vec3(0.04823, 0.01566, 0.83777)); + const mat3 ACESOutputMat = mat3(vec3(1.60475, -0.10208, -0.00327), vec3(-0.53108, 1.10813, -0.07276), vec3(-0.07367, -0.00605, 1.07602)); + color *= uExp / 0.6; color = ACESInputMat * color; color = RRTAndODTFit(color); color = ACESOutputMat * color; return clamp(color, 0.0, 1.0); } + float h12(vec2 p){ vec3 p3 = fract(vec3(p.xyx) * 0.1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); } + vec3 toSRGB(vec3 c){ return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c)); } + void main(){ + vec3 c = texture2D(tScene, vUv).rgb; + vec3 b = texture2D(tB1, vUv).rgb * 0.6 + texture2D(tB2, vUv).rgb * 0.4; + c += b * uBloom; + c = aces(c); + float l = dot(c, vec3(0.2126, 0.7152, 0.0722)); + c = mix(vec3(l), c, uSat); + c *= mix(uShadowTint, uHighTint, smoothstep(0.0, 0.5, l)); + c = c + uLift * (1.0 - c) * (1.0 - smoothstep(0.0, 0.25, l)); // lift the deepest shadows a touch (no crushed blacks) + vec2 q = vUv - 0.5; float v = 1.0 - dot(q, q) * uVig; c *= v; + vec3 o = toSRGB(clamp(c, 0.0, 1.0)); + float g = h12(gl_FragCoord.xy + fract(uTime * 7.31) * 517.0) - 0.5; + o += g * uGrain * (0.5 + 0.5 * (1.0 - l)); + o += (h12(gl_FragCoord.xy * 1.37 + 11.0) - 0.5) / 255.0; + gl_FragColor = vec4(o, 1.0); + }`; + E.GRADES = { + night: { sat: 0.72, shadow: [0.92, 1.0, 1.12], high: [1.05, 1.0, 0.93], lift: 0.012, vig: 0.9, grain: 0.035, bloom: 0.55, thr: 0.9 }, + dawn: { sat: 0.82, shadow: [0.95, 1.0, 1.06], high: [1.05, 1.0, 0.94], lift: 0.01, vig: 0.75, grain: 0.03, bloom: 0.4, thr: 1.4 }, + rain: { sat: 0.66, shadow: [0.94, 1.0, 1.08], high: [1.0, 1.0, 0.98], lift: 0.012, vig: 0.85, grain: 0.035, bloom: 0.5, thr: 1.0 }, + day: { sat: 0.78, shadow: [0.97, 1.0, 1.04], high: [1.03, 1.0, 0.96], lift: 0.008, vig: 0.65, grain: 0.025, bloom: 0.25, thr: 2.5 } + }; + + E.post = function (renderer, scene, camera, quality) { + const Q = E.QUALITY[quality] || E.Q; + if (!Q.post) { renderer.toneMapping = THREE.ACESFilmicToneMapping; return null; } + const gl2 = renderer.capabilities.isWebGL2; + const type = gl2 ? THREE.HalfFloatType : (renderer.extensions.get('OES_texture_half_float') ? THREE.HalfFloatType : THREE.UnsignedByteType); + const opt = { type, format: THREE.RGBAFormat, minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, depthBuffer: true }; + const msaa = gl2; // the canvas' own antialias does not apply when drawing into a target + let rtScene = msaa ? new THREE.WebGLMultisampleRenderTarget(4, 4, Object.assign({}, opt)) : new THREE.WebGLRenderTarget(4, 4, opt); + if (msaa) rtScene.samples = 4; + const half = new THREE.WebGLRenderTarget(4, 4, Object.assign({}, opt, { depthBuffer: false })); + const qa = new THREE.WebGLRenderTarget(4, 4, Object.assign({}, opt, { depthBuffer: false })), qb = qa.clone(), ea = qa.clone(), eb = qa.clone(); + const cam = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1), quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2)), sc = new THREE.Scene(); sc.add(quad); quad.frustumCulled = false; + const mk = (fs, u) => new THREE.ShaderMaterial({ uniforms: u, vertexShader: VS, fragmentShader: fs, depthTest: false, depthWrite: false, toneMapped: false }); + const mBright = mk(BRIGHT, { tSrc: { value: null }, uThr: { value: 1 } }); + const mBlur = mk(BLUR, { tSrc: { value: null }, uDir: { value: new THREE.Vector2() } }); + const P = { + tScene: { value: null }, tB1: { value: qa.texture }, tB2: { value: ea.texture }, uExp: { value: 1 }, uBloom: { value: 0.5 }, uGrain: { value: 0.03 }, uVig: { value: 0.8 }, + uTime: { value: 0 }, uSat: { value: 0.75 }, uLift: { value: 0.01 }, uShadowTint: { value: new THREE.Vector3(1, 1, 1) }, uHighTint: { value: new THREE.Vector3(1, 1, 1) }, uRes: { value: new THREE.Vector2() } + }; + const mComp = mk(COMP, P); + renderer.toneMapping = THREE.NoToneMapping; + const pass = (m, target) => { quad.material = m; renderer.setRenderTarget(target); renderer.render(sc, cam); }; + const blur = (src, tmp, dst, w, h) => { + mBlur.uniforms.tSrc.value = src.texture; mBlur.uniforms.uDir.value.set(1 / w, 0); pass(mBlur, tmp); + mBlur.uniforms.tSrc.value = tmp.texture; mBlur.uniforms.uDir.value.set(0, 1 / h); pass(mBlur, dst); + }; + let W = 4, H = 4; + const api = { + params: P, + setSize(w, h) { + const pr = renderer.getPixelRatio(); W = Math.max(4, Math.floor(w * pr)); H = Math.max(4, Math.floor(h * pr)); + rtScene.setSize(W, H); half.setSize(W >> 1, H >> 1); qa.setSize(W >> 2, H >> 2); qb.setSize(W >> 2, H >> 2); ea.setSize(W >> 3, H >> 3); eb.setSize(W >> 3, H >> 3); + P.uRes.value.set(W, H); + }, + render(dt) { + const g = E.GRADES[(E.atmo && E.atmo.P && E.atmo.P.grade) || 'night']; + P.uSat.value = g.sat; P.uShadowTint.value.fromArray(g.shadow); P.uHighTint.value.fromArray(g.high); P.uLift.value = g.lift; P.uVig.value = g.vig; + P.uGrain.value = g.grain; P.uBloom.value = g.bloom; mBright.uniforms.uThr.value = g.thr; + P.uExp.value = renderer.toneMappingExposure; P.uTime.value += dt || 0.016; + const ar = renderer.info.autoReset; renderer.info.autoReset = false; renderer.info.reset(); + renderer.setRenderTarget(rtScene); renderer.render(scene, camera); + E.sceneInfo = { calls: renderer.info.render.calls, triangles: renderer.info.render.triangles }; + renderer.info.autoReset = ar; + mBright.uniforms.tSrc.value = rtScene.texture; pass(mBright, half); + mBlur.uniforms.tSrc.value = half.texture; mBlur.uniforms.uDir.value.set(1 / (W >> 1), 0); pass(mBlur, qb); // half -> quarter + mBlur.uniforms.tSrc.value = qb.texture; mBlur.uniforms.uDir.value.set(0, 1 / (H >> 2)); pass(mBlur, qa); + blur(qa, eb, ea, W >> 3, H >> 3); + P.tScene.value = rtScene.texture; pass(mComp, null); + }, + dispose() { [rtScene, half, qa, qb, ea, eb].forEach(t => t.dispose()); } + }; + api.setSize(innerWidth, innerHeight); + return api; + }; +})(); diff --git a/e63334287a3deaa3/ironveil/env/props.js b/e63334287a3deaa3/ironveil/env/props.js new file mode 100644 index 00000000..5cacfc61 --- /dev/null +++ b/e63334287a3deaa3/ironveil/env/props.js @@ -0,0 +1,354 @@ +/* Midnight Ops environment: props. + IVEnv.prop(kind, seed, opts) -> { group, colliders, lights } (local space, feet on y = 0) + kinds: crate, crates (stack), barrel, barrels, sandbags (a wall, opts.length), cart, haybale, haystack, well, trough, + telegraph (pole; wires via IVEnv.wireMesh between poles: group.userData.wireTop gives the insulator positions), + lamppost (lights[0] is the lamp), gate, ladder, drums (fuel drums), ammo (ammunition boxes), truck (period lorry, + no markings), logpile, tarp (tarpaulin over a stack), bottles; camp dressing: noticeboard, flagpole (bare mast), + duckboards (opts.length), tent (ridge tent), washline (opts.length), watertower, targetframe, car (staff car), + guardtower, shelter (firing-point lean-to), aframe (assault-course frame). + Wear sits where wear happens: scuffed crate corners and bases, rust runs under rivets, chipped paint on drum rims, + worn handles, mud on wheels and the truck's lower panels. */ +(function () { + 'use strict'; + const E = window.IVEnv; + const TAU = Math.PI * 2, V3 = THREE.Vector3; + const M4 = (x, y, z, rx, ry, rz, s) => new THREE.Matrix4().compose(new V3(x, y, z), new THREE.Quaternion().setFromEuler(new THREE.Euler(rx || 0, ry || 0, rz || 0)), s ? (s.isVector3 ? s : new V3(s, s, s)) : new V3(1, 1, 1)); + const cyl = (rt, rb, h, seg, open) => new THREE.CylinderGeometry(rt, rb, h, seg || 12, 1, !!open); + + function crate(B, R, x, y, z, rot, s, worn) { + s = s || 1; const w = 0.8 * s, h = 0.6 * s, d = 0.5 * s; + B.box('planks', x, y, z, w, h, d, rot, { tint: E.tintJ(R, 0.06, 0x8a7e6c), uvOff: [R() * 9, R() * 9], grain: 'long' }); // straight weathered boards + // corner battens and lid boards, slightly proud + const c = Math.cos(rot), sn = Math.sin(rot); + for (const [i, k] of [[-1, -1], [1, -1], [-1, 1], [1, 1]]) B.box('timber', x + c * i * (w / 2 - 0.03) + sn * k * (d / 2 - 0.01), y, z - sn * i * (w / 2 - 0.03) + c * k * (d / 2 - 0.01), 0.06, h, 0.03, rot, { grain: 'long', tint: new THREE.Color(0.75, 0.68, 0.6) }); + for (const k of [-1, 1]) B.box('timber', x + sn * k * (d / 2 + 0.005), y + h * 0.45, z + c * k * (d / 2 + 0.005), w - 0.1, 0.07, 0.02, rot, { grain: 'long' }); + B.decal('scratches', [x + sn * (d / 2 + 0.02), y + h * 0.3, z + c * (d / 2 + 0.02)], [sn, 0, c], w * 0.9, h * 0.6, R() * 3); + B.decal(worn ? 'mud' : 'grime', [x + sn * (d / 2 + 0.02), y + 0.1, z + c * (d / 2 + 0.02)], [sn, 0, c], w, 0.25, 0); + if (R() < 0.5) B.decal('chalk', [x - sn * (d / 2 + 0.02), y + h * 0.55, z - c * (d / 2 + 0.02)], [-sn, 0, -c], 0.3, 0.25, 0); + B.col(x, z, w, d, y, y + h, rot, 'wood', 'crate'); + return h; + } + function barrel(B, R, x, y, z, s, metal) { + s = s || 1; const r = 0.29 * s, h = 0.88 * s; + if (metal) { + B.geo('metal_painted', cyl(r, r, h, 16), M4(x, y + h / 2, z, 0, R() * TAU, 0), { tint: E.tintJ(R, 0.1, metal === 2 ? 0x8a5a4a : 0x9aa090), keepUv: true, uvW: TAU * r, uvH: h }); + for (const yy of [0.02, 0.33, 0.66, 0.98]) B.geo('metal_rust', new THREE.TorusGeometry(r + 0.005, 0.012, 4, 18).rotateX(Math.PI / 2), M4(x, y + h * yy, z), { noFoot: true }); + B.geo('metal_painted', new THREE.CircleGeometry(r, 16).rotateX(-Math.PI / 2), M4(x, y + h - 0.01, z), { noFoot: true, tint: E.tintJ(R, 0.1, metal === 2 ? 0x8a5a4a : 0x9aa090) }); + B.decal('rust', [x + r * 0.71 + 0.005, y + h * 0.75, z + r * 0.71 + 0.005], [0.71, 0, 0.71], 0.2, 0.45, 0); + B.decal('chipped', [x - r * 0.71 - 0.005, y + h * 0.93, z + r * 0.71], [-0.71, 0, 0.71], 0.3, 0.15, 0); + } else { + const g = cyl(r, r, h, 14), p = g.attributes.position; for (let i = 0; i < p.count; i++) { const yy = p.getY(i) / (h / 2), k = 1 + 0.12 * (1 - yy * yy); p.setX(i, p.getX(i) * k); p.setZ(i, p.getZ(i) * k); } g.computeVertexNormals(); + B.geo('planks', g, M4(x, y + h / 2, z, 0, R() * TAU, 0), { keepUv: true, uvW: TAU * r * 1.1, uvH: h, tint: E.tintJ(R, 0.1, 0xd0b8a0) }); + for (const yy of [0.1, 0.3, 0.7, 0.9]) { const k = 1 + 0.12 * (1 - ((yy - 0.5) * 2) ** 2); B.geo('metal_rust', new THREE.TorusGeometry(r * k + 0.004, 0.01, 4, 18).rotateX(Math.PI / 2), M4(x, y + h * yy, z), { noFoot: true }); } + B.geo('timber', new THREE.CircleGeometry(r * 0.98, 14).rotateX(-Math.PI / 2), M4(x, y + h - 0.02, z), { noFoot: true }); + } + B.col(x, z, r * 2, r * 2, y, y + h, 0, metal ? 'metal' : 'wood', 'barrel'); + return h; + } + function wheel(B, R, x, y, z, rot, r, spokes) { + // a cart wheel: rim, hub, spokes; the iron tyre is rusty and muddy at the bottom + const c = Math.cos(rot), s = Math.sin(rot); + B.geo('timber', new THREE.TorusGeometry(r - 0.03, 0.04, 6, 24), M4(x, y, z, 0, rot, 0), { noFoot: true }); + B.geo('metal_rust', new THREE.TorusGeometry(r, 0.018, 4, 28), M4(x, y, z, 0, rot, 0), { noFoot: true }); + B.geo('timber', cyl(0.08, 0.08, 0.22, 10).rotateX(Math.PI / 2), M4(x, y, z, 0, rot, 0), { noFoot: true }); + for (let k = 0; k < (spokes || 12); k++) { const a = k / (spokes || 12) * TAU; B.box('timber', x + c * Math.cos(a) * r * 0.48, y + Math.sin(a) * r * 0.48 - 0.02, z - s * Math.cos(a) * r * 0.48, r * 0.9, 0.035, 0.035, rot, { rz: a, noFoot: true }); } + B.decal('mud', [x + s * 0.06, y - r * 0.7, z + c * 0.06], [s, 0, c], r * 1.2, r * 0.7, 0); + } + const KINDS = {}; + KINDS.crate = (B, R) => { crate(B, R, 0, 0, 0, 0, 1, R() < 0.5); }; + KINDS.crates = (B, R) => { let h = crate(B, R, 0, 0, 0, 0.05, 1, true); crate(B, R, 0.85, 0, 0.1, -0.08, 1, true); crate(B, R, 0.35, h, 0.02, 0.2, 0.9); if (R() < 0.6) crate(B, R, -0.2, 0, 0.75, 1.6, 0.8); }; + KINDS.barrel = (B, R) => barrel(B, R, 0, 0, 0, 1, 0); + KINDS.barrels = (B, R) => { barrel(B, R, 0, 0, 0); barrel(B, R, 0.62, 0, 0.1); barrel(B, R, 0.3, 0, 0.55); }; + KINDS.drums = (B, R) => { barrel(B, R, 0, 0, 0, 1, 1); barrel(B, R, 0.63, 0, 0.05, 1, 1); barrel(B, R, 0.3, 0, 0.6, 1, 2); B.geo('metal_painted', cyl(0.29, 0.29, 0.88, 16).rotateZ(Math.PI / 2), M4(-0.75, 0.29, 0.3, 0, 0.4, 0), { tint: new THREE.Color(1.1, 1.1, 1.0) }); B.decal('waterstain', [0.3, 0.01, 0.2], [0, 1, 0], 1.8, 1.4, 0); }; + KINDS.sandbags = (B, R, o) => { const L = o.length || 3, rows = o.rows || 4; for (let r = 0; r < rows; r++) for (let i = 0; i < Math.round(L / 0.5); i++) E.sandbag(B, -L / 2 + (i + 0.5 + (r % 2) * 0.5) * 0.5 - 0.25 * (r % 2), r * 0.16, R.range(-0.02, 0.02) + (r % 2) * 0.04, R.range(-0.05, 0.05), R); }; + KINDS.haybale = (B, R) => E.hayBale(B, 0, 0, 0, 0, R); + KINDS.haystack = (B, R) => { for (let l = 0; l < 4; l++) for (let i = 0; i < 4 - l; i++) for (let j = 0; j < 2; j++) E.hayBale(B, -0.9 + i * 0.92 + l * 0.46, l * 0.4, j * 0.5 - 0.25, (l % 2) * 0.03, R); for (let k = 0; k < 6; k++) B.box('straw', R.range(-1, 1.5), 0, R.range(-0.8, 0.8), R.range(0.2, 0.5), 0.03, R.range(0.2, 0.4), R() * 3, { noFoot: true }); }; + KINDS.cart = (B, R) => { + const rot = 0; B.box('planks', 0, 0.75, 0, 2.4, 0.06, 1.3, 0, { tint: new THREE.Color(0.85, 0.78, 0.7) }); + for (const s of [-1, 1]) { B.box('planks', 0, 0.81, s * 0.63, 2.4, 0.38, 0.04, 0, {}); B.box('planks', s * 1.18, 0.81, 0, 0.04, 0.38, 1.26, 0, {}); } + for (const s of [-1, 1]) wheel(B, R, -0.25, 0.62, s * 0.78, Math.PI / 2, 0.62, 12); + B.box('timber', -0.25, 0.58, 0, 0.1, 0.1, 1.7, 0, { grain: 'long' }); + for (const s of [-0.35, 0.35]) B.box('timber', 1.9, 0.35, s, 2.0, 0.08, 0.08, 0.0, { rz: -0.32, grain: 'long' }); + B.decal('scratches', [0, 1.0, 0.655], [0, 0, 1], 2, 0.3, 0); B.decal('mud', [0, 0.9, 0.655], [0, 0, 1], 2.2, 0.3, 0); + E.hayBale(B, 0.4, 0.81, 0.1, 0.1, R); + B.col(0, 0, 2.4, 1.6, 0, 1.2, 0, 'wood', 'cart'); + }; + KINDS.well = (B, R) => { + const r = 0.8; for (let k = 0; k < 14; k++) { const a = k / 14 * TAU; B.box('fieldstone', Math.cos(a) * r, 0, Math.sin(a) * r, 0.42, 0.75 + R.range(-0.04, 0.04), 0.3, -a + Math.PI / 2, { tint: E.tintJ(R, 0.12) }); B.box('ashlar', Math.cos(a) * r, 0.75, Math.sin(a) * r, 0.44, 0.08, 0.36, -a + Math.PI / 2, { tint: E.tintJ(R, 0.08) }); } + B.geo('mud', new THREE.CircleGeometry(r - 0.1, 16).rotateX(-Math.PI / 2), M4(0, 0.3, 0), { tint: new THREE.Color(0.1, 0.1, 0.1), noFoot: true }); + for (const s of [-1, 1]) B.box('timber', s * (r + 0.05), 0, 0, 0.12, 2.0, 0.12, 0, { grain: 'long' }); + B.box('timber', 0, 1.9, 0, 2 * r + 0.3, 0.1, 0.1, 0, { grain: 'long' }); + B.geo('timber', cyl(0.08, 0.08, 1.3, 10).rotateZ(Math.PI / 2), M4(0, 1.55, 0), { noFoot: true }); + B.geo('metal_rust', cyl(0.004, 0.004, 1.1, 3), M4(0, 1.0, 0), { noFoot: true }); + B.geo('planks', cyl(0.13, 0.11, 0.25, 10), M4(0, 0.4, 0), { noFoot: true }); + B.decal('moss', [0, 0.2, r + 0.16], [0, 0, 1], 0.9, 0.4, 0); + B.col(0, 0, 2 * r + 0.3, 2 * r + 0.3, 0, 0.8, 0, 'stone', 'well'); + }; + KINDS.trough = (B, R) => { + B.box('ashlar', 0, 0, 0, 1.8, 0.55, 0.65, 0, { tint: new THREE.Color(0.75, 0.73, 0.7) }); + B.box('mud', 0, 0.42, 0, 1.6, 0.04, 0.45, 0, { tint: new THREE.Color(0.1, 0.11, 0.1), noFoot: true }); + B.decal('moss', [0, 0.15, 0.33], [0, 0, 1], 1.6, 0.35, 0); B.decal('waterstain', [0, 0.01, 0.6], [0, 1, 0], 2, 0.8, 0); + B.col(0, 0, 1.8, 0.65, 0, 0.55, 0, 'stone', 'trough'); + }; + KINDS.telegraph = (B, R, o) => { + const h = 7; B.geo('timber', cyl(0.1, 0.14, h, 9), M4(0, h / 2 - 0.3, 0, R.range(-0.03, 0.03), 0, R.range(-0.03, 0.03)), { grain: 'long', tint: new THREE.Color(0.55, 0.5, 0.45) }); + B.box('timber', 0, h - 0.8, 0, 1.4, 0.1, 0.1, 0, { grain: 'long' }); + const tops = []; + for (const x of [-0.6, -0.3, 0.3, 0.6]) { B.geo('glass', cyl(0.035, 0.05, 0.1, 8), M4(x, h - 0.65, 0), { noFoot: true }); tops.push([x, h - 0.55, 0]); } + B.decal('scratches', [0, 1.4, 0.12], [0, 0, 1], 0.2, 1.0, Math.PI / 2); + B.col(0, 0, 0.3, 0.3, 0, h, 0, 'wood', 'pole'); + return { wireTop: tops }; + }; + KINDS.lamppost = (B, R) => { + const h = 3.4; + B.geo('metal_painted', cyl(0.05, 0.08, h, 10), M4(0, h / 2, 0), { tint: new THREE.Color(0.35, 0.35, 0.33) }); + B.geo('metal_painted', cyl(0.12, 0.14, 0.3, 10), M4(0, 0.15, 0), { tint: new THREE.Color(0.35, 0.35, 0.33) }); + B.box('metal_painted', 0.3, h - 0.05, 0, 0.6, 0.05, 0.05, 0, { noFoot: true, tint: new THREE.Color(0.35, 0.35, 0.33) }); + B.geo('metal_painted', cyl(0.06, 0.22, 0.16, 12, true), M4(0.55, h - 0.2, 0), { noFoot: true, tint: new THREE.Color(0.3, 0.3, 0.28) }); + B.geo('glass_lit', new THREE.SphereGeometry(0.075, 10, 8), M4(0.55, h - 0.28, 0), { noFoot: true }); + B.decal('rust', [0.051, h * 0.7, 0], [1, 0, 0], 0.08, 0.5, 0); B.decal('chipped', [0, 0.25, 0.141], [0, 0, 1], 0.25, 0.25, 0); + B.col(0, 0, 0.25, 0.25, 0, h, 0, 'metal', 'lamp'); + return { light: { x: 0.55, y: h - 0.35, z: 0, color: 0xffb060, r: 16, power: 2.2, flicker: true } }; + }; + KINDS.gate = (B, R, o) => { + const w = o.width || 3.2, open = o.open || 0; + for (const s of [-1, 1]) { B.box('timber', s * (w / 2 + 0.1), -0.4, 0, 0.18, 1.8, 0.18, 0, { grain: 'long' }); B.decal('moss', [s * (w / 2 + 0.1), 0.2, 0.091], [0, 0, 1], 0.15, 0.4, 0); B.col(s * (w / 2 + 0.1), 0, 0.2, 0.2, 0, 1.4, 0, 'wood', 'gatepost'); } + const G = E.builder(R() * 1e4 | 0); + for (const yy of [0.15, 0.55, 0.95, 1.3]) G.box('timber', w / 2, yy, 0, w - 0.1, 0.09, 0.05, 0, { grain: 'long', tint: new THREE.Color(0.8, 0.76, 0.7) }); + G.box('timber', 0.06, 0, 0, 0.1, 1.42, 0.07, 0, { grain: 'long' }); G.box('timber', w - 0.12, 0, 0, 0.1, 1.42, 0.07, 0, { grain: 'long' }); + G.box('timber', w / 2, 0.15, 0.04, Math.hypot(w - 0.2, 1.2), 0.08, 0.04, 0, { rz: Math.atan2(1.15, w - 0.2), grain: 'long' }); + G.box('metal_rust', w - 0.25, 1.0, 0.05, 0.2, 0.04, 0.04, 0, { noFoot: true }); + G.decal('mud', [w / 2, 0.2, 0.03], [0, 0, 1], w * 0.8, 0.3, 0); + const leaf = G.finish(), pv = new THREE.Group(); pv.add(leaf); pv.position.set(-w / 2, 0.1, 0); pv.rotation.y = -open; pv.userData.dynamic = true; B._extra.push(pv); + return { door: { pivot: pv, width: w, open(a) { pv.rotation.y = -a; } } }; + }; + KINDS.ladder = (B, R) => { for (const s of [-0.22, 0.22]) B.box('timber', s, 0, 0.5, 0.06, 3.2, 0.06, 0, { rx: -0.3, grain: 'long' }); for (let k = 1; k < 11; k++) B.box('timber', 0, k * 0.28, 0.5 - Math.sin(0.3) * k * 0.29, 0.5, 0.035, 0.05, 0, { noFoot: true }); }; + KINDS.ammo = (B, R) => { + const box = (x, y, z, rot) => { B.box('metal_painted', x, y, z, 0.3, 0.19, 0.11, rot, { tint: new THREE.Color(0.8, 0.85, 0.7) }); B.box('metal_painted', x, y + 0.19, z, 0.31, 0.03, 0.12, rot, { noFoot: true, tint: new THREE.Color(0.75, 0.8, 0.65) }); B.box('metal_rust', x, y + 0.22, z, 0.12, 0.02, 0.025, rot, { noFoot: true }); B.decal('scratches', [x + Math.sin(rot) * 0.058, y + 0.1, z + Math.cos(rot) * 0.058], [Math.sin(rot), 0, Math.cos(rot)], 0.28, 0.16, R() * 3); }; + box(0, 0, 0, 0); box(0.04, 0.22, 0.02, 0.1); box(0.35, 0, 0.05, -0.05); box(-0.05, 0, 0.3, 1.57); B.col(0.15, 0.1, 0.7, 0.5, 0, 0.45, 0, 'metal', 'ammo'); + }; + KINDS.logpile = (B, R) => { for (let l = 0; l < 4; l++) for (let i = 0; i < 6 - l; i++) { const r = R.range(0.09, 0.14), x = -0.7 + i * 0.27 + l * 0.135, y = 0.12 + l * 0.22; B.geo('bark_oak', cyl(r, r, 1.6, 8).rotateX(Math.PI / 2), M4(x, y, R.range(-0.08, 0.08)), { tint: new THREE.Color(0.75, 0.7, 0.62) }); for (const s of [-1, 1]) B.geo('timber', new THREE.CircleGeometry(r * 0.95, 8), M4(x, y, s * 0.801 + R.range(-0.08, 0.08) * 0, 0, s > 0 ? 0 : Math.PI, 0), { noFoot: true, tint: new THREE.Color(1.0, 0.85, 0.65) }); } B.col(0, 0, 1.7, 1.7, 0, 0.9, 0, 'wood', 'logs'); }; + KINDS.tarp = (B, R) => { + crate(B, R, -0.45, 0, 0, 0, 1); crate(B, R, 0.45, 0, 0, 0.05, 1); crate(B, R, 0, 0.6, 0, 0.1, 0.9); + // a draped tarpaulin: a grid sagging over the stack, tied down at the corners + const g = new THREE.PlaneGeometry(2.4, 1.9, 16, 12); g.rotateX(-Math.PI / 2); const p = g.attributes.position; + for (let i = 0; i < p.count; i++) { const x = p.getX(i), z = p.getZ(i), ax = Math.abs(x), az = Math.abs(z), top = ax < 0.4 && az < 0.25 ? 1.15 : ax < 0.85 && az < 0.3 ? 0.62 : 0; let y = Math.max(top, 0) ; if (ax >= 0.85 || az >= 0.3) y = Math.max(0.02, (ax < 0.9 ? 0.62 : 0.6) - Math.max(ax - 0.85, az - 0.3) * 1.6); p.setY(i, Math.max(0.03, y) + 0.03 * Math.sin(x * 9 + z * 7) + 0.02); } + g.computeVertexNormals(); B.geo('canvas', g, M4(0, 0, 0), { keepUv: true, uvW: 2.4, uvH: 1.9 }); + B.col(0, 0, 1.8, 0.6, 0, 1.2, 0, 'cloth', 'tarp'); + }; + KINDS.bottles = (B, R) => { for (let k = 0; k < 5; k++) { const x = R.range(-0.2, 0.2), z = R.range(-0.15, 0.15), lie = R() < 0.4; B.geo('glass', cyl(0.035, 0.035, 0.24, 10), M4(x, lie ? 0.035 : 0.12, z, lie ? Math.PI / 2 : 0, R() * 3, 0), { noFoot: true }); } }; + // a burnt-out lorry: what is left after the fire. Chassis rails and cross members, four wheels on bare burnt rims + // (tyres gone, one wheel off), the cab as an empty frame with no glass or doors, the bonnet buckled, bare tilt hoops + // over a bed with only a few charred boards, the tailgate dropped on its chain; rust, soot and white ash. + KINDS.wreck = (B, R) => { + const burnt = new THREE.Color(0.32, 0.27, 0.23), rust = new THREE.Color(0.75, 0.55, 0.42), black = new THREE.Color(0.12, 0.11, 0.1); + for (const s of [-1, 1]) B.box('metal_rust', 0, 0.5, s * 0.45, 6.2, 0.2, 0.09, 0, { tint: rust }); // chassis rails + for (const x of [-2.6, -1.2, 0.4, 1.9]) B.box('metal_rust', x, 0.52, 0, 0.09, 0.14, 0.9, 0, { tint: rust }); // cross members + for (const [x, sz] of [[2.4, 1], [2.4, -1], [-1.6, 1], [-1.6, -1]]) { + if (x < 0 && sz < 0 && R() < 0.8) { B.geo('metal_rust', new THREE.TorusGeometry(0.36, 0.05, 6, 16), M4(-2.9, 0.12, -1.5, Math.PI / 2 + 0.1, 0, 0.2), { tint: black }); continue; } // a wheel off, lying in the mud + B.geo('metal_rust', new THREE.TorusGeometry(0.36, 0.055, 6, 16), M4(x, 0.42, sz * 0.92, 0, 0, 0), { tint: black }); // bare rim + B.geo('metal_rust', cyl(0.24, 0.24, 0.16, 10).rotateX(Math.PI / 2), M4(x, 0.42, sz * 0.9), { tint: burnt }); // hub and disc + for (let k = 0; k < 6; k++) { const a = k / 6 * Math.PI * 2; B.box('metal_rust', x + Math.cos(a) * 0.2, 0.42 + Math.sin(a) * 0.2 - 0.02, sz * 0.92, 0.05, 0.04, 0.04, 0, { noFoot: true, tint: black }); } + } + for (const s of [-1, 1]) B.box('metal_rust', 0.7, 0.62, s * 0.55, 6.6, 0.06, 0.06, 0, { tint: burnt }); // axle beams' springs + // bonnet buckled up in the middle, grille hanging + B.box('metal_rust', 2.35, 0.75, 0, 1.4, 0.05, 1.45, 0, { rz: 0.12, rx: 0.06, tint: burnt }); + for (const s of [-1, 1]) B.box('metal_rust', 2.35, 0.7, s * 0.72, 1.4, 0.55, 0.04, 0, { rz: 0.05 * s, tint: rust }); + B.box('metal_rust', 3.1, 0.55, 0.05, 0.05, 0.62, 0.95, 0, { rz: -0.35, noFoot: true, tint: black }); + B.box('metal_rust', 2.3, 0.62, 0, 0.9, 0.45, 0.7, 0, { tint: black }); // the engine block + // cab: floor, scuttle, four pillars, roof frame, no glass, no doors; a steering column and wheel ring + B.box('metal_rust', 1.1, 0.68, 0, 1.25, 0.05, 1.9, 0, { tint: burnt }); + B.box('metal_rust', 1.7, 0.7, 0, 0.06, 0.75, 1.9, 0, { tint: rust }); + for (const [x, z] of [[1.7, 0.92], [1.7, -0.92], [0.5, 0.92], [0.5, -0.92]]) B.box('metal_rust', x, 0.7, z, 0.07, 1.5, 0.07, 0, { rz: R.range(-0.06, 0.06), tint: burnt }); + for (const s of [-1, 1]) B.box('metal_rust', 1.1, 2.18, s * 0.92, 1.3, 0.06, 0.06, 0, { tint: burnt }); + for (const x of [0.5, 1.7]) B.box('metal_rust', x, 2.18, 0, 0.06, 0.06, 1.9, 0, { tint: burnt }); + B.box('metal_rust', 1.1, 2.2, 0.2, 1.1, 0.03, 1.2, 0, { rz: 0.15, rx: -0.1, tint: black }); // a sagging piece of roof skin + B.box('metal_rust', 0.55, 0.7, 0, 0.06, 1.0, 1.9, 0, { tint: rust }); // cab back + B.box('metal_rust', 1.45, 1.1, 0.4, 0.04, 0.5, 0.04, 0, { rz: -0.6, noFoot: true, tint: black }); + B.geo('metal_rust', new THREE.TorusGeometry(0.2, 0.02, 4, 12), M4(1.32, 1.35, 0.4, 0, Math.PI / 2, 0.6), { noFoot: true, tint: black }); + // bed: two side rails, a few charred boards left, bare tilt hoops (one bent), the tailgate dropped + for (const s of [-1, 1]) B.box('metal_rust', -1.45, 0.72, s * 1.08, 3.9, 0.12, 0.05, 0, { tint: rust }); + for (let k = 0; k < 7; k++) if (R() < 0.55) B.box('planks', -1.45 + R.range(-0.2, 0.2), 0.7, -0.9 + k * 0.3, R.range(1.2, 3.6), 0.04, 0.18, R.range(-0.05, 0.05), { tint: black }); + for (let k = 0; k < 4; k++) { const g = new THREE.TorusGeometry(1.08, 0.025, 4, 16, Math.PI); B.geo('metal_rust', g, M4(-3.1 + k * 1.1, 0.8, 0, 0, Math.PI / 2, k === 2 ? 0.25 : 0, k === 2 ? new V3(1, 0.8, 1) : null), { noFoot: true, tint: burnt }); } + B.box('metal_rust', -3.55, 0.25, 0, 0.05, 0.55, 2.1, 0, { rz: 1.2, tint: rust }); // tailgate down on its chains + for (const s of [-1, 1]) B.box('metal_rust', -3.42, 0.5, s * 1.0, 0.02, 0.45, 0.02, 0, { rz: -0.5, noFoot: true, tint: black }); + // soot, ash, rust runs + B.decal('soot', [1.1, 1.2, 0.97], [0, 0, 1], 1.8, 1.6, 0); B.decal('soot', [1.1, 1.2, -0.97], [0, 0, -1], 1.8, 1.6, 0); + B.decal('rust', [2.35, 0.6, 0.75], [0, 0, 1], 1.2, 0.5, 0); B.decal('rust', [-1.45, 0.6, 1.11], [0, 0, 1], 3, 0.4, 0); + B.col(0, 0, 6.6, 2.3, 0, 2.2, 0, 'metal', 'vehicle'); + }; + KINDS.truck = (B, R) => { + // a period 3-ton lorry in plain drab, no markings: cab, bonnet, wheels with mud, a canvas tilt over the bed + const drab = new THREE.Color(0.75, 0.78, 0.62); + B.box('metal_painted', 0, 0.55, 0, 6.2, 0.18, 1.1, 0, { tint: new THREE.Color(0.45, 0.45, 0.4) }); // chassis rails + B.box('metal_painted', 2.35, 0.75, 0, 1.4, 0.75, 1.5, 0, { tint: drab }); // bonnet + B.box('metal_rust', 3.08, 0.75, 0, 0.05, 0.7, 1.1, 0, { noFoot: true }); // grille + B.box('metal_painted', 1.1, 0.75, 0, 1.2, 1.55, 2.0, 0, { tint: drab }); // cab + B.box('glass', 1.71, 1.55, 0, 0.02, 0.5, 1.7, 0, { noFoot: true }); + for (const s of [-1, 1]) B.box('glass', 1.1, 1.6, s * 1.005, 0.8, 0.45, 0.02, 0, { noFoot: true }); + for (const s of [-1, 1]) { B.geo('metal_painted', cyl(0.5, 0.5, 0.1, 14, true).rotateX(Math.PI / 2), M4(2.4, 0.95, s * 0.92), { tint: drab, noFoot: true }); B.geo('glass_lit', new THREE.CircleGeometry(0.11, 12), M4(3.11, 1.2, s * 0.6, 0, Math.PI / 2, 0), { noFoot: true }); } + B.box('planks', -1.45, 0.75, 0, 3.9, 0.08, 2.2, 0, { tint: new THREE.Color(0.7, 0.68, 0.6) }); // bed + for (const s of [-1, 1]) B.box('planks', -1.45, 0.83, s * 1.08, 3.9, 0.5, 0.04, 0, { tint: drab }); + B.box('planks', -3.38, 0.83, 0, 0.04, 0.5, 2.2, 0, { tint: drab }); + const tilt = new THREE.CylinderGeometry(1.12, 1.12, 3.9, 14, 1, true, 0, Math.PI); tilt.rotateZ(Math.PI / 2); tilt.rotateX(-Math.PI / 2 * 0); + B.geo('canvas', tilt, M4(-1.45, 1.3, 0, -Math.PI / 2, 0, 0, new V3(1, 1, 0.75)), { keepUv: true, uvW: 3.9, uvH: 3.5, tint: new THREE.Color(0.85, 0.85, 0.75) }); + for (const x of [2.4, -0.9, -2.2]) for (const s of [-1, 1]) { const r = 0.48; B.geo('metal_rust', cyl(r, r, 0.26, 18).rotateX(Math.PI / 2), M4(x, r, s * 0.95), { tint: new THREE.Color(0.25, 0.25, 0.25) }); B.geo('metal_painted', cyl(r * 0.5, r * 0.5, 0.28, 12).rotateX(Math.PI / 2), M4(x, r, s * 0.95), { noFoot: true, tint: drab }); B.decal('mud', [x, r * 0.8, s * 1.09], [0, 0, s], 1.0, 0.8, 0); } + for (const s of [-1, 1]) { B.decal('mud', [0, 0.75, s * 1.11], [0, 0, s], 6, 0.6, 0); B.decal('scratches', [1.1, 1.0, s * 1.006], [0, 0, s], 1.0, 0.8, R() * 3); B.decal('chipped', [1.6, 1.4, s * 1.006], [0, 0, s], 0.5, 0.4, 0); } + B.col(0, 0, 6.6, 2.3, 0, 2.4, 0, 'metal', 'truck'); + return { light: { x: 3.2, y: 1.2, z: 0, color: 0xffd8a0, r: 14, power: 0 } }; + }; + + // ---- camp dressing: notice board, bare flag mast, duckboards, ridge tent, wash line, water tower, target frame + const C = (r, g, b) => new THREE.Color(r, g, b); + KINDS.noticeboard = (B, R) => { + for (const s of [-1, 1]) B.box('timber', s * 0.8, 0, 0, 0.1, 2.1, 0.1, 0, { grain: 'long' }); + B.box('planks', 0, 0.9, 0, 1.5, 0.95, 0.04, 0, { tint: C(0.72, 0.7, 0.62) }); + B.box('timber', 0, 2.0, 0.04, 1.8, 0.04, 0.42, 0, { rx: 0.35, noFoot: true, tint: C(0.6, 0.58, 0.55) }); + // pinned notices: pale cards, a few curling, one rain-stained + for (let k = 0; k < 6; k++) { const w = R.range(0.2, 0.32), h = R.range(0.25, 0.38); B.box('canvas', -0.55 + (k % 3) * 0.48 + R.range(-0.04, 0.04), 0.98 + (k > 2 ? 0 : 0.42) + R.range(-0.03, 0.03), 0.025, w, h, 0.004, R.range(-0.04, 0.04), { noFoot: true, tint: C(1.25, 1.22, 1.08).multiplyScalar(R.range(0.75, 1)) }); } + B.decal('waterstain', [0, 1.3, 0.03], [0, 0, 1], 1.4, 0.8, 0); B.decal('moss', [0.8, 0.15, 0.055], [0, 0, 1], 0.12, 0.3, 0); + B.col(0, 0, 1.7, 0.2, 0, 2.1, 0, 'wood', 'board'); + }; + KINDS.flagpole = (B, R) => { + // a bare white mast with a halyard and cleat; no flag is flown on the training ground + const h = 9; + B.geo('metal_painted', cyl(0.045, 0.09, h, 10), M4(0, h / 2, 0), { tint: C(1.5, 1.5, 1.45) }); + B.geo('metal_painted', new THREE.SphereGeometry(0.1, 8, 6), M4(0, h + 0.05, 0), { noFoot: true, tint: C(1.5, 1.5, 1.45) }); + B.geo('canvas', cyl(0.006, 0.006, h - 1.2, 3), M4(0.06, h / 2 + 0.5, 0), { noFoot: true, tint: C(0.8, 0.78, 0.7) }); + B.box('metal_rust', 0.09, 1.2, 0, 0.04, 0.16, 0.04, 0, { noFoot: true }); + // whitewashed kerb stones round the foot + for (let k = 0; k < 10; k++) { const a = k / 10 * TAU; B.box('ashlar', Math.cos(a) * 1.1, 0, Math.sin(a) * 1.1, 0.34, 0.14, 0.18, -a + Math.PI / 2, { tint: C(1.3, 1.3, 1.25) }); } + B.decal('chipped', [0, 0.5, 0.06], [0, 0, 1], 0.12, 0.4, 0); + B.col(0, 0, 0.2, 0.2, 0, h, 0, 'wood', 'pole'); + }; + KINDS.duckboards = (B, R, o) => { + // slatted walkway sections on two bearers, slightly askew, sunk in at the ends + const L = o.length || 6, n = Math.max(1, Math.round(L / 2)); + for (let i = 0; i < n; i++) { + const x0 = -L / 2 + (i + 0.5) * (L / n), tw = R.range(-0.04, 0.04), dy = R.range(-0.03, 0.01); + for (const s of [-1, 1]) B.box('timber', x0, dy, s * 0.22, L / n - 0.06, 0.07, 0.07, tw, { grain: 'long', tint: C(0.55, 0.52, 0.48) }); + for (let k = 0; k < Math.round((L / n) / 0.16); k++) B.box('planks', x0 - (L / n) / 2 + 0.08 + k * 0.16, dy + 0.07, 0, 0.1, 0.03, 0.62, tw, { tint: E.tintJ(R, 0.1, 0x8a8070), noFoot: true }); + } + B.decal('mud', [0, 0.11, 0], [0, 1, 0], L * 0.8, 0.5, 0); + }; + KINDS.tent = (B, R) => { + // a ridge tent: canvas sheet over a ridge pole, walls guyed out, flaps half tied + const L = 3.6, W2 = 1.35, H = 2.0, wall = 0.45; + const g = new THREE.BufferGeometry(), P = [], I = [], UV = []; + const nx = 10, ny = 6; + for (let side of [-1, 1]) { + const b0 = P.length / 3; + for (let j = 0; j <= ny; j++) for (let i = 0; i <= nx; i++) { + const u = i / nx, v = j / ny, x = -L / 2 + u * L, sag = 0.06 * Math.sin(u * Math.PI * 3) ** 2 * Math.sin(v * Math.PI); + const z = side * (W2 * (1 - v)), y = wall + (H - wall) * v - sag + (j === 0 ? 0 : 0); + P.push(x, y, z + side * sag * 0.5); UV.push(u * L, v * 1.6); + } + for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) { const a = b0 + j * (nx + 1) + i, b = a + 1, c = a + nx + 1, d = c + 1; if (side > 0) I.push(a, b, d, a, d, c); else I.push(a, d, b, a, c, d); } + // the short wall + const w0 = P.length / 3; for (let i = 0; i <= nx; i++) { const x = -L / 2 + i / nx * L; P.push(x, 0, side * W2, x, wall, side * W2); UV.push(i / nx * L, 0, i / nx * L, 0.45); } + for (let i = 0; i < nx; i++) { const a = w0 + i * 2; if (side > 0) I.push(a, a + 2, a + 3, a, a + 3, a + 1); else I.push(a, a + 3, a + 2, a, a + 1, a + 3); } + } + g.setAttribute('position', new THREE.Float32BufferAttribute(P, 3)); g.setAttribute('uv', new THREE.Float32BufferAttribute(UV, 2)); g.setIndex(I); g.computeVertexNormals(); + B.geo('canvas', g, M4(0, 0, 0), { keepUv: true, tint: E.tintJ(R, 0.08, 0xb8b090) }); + // gable ends: back closed, front a dark opening with a tied flap + for (const e of [-1, 1]) { const t = new THREE.BufferGeometry(); t.setAttribute('position', new THREE.Float32BufferAttribute([e * L / 2, 0, -W2, e * L / 2, 0, W2, e * L / 2, H, 0, e * L / 2, wall, -W2, e * L / 2, wall, W2], 3)); t.setIndex(e > 0 ? [0, 2, 1] : [0, 1, 2]); t.computeVertexNormals(); B.geo('canvas', t, M4(0, 0, 0), { tint: e > 0 ? C(0.25, 0.24, 0.2) : E.tintJ(R, 0.08, 0xb0a888) }); } + B.box('canvas', L / 2 + 0.02, 0.2, -0.55, 0.05, 1.5, 0.5, 0, { rz: 0.1, tint: C(0.7, 0.68, 0.56) }); + for (const e of [-1, 1]) { B.box('timber', e * (L / 2 - 0.05), 0, 0, 0.05, H + 0.15, 0.05, 0, { grain: 'long' }); for (const s of [-1, 1]) B.geo('canvas', cyl(0.006, 0.006, 1.5, 3), M4(e * (L / 2 + 0.55), H * 0.5, s * (W2 * 0.6), 0, 0, e * 0.9), { noFoot: true, tint: C(0.7, 0.68, 0.6) }); } + B.decal('mud', [0, 0.02, W2 + 0.2], [0, 1, 0], L, 0.6, 0); B.decal('mud', [L / 2 + 0.5, 0.02, 0], [0, 1, 0], 1.2, 1.4, 0); + B.col(0, 0, L, W2 * 2, 0, H, 0, 'cloth', 'tent'); + }; + KINDS.washline = (B, R, o) => { + const L = o.length || 6; + for (const s of [-1, 1]) B.box('timber', s * L / 2, 0, 0, 0.09, 2.0, 0.09, 0, { grain: 'long', rz: s * 0.04 }); + B.geo('canvas', cyl(0.006, 0.006, L, 3).rotateZ(Math.PI / 2), M4(0, 1.88, 0), { noFoot: true, tint: C(0.75, 0.72, 0.65) }); + // shirts, socks and a towel: greys, khakis, one faded white + let x = -L / 2 + 0.5; + while (x < L / 2 - 0.5) { const w = R.range(0.25, 0.7), h = R.range(0.3, 0.75), sag = 0.05 * (1 - (2 * x / L) ** 2); B.box('canvas', x + w / 2, 1.88 - sag - h, 0, w, h, 0.01, R.range(-0.08, 0.08), { noFoot: true, tint: [C(0.6, 0.6, 0.5), C(0.75, 0.7, 0.55), C(1.1, 1.08, 1.0), C(0.45, 0.47, 0.42)][(R() * 4) | 0] }); x += w + R.range(0.12, 0.4); } + }; + KINDS.watertower = (B, R) => { + // a timber trestle with cross-bracing carrying a riveted steel tank, a ladder up one leg + const h = 7.5, s = 1.6; + for (const a of [-1, 1]) for (const b of [-1, 1]) B.box('timber', a * s, 0, b * s, 0.26, h, 0.26, 0, { grain: 'long', tint: C(0.65, 0.6, 0.55), rx: -b * 0.03, rz: a * 0.03 }); + for (const y of [2.4, 5.0]) for (const side of [0, 1]) for (const k of [-1, 1]) { + const len = Math.hypot(2 * s, 2.4); if (side) B.box('timber', k * s, y - 2.25, 0, 0.1, 0.12, len, 0, { rx: Math.atan2(2.4, 2 * s) * (y > 3 ? 1 : -1), noFoot: true, grain: 'long' }); else B.box('timber', 0, y - 2.25, k * s, len, 0.12, 0.1, 0, { rz: Math.atan2(2.4, 2 * s) * (y > 3 ? -1 : 1), noFoot: true, grain: 'long' }); } + for (const y of [0.4, h - 0.2]) for (const k of [-1, 1]) { B.box('timber', 0, y, k * s, 2 * s + 0.3, 0.16, 0.14, 0, { grain: 'long', noFoot: true }); B.box('timber', k * s, y, 0, 0.14, 0.16, 2 * s + 0.3, 0, { grain: 'long', noFoot: true }); } + B.box('planks', 0, h, 0, 2 * s + 0.6, 0.12, 2 * s + 0.6, 0, { noFoot: true }); + B.geo('metal_painted', cyl(2.0, 2.0, 2.7, 20), M4(0, h + 0.12 + 1.35, 0), { tint: C(0.5, 0.52, 0.48), keepUv: true, uvW: 12.6, uvH: 2.7 }); + B.geo('metal_painted', new THREE.ConeGeometry(2.1, 0.5, 20), M4(0, h + 0.12 + 2.95, 0), { noFoot: true, tint: C(0.45, 0.46, 0.43) }); + for (const yy of [0.05, 0.95, 1.85, 2.65]) B.geo('metal_rust', new THREE.TorusGeometry(2.01, 0.025, 4, 28).rotateX(Math.PI / 2), M4(0, h + 0.12 + yy, 0), { noFoot: true }); + B.geo('metal_rust', cyl(0.09, 0.09, h + 0.2, 8), M4(0.4, (h + 0.2) / 2, 0.3), { noFoot: true }); + for (let k = 0; k < 24; k++) B.box('metal_rust', s + 0.2, 0.3 + k * 0.3, s + 0.05, 0.4, 0.03, 0.03, 0.785, { noFoot: true }); + B.decal('rust', [1.42, h + 1.4, 1.42], [0.71, 0, 0.71], 0.6, 2.2, 0); B.decal('rust', [-2.01, h + 1.0, 0], [-1, 0, 0], 1.2, 1.8, 0); + B.decal('waterstain', [0, 0.02, 0], [0, 1, 0], 3.6, 3.6, 0); + for (const a of [-1, 1]) for (const b of [-1, 1]) B.col(a * s, b * s, 0.3, 0.3, 0, h, 0, 'wood', 'tower'); + }; + KINDS.targetframe = (B, R, o) => { + // a range target frame: two uprights, a paper-faced board, patched; spare frames lean on the butts + const w = 1.2, h = 1.6; + for (const s of [-1, 1]) B.box('timber', s * (w / 2 + 0.04), 0, 0, 0.08, h + 0.6, 0.08, 0, { grain: 'long' }); + B.box('canvas', 0, 0.6, 0, w, h, 0.02, 0, { tint: C(1.05, 1.0, 0.85) }); + B.box('timber', 0, 0.6, -0.03, w + 0.1, 0.06, 0.04, 0, { noFoot: true }); B.box('timber', 0, 0.6 + h - 0.06, -0.03, w + 0.1, 0.06, 0.04, 0, { noFoot: true }); + for (let k = 0; k < 7; k++) B.box('canvas', R.range(-0.45, 0.45), 0.8 + R.range(0, h - 0.4), 0.012, 0.06, 0.06, 0.004, R() * 0.8, { noFoot: true, tint: C(0.55, 0.5, 0.4) }); + B.decal('mud', [0, 0.7, 0.02], [0, 0, 1], w, 0.3, 0); + B.col(0, 0, w + 0.2, 0.15, 0, h + 0.6, 0, 'wood', 'target'); + }; + KINDS.car = (B, R) => { + // a plain staff car of the period: long bonnet, upright cab, separate wings and running boards, no markings + const paint = new THREE.Color(0.32, 0.34, 0.27); + B.box('metal_painted', 0.2, 0.42, 0, 4.1, 0.55, 1.5, 0, { tint: paint }); + B.box('metal_painted', -0.55, 0.97, 0, 2.0, 0.62, 1.42, 0, { tint: paint }); + B.box('glass', 0.47, 1.0, 0, 0.04, 0.5, 1.28, 0, { rz: 0.35, noFoot: true }); + for (const sz of [-1, 1]) { B.box('glass', -0.55, 1.05, sz * 0.715, 1.6, 0.42, 0.02, 0, { noFoot: true }); B.box('metal_painted', 0.15, 0.32, sz * 0.83, 3.4, 0.05, 0.22, 0, { tint: paint, noFoot: true }); } + for (const [x, sz] of [[1.45, -1], [1.45, 1], [-1.3, -1], [-1.3, 1]]) { B.geo('metal_rust', new THREE.CylinderGeometry(0.36, 0.36, 0.2, 14).rotateX(Math.PI / 2), M4(x, 0.36, sz * 0.72), { tint: new THREE.Color(0.12, 0.12, 0.12) }); B.box('metal_painted', x, 0.62, sz * 0.72, 0.9, 0.12, 0.34, 0, { tint: paint, noFoot: true }); } + for (const sz of [-0.45, 0.45]) B.geo('glass_lit', new THREE.SphereGeometry(0.11, 8, 6), M4(2.22, 0.78, sz), { noFoot: true }); + B.decal('mud', [0, 0.35, 0.76], [0, 0, 1], 3.6, 0.5, 0); B.decal('mud', [0, 0.35, -0.76], [0, 0, -1], 3.6, 0.5, 0); + B.col(0.1, 0, 4.4, 1.7, 0, 1.6, 0, 'metal', 'car'); + }; + KINDS.guardtower = (B, R) => { + // a timber sentry tower: four braced legs, a boarded box with a roof, a ladder + const h = 5.2, s = 1.4; + for (const a of [-1, 1]) for (const b of [-1, 1]) B.box('timber', a * s, 0, b * s, 0.2, h + 2.2, 0.2, 0, { grain: 'long', rx: -b * 0.04, rz: a * 0.04 }); + for (const k of [-1, 1]) { B.box('timber', 0, 2.2, k * s, 2 * s, 0.1, 0.1, 0, { rz: 0.9, noFoot: true }); B.box('timber', k * s, 2.2, 0, 0.1, 0.1, 2 * s, 0, { rx: 0.9, noFoot: true }); } + B.box('planks', 0, h, 0, 2 * s + 0.6, 0.12, 2 * s + 0.6, 0, { noFoot: true }); + for (const k of [-1, 1]) { B.box('planks', 0, h + 0.12, k * (s + 0.3), 2 * s + 0.6, 1.0, 0.05, 0, { noFoot: true }); B.box('planks', k * (s + 0.3), h + 0.12, 0, 0.05, 1.0, 2 * s + 0.6, 0, { noFoot: true }); } + B.box('slate', 0, h + 2.2, 0, 2 * s + 1.2, 0.08, 2 * s + 1.2, 0, { noFoot: true, rx: 0.12 }); + for (let k = 0; k < 17; k++) B.box('timber', 0, 0.3 + k * 0.3, s + 0.55, 0.5, 0.04, 0.05, 0, { noFoot: true }); + for (const a of [-0.25, 0.25]) B.box('timber', a, 0, s + 0.55, 0.06, h + 0.2, 0.06, 0, { noFoot: true }); + B.decal('mud', [0, 0.02, 0], [0, 1, 0], 4, 4, 0); + for (const a of [-1, 1]) for (const b of [-1, 1]) B.col(a * s, b * s, 0.3, 0.3, 0, h, 0, 'wood', 'tower'); + }; + KINDS.shelter = (B, R) => { + // an open firing-point shelter: posts and a lean-to roof, a bench and an ammunition table + const w = 6, d = 3; + for (const a of [-1, 1]) for (const b of [-1, 1]) B.box('timber', a * (w / 2 - 0.1), 0, b * (d / 2 - 0.1), 0.14, b > 0 ? 2.5 : 2.2, 0.14, 0, { grain: 'long' }); + B.box('slate', 0, 2.3, 0, w + 0.5, 0.06, d + 0.6, 0, { rx: -0.1, noFoot: true }); + B.box('planks', 0, 0.42, -d / 2 + 0.4, w - 0.6, 0.06, 0.35, 0, {}); B.box('planks', 0, 0.75, 0.4, 2.2, 0.06, 0.8, 0, {}); + B.col(0, 0, w, d, 0, 2.4, 0, 'wood', 'shelter'); + }; + KINDS.aframe = (B, R) => { + // an assault-course climbing frame: two A legs, rungs, a scramble net strung on poles + for (const a of [-1.6, 1.6]) for (const b of [-1, 1]) B.box('timber', a, 0, b * 0.9, 0.16, 3.6, 0.16, 0, { grain: 'long', rx: -b * 0.26 }); + for (let k = 0; k < 6; k++) B.box('timber', 0, 0.5 + k * 0.5, 0.75 - k * 0.12, 3.6, 0.08, 0.08, 0, { noFoot: true }); + B.box('canvas', 0, 1.0, -0.6, 3.2, 2.2, 0.02, 0, { rx: 0.26, noFoot: true, tint: new THREE.Color(0.45, 0.42, 0.34) }); + }; + E.prop = function (kind, seed, opts) { + opts = opts || {}; + const fn = KINDS[kind] || KINDS[({ 'sandbag wall': 'sandbags', 'hay bale': 'haybale', 'hay stack': 'haystack', 'water trough': 'trough', 'telegraph pole': 'telegraph', 'lamp post': 'lamppost', 'fuel drums': 'drums', 'ammunition boxes': 'ammo', 'log pile': 'logpile', 'tarpaulin stack': 'tarp' })[kind]]; + if (!fn) throw new Error('IVEnv.prop: unknown kind ' + kind); + const B = E.builder(seed || 1), R = E.rng((seed || 1) * 13 + 5); B._extra = []; + const extra = fn(B, R, opts) || {}; + const group = B.finish(); group.name = 'IVEnv.prop:' + kind; + for (const x of B._extra) group.add(x); + const lights = extra.light ? [extra.light] : []; + if (extra.light && kind === 'lamppost') group.add(E.glowSprite(extra.light)); + if (extra.wireTop) group.userData.wireTop = extra.wireTop; + return { group, colliders: B.colliders, lights, door: extra.door }; + }; + // a soft halo around a lamp (moist night air), additive, never above the threshold that would strobe + let glowTex = null; + E.glowSprite = function (l) { + if (!glowTex) { const c = document.createElement('canvas'); c.width = c.height = 64; const g = c.getContext('2d'), gr = g.createRadialGradient(32, 32, 0, 32, 32, 32); gr.addColorStop(0, 'rgba(255,255,255,1)'); gr.addColorStop(0.2, 'rgba(255,255,255,0.35)'); gr.addColorStop(1, 'rgba(255,255,255,0)'); g.fillStyle = gr; g.fillRect(0, 0, 64, 64); glowTex = new THREE.CanvasTexture(c); } + const m = new THREE.SpriteMaterial({ map: glowTex, color: new THREE.Color(l.color).multiplyScalar(0.18), blending: THREE.AdditiveBlending, depthWrite: false, transparent: true }); + const s = new THREE.Sprite(m); s.position.set(l.x, l.y + 0.05, l.z); s.scale.set(1.2, 1.2, 1); s.userData.dynamic = true; s.name = 'lamp-glow'; return s; + }; +})(); diff --git a/e63334287a3deaa3/ironveil/env/scans/ashlar.512.alb.webp b/e63334287a3deaa3/ironveil/env/scans/ashlar.512.alb.webp new file mode 100644 index 00000000..b8cf16ba Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/ashlar.512.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/ashlar.512.h.webp b/e63334287a3deaa3/ironveil/env/scans/ashlar.512.h.webp new file mode 100644 index 00000000..5294d079 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/ashlar.512.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/ashlar.512.nr.webp b/e63334287a3deaa3/ironveil/env/scans/ashlar.512.nr.webp new file mode 100644 index 00000000..13540636 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/ashlar.512.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/ashlar.alb.webp b/e63334287a3deaa3/ironveil/env/scans/ashlar.alb.webp new file mode 100644 index 00000000..848d3ed2 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/ashlar.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/ashlar.h.webp b/e63334287a3deaa3/ironveil/env/scans/ashlar.h.webp new file mode 100644 index 00000000..f7c5088b Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/ashlar.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/ashlar.nr.webp b/e63334287a3deaa3/ironveil/env/scans/ashlar.nr.webp new file mode 100644 index 00000000..6bd133e1 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/ashlar.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/brick_red.512.alb.webp b/e63334287a3deaa3/ironveil/env/scans/brick_red.512.alb.webp new file mode 100644 index 00000000..25b542a6 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/brick_red.512.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/brick_red.512.h.webp b/e63334287a3deaa3/ironveil/env/scans/brick_red.512.h.webp new file mode 100644 index 00000000..c06ec812 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/brick_red.512.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/brick_red.512.nr.webp b/e63334287a3deaa3/ironveil/env/scans/brick_red.512.nr.webp new file mode 100644 index 00000000..89e9f149 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/brick_red.512.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/brick_red.alb.webp b/e63334287a3deaa3/ironveil/env/scans/brick_red.alb.webp new file mode 100644 index 00000000..4843df0d Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/brick_red.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/brick_red.h.webp b/e63334287a3deaa3/ironveil/env/scans/brick_red.h.webp new file mode 100644 index 00000000..1cdd346f Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/brick_red.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/brick_red.nr.webp b/e63334287a3deaa3/ironveil/env/scans/brick_red.nr.webp new file mode 100644 index 00000000..a9079d75 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/brick_red.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/brick_sooty.512.alb.webp b/e63334287a3deaa3/ironveil/env/scans/brick_sooty.512.alb.webp new file mode 100644 index 00000000..5b7737d2 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/brick_sooty.512.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/brick_sooty.512.h.webp b/e63334287a3deaa3/ironveil/env/scans/brick_sooty.512.h.webp new file mode 100644 index 00000000..ca6e13bd Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/brick_sooty.512.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/brick_sooty.512.nr.webp b/e63334287a3deaa3/ironveil/env/scans/brick_sooty.512.nr.webp new file mode 100644 index 00000000..9674472d Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/brick_sooty.512.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/brick_sooty.alb.webp b/e63334287a3deaa3/ironveil/env/scans/brick_sooty.alb.webp new file mode 100644 index 00000000..a3caee16 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/brick_sooty.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/brick_sooty.h.webp b/e63334287a3deaa3/ironveil/env/scans/brick_sooty.h.webp new file mode 100644 index 00000000..9b2180bc Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/brick_sooty.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/brick_sooty.nr.webp b/e63334287a3deaa3/ironveil/env/scans/brick_sooty.nr.webp new file mode 100644 index 00000000..a389dbc0 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/brick_sooty.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/cobbles.512.alb.webp b/e63334287a3deaa3/ironveil/env/scans/cobbles.512.alb.webp new file mode 100644 index 00000000..2f3dc517 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/cobbles.512.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/cobbles.512.h.webp b/e63334287a3deaa3/ironveil/env/scans/cobbles.512.h.webp new file mode 100644 index 00000000..389a6040 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/cobbles.512.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/cobbles.512.nr.webp b/e63334287a3deaa3/ironveil/env/scans/cobbles.512.nr.webp new file mode 100644 index 00000000..abe50229 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/cobbles.512.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/cobbles.alb.webp b/e63334287a3deaa3/ironveil/env/scans/cobbles.alb.webp new file mode 100644 index 00000000..e498a4b6 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/cobbles.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/cobbles.h.webp b/e63334287a3deaa3/ironveil/env/scans/cobbles.h.webp new file mode 100644 index 00000000..1da2b590 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/cobbles.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/cobbles.nr.webp b/e63334287a3deaa3/ironveil/env/scans/cobbles.nr.webp new file mode 100644 index 00000000..34bac63b Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/cobbles.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/concrete.512.alb.webp b/e63334287a3deaa3/ironveil/env/scans/concrete.512.alb.webp new file mode 100644 index 00000000..01e688b7 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/concrete.512.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/concrete.512.h.webp b/e63334287a3deaa3/ironveil/env/scans/concrete.512.h.webp new file mode 100644 index 00000000..18a030e5 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/concrete.512.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/concrete.512.nr.webp b/e63334287a3deaa3/ironveil/env/scans/concrete.512.nr.webp new file mode 100644 index 00000000..84badffd Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/concrete.512.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/concrete.alb.webp b/e63334287a3deaa3/ironveil/env/scans/concrete.alb.webp new file mode 100644 index 00000000..bfbe24d3 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/concrete.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/concrete.h.webp b/e63334287a3deaa3/ironveil/env/scans/concrete.h.webp new file mode 100644 index 00000000..fecce512 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/concrete.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/concrete.nr.webp b/e63334287a3deaa3/ironveil/env/scans/concrete.nr.webp new file mode 100644 index 00000000..f63cc43d Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/concrete.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/earth.512.alb.webp b/e63334287a3deaa3/ironveil/env/scans/earth.512.alb.webp new file mode 100644 index 00000000..71fcc6fc Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/earth.512.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/earth.512.h.webp b/e63334287a3deaa3/ironveil/env/scans/earth.512.h.webp new file mode 100644 index 00000000..b102a61b Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/earth.512.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/earth.512.nr.webp b/e63334287a3deaa3/ironveil/env/scans/earth.512.nr.webp new file mode 100644 index 00000000..945f6f49 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/earth.512.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/earth.alb.webp b/e63334287a3deaa3/ironveil/env/scans/earth.alb.webp new file mode 100644 index 00000000..9d12d6cd Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/earth.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/earth.h.webp b/e63334287a3deaa3/ironveil/env/scans/earth.h.webp new file mode 100644 index 00000000..67f39b2a Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/earth.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/earth.nr.webp b/e63334287a3deaa3/ironveil/env/scans/earth.nr.webp new file mode 100644 index 00000000..d246896a Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/earth.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/fieldstone.512.alb.webp b/e63334287a3deaa3/ironveil/env/scans/fieldstone.512.alb.webp new file mode 100644 index 00000000..c0764257 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/fieldstone.512.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/fieldstone.512.h.webp b/e63334287a3deaa3/ironveil/env/scans/fieldstone.512.h.webp new file mode 100644 index 00000000..86c3daaf Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/fieldstone.512.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/fieldstone.512.nr.webp b/e63334287a3deaa3/ironveil/env/scans/fieldstone.512.nr.webp new file mode 100644 index 00000000..10d45f74 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/fieldstone.512.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/fieldstone.alb.webp b/e63334287a3deaa3/ironveil/env/scans/fieldstone.alb.webp new file mode 100644 index 00000000..dd5eaa70 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/fieldstone.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/fieldstone.h.webp b/e63334287a3deaa3/ironveil/env/scans/fieldstone.h.webp new file mode 100644 index 00000000..ed3537de Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/fieldstone.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/fieldstone.nr.webp b/e63334287a3deaa3/ironveil/env/scans/fieldstone.nr.webp new file mode 100644 index 00000000..f1e81b2d Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/fieldstone.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/floorboards.512.alb.webp b/e63334287a3deaa3/ironveil/env/scans/floorboards.512.alb.webp new file mode 100644 index 00000000..91d31023 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/floorboards.512.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/floorboards.512.h.webp b/e63334287a3deaa3/ironveil/env/scans/floorboards.512.h.webp new file mode 100644 index 00000000..cab26cad Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/floorboards.512.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/floorboards.512.nr.webp b/e63334287a3deaa3/ironveil/env/scans/floorboards.512.nr.webp new file mode 100644 index 00000000..7deb2601 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/floorboards.512.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/floorboards.alb.webp b/e63334287a3deaa3/ironveil/env/scans/floorboards.alb.webp new file mode 100644 index 00000000..6bde3a38 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/floorboards.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/floorboards.h.webp b/e63334287a3deaa3/ironveil/env/scans/floorboards.h.webp new file mode 100644 index 00000000..bd6ece2d Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/floorboards.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/floorboards.nr.webp b/e63334287a3deaa3/ironveil/env/scans/floorboards.nr.webp new file mode 100644 index 00000000..12aaaa0a Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/floorboards.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/grass_ground.512.alb.webp b/e63334287a3deaa3/ironveil/env/scans/grass_ground.512.alb.webp new file mode 100644 index 00000000..e729037c Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/grass_ground.512.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/grass_ground.512.h.webp b/e63334287a3deaa3/ironveil/env/scans/grass_ground.512.h.webp new file mode 100644 index 00000000..dfc0fb80 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/grass_ground.512.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/grass_ground.512.nr.webp b/e63334287a3deaa3/ironveil/env/scans/grass_ground.512.nr.webp new file mode 100644 index 00000000..b8ed75d3 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/grass_ground.512.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/grass_ground.alb.webp b/e63334287a3deaa3/ironveil/env/scans/grass_ground.alb.webp new file mode 100644 index 00000000..71f9177a Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/grass_ground.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/grass_ground.h.webp b/e63334287a3deaa3/ironveil/env/scans/grass_ground.h.webp new file mode 100644 index 00000000..f42edc61 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/grass_ground.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/grass_ground.nr.webp b/e63334287a3deaa3/ironveil/env/scans/grass_ground.nr.webp new file mode 100644 index 00000000..c54998cc Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/grass_ground.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/gravel.512.alb.webp b/e63334287a3deaa3/ironveil/env/scans/gravel.512.alb.webp new file mode 100644 index 00000000..f7da08cc Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/gravel.512.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/gravel.512.h.webp b/e63334287a3deaa3/ironveil/env/scans/gravel.512.h.webp new file mode 100644 index 00000000..1bddca66 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/gravel.512.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/gravel.512.nr.webp b/e63334287a3deaa3/ironveil/env/scans/gravel.512.nr.webp new file mode 100644 index 00000000..e2684933 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/gravel.512.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/gravel.alb.webp b/e63334287a3deaa3/ironveil/env/scans/gravel.alb.webp new file mode 100644 index 00000000..dd49813e Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/gravel.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/gravel.h.webp b/e63334287a3deaa3/ironveil/env/scans/gravel.h.webp new file mode 100644 index 00000000..56e60675 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/gravel.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/gravel.nr.webp b/e63334287a3deaa3/ironveil/env/scans/gravel.nr.webp new file mode 100644 index 00000000..49e20ef1 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/gravel.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/mud.512.alb.webp b/e63334287a3deaa3/ironveil/env/scans/mud.512.alb.webp new file mode 100644 index 00000000..f54f1159 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/mud.512.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/mud.512.h.webp b/e63334287a3deaa3/ironveil/env/scans/mud.512.h.webp new file mode 100644 index 00000000..9ec89036 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/mud.512.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/mud.512.nr.webp b/e63334287a3deaa3/ironveil/env/scans/mud.512.nr.webp new file mode 100644 index 00000000..ae91ef02 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/mud.512.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/mud.alb.webp b/e63334287a3deaa3/ironveil/env/scans/mud.alb.webp new file mode 100644 index 00000000..55bc2a76 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/mud.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/mud.h.webp b/e63334287a3deaa3/ironveil/env/scans/mud.h.webp new file mode 100644 index 00000000..258a8cde Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/mud.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/mud.nr.webp b/e63334287a3deaa3/ironveil/env/scans/mud.nr.webp new file mode 100644 index 00000000..b80c9a80 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/mud.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/planks.512.alb.webp b/e63334287a3deaa3/ironveil/env/scans/planks.512.alb.webp new file mode 100644 index 00000000..9c4b9abc Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/planks.512.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/planks.512.h.webp b/e63334287a3deaa3/ironveil/env/scans/planks.512.h.webp new file mode 100644 index 00000000..0fba1a94 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/planks.512.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/planks.512.nr.webp b/e63334287a3deaa3/ironveil/env/scans/planks.512.nr.webp new file mode 100644 index 00000000..b3e90650 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/planks.512.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/planks.alb.webp b/e63334287a3deaa3/ironveil/env/scans/planks.alb.webp new file mode 100644 index 00000000..b03fde70 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/planks.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/planks.h.webp b/e63334287a3deaa3/ironveil/env/scans/planks.h.webp new file mode 100644 index 00000000..9b4bd2d6 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/planks.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/planks.nr.webp b/e63334287a3deaa3/ironveil/env/scans/planks.nr.webp new file mode 100644 index 00000000..530b12ec Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/planks.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/plaster.512.alb.webp b/e63334287a3deaa3/ironveil/env/scans/plaster.512.alb.webp new file mode 100644 index 00000000..2feba4fc Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/plaster.512.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/plaster.512.h.webp b/e63334287a3deaa3/ironveil/env/scans/plaster.512.h.webp new file mode 100644 index 00000000..4c7ff374 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/plaster.512.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/plaster.512.nr.webp b/e63334287a3deaa3/ironveil/env/scans/plaster.512.nr.webp new file mode 100644 index 00000000..9cadf626 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/plaster.512.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/plaster.alb.webp b/e63334287a3deaa3/ironveil/env/scans/plaster.alb.webp new file mode 100644 index 00000000..9bcde143 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/plaster.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/plaster.h.webp b/e63334287a3deaa3/ironveil/env/scans/plaster.h.webp new file mode 100644 index 00000000..bea8765e Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/plaster.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/plaster.nr.webp b/e63334287a3deaa3/ironveil/env/scans/plaster.nr.webp new file mode 100644 index 00000000..1c7aa20f Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/plaster.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/roof_tile.512.alb.webp b/e63334287a3deaa3/ironveil/env/scans/roof_tile.512.alb.webp new file mode 100644 index 00000000..56066af1 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/roof_tile.512.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/roof_tile.512.h.webp b/e63334287a3deaa3/ironveil/env/scans/roof_tile.512.h.webp new file mode 100644 index 00000000..5e69300a Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/roof_tile.512.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/roof_tile.512.nr.webp b/e63334287a3deaa3/ironveil/env/scans/roof_tile.512.nr.webp new file mode 100644 index 00000000..99364ccc Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/roof_tile.512.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/roof_tile.alb.webp b/e63334287a3deaa3/ironveil/env/scans/roof_tile.alb.webp new file mode 100644 index 00000000..2b55ec7d Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/roof_tile.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/roof_tile.h.webp b/e63334287a3deaa3/ironveil/env/scans/roof_tile.h.webp new file mode 100644 index 00000000..3540a90e Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/roof_tile.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/roof_tile.nr.webp b/e63334287a3deaa3/ironveil/env/scans/roof_tile.nr.webp new file mode 100644 index 00000000..e6e23807 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/roof_tile.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/slate.512.alb.webp b/e63334287a3deaa3/ironveil/env/scans/slate.512.alb.webp new file mode 100644 index 00000000..e114dd13 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/slate.512.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/slate.512.h.webp b/e63334287a3deaa3/ironveil/env/scans/slate.512.h.webp new file mode 100644 index 00000000..729cfbf3 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/slate.512.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/slate.512.nr.webp b/e63334287a3deaa3/ironveil/env/scans/slate.512.nr.webp new file mode 100644 index 00000000..87d65547 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/slate.512.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/slate.alb.webp b/e63334287a3deaa3/ironveil/env/scans/slate.alb.webp new file mode 100644 index 00000000..08945498 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/slate.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/slate.h.webp b/e63334287a3deaa3/ironveil/env/scans/slate.h.webp new file mode 100644 index 00000000..41883fc3 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/slate.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/slate.nr.webp b/e63334287a3deaa3/ironveil/env/scans/slate.nr.webp new file mode 100644 index 00000000..a5dca346 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/slate.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/timber.512.alb.webp b/e63334287a3deaa3/ironveil/env/scans/timber.512.alb.webp new file mode 100644 index 00000000..28c17ef2 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/timber.512.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/timber.512.h.webp b/e63334287a3deaa3/ironveil/env/scans/timber.512.h.webp new file mode 100644 index 00000000..65d851c4 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/timber.512.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/timber.512.nr.webp b/e63334287a3deaa3/ironveil/env/scans/timber.512.nr.webp new file mode 100644 index 00000000..0cac3550 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/timber.512.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/timber.alb.webp b/e63334287a3deaa3/ironveil/env/scans/timber.alb.webp new file mode 100644 index 00000000..d22e2b82 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/timber.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/timber.h.webp b/e63334287a3deaa3/ironveil/env/scans/timber.h.webp new file mode 100644 index 00000000..e8e8497a Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/timber.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/timber.nr.webp b/e63334287a3deaa3/ironveil/env/scans/timber.nr.webp new file mode 100644 index 00000000..768c5737 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/timber.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/wood_painted.512.alb.webp b/e63334287a3deaa3/ironveil/env/scans/wood_painted.512.alb.webp new file mode 100644 index 00000000..d3cdf455 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/wood_painted.512.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/wood_painted.512.h.webp b/e63334287a3deaa3/ironveil/env/scans/wood_painted.512.h.webp new file mode 100644 index 00000000..b4f3c06a Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/wood_painted.512.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/wood_painted.512.nr.webp b/e63334287a3deaa3/ironveil/env/scans/wood_painted.512.nr.webp new file mode 100644 index 00000000..8c32b82d Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/wood_painted.512.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/wood_painted.alb.webp b/e63334287a3deaa3/ironveil/env/scans/wood_painted.alb.webp new file mode 100644 index 00000000..0f2f0b86 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/wood_painted.alb.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/wood_painted.h.webp b/e63334287a3deaa3/ironveil/env/scans/wood_painted.h.webp new file mode 100644 index 00000000..10697882 Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/wood_painted.h.webp differ diff --git a/e63334287a3deaa3/ironveil/env/scans/wood_painted.nr.webp b/e63334287a3deaa3/ironveil/env/scans/wood_painted.nr.webp new file mode 100644 index 00000000..18ab7ddd Binary files /dev/null and b/e63334287a3deaa3/ironveil/env/scans/wood_painted.nr.webp differ diff --git a/e63334287a3deaa3/ironveil/env/texgen.js b/e63334287a3deaa3/ironveil/env/texgen.js new file mode 100644 index 00000000..b1f4860b --- /dev/null +++ b/e63334287a3deaa3/ironveil/env/texgen.js @@ -0,0 +1,829 @@ +/* Midnight Ops environment: texture generator. Plain JavaScript with no three.js, so the same file runs on the page and + inside Web Workers (see IVEnv.load in core.js). Every material is made HEIGHT FIRST: a height field in 0..1 is built + per brick / stone / board / tile, then the normal map, roughness and baked cavity are derived from it. + Output per material, two RGBA8 images of S x S, tileable, row 0 = v 0: + alb : R,G,B = albedo (sRGB), A = height (0 deep .. 1 proud; used for parallax, cavity AO and where damp gathers) + nri : R,G = tangent-space normal x,y (z is rebuilt in the shader), B = roughness, A = element id byte + The element id byte lets the shader give every brick/stone/board a tint of its own that is different in every + repeat of the tile, so a wall does not show the same bricks every 1.35 m: byte = combo*28 + k, k in 1..27 is the + element's id (0 = mortar / no element), combo = (wx+1)*3 + (wy+1) says which neighbouring tile the element's centre + lies in (elements that cross the tile edge). For metals the A channel is the bare-metal mask instead. */ +(function (root) { + 'use strict'; + + // ------------------------------------------------------------------ random numbers and noise + function rng(seed) { + let a = (seed >>> 0) || 1; + const f = function () { a = (a + 0x6D2B79F5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; + f.range = (a0, a1) => a0 + (a1 - a0) * f(); + f.int = (n) => Math.floor(f() * n); + return f; + } + function hash2(i, j, s) { + let h = (Math.imul(i, 374761393) + Math.imul(j, 668265263) + Math.imul(s, 1442695041)) | 0; + h = Math.imul(h ^ (h >>> 13), 1274126177); h ^= h >>> 16; return (h >>> 0) / 4294967296; + } + const fade = t => t * t * t * (t * (t * 6 - 15) + 10); + + // One octave of periodic value noise over the whole S x S field, added into out with weight amp. + // px, py: lattice cells across the tile (integers, so it tiles). + function octave(S, px, py, seed, out, amp) { + const lat = new Float32Array(px * py); + for (let j = 0; j < py; j++) for (let i = 0; i < px; i++) lat[j * px + i] = hash2(i, j, seed); + const X0 = new Int32Array(S), X1 = new Int32Array(S), UX = new Float32Array(S); + for (let x = 0; x < S; x++) { const f = x / S * px, i = Math.floor(f); X0[x] = i % px; X1[x] = (i + 1) % px; UX[x] = fade(f - i); } + for (let y = 0; y < S; y++) { + const f = y / S * py, j = Math.floor(f), uy = fade(f - j), r0 = (j % py) * px, r1 = ((j + 1) % py) * px, row = y * S; + for (let x = 0; x < S; x++) { + const a = lat[r0 + X0[x]], b = lat[r0 + X1[x]], c = lat[r1 + X0[x]], d = lat[r1 + X1[x]], ux = UX[x]; + out[row + x] += amp * (a + (b - a) * ux + (c - a) * uy + (a - b - c + d) * ux * uy); + } + } + } + // fractal noise in 0..1. px/py = lattice size of the first octave (py defaults to px). + function fbm(S, px, oct, seed, py, gain) { + py = py || px; gain = gain || 0.5; + const out = new Float32Array(S * S); let amp = 1, tot = 0; + for (let o = 0; o < oct; o++) { + const qx = Math.min(px << o, S), qy = Math.min(py << o, S); + octave(S, qx, qy, seed * 31 + o * 101, out, amp); tot += amp; amp *= gain; + } + for (let i = 0; i < out.length; i++) out[i] /= tot; + return out; + } + // stretch a field so it spans 0..1 (keeps the tiling) + function norm(f, lo, hi) { + let mn = 1e9, mx = -1e9; for (let i = 0; i < f.length; i++) { if (f[i] < mn) mn = f[i]; if (f[i] > mx) mx = f[i]; } + const k = 1 / Math.max(1e-6, mx - mn); lo = lo || 0; hi = hi == null ? 1 : hi; + for (let i = 0; i < f.length; i++) f[i] = lo + (f[i] - mn) * k * (hi - lo); + return f; + } + // separable wrap-around box blur, radius r, applied twice (close to a Gaussian) + function blur(f, S, r, passes) { + r = Math.max(1, Math.round(r)); passes = passes || 2; + let a = Float32Array.from(f), b = new Float32Array(f.length); + const inv = 1 / (2 * r + 1); + for (let p = 0; p < passes; p++) { + for (let y = 0; y < S; y++) { + const row = y * S; let s = 0; + for (let k = -r; k <= r; k++) s += a[row + ((k % S) + S) % S]; + for (let x = 0; x < S; x++) { b[row + x] = s * inv; s += a[row + (x + r + 1) % S] - a[row + ((x - r) % S + S) % S]; } + } + for (let x = 0; x < S; x++) { + let s = 0; + for (let k = -r; k <= r; k++) s += b[(((k % S) + S) % S) * S + x]; + for (let y = 0; y < S; y++) { a[y * S + x] = s * inv; s += b[((y + r + 1) % S) * S + x] - b[(((y - r) % S + S) % S) * S + x]; } + } + } + return a; + } + const clamp = (v, a, b) => v < a ? a : v > b ? b : v; + const sstep = (a, b, v) => { const t = clamp((v - a) / (b - a), 0, 1); return t * t * (3 - 2 * t); }; + const lerp = (a, b, t) => a + (b - a) * t; + + // Worley / cellular noise over toroidal points. pts: [{x,y,...}] in pixels. Returns F1, F2 (pixels), nearest index, + // and the wrap offset (-1/0/1) of the nearest point in x and y. metric aspect ay stretches y distances. + // half: compute at half resolution and upsample (F1/F2 bilinear, ids nearest): 4x faster, edges a touch softer + function worley(S, pts, ay, half) { + if (half && S >= 512) { + const h = S >> 1, hp = pts.map(p => Object.assign({}, p, { x: p.x / 2, y: p.y / 2, w: p.w })); + const W = worley(h, hp, ay, false), F1 = new Float32Array(S * S), F2 = new Float32Array(S * S), ID = new Int32Array(S * S), WX = new Int8Array(S * S), WY = new Int8Array(S * S); + for (let y = 0; y < S; y++) { + const fy = (y - 0.5) / 2, j0 = Math.floor(fy), v = fy - j0, ja = ((j0 % h) + h) % h, jb = (ja + 1) % h, jn = (Math.round(fy) % h + h) % h; + for (let x = 0; x < S; x++) { + const fx = (x - 0.5) / 2, i0 = Math.floor(fx), u = fx - i0, ia = ((i0 % h) + h) % h, ib = (ia + 1) % h, q = y * S + x; + const a = ja * h + ia, b = ja * h + ib, c = jb * h + ia, d = jb * h + ib; + F1[q] = 2 * ((W.F1[a] * (1 - u) + W.F1[b] * u) * (1 - v) + (W.F1[c] * (1 - u) + W.F1[d] * u) * v); + F2[q] = 2 * ((W.F2[a] * (1 - u) + W.F2[b] * u) * (1 - v) + (W.F2[c] * (1 - u) + W.F2[d] * u) * v); + const n = jn * h + (Math.round(fx) % h + h) % h; ID[q] = W.ID[n]; WX[q] = W.WX[n]; WY[q] = W.WY[n]; + } + } + return { F1, F2, ID, WX, WY }; + } + ay = ay || 1; + const n = pts.length, G = Math.max(1, Math.floor(Math.sqrt(n / 1.5))), cs = S / G; + const grid = []; for (let i = 0; i < G * G; i++) grid.push([]); + for (let i = 0; i < n; i++) { const p = pts[i]; grid[(Math.floor(p.y / cs) % G) * G + (Math.floor(p.x / cs) % G)].push(i); } + const F1 = new Float32Array(S * S), F2 = new Float32Array(S * S), ID = new Int32Array(S * S), WX = new Int8Array(S * S), WY = new Int8Array(S * S); + const reach = Math.max(2, Math.ceil(2 * ay)); + for (let y = 0; y < S; y++) { + const gy = Math.floor(y / cs); + for (let x = 0; x < S; x++) { + const gx = Math.floor(x / cs); let d1 = 1e18, d2 = 1e18, b = 0, bwx = 0, bwy = 0; + for (let j = -reach; j <= reach; j++) for (let i = -2; i <= 2; i++) { + let cx = gx + i, cy = gy + j, ox = 0, oy = 0; + if (cx < 0) { cx += G; ox = -S; } else if (cx >= G) { cx -= G; ox = S; } + if (cy < 0) { cy += G; oy = -S; } else if (cy >= G) { cy -= G; oy = S; } + const cell = grid[cy * G + cx]; + for (let k = 0; k < cell.length; k++) { + const p = pts[cell[k]], dx = p.x + ox - x, dy = (p.y + oy - y) * ay, w = p.w || 1, d = (dx * dx + dy * dy) / (w * w); + if (d < d1) { d2 = d1; d1 = d; b = cell[k]; bwx = ox; bwy = oy; } else if (d < d2) d2 = d; + } + } + const q = y * S + x; F1[q] = Math.sqrt(d1); F2[q] = Math.sqrt(d2); ID[q] = b; WX[q] = bwx > 0 ? 1 : bwx < 0 ? -1 : 0; WY[q] = bwy > 0 ? 1 : bwy < 0 ? -1 : 0; + } + } + return { F1, F2, ID, WX, WY }; + } + function idByte(k, wx, wy) { if (!k) return 112; return ((wx + 1) * 3 + (wy + 1)) * 28 + 1 + (k % 27); } + + // draw a wobbling crack (random walk) into a field: f = min(f, depth profile) + function crack(f, S, R, x, y, len, ang, width, depth, branch) { + let a = ang; + for (let s = 0; s < len; s++) { + a += R.range(-0.35, 0.35); x += Math.cos(a); y += Math.sin(a); + const w = width * (1 - s / len * 0.7), r = Math.ceil(w + 1); + for (let j = -r; j <= r; j++) for (let i = -r; i <= r; i++) { + const d = Math.sqrt(i * i + j * j); if (d > w + 1) continue; + const xi = ((Math.round(x) + i) % S + S) % S, yi = ((Math.round(y) + j) % S + S) % S, q = yi * S + xi; + const v = depth * clamp(1 - d / (w + 1), 0, 1); if (v > f[q]) f[q] = v; + } + if (branch && R() < 0.012) crack(f, S, R, x, y, len * 0.4, a + R.range(-1.2, 1.2), width * 0.6, depth * 0.8, false); + } + } + // stamp a soft disc into a field with an op + function disc(f, S, cx, cy, r, fn) { + const ri = Math.ceil(r); + for (let j = -ri; j <= ri; j++) for (let i = -ri; i <= ri; i++) { + const d = Math.sqrt(i * i + j * j) / r; if (d > 1) continue; + const q = ((((Math.round(cy) + j) % S) + S) % S) * S + (((Math.round(cx) + i) % S) + S) % S; + f[q] = fn(f[q], d, q); + } + } + // thin line segment stamp (strokes: grass, straw, scratches) + function line(S, x0, y0, x1, y1, w, cb) { + const len = Math.hypot(x1 - x0, y1 - y0), n = Math.max(1, Math.ceil(len)); + for (let s = 0; s <= n; s++) { + const t = s / n, x = x0 + (x1 - x0) * t, y = y0 + (y1 - y0) * t, r = Math.ceil(w); + for (let j = -r; j <= r; j++) for (let i = -r; i <= r; i++) { + const d = Math.sqrt(i * i + j * j); if (d > w) continue; + const q = ((((Math.round(y) + j) % S) + S) % S) * S + (((Math.round(x) + i) % S) + S) % S; + cb(q, t, d / w); + } + } + } + + // ------------------------------------------------------------------ output assembly + function Out(S) { + const n = S * S; + return { S, r: new Float32Array(n), g: new Float32Array(n), b: new Float32Array(n), h: new Float32Array(n), ro: new Float32Array(n).fill(0.85), id: new Uint8Array(n).fill(112) }; + } + // depthPx: how many pixels of real depth one unit of height is (sets normal strength); ao: cavity bake strength + function finish(o, depthPx, ao, aoR) { + const S = o.S, n = S * S, h = o.h, alb = new Uint8ClampedArray(n * 4), nri = new Uint8ClampedArray(n * 4); + let cav = null; + if (ao) { const bl = blur(h, S, aoR || Math.max(2, S / 128)); cav = new Float32Array(n); for (let i = 0; i < n; i++) cav[i] = clamp(1 - (bl[i] - h[i]) * ao, 0.62, 1.04); } // joints read as recessed, not drawn in ink + for (let y = 0; y < S; y++) { + const yu = ((y + 1) % S) * S, yd = ((y - 1 + S) % S) * S, row = y * S; + for (let x = 0; x < S; x++) { + const q = row + x, xr = row + (x + 1) % S, xl = row + (x - 1 + S) % S; + // Sobel for a steadier normal + const hx = (h[xr] - h[xl]) * 2 + (h[yu + (x + 1) % S] - h[yu + (x - 1 + S) % S]) + (h[yd + (x + 1) % S] - h[yd + (x - 1 + S) % S]); + const hy = (h[yu + x] - h[yd + x]) * 2 + (h[yu + (x + 1) % S] - h[yd + (x + 1) % S]) + (h[yu + (x - 1 + S) % S] - h[yd + (x - 1 + S) % S]); + let nx = -hx / 8 * depthPx, ny = -hy / 8 * depthPx; const l = 1 / Math.sqrt(nx * nx + ny * ny + 1); nx *= l; ny *= l; + const c = cav ? cav[q] : 1; + alb[q * 4] = o.r[q] * c * 255; alb[q * 4 + 1] = o.g[q] * c * 255; alb[q * 4 + 2] = o.b[q] * c * 255; alb[q * 4 + 3] = h[q] * 255; + nri[q * 4] = (nx * 0.5 + 0.5) * 255; nri[q * 4 + 1] = (ny * 0.5 + 0.5) * 255; nri[q * 4 + 2] = clamp(o.ro[q], 0.02, 1) * 255; nri[q * 4 + 3] = o.id[q]; + } + } + return { S, alb: new Uint8Array(alb.buffer), nri: new Uint8Array(nri.buffer) }; + } + function setc(o, q, c, k) { k = k == null ? 1 : k; o.r[q] = c[0] / 255 * k; o.g[q] = c[1] / 255 * k; o.b[q] = c[2] / 255 * k; } + function mixc(o, q, c, t) { o.r[q] = lerp(o.r[q], c[0] / 255, t); o.g[q] = lerp(o.g[q], c[1] / 255, t); o.b[q] = lerp(o.b[q], c[2] / 255, t); } + function mulc(o, q, k) { o.r[q] *= k; o.g[q] *= k; o.b[q] *= k; } + function jitterCol(c, R, v, hue) { const k = 1 + R.range(-v, v), hh = R.range(-hue, hue); return [c[0] * k * (1 + hh), c[1] * k, c[2] * k * (1 - hh)]; } + + // ------------------------------------------------------------------ the materials + const G = {}; + + // RED BRICK. Tile 1.35 m: 6 stretchers x 18 courses (225 x 75 mm with 10 mm lime mortar), stretcher bond. + G.brick = function (S, seed, opt) { + opt = opt || {}; + const R = rng(seed), o = Out(S), cols = 6, rows = 18, bw = S / cols, ch = S / rows, m = S * 0.0105 / 1.35 * 1.1; + const n1 = fbm(S, 64, 3, seed + 1), n2 = fbm(S, 16, 4, seed + 2), n3 = fbm(S, 128, 2, seed + 3), grit = fbm(S, 256, 2, seed + 4); + const B = []; + const base = opt.palette || [[126, 72, 58], [122, 70, 57], [130, 76, 60], [120, 70, 58], [128, 78, 63]]; // weathered, not new red // close tones: one wall first, bricks second + for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) { + const kind = R(), b = { + dx: R.range(-1, 1) * S / 1024, dy: R.range(-0.8, 0.8) * S / 1024, sw: R.range(0, 2.5) * S / 1024, sh: R.range(0, 1.6) * S / 1024, + col: jitterCol(base[R.int(base.length)], R, 0.035, 0.015), k: 1 + R.int(27), rough: R.range(0.76, 0.94), + clinker: kind < 0.025, pale: kind > 0.975, spall: R() < 0.07, crack: R() < 0.06, chips: [], tilt: R.range(-0.04, 0.04) + }; + if (b.clinker) b.col = jitterCol([112, 58, 46], R, 0.05, 0.02); + if (b.pale) b.col = jitterCol([158, 92, 66], R, 0.04, 0.02); + const nc = R() < 0.55 ? R.int(3) + 1 : 0; + for (let i = 0; i < nc; i++) b.chips.push({ x: R() < 0.5 ? R.range(0, 0.12) : R.range(0.88, 1), y: R() < 0.5 ? 0 : 1, r: R.range(3, 11) * S / 1024 }); + if (R() < 0.08) b.chips.push({ x: R.range(0.2, 0.8), y: R() < 0.5 ? 0 : 1, r: R.range(4, 9) * S / 1024 }); + b.cr = { x: R.range(0.25, 0.75), a: R.range(1.2, 1.9) }; + B.push(b); + } + for (let y = 0; y < S; y++) { + const r = Math.floor(y / ch), ly0 = y - r * ch, off = (r % 2) * bw / 2; + for (let x = 0; x < S; x++) { + const q = y * S + x, xx = x - off, cu = Math.floor(xx / bw), c = ((cu % cols) + cols) % cols, b = B[r * cols + c]; + const ccx = off + cu * bw + bw / 2, wx = ccx < 0 ? -1 : ccx >= S ? 1 : 0; + const lx = xx - cu * bw - bw / 2 - b.dx, ly = ly0 - ch / 2 - b.dy + lx * b.tilt * 0.05; + // rounded-rect distance (negative inside the brick), edges made ragged with noise + const hw = bw / 2 - m / 2 - b.sw / 2, hh = ch / 2 - m / 2 - b.sh / 2, rad = 2.2 * S / 1024; + const qx = Math.abs(lx) - hw + rad, qy = Math.abs(ly) - hh + rad; + let sd = Math.min(Math.max(qx, qy), 0) + Math.hypot(Math.max(qx, 0), Math.max(qy, 0)) - rad; + sd += (n1[q] - 0.5) * 3.2 * S / 1024; + const u = (lx + hw) / (2 * hw), v = (ly + hh) / (2 * hh); + // chips knocked off the arrises + let chip = 0; + for (let i = 0; i < b.chips.length; i++) { + const cp = b.chips[i], dx = (u - cp.x) * 2 * hw, dy = (v - cp.y) * 2 * hh, d = Math.hypot(dx, dy) / (cp.r * (0.8 + 0.5 * n1[q])); + if (d < 1) chip = Math.max(chip, 1 - d); + } + const inside = sstep(0.5, -2.2 * S / 1024, sd); // 0 in mortar .. 1 on the face + const mortarH = 0.16 + 0.12 * n2[q] + 0.06 * grit[q] + 0.1 * sstep(-m, 0, -Math.abs(sd)) * 0; + let face = 0.84 + 0.1 * n2[q] + 0.035 * (n3[q] - 0.5) + 0.02 * (grit[q] - 0.5); + if (chip > 0) face -= sstep(0, 0.35, chip) * 0.42 * (0.7 + 0.6 * grit[q]); + let sp = 0; + if (b.spall) { sp = sstep(0.52, 0.6, n2[q] * 0.6 + (1 - Math.abs(u - 0.5) * 2) * 0.35 + n3[q] * 0.15); face -= sp * 0.22; } + let cr = 0; + if (b.crack) { const cx = b.cr.x + (v - 0.5) / Math.tan(b.cr.a) * (hh / hw) + (n1[q] - 0.5) * 0.05; cr = sstep(1.6 * S / 1024, 0.3, Math.abs(u - cx) * 2 * hw); face -= cr * 0.45; } + o.h[q] = lerp(mortarH, face, inside); + // colour + const mc = [162 + 30 * (grit[q] - 0.5), 154 + 28 * (grit[q] - 0.5), 138 + 24 * (grit[q] - 0.5)]; + const mortarDirt = 0.55 + 0.45 * n2[q]; + const edgeDark = 1 - 0.18 * sstep(-6 * S / 1024, 0, sd); // fire-flashed, dirtier arrises + const mott = 0.86 + 0.28 * n3[q] + 0.12 * (n1[q] - 0.5); + const bc = [b.col[0] * mott * edgeDark, b.col[1] * mott * edgeDark, b.col[2] * mott * edgeDark]; + if (grit[q] > 0.8) { bc[0] += 22; bc[1] += 18; bc[2] += 12; } // sand specks + if (chip > 0.05 || sp > 0.3) { const t = Math.max(sstep(0.05, 0.3, chip), sp * 0.8); bc[0] = lerp(bc[0], 178, t * 0.6); bc[1] = lerp(bc[1], 98, t * 0.6); bc[2] = lerp(bc[2], 70, t * 0.6); } + if (cr > 0.2) { bc[0] *= 0.5; bc[1] *= 0.5; bc[2] *= 0.5; } + o.r[q] = lerp(mc[0] * mortarDirt, bc[0], inside) / 255; o.g[q] = lerp(mc[1] * mortarDirt, bc[1], inside) / 255; o.b[q] = lerp(mc[2] * mortarDirt, bc[2], inside) / 255; + o.ro[q] = lerp(0.96, b.rough + 0.06 * (grit[q] - 0.5) + chip * 0.08, inside); + o.id[q] = inside > 0.5 ? idByte(b.k, wx, 0) : 112; + } + } + return o; + }; + G.brick_red = (S, seed) => finish(G.brick(S, seed), S * 0.013 / 1.35, 2.2); + // SOOTY BRICK: the same bond, darker and streaked with soot from the top down, glossier where the soot is thick. + G.brick_sooty = function (S, seed) { + const o = G.brick(S, seed, { palette: [[118, 58, 44], [104, 52, 42], [126, 70, 52], [96, 50, 42]] }); + const streak = fbm(S, 24, 4, seed + 9, 3), blot = fbm(S, 6, 4, seed + 10); + for (let q = 0; q < S * S; q++) { + const s = clamp((streak[q] - 0.35) * 1.8 + (blot[q] - 0.5) * 0.9, 0, 1) * (0.55 + 0.45 * o.h[q]); + const k = 1 - 0.72 * s; o.r[q] = lerp(o.r[q], 0.06, s * 0.75) * (0.9 + 0.1 * k); o.g[q] = lerp(o.g[q], 0.055, s * 0.75); o.b[q] = lerp(o.b[q], 0.05, s * 0.75); + o.ro[q] = lerp(o.ro[q], 0.72, s * 0.6); + } + return finish(o, S * 0.013 / 1.35, 2.2); + }; + + // FIELDSTONE: roughly coursed rubble limestone, tile 1.6 m. Courses of mixed height; in each course flat-bedded + // stones of very mixed length, a few deep enough to span two courses, small packing stones in the gaps; tight, + // irregular joints of pale lime mortar, washed back in places. Stones are flattish with chipped, slightly rounded + // arrises, not pebbles. + G.fieldstone = function (S, seed) { + const R = rng(seed), o = Out(S), px = S / 1.6; // pixels per metre + const n1 = fbm(S, 32, 4, seed + 1), n2 = fbm(S, 8, 4, seed + 2), grit = fbm(S, 256, 2, seed + 3), lich = fbm(S, 96, 3, seed + 4), wash = fbm(S, 6, 4, seed + 5); + // courses: heights from 0.07 to 0.32 m, scaled so they fill the tile exactly (it must tile vertically) + const hs = []; let tot = 0; while (tot < 1.6) { const h = R() < 0.25 ? R.range(0.2, 0.32) : R() < 0.5 ? R.range(0.07, 0.12) : R.range(0.12, 0.2); hs.push(h); tot += h; } + const scale = 1.6 / tot, rows = []; let y = 0; + for (const h of hs) { rows.push({ y0: y * px, h: h * scale * px }); y += h * scale; } + const stones = []; // per row a list of stones covering the row width exactly + rows.forEach((r, ri) => { + const list = []; let x = 0; const wTot = []; + while (x < 1.6) { const w = R() < 0.15 ? R.range(0.5, 0.8) : R() < 0.5 ? R.range(0.07, 0.2) : R.range(0.2, 0.45); wTot.push(w); x += w; } + const sc = 1.6 / x, off = R() * S; let cx = 0; + for (const w of wTot) { + const ww = w * sc * px; + list.push({ x0: (cx * px + off) % S, w: ww, hk: R.range(0.6, 1.0), dy: R.range(-0.1, 0.1), tilt: R.range(-0.09, 0.09), col: R(), t: R.range(0.96, 1.04), k: 1 + R.int(27), bulge: R.range(0.04, 0.16), rad: R.range(0.06, 0.2) }); + cx += ww / px; + } + stones.push(list); + }); + const pal = [[106, 100, 90], [109, 102, 90], [104, 99, 90], [108, 103, 93], [105, 98, 88], [107, 100, 89]]; // one stone, not a patchwork + const joint = 2.2 * S / 1024; + for (let yy = 0; yy < S; yy++) { + let ri = 0; while (ri < rows.length - 1 && yy >= rows[ri + 1].y0) ri++; + const r = rows[ri], ly = yy - r.y0; + for (let x = 0; x < S; x++) { + const q = yy * S + x, list = stones[ri]; + // which stone: the one whose span contains x (wrapping) + let st = list[0], lx = 0; + for (let i = 0; i < list.length; i++) { const s0 = list[i].x0; let d = x - s0; if (d < 0) d += S; if (d < list[i].w) { st = list[i]; lx = d; break; } } + const sh = r.h * st.hk, top = (r.h - sh) * 0.5 + st.dy * r.h; + const cy = ly - top - sh / 2 + (lx - st.w / 2) * st.tilt, cxl = lx - st.w / 2; + const hw = st.w / 2 - joint, hh = sh / 2 - joint, rad = Math.min(hw, hh) * st.rad; + const qx = Math.abs(cxl) - hw + rad, qy = Math.abs(cy) - hh + rad; + let sd = Math.min(Math.max(qx, qy), 0) + Math.hypot(Math.max(qx, 0), Math.max(qy, 0)) - rad; + sd += (n1[q] - 0.5) * 16 * S / 1024 + (n2[q] - 0.5) * 10 * S / 1024 + (grit[q] - 0.5) * 2.5 * S / 1024; // chipped, irregular edges + let inside = sstep(1.0, -1.5 * S / 1024, sd); + // packing stones fill the bigger gaps left by shorter stones + let pack = 0; + if (inside < 0.5 && Math.abs(cy) > hh) { const pn = n2[q] * 0.7 + n1[q] * 0.3; pack = sstep(0.58, 0.66, pn) * sstep(0, 3 * S / 1024, Math.abs(cy) - hh - joint); } + const u = cxl / Math.max(1, hw), v = cy / Math.max(1, hh); + const face = 0.7 + st.bulge * (1 - 0.5 * (u * u + v * v)) + 0.08 * (n2[q] - 0.5) + 0.05 * (grit[q] - 0.5) - 0.12 * sstep(-6 * S / 1024, 0, sd) * (0.5 + n1[q]); + const washed = sstep(0.55, 0.75, wash[q]); + const mortarH = 0.42 - washed * 0.22 + 0.05 * grit[q]; + o.h[q] = Math.max(lerp(mortarH, face, inside), pack * (0.55 + 0.1 * grit[q])); + const c = pal[Math.floor(st.col * pal.length)], t = st.t * (0.9 + 0.18 * n1[q]) * (0.93 + 0.1 * grit[q]); + let cr = c[0] * t, cg = c[1] * t, cb = c[2] * t; + const l = sstep(0.76, 0.82, lich[q] * 0.8 + grit[q] * 0.2) * inside; + if (l > 0) { cr = lerp(cr, 160, l * 0.45); cg = lerp(cg, 162, l * 0.45); cb = lerp(cb, 138, l * 0.45); } + const mk = (0.95 + 0.12 * (grit[q] - 0.5)) * (1 - washed * 0.25); + const mc = [150 * mk, 144 * mk, 130 * mk]; // lime mortar, close to the stone + const pc = [130 * t, 124 * t, 112 * t]; + o.r[q] = lerp(lerp(mc[0], pc[0], pack), cr, inside) / 255; o.g[q] = lerp(lerp(mc[1], pc[1], pack), cg, inside) / 255; o.b[q] = lerp(lerp(mc[2], pc[2], pack), cb, inside) / 255; + o.ro[q] = lerp(0.95, 0.86 + 0.1 * n1[q] + l * 0.04, Math.max(inside, pack)); + o.id[q] = inside > 0.5 ? idByte(st.k, 0, 0) : 112; + } + } + return finish(o, S * 0.05 / 1.6, 1.3, S / 160); + }; + + // ASHLAR: dressed limestone blocks for quoins, sills, lintels and the church. Tile 1.2 m. + G.ashlar = function (S, seed) { + const R = rng(seed), o = Out(S), rows = 4, ch = S / rows, m = 3 * S / 1024; + const n1 = fbm(S, 32, 4, seed + 1), n2 = fbm(S, 8, 3, seed + 2), grit = fbm(S, 256, 2, seed + 3), tool = fbm(S, 160, 2, seed + 4, 40); + const rowsB = []; + for (let r = 0; r < rows; r++) { const cuts = []; let x = R.range(0, S); const n = 2 + R.int(2); for (let i = 0; i < n; i++) cuts.push((x + i * S / n + R.range(-30, 30)) % S); cuts.sort((a, b) => a - b); rowsB.push({ cuts, tints: cuts.map(() => R.range(0.86, 1.1)), ks: cuts.map(() => 1 + R.int(27)) }); } + for (let y = 0; y < S; y++) { + const r = Math.floor(y / ch), ly = y - r * ch, rb = rowsB[r]; + for (let x = 0; x < S; x++) { + const q = y * S + x; let bi = rb.cuts.length - 1, dx = 1e9; + for (let i = 0; i < rb.cuts.length; i++) { if (x >= rb.cuts[i]) bi = i; const d = Math.min(Math.abs(x - rb.cuts[i]), S - Math.abs(x - rb.cuts[i])); if (d < dx) dx = d; } + const dy = Math.min(ly, ch - ly), d = Math.min(dx, dy) + (n1[q] - 0.5) * 3 * S / 1024; + const inside = sstep(m * 0.5, m * 1.6, d), chip = sstep(0.62, 0.7, n1[q] * 0.7 + n2[q] * 0.3) * (1 - sstep(m, m * 5, d)); + o.h[q] = lerp(0.3, 0.86 + 0.05 * tool[q] + 0.06 * n2[q] - chip * 0.25, inside); + const t = rb.tints[bi] * (0.88 + 0.18 * n1[q]) * (0.95 + 0.08 * grit[q]); + setc(o, q, [lerp(120, 168 * t, inside), lerp(114, 160 * t, inside), lerp(104, 140 * t, inside)]); + o.ro[q] = 0.82 + 0.1 * grit[q]; o.id[q] = inside > 0.5 ? idByte(rb.ks[bi], 0, 0) : 112; + } + } + return finish(o, S * 0.012 / 1.2, 1.6); + }; + + // PLANK helper used by old timber planks, floorboards and painted boards. Boards run along v. + function planks(S, seed, P) { + const R = rng(seed), o = Out(S), nb = P.boards, bw = S / nb, gap = P.gap * S / 1024; + const grainA = fbm(S, 96, 3, seed + 1, 3), grainB = fbm(S, 300, 2, seed + 2, 6), warp = fbm(S, 12, 3, seed + 3, 2), n2 = fbm(S, 16, 4, seed + 4), grit = fbm(S, 256, 2, seed + 5); + const boards = []; + for (let i = 0; i < nb; i++) { + const joints = []; const nj = R() < P.jointP ? 1 : 0; for (let k = 0; k < nj; k++) joints.push(R.range(0.1, 0.9) * S); + const knots = []; const nk = R() < 0.55 ? 1 + R.int(2) : 0; for (let k = 0; k < nk; k++) knots.push({ x: R.range(0.25, 0.75), y: R.range(0, S), r: R.range(5, 13) * S / 1024 }); + boards.push({ joints, knots, tint: jitterCol(P.col, R, P.var, 0.04), k: 1 + R.int(27), wg: R.range(0, 1000), cup: R.range(0.02, 0.07), w: R.range(-2, 2) * S / 1024, rough: R.range(-0.06, 0.06), freq: R.range(0.8, 1.3) }); + } + for (let y = 0; y < S; y++) for (let x = 0; x < S; x++) { + const q = y * S + x, bi = Math.floor(x / bw), b = boards[bi], lx = x - bi * bw, u = lx / bw; + const dEdge = Math.min(lx - b.w * 0.5, bw - lx + b.w * 0.5); + let inside = sstep(gap * 0.5, gap * 0.5 + 2.2 * S / 1024, dEdge + (warp[q] - 0.5) * 2 * S / 1024); + for (let k = 0; k < b.joints.length; k++) { const dj = Math.abs(y - b.joints[k]); inside *= sstep(gap * 0.4, gap * 0.4 + 2 * S / 1024, Math.min(dj, S - dj)); } + // grain: warped ring lines along the board + fine fibres + let gx = u * 9 * b.freq + warp[q] * 5 + b.wg; + let kn = 0; + for (let k = 0; k < b.knots.length; k++) { + const kk = b.knots[k]; let dy = y - kk.y; if (dy > S / 2) dy -= S; if (dy < -S / 2) dy += S; + const dx = (u - kk.x) * bw, d = Math.hypot(dx, dy * 0.6) / kk.r; + if (d < 4) { gx += Math.sign(dx) * 2.2 / (1 + d * d); kn = Math.max(kn, sstep(1.2, 0.5, d)); } + } + const ring = Math.pow(Math.abs(Math.sin(gx * Math.PI)), 0.45), fib = grainB[q]; + const cup = -b.cup * Math.pow((u - 0.5) * 2, 2); + const weatherRaise = P.raise * (1 - ring) * 0.5; + o.h[q] = lerp(0.05, 0.82 + cup + weatherRaise + 0.05 * (fib - 0.5) + 0.05 * (n2[q] - 0.5) - kn * 0.08, inside); + const t = (0.66 + 0.34 * ring) * (0.84 + 0.3 * grainA[q]) * (0.86 + 0.26 * n2[q]) * (0.9 + 0.2 * fib); + let cr = b.tint[0] * t, cg = b.tint[1] * t, cb = b.tint[2] * t; + if (kn > 0) { cr *= 1 - kn * 0.5; cg *= 1 - kn * 0.55; cb *= 1 - kn * 0.6; } + o.r[q] = lerp(34, cr, inside) / 255; o.g[q] = lerp(26, cg, inside) / 255; o.b[q] = lerp(19, cb, inside) / 255; + o.ro[q] = lerp(0.95, P.rough + b.rough + 0.08 * (fib - 0.5) + 0.05 * ring, inside); + o.id[q] = inside > 0.5 ? idByte(b.k, 0, 0) : 112; + } + // nail heads in rows (the battens / joists behind), with a rust run below each one + const rowsY = P.nailRows; + for (let i = 0; i < nb; i++) for (let k = 0; k < rowsY.length; k++) for (let s = 0; s < 2; s++) { + if (R() < 0.12) continue; + const cx = i * bw + (s ? 0.72 : 0.28) * bw + R.range(-3, 3), cy = rowsY[k] * S + R.range(-4, 4), r = R.range(3.2, 4.6) * S / 1024; + disc(o.h, S, cx, cy, r, (v, d, q) => { o.r[q] = o.g[q] = o.b[q] = 0; o.r[q] = 0.16; o.g[q] = 0.12; o.b[q] = 0.1; o.ro[q] = 0.55; return Math.max(v, 0.92 - d * d * 0.1); }); + if (P.rust) { + const len = R.range(10, 50) * S / 1024; + for (let t = 0; t < len; t++) disc(o.h, S, cx + R.range(-1, 1), cy - r - t, r * (1 - t / len) * 0.9, (v, d, q) => { const a = (1 - t / len) * 0.35 * (1 - d); o.r[q] = lerp(o.r[q], 0.32, a); o.g[q] = lerp(o.g[q], 0.16, a); o.b[q] = lerp(o.b[q], 0.08, a); return v; }); + } + } + return o; + } + G.planks = (S, seed) => finish(planks(S, seed, { boards: 8, gap: 7, jointP: 0.45, col: [146, 138, 124], var: 0.04, rough: 0.86, raise: 0.12, nailRows: [0.18, 0.68], rust: true }), S * 0.008 / 1.6, 1.8); + G.floorboards = (S, seed) => finish(planks(S, seed, { boards: 11, gap: 4, jointP: 0.8, col: [112, 82, 56], var: 0.05, rough: 0.68, raise: 0.03, nailRows: [0.05, 0.55], rust: false }), S * 0.004 / 2, 1.6); + // PAINTED BOARDS for doors and shutters: tongue-and-groove boards under flaking old paint, worn to bare wood. + G.wood_painted = function (S, seed) { + const o = planks(S, seed, { boards: 8, gap: 5, jointP: 0, col: [104, 92, 78], var: 0.12, rough: 0.85, raise: 0.08, nailRows: [0.12, 0.5, 0.88], rust: true }); + const peel = fbm(S, 10, 5, seed + 21), fine = fbm(S, 120, 2, seed + 22), R = rng(seed + 23); + const pc = [64, 80, 68], bwp = S / 8; + for (let q = 0; q < S * S; q++) { + const x = q % S, lx = x % bwp, edgeW = 1 - sstep(0, bwp * 0.22, Math.min(lx, bwp - lx)); + const v = peel[q] * 0.8 + fine[q] * 0.2 + edgeW * 0.16, bare = sstep(0.64, 0.655, v), lip = sstep(0.6, 0.64, v) * (1 - bare); + if (o.h[q] < 0.2) continue; + const fadeK = 0.78 + 0.3 * peel[q] + 0.08 * fine[q]; + if (bare < 1) { + o.r[q] = lerp(pc[0] * fadeK / 255, o.r[q], bare); o.g[q] = lerp(pc[1] * fadeK / 255, o.g[q], bare); o.b[q] = lerp(pc[2] * fadeK / 255, o.b[q], bare); + o.h[q] += 0.04 * (1 - bare) + lip * 0.02; o.ro[q] = lerp(0.62 + 0.1 * fine[q], o.ro[q], bare); + } + } + // scratches through the paint + for (let i = 0; i < 40; i++) { const x = R() * S, y = R() * S, a = R.range(-0.6, 0.6) + (R() < 0.5 ? 0 : Math.PI / 2), l = R.range(10, 70) * S / 1024; line(S, x, y, x + Math.cos(a) * l, y + Math.sin(a) * l, 0.8 * S / 1024, q => { o.r[q] = lerp(o.r[q], 0.5, 0.5); o.g[q] = lerp(o.g[q], 0.44, 0.5); o.b[q] = lerp(o.b[q], 0.36, 0.5); o.h[q] -= 0.03; }); } + return finish(o, S * 0.006 / 1.0, 1.6); + }; + + // TIMBER FRAME: adzed oak beams, grain along v, long drying checks. + G.timber = function (S, seed) { + const R = rng(seed), o = Out(S); + const grain = fbm(S, 64, 4, seed + 1, 2), warp = fbm(S, 6, 3, seed + 2, 2), adze = fbm(S, 3, 2, seed + 3, 14), fine = fbm(S, 256, 2, seed + 4, 8), n2 = fbm(S, 12, 4, seed + 5); + const ck = new Float32Array(S * S); + for (let i = 0; i < 7; i++) crack(ck, S, R, R() * S, R() * S, R.range(80, 300) * S / 1024, Math.PI / 2 + R.range(-0.1, 0.1), R.range(0.8, 2.2) * S / 1024, 1, false); + for (let q = 0; q < S * S; q++) { + const x = q % S, ring = Math.pow(Math.abs(Math.sin((x / S * 14 + warp[q] * 6) * Math.PI)), 0.5); + const sc = 0.5 + 0.5 * Math.sin(adze[q] * 30); + o.h[q] = 0.7 + 0.12 * sc + 0.06 * (grain[q] - 0.5) + 0.06 * (1 - ring) * 0.5 + 0.03 * fine[q] - ck[q] * 0.6; + const t = (0.72 + 0.28 * ring) * (0.85 + 0.25 * grain[q]) * (0.88 + 0.2 * n2[q]) * (1 - ck[q] * 0.7); + setc(o, q, [92 * t, 76 * t, 62 * t]); o.ro[q] = 0.8 + 0.1 * fine[q] - 0.05 * sc; + } + return finish(o, S * 0.01 / 1.0, 1.8); + }; + + // CLAY ROOF TILE: plain tiles, 100 mm gauge, half-bond; each row stands proud over the row below. + function roofTiles(S, seed, P) { + const R = rng(seed), o = Out(S), rows = P.rows, cols = P.cols, ch = S / rows, tw = S / cols, gap = P.gap * S / 1024; + const n1 = fbm(S, 32, 4, seed + 1), n2 = fbm(S, 8, 4, seed + 2), grit = fbm(S, 256, 2, seed + 3), lay = fbm(S, 200, 2, seed + 4, 24), moss = fbm(S, 20, 4, seed + 5); + const T = []; + for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) T.push({ col: jitterCol(P.pal[R.int(P.pal.length)], R, P.var, 0.04), k: 1 + R.int(27), dy: (R() < P.slip ? R.range(4, 10) : R.range(-1.5, 1.5)) * S / 1024, rot: R.range(-0.015, 0.015), dx: R.range(-2, 2) * S / 1024, chip: R() < P.chipP ? { s: R() < 0.5 ? 0 : 1, r: R.range(6, 16) * S / 1024 } : null }); + for (let y = 0; y < S; y++) for (let x = 0; x < S; x++) { + const q = y * S + x; + // the row whose visible strip contains y (row r covers y in [r*ch, (r+1)*ch) as seen; its lower edge is at r*ch) + const r = Math.floor(y / ch), off = (r % 2) * tw / 2, xx = x - off, cu = Math.floor(xx / tw), c = ((cu % cols) + cols) % cols, t = T[r * cols + c]; + const ccx = off + cu * tw + tw / 2, wx = ccx < 0 ? -1 : ccx >= S ? 1 : 0; + const lx = xx - cu * tw - tw / 2 - t.dx + (y - r * ch) * t.rot, ly = y - r * ch - t.dy; + const dSide = tw / 2 - gap / 2 - Math.abs(lx) + (n1[q] - 0.5) * 1.5 * S / 1024; + let inside = sstep(0, 1.6 * S / 1024, dSide) * sstep(-1, 1.2 * S / 1024, ly + (n1[q] - 0.5) * 2 * S / 1024); + if (t.chip && t.chip.s === (lx < 0 ? 0 : 1)) { const d = Math.hypot(Math.abs(lx) - tw / 2, Math.max(ly, 0)); if (d < t.chip.r * (0.8 + 0.4 * n1[q])) inside = 0; } + const fy = clamp(ly / ch, 0, 1.2); + const thick = 1 - fy * 0.32; // proud at the lower edge + const camber = -0.04 * Math.pow((lx / (tw / 2)), 2); + const below = 0.38 + 0.25 * clamp((y - r * ch) / ch, 0, 1); // what shows through a gap: the tile underneath, lower + o.h[q] = lerp(below * 0.6, thick * 0.92 + camber + 0.03 * (n2[q] - 0.5) + P.lay * (lay[q] - 0.5), inside); + const tt = (0.86 + 0.22 * n1[q]) * (0.92 + 0.12 * grit[q]) * (1 - 0.18 * sstep(0.7, 1.0, fy)); + let cr = t.col[0] * tt, cg = t.col[1] * tt, cb = t.col[2] * tt; + // lichen and moss collect at the lower edges and in the shade under the row above + const ms = sstep(0.55, 0.75, moss[q] + (1 - clamp(ly / (ch * 0.5), 0, 1)) * 0.25) * P.moss; + if (ms > 0) { cr = lerp(cr, 74, ms * 0.7); cg = lerp(cg, 82, ms * 0.7); cb = lerp(cb, 50, ms * 0.7); } + const shadow = 1 - 0.45 * (1 - inside); + o.r[q] = cr * shadow / 255; o.g[q] = cg * shadow / 255; o.b[q] = cb * shadow / 255; + o.ro[q] = P.rough + 0.1 * (grit[q] - 0.5) + ms * 0.08; + o.id[q] = inside > 0.5 ? idByte(t.k, wx, 0) : 112; + } + return o; + } + G.roof_tile = (S, seed) => finish(roofTiles(S, seed, { rows: 10, cols: 6, gap: 4, pal: [[146, 76, 52], [140, 72, 50], [150, 80, 56], [138, 72, 52], [144, 78, 56]], var: 0.04, slip: 0.03, chipP: 0.18, rough: 0.78, moss: 0.9, lay: 0.0 }), S * 0.016 / 1.0, 2.0); + G.slate = (S, seed) => finish(roofTiles(S, seed, { rows: 9, cols: 4, gap: 3, pal: [[72, 75, 82], [70, 72, 79], [75, 77, 83], [71, 71, 77], [68, 71, 76]], var: 0.035, slip: 0.02, chipP: 0.3, rough: 0.62, moss: 0.5, lay: 0.05 }), S * 0.009 / 1.0, 1.8); + + // COBBLES: granite setts in rough rows with dirt and moss in the joints. Tile 1.5 m. + G.cobbles = function (S, seed) { + const R = rng(seed), o = Out(S), pts = []; let y = 0; + const rows = 12, ch = S / rows; + for (let r = 0; r < rows; r++) { let x = R.range(0, 30); while (x < S - 10) { const w = R.range(0.09, 0.16) / 1.5 * S; pts.push({ x: (x + w / 2) % S, y: (r + 0.5) * ch + R.range(-3, 3), w: 1, k: 1 + R.int(27), t: R.range(0.94, 1.05), hue: R() }); x += w; } } + const W = worley(S, pts, 1.15, true); + const n1 = fbm(S, 32, 4, seed + 1), n2 = fbm(S, 8, 3, seed + 2), grit = fbm(S, 256, 2, seed + 3); + for (let q = 0; q < S * S; q++) { + const p = pts[W.ID[q]], e = W.F2[q] - W.F1[q] + (n1[q] - 0.5) * 6 * S / 1024; + const inside = sstep(4 * S / 1024, 12 * S / 1024, e), dome = sstep(0, 30 * S / 1024, e); + o.h[q] = lerp(0.1 + 0.1 * n2[q], 0.55 + 0.4 * dome + 0.04 * (grit[q] - 0.5), inside); + const t = p.t * (0.85 + 0.25 * n1[q]) * (0.9 + 0.2 * grit[q]); + const c = p.hue < 0.3 ? [108, 104, 98] : p.hue < 0.7 ? [104, 101, 96] : [110, 104, 96]; + const dirt = [56, 48, 38], ms = sstep(0.5, 0.7, n2[q]) * (1 - inside); + setc(o, q, [lerp(lerp(dirt[0], 52, ms), c[0] * t, inside), lerp(lerp(dirt[1], 62, ms), c[1] * t, inside), lerp(lerp(dirt[2], 34, ms), c[2] * t, inside)]); + o.ro[q] = lerp(0.95, 0.5 + 0.25 * (1 - dome) + 0.1 * grit[q], inside); + o.id[q] = inside > 0.5 ? idByte(p.k, W.WX[q], W.WY[q]) : 112; + } + return finish(o, S * 0.03 / 1.5, 2.2); + }; + + // ROUGH LIME PLASTER (render) with cracks and patches fallen away to the stone behind. Tile 2.5 m. + G.plaster = function (S, seed, interior) { + const R = rng(seed), o = Out(S); + const n1 = fbm(S, 6, 5, seed + 1), n2 = fbm(S, 24, 4, seed + 2), grit = fbm(S, 256, 2, seed + 3), patch = fbm(S, 4, 5, seed + 4), stain = fbm(S, 14, 4, seed + 5, 3); + const ck = new Float32Array(S * S); + for (let i = 0; i < (interior ? 2 : 9); i++) crack(ck, S, R, R() * S, R() * S, R.range(60, 260) * S / 1024, R() * 6.28, R.range(0.7, 1.4) * S / 1024 * (interior ? 0.5 : 1), interior ? 0.5 : 1, true); + const pts = []; for (let i = 0; i < 260; i++) pts.push({ x: R() * S, y: R() * S, w: R.range(0.8, 1.2) }); + const Wn = worley(S, pts, 1.5, true); + const base = interior ? [200, 192, 172] : [184, 176, 156]; + for (let q = 0; q < S * S; q++) { + const fall = interior ? 0 : sstep(0.66, 0.69, patch[q] + n2[q] * 0.08); + const st = Wn.F2[q] - Wn.F1[q], stone = sstep(2, 7, st * S / 1024 * 1.8); + const ph = 0.86 + 0.06 * n1[q] + 0.03 * n2[q] + 0.015 * grit[q] - ck[q] * 0.35; + const sh = 0.25 + 0.25 * stone + 0.05 * grit[q]; + o.h[q] = lerp(ph, sh, fall); + const t = (0.88 + 0.16 * n1[q]) * (0.95 + 0.08 * grit[q]) * (1 - ck[q] * 0.45); + const s = clamp((stain[q] - 0.45) * 1.6, 0, 1) * (interior ? 0.4 : 1); + let c = [base[0] * t * (1 - s * 0.25), base[1] * t * (1 - s * 0.23), base[2] * t * (1 - s * 0.28)]; + const stc = [118 * (0.8 + 0.4 * grit[q]), 110 * (0.8 + 0.4 * grit[q]), 96 * (0.8 + 0.4 * grit[q])]; + c = [lerp(c[0], lerp(70, stc[0], stone), fall), lerp(c[1], lerp(66, stc[1], stone), fall), lerp(c[2], lerp(58, stc[2], stone), fall)]; + // a dark rim where the plaster edge has broken away + const rim = interior ? 0 : sstep(0.62, 0.66, patch[q] + n2[q] * 0.08) * (1 - fall); c = c.map(v => v * (1 - rim * 0.3)); + setc(o, q, c); o.ro[q] = 0.9 + 0.06 * grit[q] - s * 0.05; + } + return finish(o, S * 0.012 / 2.5, 2.0, S / 90); + }; + G.plaster_interior = (S, seed) => G.plaster(S, seed, true); + + // CONCRETE with board-formwork marks, tie holes, blowholes and rain stains. Tile 2.4 m. + G.concrete = function (S, seed) { + const R = rng(seed), o = Out(S), nb = 16, bh = S / nb; + const grainA = fbm(S, 4, 4, seed + 1, 64), n1 = fbm(S, 16, 4, seed + 2), grit = fbm(S, 256, 2, seed + 3), stain = fbm(S, 28, 4, seed + 4, 2), pores = fbm(S, 180, 1, seed + 5); + const off = []; for (let i = 0; i < nb; i++) off.push({ h: R.range(-0.05, 0.05), t: R.range(0.92, 1.06), g: R.range(0, 100) }); + for (let y = 0; y < S; y++) for (let x = 0; x < S; x++) { + const q = y * S + x, b = Math.floor(y / bh), ly = y - b * bh, B = off[b]; + const joint = sstep(2.5 * S / 1024, 0, Math.min(ly, bh - ly)); + const gr = Math.sin((x / S * 3 + grainA[q] * 2 + B.g) * 40) * 0.5 + 0.5; + const pit = pores[q] > 0.86 ? (pores[q] - 0.86) * 4 : 0; + o.h[q] = 0.7 + B.h + 0.03 * gr + 0.04 * (n1[q] - 0.5) + joint * 0.05 - pit; + const s = clamp((stain[q] - 0.4) * 1.5, 0, 1); + const t = B.t * (0.86 + 0.18 * n1[q]) * (0.92 + 0.12 * grit[q]) * (1 - s * 0.32) * (1 - pit * 1.5); + setc(o, q, [124 * t, 122 * t, 116 * t]); o.ro[q] = 0.86 + 0.08 * grit[q] - s * 0.08; + } + // tie-bolt holes + for (let i = 0; i < 4; i++) disc(o.h, S, (i % 2 + 0.25) * S / 2, (Math.floor(i / 2) + 0.5) * S / 2, 7 * S / 1024, (v, d, q) => { mulc(o, q, 0.4 + 0.6 * d); return v - (1 - d) * 0.4; }); + return finish(o, S * 0.006 / 2.4, 2.0); + }; + + // PAINTED METAL: olive-grey paint chipped to red primer and bright steel; scratches. A = bare-metal mask. + G.metal_painted = function (S, seed) { + const R = rng(seed), o = Out(S); + const n1 = fbm(S, 12, 5, seed + 1), fine = fbm(S, 128, 2, seed + 2), dent = fbm(S, 6, 3, seed + 3), rust = fbm(S, 20, 4, seed + 4); + for (let q = 0; q < S * S; q++) { + const v = n1[q] * 0.8 + fine[q] * 0.2, prim = sstep(0.66, 0.68, v), bare = sstep(0.71, 0.73, v); + o.h[q] = 0.8 + 0.08 * (dent[q] - 0.5) - prim * 0.04 - bare * 0.03 + 0.01 * fine[q]; + let c = [80, 86, 72].map(k => k * (0.9 + 0.15 * fine[q]) * (0.9 + 0.12 * n1[q])); + c = c.map((k, i) => lerp(k, [112, 54, 38][i], prim)); c = c.map((k, i) => lerp(k, [150, 148, 144][i], bare)); + const rs = sstep(0.68, 0.78, rust[q]) * (1 - bare * 0.5); c = c.map((k, i) => lerp(k, [96, 50, 26][i] * (0.7 + 0.5 * fine[q]), rs * 0.8)); + setc(o, q, c); o.ro[q] = lerp(lerp(0.58 + 0.1 * fine[q], 0.72, prim), 0.36, bare) + rs * 0.25; o.id[q] = Math.round(bare * (1 - rs) * 255); + } + for (let i = 0; i < 70; i++) { const x = R() * S, y = R() * S, a = R() * 6.28, l = R.range(8, 80) * S / 1024; line(S, x, y, x + Math.cos(a) * l, y + Math.sin(a) * l, R.range(0.5, 1.1) * S / 1024, q => { mixc(o, q, [150, 148, 140], 0.6); o.id[q] = 200; o.ro[q] = 0.4; o.h[q] -= 0.02; }); } + return finish(o, S * 0.002 / 1.0, 0.8); + }; + // RUSTY METAL: corroded steel with pits and flakes and a little old paint. + G.metal_rust = function (S, seed) { + const o = Out(S); + const n1 = fbm(S, 10, 5, seed + 1), fine = fbm(S, 160, 2, seed + 2), pit = fbm(S, 64, 3, seed + 3), paint = fbm(S, 8, 4, seed + 4); + for (let q = 0; q < S * S; q++) { + const p = sstep(0.62, 0.72, pit[q]), pa = sstep(0.62, 0.64, paint[q]); + o.h[q] = 0.7 + 0.12 * (n1[q] - 0.5) - p * 0.25 + 0.04 * fine[q] + pa * 0.05; + const t = 0.75 + 0.45 * n1[q] * (0.8 + 0.4 * fine[q]); + let c = [104 * t, 58 * t, 32 * t]; if (n1[q] > 0.6) c = c.map((k, i) => lerp(k, [64, 44, 34][i], (n1[q] - 0.6) * 2)); + c = c.map((k, i) => lerp(k, [70, 76, 64][i], pa)); c = c.map(k => k * (1 - p * 0.45)); + setc(o, q, c); o.ro[q] = 0.88 + 0.08 * fine[q] - pa * 0.25; o.id[q] = Math.round(sstep(0.8, 0.95, fine[q]) * (1 - pa) * 120); + } + return finish(o, S * 0.004 / 1.0, 1.2); + }; + + // WOVEN CLOTH helper (sandbags = coarse hessian, canvas = tight cotton duck). + function weave(S, seed, P) { + const o = Out(S), n = P.threads, tp = S / n; + const n1 = fbm(S, 8, 4, seed + 1), fine = fbm(S, 256, 2, seed + 2), wob = fbm(S, 32, 3, seed + 3), stain = fbm(S, 6, 4, seed + 4), th = fbm(S, n, 1, seed + 5); + for (let y = 0; y < S; y++) for (let x = 0; x < S; x++) { + const q = y * S + x, xx = x + (wob[q] - 0.5) * tp * 0.8, yy = y + (wob[(q + S * 7) % (S * S)] - 0.5) * tp * 0.8; + const ix = Math.floor(xx / tp), iy = Math.floor(yy / tp), fx = xx / tp - ix, fy = yy / tp - iy; + const over = ((ix + iy) & 1) === 0; + const warp = Math.sin(fx * Math.PI), weft = Math.sin(fy * Math.PI); + const hv = over ? Math.max(warp * 0.95, weft * 0.6) : Math.max(weft * 0.95, warp * 0.6); + o.h[q] = 0.3 + 0.6 * Math.pow(hv, 0.7) + 0.08 * (n1[q] - 0.5); + const t = (0.7 + 0.35 * hv) * (0.82 + 0.3 * th[q]) * (0.9 + 0.2 * n1[q]) * (0.92 + 0.12 * fine[q]); + const s = clamp((stain[q] - 0.5) * 2, 0, 1) * P.stain; + setc(o, q, P.col.map((k, i) => lerp(k * t, [52, 42, 30][i], s))); + o.ro[q] = 0.92 + 0.05 * fine[q]; + } + return o; + } + G.sandbag = (S, seed) => finish(weave(S, seed, { threads: 48, col: [138, 116, 80], stain: 0.6 }), S * 0.003 / 0.5, 1.8); + G.canvas = (S, seed) => finish(weave(S, seed, { threads: 128, col: [96, 94, 66], stain: 0.5 }), S * 0.001 / 0.8, 1.2); + + // DIRTY GLASS: dark, smooth where clean, grime in the corners and run-down streaks. + G.glass = function (S, seed) { + const o = Out(S); + const n1 = fbm(S, 6, 5, seed + 1), streak = fbm(S, 40, 3, seed + 2, 3), fine = fbm(S, 128, 2, seed + 3); + for (let y = 0; y < S; y++) for (let x = 0; x < S; x++) { + const q = y * S + x, u = x / S, v = y / S, edge = Math.min(u, 1 - u, v, 1 - v); + const d = clamp(sstep(0.16, 0.0, edge) * 0.8 + sstep(0.35, 0.0, v) * 0.35 * streak[q] + (n1[q] - 0.5) * 0.5 + sstep(0.62, 0.72, streak[q]) * 0.25, 0, 1); + o.h[q] = 0.9 + d * 0.05 + fine[q] * 0.01; + setc(o, q, [lerp(26, 92, d), lerp(30, 88, d), lerp(30, 74, d)]); o.ro[q] = lerp(0.05, 0.7, d); + } + return finish(o, S * 0.001, 0); + }; + + // GROUND: grass turf. Tile 2.5 m. Short blades, dead straw, bare soil showing. + G.grass_ground = function (S, seed) { + const R = rng(seed), o = Out(S); + const n1 = fbm(S, 8, 5, seed + 1), n2 = fbm(S, 40, 3, seed + 2), grit = fbm(S, 256, 2, seed + 3); + for (let q = 0; q < S * S; q++) { + const soil = sstep(0.62, 0.72, n1[q] * 0.7 + n2[q] * 0.3); + o.h[q] = 0.25 + 0.15 * n2[q] + 0.05 * grit[q]; + setc(o, q, [lerp(40, 54, grit[q]), lerp(34, 44, grit[q]), lerp(24, 31, grit[q])]); + o.ro[q] = 0.92; + o.id[q] = Math.round(soil * 255); // (reused below as the 'soil shows' weight) + } + const nBl = Math.round(S * S / 22); + for (let i = 0; i < nBl; i++) { + const x = R() * S, y = R() * S, q0 = (Math.floor(y) % S) * S + (Math.floor(x) % S); + if (o.id[q0] > 160 && R() < 0.8) continue; + const a = -Math.PI / 2 + R.range(-0.9, 0.9) + (n1[q0] - 0.5) * 2, l = R.range(6, 20) * S / 1024, dead = R() < 0.18 + n2[q0] * 0.25; + const c = dead ? [R.range(84, 104), R.range(74, 90), R.range(50, 62)] : [R.range(48, 70), R.range(60, 84), R.range(30, 42)]; + const hh = R.range(0.5, 1); + line(S, x, y, x + Math.cos(a) * l, y + Math.sin(a) * l, R.range(0.7, 1.3) * S / 1024, (q, t) => { const k = 0.65 + 0.35 * t; if (o.h[q] < 0.3 + hh * 0.6 * t + 0.1) { o.h[q] = 0.3 + hh * 0.6 * t + 0.1; setc(o, q, c, k); o.ro[q] = dead ? 0.85 : 0.72; } }); + } + for (let q = 0; q < S * S; q++) o.id[q] = 112; + return finish(o, S * 0.01 / 2.5, 2.4, S / 200); + }; + // MUD LANE: wet churned mud with hoof and boot prints, pebbles, straw and glossy wet hollows. Tile 3 m. + G.mud = function (S, seed) { + const R = rng(seed), o = Out(S); + const n1 = fbm(S, 8, 5, seed + 1), n2 = fbm(S, 48, 3, seed + 2), grit = fbm(S, 256, 2, seed + 3), streak = fbm(S, 4, 4, seed + 4, 24); + for (let q = 0; q < S * S; q++) o.h[q] = 0.45 + 0.25 * (n1[q] - 0.5) + 0.1 * (n2[q] - 0.5) + 0.08 * (streak[q] - 0.5) + 0.03 * grit[q]; + for (let i = 0; i < 70; i++) { const x = R() * S, y = R() * S, r = R.range(10, 22) * S / 1024, rx = R.range(0.6, 1); disc(o.h, S, x, y, r, (v, d) => v - (1 - d * d) * 0.08 * rx + (d > 0.8 ? 0.02 : 0)); } + for (let i = 0; i < 160; i++) { const x = R() * S, y = R() * S, r = R.range(1.5, 4) * S / 1024, t = R.range(0.55, 0.9); disc(o.h, S, x, y, r, (v, d, q) => { setc(o, q, [96 * t, 90 * t, 80 * t]); o.id[q] = 99; return Math.max(v, 0.7 + (1 - d * d) * 0.2); }); } + for (let q = 0; q < S * S; q++) { + if (o.id[q] === 99) { o.ro[q] = 0.6; o.id[q] = 112; continue; } + const h = o.h[q], wet = sstep(0.42, 0.3, h), dry = sstep(0.55, 0.7, h); + const t = 0.85 + 0.2 * n2[q] + 0.08 * grit[q]; + setc(o, q, [lerp(lerp(70, 44, wet), 96, dry) * t, lerp(lerp(58, 36, wet), 84, dry) * t, lerp(lerp(44, 28, wet), 66, dry) * t]); + o.ro[q] = lerp(0.82, 0.22, wet) + 0.08 * grit[q]; + } + for (let i = 0; i < 90; i++) { const x = R() * S, y = R() * S, a = R() * 6.28, l = R.range(12, 40) * S / 1024; line(S, x, y, x + Math.cos(a) * l, y + Math.sin(a) * l, 0.9 * S / 1024, q => { setc(o, q, [120, 104, 70]); o.h[q] += 0.04; o.ro[q] = 0.8; }); } + return finish(o, S * 0.03 / 3, 1.6, S / 120); + }; + // PLOUGHED EARTH: furrows along u, clods, stubble. + G.earth = function (S, seed) { + const R = rng(seed), o = Out(S), nf = 10; + const n1 = fbm(S, 8, 5, seed + 1), n2 = fbm(S, 40, 3, seed + 2), grit = fbm(S, 256, 2, seed + 3), warp = fbm(S, 4, 3, seed + 4); + const pts = []; for (let i = 0; i < 900; i++) pts.push({ x: R() * S, y: R() * S, w: R.range(0.7, 1.3) }); + const Wc = worley(S, pts, 1, true); + for (let y = 0; y < S; y++) for (let x = 0; x < S; x++) { + const q = y * S + x, f = Math.sin((y / S * nf + warp[q] * 0.6) * Math.PI * 2) * 0.5 + 0.5; + const clod = sstep(0, 14 * S / 1024, Wc.F2[q] - Wc.F1[q]); + o.h[q] = 0.2 + 0.45 * f + 0.2 * clod * (0.5 + 0.5 * f) + 0.08 * (n1[q] - 0.5); + const t = (0.8 + 0.25 * n1[q]) * (0.9 + 0.15 * grit[q]) * (0.85 + 0.25 * f); + setc(o, q, [74 * t, 60 * t, 46 * t]); o.ro[q] = 0.9 - 0.15 * (1 - f) * sstep(0.5, 0.7, n2[q]); + } + for (let i = 0; i < 400; i++) { const x = R() * S, y = R() * S, a = R() * 6.28, l = R.range(6, 18) * S / 1024; line(S, x, y, x + Math.cos(a) * l, y + Math.sin(a) * l, 0.8 * S / 1024, q => { setc(o, q, [130, 116, 80]); o.h[q] += 0.06; }); } + return finish(o, S * 0.06 / 3, 1.8); + }; + // GRAVEL: packed small stones in dust. + G.gravel = function (S, seed) { + const R = rng(seed), o = Out(S), pts = []; + for (let i = 0; i < 2600; i++) pts.push({ x: R() * S, y: R() * S, w: R.range(0.6, 1.4), t: R.range(0.88, 1.06), c: R() }); + const W = worley(S, pts, 1, true); const n1 = fbm(S, 8, 4, seed + 1), grit = fbm(S, 256, 2, seed + 2); + for (let q = 0; q < S * S; q++) { + const p = pts[W.ID[q]], e = W.F2[q] - W.F1[q], ins = sstep(1.5 * S / 1024, 5 * S / 1024, e); + o.h[q] = lerp(0.2 + 0.1 * n1[q], 0.5 + 0.35 * sstep(0, 10 * S / 1024, e) * p.w * 0.8, ins); + const c = p.c < 0.5 ? [112, 106, 96] : p.c < 0.8 ? [116, 106, 90] : [104, 100, 94]; + setc(o, q, c.map((k, i) => lerp([80, 72, 60][i] * (0.8 + 0.3 * n1[q]), k * p.t * (0.9 + 0.15 * grit[q]), ins))); + o.ro[q] = lerp(0.95, 0.7, ins); + } + return finish(o, S * 0.015 / 1.5, 2.0); + }; + // LEAF LITTER: fallen oak and ash leaves over damp soil, tile 2 m. + G.leaves = function (S, seed) { + const R = rng(seed), o = Out(S); + const n1 = fbm(S, 8, 4, seed + 1), grit = fbm(S, 256, 2, seed + 2); + for (let q = 0; q < S * S; q++) { o.h[q] = 0.15 + 0.1 * n1[q]; setc(o, q, [46 * (0.8 + 0.3 * grit[q]), 38 * (0.8 + 0.3 * grit[q]), 30]); o.ro[q] = 0.85; } + const pal = [[112, 70, 36], [92, 58, 34], [130, 96, 52], [70, 48, 32], [104, 84, 46], [62, 56, 38]]; + const nL = Math.round(1700 * (S / 1024) * (S / 1024)); + for (let i = 0; i < nL; i++) { + const cx = R() * S, cy = R() * S, a = R() * Math.PI, L = R.range(18, 40) * S / 1024, Wd = L * R.range(0.28, 0.45), c = jitterCol(pal[R.int(pal.length)], R, 0.18, 0.05), hh = 0.3 + i / nL * 0.6, curl = R.range(0, 0.2); + const ca = Math.cos(a), sa = Math.sin(a), rr = Math.ceil(L); + for (let j = -rr; j <= rr; j++) for (let k = -rr; k <= rr; k++) { + const lu = (k * ca + j * sa) / L, lv = (-k * sa + j * ca) / Wd; + const lobe = 1 + 0.15 * Math.sin(lu * 18) ; const d = lu * lu + lv * lv * lobe * lobe; + if (d > 1) continue; + const q = ((((Math.round(cy) + j) % S) + S) % S) * S + (((Math.round(cx) + k) % S) + S) % S; + const vein = Math.abs(lv) < 0.08 ? 0.75 : 1; + o.h[q] = hh + (1 - d) * 0.05 + curl * lv * lv; setc(o, q, c, vein * (0.85 + 0.2 * grit[q])); o.ro[q] = 0.75; + } + } + return finish(o, S * 0.01 / 2, 2.2); + }; + + // BARK: deep vertical furrows (oak/ash/poplar/apple; tinted per tree) and plated pine bark. Tile 1 x 1 m. + G.bark_oak = function (S, seed) { + const R = rng(seed), o = Out(S), pts = []; + for (let i = 0; i < 160; i++) pts.push({ x: R() * S, y: R() * S, w: 1 }); + const W = worley(S, pts, 0.22, true); + const n1 = fbm(S, 16, 4, seed + 1, 4), fine = fbm(S, 128, 2, seed + 2, 32), lich = fbm(S, 12, 4, seed + 3); + for (let q = 0; q < S * S; q++) { + const e = W.F2[q] - W.F1[q], ridge = sstep(0, 26 * S / 1024, e + (n1[q] - 0.5) * 16 * S / 1024); + o.h[q] = 0.15 + 0.75 * Math.pow(ridge, 0.7) + 0.06 * (fine[q] - 0.5); + const t = (0.55 + 0.55 * ridge) * (0.85 + 0.25 * fine[q]); + let c = [92 * t, 84 * t, 74 * t]; + const l = sstep(0.6, 0.72, lich[q]) * ridge; c = c.map((k, i) => lerp(k, [96, 106, 78][i], l * 0.7)); + setc(o, q, c); o.ro[q] = 0.9; + } + return finish(o, S * 0.04 / 1, 2.4); + }; + G.bark_pine = function (S, seed) { + const R = rng(seed), o = Out(S), pts = []; + for (let i = 0; i < 70; i++) pts.push({ x: R() * S, y: R() * S, w: R.range(0.8, 1.2), t: R.range(0.8, 1.15) }); + const W = worley(S, pts, 0.6); + const n1 = fbm(S, 16, 4, seed + 1), fine = fbm(S, 128, 2, seed + 2, 16); + for (let q = 0; q < S * S; q++) { + const p = pts[W.ID[q]], e = W.F2[q] - W.F1[q] + (n1[q] - 0.5) * 10 * S / 1024, plate = sstep(3 * S / 1024, 14 * S / 1024, e); + const flake = Math.floor(fine[q] * 4) / 4; + o.h[q] = 0.1 + 0.7 * plate + 0.08 * flake * plate; + const t = p.t * (0.8 + 0.3 * fine[q]); + setc(o, q, [lerp(40, 118 * t, plate), lerp(32, 80 * t, plate), lerp(28, 60 * t, plate)]); o.ro[q] = 0.88; + } + return finish(o, S * 0.03 / 1, 2.2); + }; + + // STRAW: hay bales and loose straw. Tile 1 m. + G.straw = function (S, seed) { + const R = rng(seed), o = Out(S); const n1 = fbm(S, 8, 4, seed + 1); + for (let q = 0; q < S * S; q++) { o.h[q] = 0.1; setc(o, q, [60, 50, 32]); o.ro[q] = 0.9; } + const n = Math.round(9000 * (S / 1024) * (S / 1024)); + for (let i = 0; i < n; i++) { + const x = R() * S, y = R() * S, a = R.range(-0.5, 0.5) + (R() < 0.15 ? R() * 3 : 0), l = R.range(30, 120) * S / 1024, hh = 0.2 + i / n * 0.7; + const c = jitterCol(R() < 0.7 ? [168, 148, 96] : [130, 118, 82], R, 0.18, 0.04); + const k = 0.7 + 0.3 * n1[(Math.floor(y) % S) * S + (Math.floor(x) % S)]; + line(S, x, y, x + Math.cos(a) * l, y + Math.sin(a) * l, R.range(0.8, 1.6) * S / 1024, (q, t, d) => { o.h[q] = hh + (1 - d) * 0.03; setc(o, q, c, k * (1 - d * 0.3)); o.ro[q] = 0.7; }); + } + return finish(o, S * 0.01, 1.8); + }; + + // ------------------------------------------------------------------ decal atlas (4 x 4 cells), wear and damage + // Each cell: RGB colour, A coverage; NRI: normal, roughness, A = 255. Cells (row-major from v=0): + // 0 scratches, 1 gouges, 2 chipped paint, 3 bullet pocks, 4 scorch, 5 soot streak, 6 damp, 7 moss, 8 rust run, + // 9 mud splash, 10 crack, 11 bullet hole, 12 leaf litter, 13 water stain, 14 chalk marks (tally lines), 15 grime + G.decals = function (S, seed) { + const R = rng(seed), C = S / 4, n = S * S; + const col = new Float32Array(n * 3), al = new Float32Array(n), h = new Float32Array(n).fill(0.5), ro = new Float32Array(n).fill(0.85); + const nA = fbm(S, 32, 5, seed + 1), nB = fbm(S, 128, 2, seed + 2), nC = fbm(S, 12, 4, seed + 3, 2); + function cell(ci, fn) { + const ox = (ci % 4) * C, oy = Math.floor(ci / 4) * C; + for (let y = 0; y < C; y++) for (let x = 0; x < C; x++) { + const q = (oy + y) * S + ox + x, u = x / C, v = y / C, rr = Math.hypot(u - 0.5, v - 0.5) * 2; + const edge = sstep(1, 0.8, Math.max(Math.abs(u - 0.5), Math.abs(v - 0.5)) * 2); + fn(q, u, v, rr, edge); + } + } + const put = (q, c, a, hh, r) => { col[q * 3] = c[0] / 255; col[q * 3 + 1] = c[1] / 255; col[q * 3 + 2] = c[2] / 255; al[q] = clamp(a, 0, 1); if (hh != null) h[q] = hh; if (r != null) ro[q] = r; }; + const strokes = (ci, cnt, wmin, wmax, lmin, lmax, c, depth, a0, angJ) => { + const ox = (ci % 4) * C, oy = Math.floor(ci / 4) * C; + for (let i = 0; i < cnt; i++) { + const x = R.range(0.1, 0.9) * C, y = R.range(0.1, 0.9) * C, a = a0 + R.range(-angJ, angJ), l = R.range(lmin, lmax) * C; + const x1 = clamp(x + Math.cos(a) * l, 2, C - 2), y1 = clamp(y + Math.sin(a) * l, 2, C - 2), w = R.range(wmin, wmax) * C; + line(S, ox + x, oy + y, ox + x1, oy + y1, w, (q, t, d) => { const taper = Math.sin(t * Math.PI); if (taper < 0.15) return; put(q, c, Math.max(al[q], taper * (1 - d * 0.5)), 0.5 - depth * (1 - d) * taper, 0.45); }); + } + }; + strokes(0, 26, 0.004, 0.009, 0.15, 0.5, [176, 170, 158], 0.25, 0.3, 0.6); // scratches + strokes(1, 6, 0.012, 0.024, 0.2, 0.55, [70, 62, 54], 0.9, -0.2, 0.5); // gouges + cell(2, (q, u, v, r, e) => { const m = sstep(0.55, 0.57, nA[q] * 0.8 + (1 - r) * 0.35) * e; if (m > 0) put(q, [122, 108, 90].map(k => k * (0.85 + 0.3 * nB[q])), m, 0.42, 0.8); }); // chipped paint (bare wood/primer) + cell(3, (q, u, v, r, e) => { // bullet pocks (several small craters) + let m = 0, hh = 0.5; + for (let i = 0; i < 6; i++) { const cx = 0.2 + 0.6 * hash2(i, 3, seed), cy = 0.2 + 0.6 * hash2(i, 4, seed), d = Math.hypot(u - cx, v - cy) / (0.05 + 0.03 * hash2(i, 5, seed)); if (d < 1.6) { m = Math.max(m, sstep(1.6, 0.9, d + (nB[q] - 0.5) * 0.4)); hh = Math.min(hh, 0.5 - sstep(1, 0, d) * 0.6); } } + if (m > 0) put(q, [128, 118, 104].map(k => k * (0.6 + 0.6 * nB[q]) * (hh < 0.3 ? 0.55 : 1)), m, hh, 0.95); + }); + cell(4, (q, u, v, r, e) => { const m = sstep(1, 0.2, r + (nA[q] - 0.5) * 0.6) * e; put(q, [14, 12, 10], m * 0.95, 0.5, 0.95); }); // scorch + cell(5, (q, u, v, r, e) => { const m = sstep(0.9, 0.0, Math.abs(u - 0.5) * 2 + (nC[q] - 0.5) * 0.9) * sstep(0, 0.3, v) * e; put(q, [16, 14, 13], m * 0.85 * (0.4 + 0.6 * v), 0.5, 0.92); }); // soot streak (rises up) + cell(6, (q, u, v, r, e) => { const m = sstep(0.8, 0.0, v + (nA[q] - 0.5) * 0.5) * e; put(q, [42, 44, 36], m * 0.75, 0.5, 0.55); }); // damp (rising) + cell(7, (q, u, v, r, e) => { const m = sstep(0.55, 0.6, nA[q] * 0.7 + (1 - r) * 0.4) * e; put(q, [56, 72, 34].map(k => k * (0.7 + 0.5 * nB[q])), m, 0.5 + m * 0.2 * nB[q], 0.95); }); // moss + cell(8, (q, u, v, r, e) => { const m = sstep(0.5, 0.0, Math.abs(u - 0.5) * 2 + (nC[q] - 0.5) * 0.7) * sstep(0, 0.2, 1 - v) * sstep(0, 0.6, v + nA[q] * 0.3) * e; put(q, [104, 50, 22], m * 0.85, 0.5, 0.8); }); // rust run (from the top down) + cell(9, (q, u, v, r, e) => { const m = sstep(0.62, 0.66, nB[q] * 0.5 + nA[q] * 0.3 + (1 - v) * 0.3) * e; put(q, [62, 50, 36], m * 0.9, 0.5 + m * 0.05, 0.75); }); // mud splash (from the ground up) + { const tmp = new Float32Array(n); const ox = 2 * C, oy = 2 * C; crack(tmp, S, R, ox + C / 2, oy + C * 0.15, C * 0.75, Math.PI / 2, C * 0.012, 1, true); cell(10, (q, u, v, r, e) => { if (tmp[q] > 0) put(q, [20, 18, 16], tmp[q] * e, 0.5 - tmp[q] * 0.5, 0.95); }); } // crack + cell(11, (q, u, v, r, e) => { // bullet hole: dark hole, torn ring, dust halo + const rr2 = r + (nB[q] - 0.5) * 0.12; + if (rr2 < 0.14) put(q, [6, 5, 5], 1, 0.0, 1); else if (rr2 < 0.34) put(q, [150, 140, 124].map(k => k * (0.6 + 0.5 * nB[q])), 1, 0.25 + (rr2 - 0.14) * 1.6, 0.95); + else { const m = sstep(0.9, 0.34, rr2 + (nA[q] - 0.5) * 0.3); if (m > 0) put(q, [96, 90, 80], m * 0.5, 0.5, 0.95); } + }); + cell(12, (q, u, v, r, e) => { const m = sstep(0.5, 0.56, nB[q] * 0.6 + nA[q] * 0.3 + (1 - r) * 0.25) * e; put(q, [92, 62, 34].map(k => k * (0.6 + 0.6 * nA[q])), m, 0.5 + m * 0.1, 0.8); }); // leaf litter clump + cell(13, (q, u, v, r, e) => { const m = sstep(0.95, 0.6, r + (nA[q] - 0.5) * 0.4) * e; const ring = sstep(0.12, 0, Math.abs(r - 0.75 + (nA[q] - 0.5) * 0.3)); put(q, [60, 56, 46], m * 0.35 + ring * 0.35, 0.5, 0.6); }); // water stain + strokes(14, 5, 0.006, 0.01, 0.25, 0.35, [210, 204, 190], 0.0, Math.PI / 2, 0.08); // chalk tally marks + cell(15, (q, u, v, r, e) => { const m = sstep(1, 0.3, r) * (0.4 + 0.6 * nA[q]) * e; put(q, [30, 26, 22], m * 0.6, 0.5, 0.9); }); // grime + // pack (coverage-aware: colour kept under alpha 0 so filtering does not bleed black) + const alb = new Uint8Array(n * 4), nri = new Uint8Array(n * 4), hb = blur(h, S, 1, 1); + for (let y = 0; y < S; y++) for (let x = 0; x < S; x++) { + const q = y * S + x, xr = y * S + (x + 1) % S, xl = y * S + (x - 1 + S) % S, yu = ((y + 1) % S) * S + x, yd = ((y - 1 + S) % S) * S + x; + let nx = -(hb[xr] - hb[xl]) * 6, ny = -(hb[yu] - hb[yd]) * 6; const l = 1 / Math.sqrt(nx * nx + ny * ny + 1); + alb[q * 4] = col[q * 3] * 255; alb[q * 4 + 1] = col[q * 3 + 1] * 255; alb[q * 4 + 2] = col[q * 3 + 2] * 255; alb[q * 4 + 3] = al[q] * 255; + nri[q * 4] = (nx * l * 0.5 + 0.5) * 255; nri[q * 4 + 1] = (ny * l * 0.5 + 0.5) * 255; nri[q * 4 + 2] = ro[q] * 255; nri[q * 4 + 3] = 255; + } + return { S, alb, nri }; + }; + + // Shared tileable grey noise (R: large blotches, G: medium, B: fine, A: streaks) for macro variation in shaders. + G.macro = function (S, seed) { + const a = norm(fbm(S, 4, 5, seed + 1)), b = norm(fbm(S, 16, 4, seed + 2)), c = norm(fbm(S, 64, 2, seed + 3)), d = norm(fbm(S, 24, 3, seed + 4, 3)); + const alb = new Uint8Array(S * S * 4); + for (let q = 0; q < S * S; q++) { alb[q * 4] = a[q] * 255; alb[q * 4 + 1] = b[q] * 255; alb[q * 4 + 2] = c[q] * 255; alb[q * 4 + 3] = d[q] * 255; } + return { S, alb, nri: null }; + }; + + const API = { G, rng, fbm, worley, blur, hash2, generate: (name, S, seed) => G[name](S, seed) }; + if (typeof module !== 'undefined' && module.exports) module.exports = API; + else root.IVEnvTexGen = API; + // worker entry: {name, S, seed} -> {name, S, alb, nri, ms} + if (typeof WorkerGlobalScope !== 'undefined' && root instanceof WorkerGlobalScope) { + root.onmessage = function (e) { + const t0 = Date.now(), d = e.data, r = API.generate(d.name, d.S, d.seed), bufs = [r.alb.buffer]; if (r.nri) bufs.push(r.nri.buffer); + root.postMessage({ job: d.job, name: d.name, S: r.S, alb: r.alb, nri: r.nri, ms: Date.now() - t0 }, bufs); + }; + } +})(typeof self !== 'undefined' ? self : this); diff --git a/e63334287a3deaa3/ironveil/es.js b/e63334287a3deaa3/ironveil/es.js new file mode 100644 index 00000000..27c958fb --- /dev/null +++ b/e63334287a3deaa3/ironveil/es.js @@ -0,0 +1,137 @@ +/* Midnight Ops (folder ironveil/) in Spanish (lang.js; see README). English -> Spanish, in our own words. Loaded right + after lang.js, before the game's scripts. The game name itself comes from IV.GAME_NAME and is not translated. */ +(function () { + if (!window.BackRoomLang) return; + BackRoomLang.add({ + // ---- content note, title, menus + 'Before you play': 'Antes de jugar', '{n} contains war violence and blood.': '{n} tiene violencia bélica y sangre.', + 'Realistic Second World War weapons': 'Armas realistas de la Segunda Guerra Mundial', 'Enemy soldiers are shot and killed': 'Se dispara y se abate a soldados enemigos', + 'Blood effects (they can be turned off in Settings)': 'Efectos de sangre (se pueden quitar en Ajustes)', 'I understand, continue': 'Entiendo, continuar', 'Back': 'Volver', + 'Behind the lines, Normandy country, 1944.': 'Detrás de las líneas, campiña de Normandía, 1944.', + 'Continue': 'Continuar', 'Campaign': 'Campaña', 'Settings': 'Ajustes', 'Controls': 'Controles', 'checkpoint': 'punto de control', + 'Single player · progress saves in this browser': 'Un jugador · el progreso se guarda en este navegador', 'Back Room': 'Back Room', + 'The Farmhouse': 'La granja', 'Map table. Pick an operation. Each one can be replayed for a better rating.': 'Mesa de mapas. Elige una operación. Puedes repetirlas para mejorar la nota.', + 'Difficulty': 'Dificultad', 'Recruit': 'Recluta', 'Regular': 'Soldado', 'Veteran': 'Veterano', + 'Strong aim assist. Enemies slow to notice and miss more.': 'Mucha ayuda de puntería. Los enemigos tardan en verte y fallan más.', + 'Mild aim assist. A fair fight.': 'Ayuda de puntería suave. Una pelea pareja.', 'No aim assist. Sharp eyes, hard hits.': 'Sin ayuda de puntería. Ven bien y pegan fuerte.', + 'Done': 'Hecha', 'Locked': 'Bloqueada', 'New': 'Nueva', 'Coming soon': 'Muy pronto', 'gold': 'oro', 'silver': 'plata', 'bronze': 'bronce', + 'Secret': 'Secreto', 'Training': 'Entrenamiento', 'Objectives': 'Objetivos', 'Begin': 'Empezar', 'Skip tutorial': 'Saltar el tutorial', 'optional': 'opcional', + 'Sketch map of the area': 'Croquis de la zona', 'Game view': 'Vista del juego', + 'PAUSED': 'PAUSA', 'Resume': 'Seguir', 'Restart from checkpoint': 'Volver al punto de control', 'Restart mission': 'Reiniciar la misión', 'Quit to map table': 'Salir a la mesa de mapas', + 'Game': 'Juego', 'Video': 'Video', 'Audio': 'Audio', 'Look sensitivity': 'Sensibilidad de la vista', 'Aim sensitivity': 'Sensibilidad al apuntar', 'While aiming or scoped': 'Al apuntar o con la mira', + 'Invert look up and down': 'Invertir la vista arriba y abajo', 'Aim assist strength': 'Fuerza de la ayuda de puntería', "Multiplies the difficulty's assist. 0 turns it off.": 'Multiplica la ayuda de la dificultad. 0 la apaga.', + 'Auto-fire on target': 'Disparo automático sobre el blanco', 'Touch screens: fires when the reticle is on an enemy': 'Pantallas táctiles: dispara cuando la mira está sobre un enemigo', + 'Subtitle size': 'Tamaño de subtítulos', 'Small': 'Chico', 'Medium': 'Mediano', 'Large': 'Grande', 'Blood effects': 'Efectos de sangre', 'Off: hits show dust puffs instead': 'Apagado: los impactos muestran polvo', + 'Reduced motion': 'Menos movimiento', 'View': 'Vista', 'First person, or the camera over your shoulder': 'Primera persona, o la cámara sobre el hombro', 'First person': 'Primera persona', 'Over the shoulder': 'Sobre el hombro', 'Lean left': 'Asomarse a la izquierda', 'Lean L': 'Asom. I', 'Lean R': 'Asom. D', 'Lean right': 'Asomarse a la derecha', 'Swap shoulder (over-the-shoulder view)': 'Cambiar de hombro (vista sobre el hombro)', 'Camera bob': 'Balanceo de cámara', 'A small step bob and a dip when you land': 'Un leve balanceo al caminar y al caer', 'Less camera shake and sway, no lightning flashes': 'Menos sacudidas y balanceo de cámara, sin relámpagos', + 'Quality': 'Calidad', 'Low is best for school laptops and phones': 'Baja es mejor para laptops de la escuela y celulares', 'Low': 'Baja', 'High': 'Alta', 'Field of view': 'Campo de visión', 'Brightness': 'Brillo', + 'Master volume': 'Volumen general', 'Effects': 'Efectos', 'Music': 'Música', 'Mute (M)': 'Silencio (M)', 'Change keys': 'Cambiar teclas', + 'Quality changes apply when the page reloads': 'Los cambios de calidad se aplican al recargar la página', + 'Mission complete': 'Misión cumplida', 'Training complete': 'Entrenamiento completo', 'Mission failed': 'Misión fallida', 'Map table': 'Mesa de mapas', 'Replay': 'Repetir', 'Next: {t}': 'Siguiente: {t}', + 'Retry': 'Reintentar', 'Retry from checkpoint': 'Reintentar desde el punto de control', 'Gold': 'Oro', 'Silver': 'Plata', 'Bronze': 'Bronce', + 'Time': 'Tiempo', 'Accuracy': 'Puntería', 'Times spotted': 'Veces que te vieron', 'Enemies down': 'Enemigos abatidos', 'Takedowns': 'Derribos', 'Optional objectives': 'Objetivos opcionales', + 'You were killed.': 'Te mataron.', 'Killed. Back to the last checkpoint.': 'Caíste. Vuelves al último punto de control.', "Farm's north-east, past the orchard. Keep moving.": 'La granja está al noreste, pasando el huerto. Sigue.', 'Down the lane! Go!': '¡Camino abajo! ¡Vamos!', '{n} is down.': '{n} cayó.', 'Turn your phone sideways to play {n}.': 'Pon el celular de costado para jugar a {n}.', 'Loading…': 'Cargando…', + 'Loading soldiers…': 'Cargando soldados…', 'Laying out the country…': 'Trazando el campo…', 'Planting hedgerows…': 'Plantando setos…', 'Walking the lanes…': 'Recorriendo los caminos…', 'Briefing the squad…': 'Informando al pelotón…', + // ---- HUD + 'Standing': 'De pie', 'Crouched': 'Agachado', 'Prone': 'Cuerpo a tierra', 'Following': 'Te sigue', 'Holding': 'Espera', 'Fire at will': 'Fuego a discreción', 'Down': 'Caído', + 'Scoped rifle': 'Fusil con mira', 'Submachine gun': 'Subfusil', 'Pistol': 'Pistola', 'Binoculars': 'Binoculares', 'Grenade': 'Granada', 'Rock': 'Piedra', 's fuse': ' s de mecha', + 'Grenades': 'Granadas', 'Rocks': 'Piedras', 'Reloading': 'Recargando', 'Reload': 'Recargar', 'Takedown': 'Derribar', 'Use': 'Usar', 'Range': 'Distancia', 'Wind {s} m/s': 'Viento {s} m/s', + 'Checkpoint reached': 'Punto de control', 'Soldier marked': 'Soldado marcado', 'Bombing run: your noise is masked': 'Bombardeo: tapa tu ruido', + 'Tap Fire to mark the soldier in the middle': 'Toca Disparar para marcar al soldado del centro', '{k} marks the soldier in the middle': '{k} marca al soldado del centro', + 'N': 'N', 'NW': 'NO', 'W': 'O', 'SW': 'SO', 'S': 'S', 'SE': 'SE', 'E': 'E', 'NE': 'NE', + 'On you.': 'Detrás de ti.', 'Holding here.': 'Me quedo acá.', 'Weapons free. Say the word, I shoot.': 'Armas libres. Si hace falta, disparo.', + // keybinds actions + 'Sprint': 'Correr', 'Crouch': 'Agacharse', 'Go prone': 'Tirarse al suelo', 'Vault over / stand up': 'Saltar el obstáculo / pararse', 'Hold breath (scoped)': 'Contener la respiración (con mira)', + 'Grenade ': 'Granada', 'Throw a rock': 'Tirar una piedra', 'Knife takedown': 'Derribo con cuchillo', 'Use / interact': 'Usar / interactuar', 'Squad order': 'Orden al compañero', 'Swap shoulder': 'Cambiar de hombro', 'Mute': 'Silencio', + 'Hold. The rifle goes to its scope': 'Mantener. El fusil usa la mira', 'Hold to cook and aim, let go to throw': 'Mantén para quitar el seguro y apuntar, suelta para tirar', + 'Hold to aim, let go to throw. Guards go to look': 'Mantén para apuntar, suelta para tirar. Los guardias van a mirar', 'From behind, close up': 'Desde atrás, de cerca', + 'Hold. Fire tags the soldier in the middle': 'Mantener. Disparar marca al soldado del centro', 'Hold for longer jobs': 'Mantén para tareas largas', 'Follow, hold, fire at will': 'Seguir, esperar, fuego a discreción', 'Fight': 'Combate', + // ---- enemy barks + 'Hm? Who is there?': '¿Mm? ¿Quién anda ahí?', 'Did you hear that?': '¿Oíste eso?', 'Something moved.': 'Algo se movió.', 'I will take a look.': 'Voy a mirar.', 'Stay here. I am checking it.': 'Quédate acá. Voy a revisar.', + 'Nothing. Just the wind.': 'Nada. Solo el viento.', 'Probably a fox.': 'Seguro era un zorro.', 'Back to it.': 'A lo nuestro.', 'There! Enemy!': '¡Ahí! ¡Enemigo!', 'Alarm! Over there!': '¡Alarma! ¡Por allá!', 'Contact!': '¡Contacto!', + 'Man down! Over here!': '¡Hombre caído! ¡Acá!', 'He is dead! Search the area!': '¡Está muerto! ¡Revisen la zona!', 'Grenade!': '¡Granada!', 'Reloading!': '¡Recargando!', 'Go round the side!': '¡Rodéalo por el costado!', 'Falling back!': '¡Me repliego!', + // ---- campaign list + 'Boot Camp': 'Instrucción', 'A morning on the training range: moving, shooting, sneaking. About five minutes.': 'Una mañana en el campo de prácticas: moverse, disparar, escabullirse. Unos cinco minutos.', + 'Night Drop': 'Salto nocturno', 'Behind the lines at night. Find your corporal, then the flak gun at Mauvenant Farm.': 'Detrás de las líneas, de noche. Encuentra a tu cabo y luego el antiaéreo de la granja Mauvenant.', + 'The Radio Mast': 'La antena', 'A signals compound with three ways in. Silence the transmitter before it calls in the guns.': 'Un recinto de transmisiones con tres entradas. Calla el transmisor antes de que pida artillería.', + 'Bridge at Dawn': 'Puente al amanecer', 'Take the river bridge with the platoon, then hold it through three counter-attacks.': 'Toma el puente con el pelotón y resiste tres contraataques.', + 'The Clocktower': 'El campanario', 'Sniper overwatch over an occupied town while a courier crosses the square.': 'Cubres como francotirador un pueblo ocupado mientras un mensajero cruza la plaza.', + 'Rail Yard': 'La estación de carga', 'Charges on a fuel train, a fuse already burning, and a truck out of the yard.': 'Cargas en un tren de combustible, una mecha encendida y un camión para salir.', + 'The Chateau': 'El castillo', "Lift the plans from an officers' dinner. If the alarm goes, out through the cellars.": 'Roba los planos durante una cena de oficiales. Si suena la alarma, sales por los sótanos.', + 'The Bunker Line': 'La línea de búnkeres', 'Trenches, pillboxes and machine-gun nests, with the whole company behind you.': 'Trincheras, fortines y nidos de ametralladora, con toda la compañía detrás.', + 'Last Light': 'Última luz', 'A mountain research site, a prototype to wreck and a long shot at a fleeing convoy.': 'Un laboratorio en la montaña, un prototipo que destruir y un tiro largo a un convoy que huye.', + // ---- boot camp + 'Training range, England, the week before the jump. Sergeant Okafor runs the course.': 'Campo de prácticas en Inglaterra, la semana antes del salto. El sargento Okafor dirige el circuito.', + 'One thing at a time. Each station waits until you have done it, and the prompts show your own keys.': 'Una cosa por vez. Cada puesto espera a que lo hagas, y las ayudas muestran tus propias teclas.', + 'Move, sprint, crouch, crawl and vault': 'Moverse, correr, agacharse, arrastrarse y saltar', 'Pop-up targets with the aim assist': 'Blancos emergentes con ayuda de puntería', 'The scoped rifle at 100, 200 and 300 m': 'El fusil con mira a 100, 200 y 300 m', + 'Distract a guard and take him down': 'Distraer a un guardia y derribarlo', 'Binoculars and grenades': 'Binoculares y granadas', + 'Walk to the first post': 'Camina hasta el primer poste', 'Sprint to the next post': 'Corre hasta el siguiente poste', 'Crouch under the log': 'Pasa agachado bajo el tronco', 'Crawl under the wire': 'Arrástrate bajo el alambre', + 'Vault the wall': 'Salta el muro', 'Hit the three pop-up targets': 'Acierta a los tres blancos', 'Go to the rifle bench': 'Ve al puesto de tiro', 'Hit the 100, 200 and 300 m plates': 'Acierta a las placas de 100, 200 y 300 m', + 'Throw a rock to distract the guard': 'Tira una piedra para distraer al guardia', 'Sneak up behind him and take him down': 'Acércate por detrás y derríbalo', 'Mark the three dummies with the binoculars': 'Marca los tres muñecos con los binoculares', 'Throw a grenade into the pit': 'Tira una granada al pozo', + 'Morning. One thing at a time. Walk up to the first post.': 'Buen día. Una cosa por vez. Camina hasta el primer poste.', 'Now run. Hold sprint all the way to the flag.': 'Ahora corre. Mantén correr hasta la bandera.', + 'Under the log. Crouch and go through.': 'Bajo el tronco. Agáchate y pasa.', "Wire's low. On your belly and crawl.": 'El alambre está bajo. Al suelo y arrástrate.', "Wall. Over it, don't walk round it.": 'El muro. Por encima, no lo rodees.', + 'Pop-ups to your left. Aim, and the sights settle on the nearest one. Then squeeze.': 'Blancos a tu izquierda. Apunta y la mira se va al más cercano. Después aprieta.', + 'Rifle. Plates at one, two and three hundred yards. Well, metres. Close enough.': 'Fusil. Placas a cien, doscientos y trescientos metros.', + "Middle of the scope hits at one hundred. The marks under it are for two and three hundred. Wind's from the west, so lean into it.": 'El centro de la mira pega a cien. Las marcas de abajo son para doscientos y trescientos. El viento viene del oeste, corrígelo.', + "Corporal Hale is playing the guard in the pen. He's watching the gate. Draw him off with a stone, get behind him, and put him down. Gently.": 'El cabo Hale hace de guardia en el corral y vigila la tranquera. Atráelo con una piedra, ponte detrás y derríbalo. Con cuidado.', + 'Dummies downrange, dressed like the other side. Binoculars up and mark all three.': 'Hay muñecos en el campo, vestidos como el enemigo. Binoculares arriba y márcalos a los tres.', + "Last one. Grenade into the pit. The fuse starts when you pull the pin, so don't hang on to it.": 'El último. Granada al pozo. La mecha arranca al quitar el seguro, así que no la retengas.', + 'Missed. Have another.': 'Fallaste. Toma otra.', 'Seen you! Back out and try again.': '¡Te vi! Sal y prueba de nuevo.', "Ow. Alright, that'll do.": 'Ay. Bueno, alcanza.', + "That's the course. You'll do. Get some sleep, you jump tomorrow night.": 'Ese es el circuito. Sirves. Duerme un poco: saltas mañana a la noche.', + 'Move with {k}. Look with the mouse.': 'Muévete con {k}. Mira con el mouse.', 'the mouse': 'el mouse', 'a finger on the right side': 'un dedo en el lado derecho', 'the left stick': 'el joystick izquierdo', + 'Hold {k} to sprint': 'Mantén {k} para correr', '{k} crouches (and stands up again)': '{k} te agacha (y te vuelve a parar)', + '{k} goes prone. Crouched or prone, you are quieter and harder to see.': '{k} te tira al suelo. Agachado o en el suelo haces menos ruido y cuesta más verte.', + 'Run at it and press {k} to vault': 'Corre hacia él y pulsa {k} para saltarlo', 'Hold {a} to aim, {f} to fire. The aim pulls onto targets: that is the aim assist.': 'Mantén {a} para apuntar y {f} para disparar. La mira se va sola al blanco: esa es la ayuda de puntería.', + 'Good. Now get your head round cover without stepping out. Lean left, then right.': 'Bien. Ahora asoma la cabeza por la cobertura sin salir. Inclínate a la izquierda y luego a la derecha.', + 'Lean out to the left and to the right': 'Asómate a la izquierda y a la derecha', + 'Hold {l} to lean left and {r} to lean right. You can aim and fire while leaning.': 'Mantén {l} para asomarte a la izquierda y {r} a la derecha. Puedes apuntar y disparar asomado.', + 'Pop-ups to your left. Bring the gun up, look down the sights, then squeeze.': 'Blancos a tu izquierda. Sube el arma, mira por el alza y después aprieta.', + 'Hold {a} to look down the sights, {f} to fire. From the hip the crosshair opens up while you move. Your aim slows over a target: that is the aim assist.': 'Mantén {a} para mirar por el alza y {f} para disparar. Desde la cadera la cruz se abre al moverte. La puntería se frena sobre un blanco: esa es la ayuda de puntería.', + 'Hold {a} to put your eye to the scope. Hold {b} to steady your breath. Lie down for the steadiest shot.': 'Mantén {a} para llevar el ojo a la mira. Mantén {b} para contener la respiración. Acostado es el tiro más firme.', + 'Behind him and close: {k} for the knife': 'Por detrás y de cerca: {k} para el cuchillo', + 'Move, sprint, crouch, crawl, vault and lean': 'Moverse, correr, agacharse, arrastrarse, saltar y asomarse', 'Pop-up targets down the sights': 'Blancos emergentes con el alza', + 'Play upright anyway': 'Jugar en vertical igualmente', + 'In progress': 'En preparación', + 'Press {k} for the rifle': 'Pulsa {k} para el fusil', 'Hold {a} for the scope. Hold {b} to steady your breath. Lie down for the steadiest shot.': 'Mantén {a} para la mira. Mantén {b} para contener la respiración. Acostado es el tiro más firme.', + 'Hold {k} to aim a rock, let go to throw. Land it away from where you want to go.': 'Mantén {k} para apuntar una piedra y suelta para tirarla. Que caiga lejos de donde quieres ir.', + 'Behind him and close: {k}': 'Detrás y cerca: {k}', 'Hold {b} for binoculars, then {f} marks the one in the middle. Marked soldiers stay on your compass.': 'Mantén {b} para los binoculares; {f} marca al del centro. Los marcados quedan en tu brújula.', + 'Hold {g} to pull the pin and aim (the line shows where it lands), let go to throw.': 'Mantén {g} para quitar el seguro y apuntar (la línea muestra dónde cae), suelta para tirar.', + 'Finish in under 6:00': 'Terminar en menos de 6:00', 'Three plates in six rifle shots or fewer': 'Las tres placas en seis tiros o menos', 'Accuracy of 50% or better': 'Puntería del 50 % o más', + // ---- night drop + 'June 1944. Your stick of pathfinders jumps ahead of the main drop. A flak gun at Mauvenant Farm covers the drop zone, and it has to be gone before the transports come over.': 'Junio de 1944. Tu grupo de exploradores salta antes que el resto. Un antiaéreo en la granja Mauvenant cubre la zona de salto y hay que eliminarlo antes de que lleguen los aviones de transporte.', + "You will land wide. Find Cpl. Dunning, keep off the lanes the patrols walk, and cut the farm's field-telephone line on the way.": 'Vas a caer lejos. Encuentra al cabo Dunning, evita los caminos de las patrullas y corta la línea de teléfono de campaña de la granja.', + "Set the charge on the gun. When it goes up the whole farm will be on you: get clear and down the sunken lane to the east, where Rook's men are waiting.": 'Pon la carga en el cañón. Cuando explote, toda la granja irá por ti: sal y baja por el camino hundido del este, donde esperan los hombres de Rook.', + 'Find Cpl. Dunning': 'Encuentra al cabo Dunning', 'Cut the field-telephone line': 'Corta la línea de teléfono de campaña', 'Destroy the flak gun': 'Destruye el antiaéreo', 'Reach the extraction lane': 'Llega al camino de extracción', + 'Take the map from the farm office': 'Llévate el mapa de la oficina de la granja', 'Take out the sniper in the barn loft': 'Elimina al francotirador del altillo del granero', + 'Cut yourself free of the harness': 'Libérate del arnés', 'Cut the harness': 'Cortar el arnés', 'Get to the orchard west of the farm': 'Llega al huerto al oeste de la granja', 'Cut the telephone line': 'Cortar la línea', + 'Plant the charge on the flak gun': 'Pon la carga en el antiaéreo', 'Plant the charge': 'Poner la carga', 'Charge set on the flak gun': 'Carga puesta en el antiaéreo', "The house! Clear it, or we'll never hold this yard.": '¡La casa! Límpiala o no vamos a aguantar en el patio.', 'Clear the farmhouse': 'Limpia la casa', 'Take the map from the office desk': 'Llévate el mapa del escritorio', + 'Take the map': 'Tomar el mapa', 'Breach the door': 'Abrir la puerta', 'Hold the yard until the charge blows: {s}': 'Resiste en el patio hasta que explote la carga: {s}', + 'Pathfinder Two, Rook. You came down short. The stick is scattered east of the river.': 'Explorador Dos, aquí Rook. Caíste corto. El grupo está disperso al este del río.', + 'The flak gun at the farm is still yours. Find your corporal and get it done.': 'El antiaéreo de la granja sigue siendo tuyo. Encuentra a tu cabo y cúmplelo.', + '(low whistle from the hedge to the north-east)': '(un silbido bajo desde el seto, al noreste)', 'Crouch to move quietly': 'Agáchate para moverte en silencio', + "Easy, it's me. Dunning. Thought you were hung up for the night.": 'Tranquilo, soy yo, Dunning. Pensé que te quedabas colgado toda la noche.', + "Rest of the stick landed past the river. So it's you and me for the gun.": 'El resto cayó pasando el río. Así que el cañón es cosa tuya y mía.', + "Farm's north-east. There's a lane patrol and a post at the crossroads. We go quiet.": 'La granja está al noreste. Hay una patrulla en el camino y un puesto en el cruce. Vamos en silencio.', + 'Patrol in the lane. Keep low and stay in the dark under the bank.': 'Patrulla en el camino. Agachado y en la sombra del talud.', 'Freeze. He heard something. Let him settle.': 'Quieto. Oyó algo. Deja que se calme.', + "Good. Down in the wheat they'll walk right past us.": 'Bien. Agachados en el trigo nos pasan al lado.', "Throw a stone past him. He'll go and look, and we slip by.": 'Tira una piedra más allá. Va a ir a mirar y pasamos.', + "Stream bed's low, but the water is noisy. Slow and steady.": 'El arroyo está bajo, pero el agua hace ruido. Despacio.', "Crossroads post, two of them. Wheat field's east of the road, it takes us right past.": 'Puesto del cruce, son dos. El trigal al este del camino nos deja pasar.', + 'Rook to all units: bombers on the rail junction east of you in thirty seconds.': 'Rook a todas las unidades: bombarderos sobre el empalme ferroviario al este en treinta segundos.', + 'When they hit, move. Nobody will hear us over that.': 'Cuando caigan las bombas, nos movemos. Nadie nos va a oír.', + "Line's dead. Now all they've got is the bell.": 'La línea está muerta. Ahora solo les queda la campana.', "Line's cut. Orchard next, then the farm.": 'Línea cortada. Ahora el huerto y después la granja.', + "Hold. Barn loft, the hay door. There's a sniper up there.": 'Espera. Altillo del granero, la puerta del heno. Hay un francotirador.', + "Rifle's yours. Mind the drop and the wind. Or we go round below his window.": 'El fusil es tuyo. Ojo con la caída y el viento. O lo rodeamos por debajo de su ventana.', + "Good shot. Loft's clear.": 'Buen tiro. Altillo limpio.', 'Hold aim with the rifle to use the scope': 'Mantén apuntar con el fusil para usar la mira', + "Charge is set. Pencil fuse, a few minutes. Now let's get clear of—": 'Carga puesta. Mecha de lápiz, unos minutos. Ahora salgamos de—', + "That's torn it! They're in the house, shooting from the windows!": '¡Se arruinó todo! ¡Están en la casa, disparando por las ventanas!', + "On the back door. Get on the other side, I'll go in first.": 'En la puerta de atrás. Ponte del otro lado, entro yo primero.', 'Going in!': '¡Entro!', + 'Their gun plan for the whole sector. Rook will want that.': 'Su plan de baterías de todo el sector. Rook lo va a querer.', 'House clear!': '¡Casa limpia!', + 'Charge is still burning. Hold the yard!': 'La carga sigue encendida. ¡Resistan en el patio!', 'Truck on the east road! Get to the wall and hold them off!': '¡Camión por el camino del este! ¡Al muro y aguántenlos!', + "They're off the truck! Four of them!": '¡Bajaron del camión! ¡Son cuatro!', "Gun's gone! Out the gap by the barn and down the lane! Go, go!": '¡Cañón destruido! ¡Por el hueco del granero y camino abajo! ¡Vamos, vamos!', + 'Contact in the lane! Down the side, use the bank!': '¡Contacto en el camino! ¡Por el costado, usa el talud!', 'Pathfinder Two, Rook. We see you. Come on in.': 'Explorador Dos, aquí Rook. Te vemos. Vengan.', + "That's the bell. Every soldier on the farm is awake now.": 'Es la campana. Ahora toda la granja está despierta.', + 'Finish in under 15:00': 'Terminar en menos de 15:00', 'Spotted no more than once before the farm': 'Que te vean como mucho una vez antes de la granja', + // sketch labels + 'FLAK': 'ANTIAÉREO', 'MG': 'AMETR.', 'post': 'puesto', 'sniper?': '¿francotirador?', 'Mauvenant Farm': 'Granja Mauvenant', 'orchard': 'huerto', 'wheat': 'trigo', 'the Lirette': 'el Lirette', 'telephone line': 'línea telefónica', + 'you are here (roughly)': 'estás acá (más o menos)', 'out': 'salida', 'start': 'inicio', 'run': 'correr', 'crouch': 'agacharse', 'crawl': 'arrastrarse', 'vault': 'saltar', 'pop-ups': 'blancos', 'rifle': 'fusil', 'pen': 'corral', 'binoculars': 'binoculares', 'pit': 'pozo', + 'Camp Hollowmere': 'Campamento Hollowmere' + }); +})(); diff --git a/e63334287a3deaa3/ironveil/index.html b/e63334287a3deaa3/ironveil/index.html new file mode 100644 index 00000000..9547c900 --- /dev/null +++ b/e63334287a3deaa3/ironveil/index.html @@ -0,0 +1,459 @@ + + + + + + + + +Midnight Ops + + + + + + +
+ + +
+
+
+ +
+
+ + + + + + +
+ +
+

Loading…

+
+ + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + diff --git a/e63334287a3deaa3/ironveil/js/ai.js b/e63334287a3deaa3/ironveil/js/ai.js new file mode 100644 index 00000000..86c96fdf --- /dev/null +++ b/e63334287a3deaa3/ironveil/js/ai.js @@ -0,0 +1,608 @@ +/* Ironveil enemy AI. Each soldier sees (cone + range scaled by light, stance, movement and crops), hears (footsteps by + speed and surface, shots, rocks, impacts; masked by aircraft and engines), and moves through six states: + unaware -> suspicious -> investigating -> searching -> combat -> returning. Searches go in pairs, bodies raise the + alarm, officers run for the bell, and in combat they take cover, peek, suppress, flank in pairs, lob the odd grenade + and fall back when alone and hurt. Accuracy ramps up over about a second of seeing you, so being spotted is not + instant death. Kinds: rifleman, officer, sniper (scope glint), gunner (MG). */ +(function () { + 'use strict'; + const T = IV.TUNING, A = T.ai, W = IV.world, F = IV.CF; + const ZERO = new THREE.Vector3(); + const AI = IV.ai = { list: [], bodies: [], maskUntil: 0, masks: [], loud: false, alarm: null, alarmRung: false, grenadeCool: 0, lastSpotted: -99, spottedCount: 0, perceiveP: null }; + const P = IV.player; + const diff = () => (IV.mission && IV.mission.diff) || 0; + const BARK = { + suspicious: ['Hm? Who is there?', 'Did you hear that?', 'Something moved.'], + investigate: ['I will take a look.', 'Stay here. I am checking it.'], + lost: ['Nothing. Just the wind.', 'Probably a fox.', 'Back to it.'], + spotted: ['There! Enemy!', 'Alarm! Over there!', 'Contact!'], + body: ['Man down! Over here!', 'He is dead! Search the area!'], + grenade: ['Grenade!'], reload: ['Reloading!'], flank: ['Go round the side!'], fallback: ['Falling back!'] + }; + AI.bark = function (e, kind) { + if (IV.time < (e.barkT || 0) || !BARK[kind]) return; + const d = Math.hypot(e.pos.x - P.pos.x, e.pos.z - P.pos.z); if (d > 45) return; + e.barkT = IV.time + 6; + IV.hud && IV.hud.bark(e, IV.t(BARK[kind][Math.floor(Math.random() * BARK[kind].length)])); + }; + + // ---------------------------------------------------------------- the soldier + function Enemy(o) { + this.kind = o.kind || 'rifleman'; this.team = 'them'; this.id = AI.list.length; this.name = o.name || ''; + this.actor = IVChars.spawn(this.kind); + this.wkind = o.weapon || (this.kind === 'gunner' ? 'mg' : this.kind === 'officer' ? 'pistol' : this.kind === 'sniper' ? 'rifleScoped' : (o.smg ? 'enemySmg' : 'enemyRifle')); + this.weapon = IVChars.weapon(this.wkind); + this.actor.attach(this.weapon, 'handR'); + if (this.wkind === 'mg' && IV.weapons.prepMG) IV.weapons.prepMG(this.weapon); + this.actor.groundAt = (x, z) => W.groundAt(x, z, this.pos.y + 0.4); + this.actor.onFoot = (side, k) => { if (Math.hypot(this.pos.x - W.camera.position.x, this.pos.z - W.camera.position.z) < 32) IV.footFx(this.pos, this.speed > 3 ? 'run' : this.stance === 'crouch' ? 'crouch' : 'walk', k, false, 0.5); }; + // never start inside a hedge or a wall (scripted spawns use rough positions) + if (o.y == null && IV.nav.grid && !IV.nav.walkable(o.x, o.z)) { const p = IV.nav.nearest(o.x, o.z, 6); if (p) { o.x = p.x; o.z = p.z; } } + this.pos = new THREE.Vector3(o.x, W.height(o.x, o.z), o.z); this.prev = this.pos.clone(); this.vel = new THREE.Vector3(); + // footsteps from the animation's foot contacts (only near the camera) + this.actor_onFoot = true; + this.bodyYaw = o.yaw || 0; this.bodyPrev = this.bodyYaw; this.headYaw = 0; this.aimPitch = 0; + this.hp = o.hp || (this.kind === 'gunner' ? 120 : 100); this.alive = true; this.stance = 'stand'; + this.state = 'unaware'; this.aw = 0; this.alerted = false; this.lkp = null; this.interest = null; this.stateT = 0; + this.route = o.route ? { pts: o.route, i: 0, wait: 0, loop: o.loop !== false, dir: 1 } : null; + this.post = o.post || (o.route ? null : { x: o.x, z: o.z, yaw: o.yaw || 0, scan: o.scan || [0.6, -0.6] }); + this.home = { x: o.x, z: o.z, yaw: o.yaw || 0 }; + this.fixed = !!o.fixed || this.kind === 'sniper' || this.kind === 'gunner'; + this.path = null; this.pathI = 0; this.goal = null; this.repath = 0; + this.seeT = 0; this.seeing = false; this.target = null; this.shotT = 1; this.burst = 0; this.mag = this.kind === 'gunner' ? 50 : 10; + this.cover = null; this.coverT = 0; this.peek = false; this.suppr = 0; this.role = 'normal'; this.partner = null; + this.perT = Math.random() * 0.1; this.speed = 0; this.tagged = false; this.busy = false; this.found = false; + this.search = null; this.ringT = 0; this.o = o; this.eyeH = o.eyeH || 0; this.y0 = o.y; + this.sightMul = o.sightMul || (this.kind === 'sniper' ? 1.5 : 1); + this.noRoam = !!o.noRoam; + if (o.y != null) this.pos.y = o.y; + this.actor.root.position.copy(this.pos); this.actor.root.rotation.y = this.bodyYaw + Math.PI; + this.actor.play(o.anim || 'idle', { fade: 0 }); + this.pose = o.anim && o.anim !== 'idle' ? o.anim : null; // an ambient pose (sitting): held until he reacts or moves + W.dynamic.add(this.actor.root); + if (this.kind === 'sniper') { this.glint = new THREE.Sprite(new THREE.SpriteMaterial({ map: W.tex.glow(), color: 0xddeeff, blending: THREE.AdditiveBlending, transparent: true, depthWrite: false, toneMapped: false, opacity: 0 })); this.glint.scale.set(0.9, 0.9, 1); W.dynamic.add(this.glint); } + } + Enemy.prototype.stanceKey = function () { return this.stance; }; + Enemy.prototype.chestH = function () { return this.stance === 'prone' ? 0.25 : this.stance === 'crouch' ? 0.9 : 1.3; }; + Enemy.prototype.eye = function () { return this.pos.y + (this.stance === 'crouch' ? 1.12 : this.stance === 'prone' ? 0.4 : 1.62); }; + Enemy.prototype.setState = function (s) { + if (this.state === s || !this.alive) return; + const was = this.state; this.state = s; this.stateT = 0; this.path = null; + if (s === 'combat') { this.alerted = true; if (was !== 'combat') { AI.spotted(this); } } + if (s === 'searching' || s === 'investigating') this.alerted = true; + IV.emit('aiState', { e: this, s, was }); + }; + // ---------------------------------------------------------------- damage + Enemy.prototype.hit = function (zone, dmg, dir, from, b) { + if (!this.alive) return; + this.hp -= dmg; + if (this.hp <= 0) return this.die(dir, b && b.explosive); + // flinch (upper body) for light hits, a full stagger for heavy ones; either way his aim is thrown off for a moment + if (dmg >= 60 && IVChars.clips && IVChars.clips.indexOf('stagger') >= 0) this.actor.play('stagger', { once: true, fade: 0.08 }); else this.actor.setUpper('hit'); + this.suppr = Math.min(1, this.suppr + 0.6); this.stagger = dmg >= 60 ? 0.7 : 0.45; this.shotT = Math.max(this.shotT, 0.5); + if (from) { this.lkp = { x: from.x, z: from.z, t: IV.time }; this.target = this.target || WPent(); } + this.aw = 1; this.setState('combat'); + AI.noise(this.pos.x, this.pos.z, 25, 'shout', this); + }; + const WPent = () => IV.weapons.playerEnt; + Enemy.prototype.die = function (dir, blast) { + this.alive = false; this.state = 'dead'; this.hp = 0; this.aw = 0; + const front = dir ? (dir.x * -Math.sin(this.bodyYaw) + dir.z * -Math.cos(this.bodyYaw)) < 0 : Math.random() < 0.5; + // shot from the front falls backwards + this.actor.setUpper(null); + const running = this.speed > 3 && IVChars.clips && IVChars.clips.indexOf('deathRun') >= 0; + this.actor.play(running ? 'deathRun' : front ? 'deathBack' : 'deathFront', { fade: 0.08, once: true }); + // the body carries its momentum: running men tumble forward, a shot pushes a little + if (dir && !blast) { this.fallV = { x: dir.x * 1.2 + this.vel.x * 0.5, z: dir.z * 1.2 + this.vel.z * 0.5 }; } + if (blast && dir) this.fallV = { x: dir.x * 3, z: dir.z * 3 }; + this.deadT = 0; this.bodyAt = null; + if (this.glint) this.glint.material.opacity = 0; + AI.bodies.push(this); + if (this.cover) { this.cover.used = null; this.cover = null; } + IV.emit('enemyDied', this); + }; + Enemy.prototype.takedown = function () { + this.alive = false; this.busy = true; this.state = 'dead'; this.quiet = true; + this.actor.setUpper(null); this.actor.play('takedownVictim', { fade: 0.1, once: true }); + this.deadT = -0.5; AI.bodies.push(this); IV.emit('enemyDied', this); + }; + Enemy.prototype.suppress = function (k, by) { + if (!this.alive) return; + this.suppr = Math.min(1, this.suppr + k * 0.5); + if (this.state !== 'combat') { this.aw = Math.max(this.aw, 0.75); this.interest = by && by.pos ? { x: by.pos.x + (Math.random() - 0.5) * 8, z: by.pos.z + (Math.random() - 0.5) * 8 } : null; if (this.aw >= 0.75) this.setState('searching'); } + }; + + // ---------------------------------------------------------------- perception + // how far away this soldier could see the player right now (0 = can't) + let pLight = 0.3, pLightT = -1; + AI.playerLight = function () { if (IV.time - pLightT > 0.1) { pLight = W.lightAt(P.pos.x, P.pos.y + (P.stance === 'prone' ? 0.3 : 1.0), P.pos.z); pLightT = IV.time; } return pLight; }; + AI.visRange = function (e, light) { + const st = P.stance, mv = P.speed < 0.3 ? 'still' : P.sprinting ? 'sprint' : P.speed > 2.8 ? 'run' : 'walk'; + let r = A.sightRange * e.sightMul * Math.min(1.2, light) * A.stance[st] * A.move[mv]; + if (P.crops) r *= A.conceal[st]; + if (e.state === 'combat') r *= 1.6; else if (e.alerted) r *= 1.3; + if (IV.weapons.firingRecently) r = Math.max(r, 60); // muzzle flash gives you away + return r; + }; + // can e see point (x,y,z)? returns the angle factor (1 clear, ~0.35 peripheral, 0 no) + function inView(e, x, y, z, d) { + const face = e.bodyYaw + e.headYaw, a = Math.abs(IV.wrapA(IV.yawTo(x - e.pos.x, z - e.pos.z) - face)); + let k = a < A.fovH ? 1 : a < A.fovPeriph ? 0.35 : 0; + if (d < 0.9 && k === 0) k = 0.3; // bumping into him (a takedown from behind at 1.7 m still works) + if (k === 0) return 0; + const ey = e.eye(); + if (!W.clear(e.pos.x, ey, e.pos.z, x, y, z, F.SIGHT)) return 0; + return k; + } + AI.canSee = inView; + function perceive(e, dt) { + const d = Math.hypot(P.pos.x - e.pos.x, P.pos.z - e.pos.z); + e.seeing = false; + if (P.alive && !AI.ignorePlayer) { + const light = AI.playerLight(), r = AI.visRange(e, light); + if (d < r) { + const chestY = P.pos.y + (P.stance === 'prone' ? 0.3 : P.stance === 'crouch' ? 0.95 : 1.35), headY = P.eyeY(); + let k = inView(e, P.pos.x, headY, P.pos.z, d); if (!k) k = inView(e, P.pos.x, chestY, P.pos.z, d); + if (k) { + e.seeing = true; + const close = 1 - d / r; + const gain = A.gain[diff()] * (0.6 + 3.2 * close * close) * k * (e.alerted ? 1.35 : 1) * (IV.mission.awareMul || 1); + e.aw = Math.min(1.2, e.aw + gain * dt); + e.lkp = { x: P.pos.x, z: P.pos.z, t: IV.time }; + } + } + } + // the squadmate is only noticed once the shooting has started + if (!e.seeing && e.state === 'combat' && IV.ally && IV.ally.ent && IV.ally.ent.alive) { + const al = IV.ally.ent, da = Math.hypot(al.pos.x - e.pos.x, al.pos.z - e.pos.z); + if (da < 45 && inView(e, al.pos.x, al.pos.y + 1.2, al.pos.z, da)) { e.seeAlly = true; } else e.seeAlly = false; + } else e.seeAlly = false; + if (e.seeing) e.seeT += dt; else e.seeT = Math.max(0, e.seeT - dt * 2); + if (!e.seeing && e.state !== 'combat') e.aw = Math.max(0, e.aw - A.decay * dt * (e.state === 'unaware' ? 1.6 : 1)); + // bodies + if (e.state !== 'combat') for (const b of AI.bodies) { + if (b.found || b === e) continue; + const db = Math.hypot(b.pos.x - e.pos.x, b.pos.z - e.pos.z); + const lit = W.lightAt(b.pos.x, b.pos.y + 0.3, b.pos.z); + const rb = 34 * Math.min(1.1, lit) * (W.surfAt(b.pos.x, b.pos.z) === IV.S.crops ? 0.25 : 1) + 2; + if (db < rb && inView(e, b.pos.x, b.pos.y + 0.3, b.pos.z, db)) { + b.found = true; e.alerted = true; AI.bark(e, 'body'); + e.interest = { x: b.pos.x, z: b.pos.z }; e.aw = Math.max(e.aw, 0.8); + e.setState('searching'); e.lkp = { x: b.pos.x, z: b.pos.z, t: IV.time }; + AI.alertNear(e, 30, b.pos); + IV.emit('bodyFound', { by: e, body: b }); + break; + } + } + } + // others nearby join a search + AI.alertNear = function (e, r, at) { + for (const o of AI.list) { + if (o === e || !o.alive || o.state === 'combat') continue; + if (Math.hypot(o.pos.x - e.pos.x, o.pos.z - e.pos.z) < r) { o.alerted = true; o.aw = Math.max(o.aw, 0.7); o.lkp = { x: at.x, z: at.z, t: IV.time }; o.interest = { x: at.x, z: at.z }; o.setState('searching'); } + } + }; + + // ---------------------------------------------------------------- hearing + // radius already reflects how loud the thing was; masking (aircraft, bombing, engines) shrinks it + AI.mask = function () { let m = IV.time < AI.maskUntil ? T.noise.maskedMul : 1; return m; }; + AI.noise = function (x, z, radius, type, src) { + const m = AI.mask(); + for (const e of AI.list) { + if (!e.alive || e.busy) continue; + let r = radius * m; + for (const mk of AI.masks) if (mk.on && Math.hypot(e.pos.x - mk.x, e.pos.z - mk.z) < mk.r) r *= mk.mul; + if (e.alerted) r *= 1.2; + const d = Math.hypot(e.pos.x - x, e.pos.z - z); + if (d > r) continue; + const k = 1 - d / r; + if (type === 'step') { + if (src === P && AI.ignorePlayer) continue; + e.aw = Math.min(1.1, e.aw + A.hearGain * (0.4 + k) * (A.gain[diff()] / 0.85)); + e.interest = { x: x + (Math.random() - 0.5) * d * 0.3, z: z + (Math.random() - 0.5) * d * 0.3 }; + if (e.state === 'combat') e.lkp = { x, z, t: IV.time }; + IV.emit('heard', { e, type }); + } else if (type === 'rock' || type === 'impact') { + if (e.state === 'combat') continue; + e.aw = Math.max(e.aw, type === 'rock' ? 0.66 : 0.72); e.interest = { x, z }; + if (e.state === 'unaware' || e.state === 'suspicious' || e.state === 'returning') { e.setState('investigating'); AI.bark(e, 'investigate'); } + IV.emit('heard', { e, type }); + } else if (type === 'shot' || type === 'explosion' || type === 'shout') { + if (type === 'shout' && src === e) continue; + if (src === P || (src && src.team === 'us')) { + const err = d * (type === 'explosion' ? 0.25 : 0.12); + const px = src.pos ? src.pos.x : x, pz = src.pos ? src.pos.z : z; + e.lkp = { x: px + (Math.random() - 0.5) * err, z: pz + (Math.random() - 0.5) * err, t: IV.time }; + e.alerted = true; + if (e.state !== 'combat') { + if (d < 30 || type === 'explosion' && d < 50) { e.aw = 1; e.setState('combat'); } + else { e.aw = Math.max(e.aw, 0.8); e.interest = { x: e.lkp.x, z: e.lkp.z }; e.setState('searching'); } + } + } else if (e.state !== 'combat') { e.alerted = true; e.aw = Math.max(e.aw, 0.75); e.interest = { x, z }; e.setState('searching'); } + IV.emit('heard', { e, type }); + } + } + }; + + // ---------------------------------------------------------------- movement helpers + const o = { x: 0, z: 0 }; + function moveTo(e, tx, tz, speed, dt) { + // (re)path when the goal moved or we have none + if (!e.path || !e.goal || Math.hypot(e.goal.x - tx, e.goal.z - tz) > 1.5 || e.repath <= 0) { + e.goal = { x: tx, z: tz }; e.path = IV.nav.path(e.pos.x, e.pos.z, tx, tz) || [{ x: tx, z: tz }]; e.pathI = 0; e.repath = 2.5; + } + e.repath -= dt; + const p = e.path[e.pathI]; if (!p) { e.speed = IV.damp(e.speed, 0, 8, dt); return true; } + const dx = p.x - e.pos.x, dz = p.z - e.pos.z, d = Math.hypot(dx, dz); + if (d < 0.45) { e.pathI++; if (e.pathI >= e.path.length) { e.speed = 0; return true; } return false; } + e.speed = IV.damp(e.speed, speed, 6, dt); + // no gliding and no instant 180s: turn first (in place) when the way on is well behind, at a capped rate + const want = IV.yawTo(dx, dz), off = Math.abs(IV.wrapA(want - e.bodyYaw)); + e.bodyYaw = IV.turnToward(e.bodyYaw, want, A.turnRate * (off > 1.7 ? 0.8 : 1), dt); + if (off > 1.7) e.speed = IV.damp(e.speed, 0, 10, dt); + const st = Math.min(d, e.speed * dt); + o.x = e.pos.x + dx / d * st; o.z = e.pos.z + dz / d * st; + // keep apart from other soldiers + for (const q of AI.list) { if (q === e || !q.alive) continue; const sx = o.x - q.pos.x, sz = o.z - q.pos.z, sd = Math.hypot(sx, sz); if (sd < 0.75 && sd > 0.001) { o.x += sx / sd * (0.75 - sd) * 0.5; o.z += sz / sd * (0.75 - sd) * 0.5; } } + W.collide(o, 0.3, e.pos.y + 0.45, e.pos.y + 1.7); + e.vel.set((o.x - e.pos.x) / dt, 0, (o.z - e.pos.z) / dt); + e.pos.x = o.x; e.pos.z = o.z; e.pos.y = W.groundAt(e.pos.x, e.pos.z, e.pos.y); + return false; + } + function faceTo(e, x, z, k, dt) { e.bodyYaw = IV.turnToward(e.bodyYaw, IV.yawTo(x - e.pos.x, z - e.pos.z), Math.min(A.turnRate, (k || 5) * 0.9), dt); } + + // ---------------------------------------------------------------- combat helpers + function pickTarget(e) { + const pe = WPent(); + const al = IV.ally && IV.ally.ent; + if (e.seeing || !al || !al.alive) return pe; + if (e.seeAlly) return al; + return pe; + } + function targetPoint(t) { return { x: t.pos.x, y: t.pos.y + t.chestH(), z: t.pos.z }; } + function chooseCover(e, tgt, flank, back) { + const pts = IV.nav.coverNear(e.pos.x, e.pos.z, flank ? 30 : 22); + let best = null, bs = -1e9; + const tx = tgt.x, tz = tgt.z; + for (const c of pts) { + if (c.used && c.used !== e) continue; + const dT = Math.hypot(c.x - tx, c.z - tz); if (dT < 6 || dT > 55) continue; + // the cover's face must point away from the target (the wall is between us) + const ux = (tx - c.x) / dT, uz = (tz - c.z) / dT, facing = -(c.nx * ux + c.nz * uz); + if (facing < 0.35) continue; + const dS = Math.hypot(c.x - e.pos.x, c.z - e.pos.z); + let s = facing * 4 - dS * 0.35 - Math.abs(dT - (e.kind === 'officer' ? 20 : 16)) * 0.12 + (c.low ? 0.5 : 0); + if (back) s += (dT - Math.hypot(e.pos.x - tx, e.pos.z - tz)) * 0.6; + if (flank) { const a0 = IV.yawTo(e.pos.x - tx, e.pos.z - tz), a1 = IV.yawTo(c.x - tx, c.z - tz); s += Math.min(1.4, Math.abs(IV.wrapA(a1 - a0))) * 6; } + // other soldiers' cover: spread out + for (const q of AI.list) if (q !== e && q.alive && q.cover && Math.hypot(q.cover.x - c.x, q.cover.z - c.z) < 3) s -= 3; + if (s > bs) { bs = s; best = c; } + } + return best; + } + // attack tokens: only a few soldiers shoot at you at once (the rest move, hide or suppress), so fights stay readable + AI.tokens = new Map(); + function haveToken(e) { + const now = IV.time; for (const [k, t] of AI.tokens) if (t < now || !k.alive) AI.tokens.delete(k); + if (AI.tokens.has(e)) return true; + if (AI.tokens.size >= A.tokens[diff()]) return false; + AI.tokens.set(e, now + 2.5 + Math.random()); return true; + } + function shoot(e, tgt, dt) { + const d = Math.hypot(tgt.pos.x - e.pos.x, tgt.pos.z - e.pos.z); + const isP = !!tgt.isPlayer; + if (isP && e.kind !== 'gunner' && !haveToken(e)) { if (e.lkp && Math.random() < 0.35) suppressFire(e, e.lkp); return; } + // the accuracy ramp: grows with continuous exposure, shrinks when suppressed + const exp = isP ? e.seeT : 1.5; + const ramp = IV.clamp(exp / (A.accRamp * (e.kind === 'sniper' ? 2.3 : 1)), 0.05, 1); + let p = A.acc[diff()] * ramp * IV.clamp(15 / Math.max(5, d), 0.25, 1.3) * (1 - e.suppr * 0.6); + if (isP) { p *= P.stance === 'prone' ? 0.5 : P.stance === 'crouch' ? 0.75 : 1; if (P.sprinting) p *= 0.6; if (P.crops) p *= 0.7; } + if (e.kind === 'sniper') p = Math.min(0.9, p * 2.4); + if (e.kind === 'gunner') p *= 0.55; + if (IV.mission.enemyAccMul) p *= IV.mission.enemyAccMul; + // the first shots of an engagement miss close by on purpose: a warning, and a direction + e.engShots = e.seeT < 0.2 ? 0 : (e.engShots || 0) + 1; + const hit = (!isP || e.engShots > 2 || e.kind === 'sniper') && Math.random() < p; + const muz = e.weapon.userData.muzzle.getWorldPosition(new THREE.Vector3()); + const tp = targetPoint(tgt); + if (hit) { tp.y += (Math.random() - 0.5) * 0.4; } + else { const a = Math.random() * 6.28, r = 0.7 + Math.random() * 2; tp.x += Math.cos(a) * r; tp.y += Math.sin(a) * r * 0.5 + 0.3; tp.z += Math.sin(a) * r; } + const dx = tp.x - muz.x, dy = tp.y - muz.y, dz = tp.z - muz.z, l = Math.hypot(dx, dy, dz), v = 720; + const dmg = e.kind === 'sniper' ? A.sniperDmg[diff()] : A.dmg[diff()] * (isP ? 1 : 0.6); + IV.weapons.spawnBullet({ x: muz.x, y: muz.y, z: muz.z, vx: dx / l * v, vy: dy / l * v + (l / v) * 4.9, vz: dz / l * v, drag: 0, dmg, flat: true, owner: e, team: 'them', tracer: !W.day && (e.kind === 'gunner' || Math.random() < 0.45), enemy: true, life: 1.4 }); + IV.fx.muzzle(muz.x, muz.y, muz.z, dx / l, dy / l, dz / l, e.kind !== 'officer'); + if (IV.weapons.gunShot) IV.weapons.gunShot(e.weapon, e.wkind); e.lastShotT = IV.time; + IV.audio && IV.audio.play(e.kind === 'gunner' ? 'mg' : e.kind === 'officer' ? 'epistol' : e.kind === 'sniper' ? 'erifle' : (e.wkind === 'enemySmg' ? 'esmg' : 'erifle'), { x: muz.x, z: muz.z }); + AI.noise(e.pos.x, e.pos.z, 120, 'shout', e); + e.mag--; + } + + // ---------------------------------------------------------------- the brain (fixed step) + Enemy.prototype.step = function (dt) { + this.prev.copy(this.pos); this.bodyPrev = this.bodyYaw; + if (!this.alive) { + // the body settles; then dust (and a small stain) where it fell + this.deadT += dt; + if (this.fallV && this.deadT < 0.6) { o.x = this.pos.x + this.fallV.x * dt; o.z = this.pos.z + this.fallV.z * dt; W.collide(o, 0.3, this.pos.y + 0.4, this.pos.y + 1.2); this.pos.x = o.x; this.pos.z = o.z; this.pos.y = W.groundAt(o.x, o.z, this.pos.y); } + if (this.deadT > 0.75 && !this.landed) { this.landed = true; IV.fx.dust(this.pos.x, this.pos.y + 0.1, this.pos.z, 12, 0.5); if (!this.quiet) IV.fx.bloodPool(this.pos.x, this.pos.z); AI.noise(this.pos.x, this.pos.z, T.noise.bodyFall, 'step', this); IV.audio && IV.audio.play('bodyfall', { x: this.pos.x, z: this.pos.z }); } + return; + } + if (this.scripted) { this.scripted(dt, this); return; } + this.perT -= dt; + if (this.perT <= 0) { perceive(this, 0.1); this.perT += 0.1; } + this.suppr = Math.max(0, this.suppr - dt * 0.35); + if (this.stagger > 0) { this.stagger -= dt; } + this.stateT += dt; + // escalate on awareness + if (this.state !== 'combat') { + if (this.aw >= A.spotted) { this.setState('combat'); this.target = WPent(); } + else if (this.aw >= A.investigate && (this.state === 'unaware' || this.state === 'suspicious' || this.state === 'returning')) { this.interest = this.interest || this.lkp; if (!this.fixed) { this.setState('investigating'); AI.bark(this, 'investigate'); } else this.setState('suspicious'); } + else if (this.aw >= A.suspicious && (this.state === 'unaware' || this.state === 'returning')) { this.setState('suspicious'); AI.bark(this, 'suspicious'); } + } + const sp0 = this.speed; + BEH[this.state](this, dt); + if (this.speed < 0.05 || this.speed === sp0 && this.vel.lengthSq() > 0 && !this.path) this.vel.multiplyScalar(Math.exp(-12 * dt)); + if (this.speed < 0.05) this.vel.set(0, 0, 0); + }; + const BEH = { + unaware(e, dt) { + e.stance = 'stand'; e.actor.setUpper(null); + if (e.route && !e.fixed) { + const r = e.route, p = r.pts[r.i]; + if (r.wait > 0) { r.wait -= dt; e.speed = IV.damp(e.speed, 0, 8, dt); if (p[3] != null) faceTo(e, e.pos.x - Math.sin(p[3]), e.pos.z - Math.cos(p[3]), 3, dt); e.idleLook = true; return; } + e.idleLook = false; + if (moveTo(e, p[0], p[1], A.walkSpeed * (e.alerted ? 1.15 : 1), dt)) { + r.wait = p[2] || 0; e.path = null; + if (r.loop) r.i = (r.i + 1) % r.pts.length; else { r.i += r.dir; if (r.i >= r.pts.length || r.i < 0) { r.dir *= -1; r.i += 2 * r.dir; } } + } + } else { + const ps = e.post; + if (Math.hypot(e.pos.x - ps.x, e.pos.z - ps.z) > 0.8 && !e.fixed) { moveTo(e, ps.x, ps.z, A.walkSpeed, dt); return; } + e.speed = IV.damp(e.speed, 0, 8, dt); + // scan slowly between the post's look directions + const sc = ps.scan || [0], k = Math.floor(IV.time / 6 + e.id) % sc.length; + e.bodyYaw = IV.dampA(e.bodyYaw, ps.yaw + sc[k] * 0.6, 0.8, dt); + e.headYaw = Math.sin(IV.time * 0.4 + e.id) * 0.35; + } + }, + suspicious(e, dt) { + e.speed = IV.damp(e.speed, 0, 8, dt); + const at = e.interest || e.lkp; if (at) faceTo(e, at.x, at.z, 4, dt); + e.headYaw = Math.sin(e.stateT * 1.3) * 0.25; + if (e.stateT > 4 && e.aw < A.suspicious) { AI.bark(e, 'lost'); e.setState(e.home ? 'returning' : 'unaware'); } + }, + investigating(e, dt) { + const at = e.interest || e.lkp; if (!at) { e.setState('returning'); return; } + e.actor.setUpper('aimIdle'); + if (e.fixed) { faceTo(e, at.x, at.z, 4, dt); if (e.stateT > 8) e.setState('returning'); return; } + const arrived = Math.hypot(at.x - e.pos.x, at.z - e.pos.z) < 1.6 || moveTo(e, at.x, at.z, A.searchSpeed * 0.8, dt); + if (arrived) { + e.speed = IV.damp(e.speed, 0, 8, dt); + e.lookT = (e.lookT || 0) + dt; e.headYaw = Math.sin(e.lookT * 1.3) * 0.45; + if (e.lookT > (e.lookTime || 5)) { e.lookT = 0; AI.bark(e, 'lost'); e.aw = Math.min(e.aw, 0.25); e.interest = null; e.setState('returning'); } + } + if (e.stateT > 30) e.setState('returning'); + }, + searching(e, dt) { + e.actor.setUpper('aimIdle'); + const at = e.lkp || e.interest || e.home; + if (!e.search || e.search.at !== at) { + // search points round the last known position; a partner takes the other half + const pts = [], R = IV.R; + for (let i = 0; i < 6; i++) { const a = i / 6 * 6.283 + R() * 0.5, r = 4 + R() * 10, p = IV.nav.nearest(at.x + Math.cos(a) * r, at.z + Math.sin(a) * r, 4); if (p) pts.push(p); } + if (!e.partner || !e.partner.alive || e.partner.state === 'dead') { + let bp = null, bd = 25; for (const q of AI.list) if (q !== e && q.alive && !q.fixed && q.state !== 'combat' && !q.partner) { const d = Math.hypot(q.pos.x - e.pos.x, q.pos.z - e.pos.z); if (d < bd) { bd = d; bp = q; } } + if (bp) { e.partner = bp; bp.partner = e; bp.alerted = true; bp.lkp = at; if (bp.state !== 'searching') bp.setState('searching'); } + } + const half = e.partner && e.partner.id < e.id ? 1 : 0; + e.search = { at, pts: [{ x: at.x, z: at.z }].concat(pts.filter((p, i) => !e.partner || i % 2 === half)), i: 0, t: 0 }; + } + if (e.fixed) { faceTo(e, at.x, at.z, 3, dt); e.headYaw = Math.sin(e.stateT) * 0.5; if (e.stateT > A.searchTime) e.setState('returning'); return; } + const s = e.search, p = s.pts[s.i]; + if (p) { + if (moveTo(e, p.x, p.z, A.searchSpeed, dt)) { s.t += dt; e.headYaw = Math.sin(s.t * 2) * 0.6; if (s.t > 2.2) { s.t = 0; s.i++; e.path = null; } } + } else { e.speed = 0; e.headYaw = Math.sin(e.stateT * 1.5) * 0.8; } + if (e.stateT > A.searchTime * (AI.alarmRung ? 2 : 1)) { AI.bark(e, 'lost'); e.aw = 0.3; e.setState('returning'); e.search = null; } + }, + returning(e, dt) { + e.actor.setUpper(null); + const h = e.route ? { x: e.route.pts[e.route.i][0], z: e.route.pts[e.route.i][1] } : e.post || e.home; + if (e.fixed || moveTo(e, h.x, h.z, A.walkSpeed * 1.1, dt)) { e.setState('unaware'); e.headYaw = 0; } + }, + combat(e, dt) { + // a live grenade close by: get away from it first + const g = IV.weapons.throws.find(g => g.kind === 'grenade' && !g.enemy && g.fuse < 3.5 && Math.hypot(g.x - e.pos.x, g.z - e.pos.z) < 6.5); + if (g && !e.fixed) { if (!e.fleeT) AI.bark(e, 'grenade'); e.fleeT = 1; const ax = e.pos.x - g.x, az = e.pos.z - g.z, al = Math.hypot(ax, az) || 1; moveTo(e, e.pos.x + ax / al * 9, e.pos.z + az / al * 9, A.runSpeed * 1.1, dt); e.stance = 'stand'; return; } + e.fleeT = 0; + const tgt = e.target = pickTarget(e); + if (e.o.noShoot) { e.speed = IV.damp(e.speed, 0, 8, dt); faceTo(e, P.pos.x, P.pos.z, 6, dt); e.actor.setUpper('aimIdle'); return; } + const tp = e.seeing || (tgt !== WPent() && e.seeAlly) ? tgt.pos : e.lkp ? e.lkp : tgt.pos; + if (e.seeing) e.lkp = { x: P.pos.x, z: P.pos.z, t: IV.time }; + const canShoot = (e.seeing || e.seeAlly) && IV.time - (e.firstSee || 0) > A.reaction[diff()]; + if (!e.seeing && !e.seeAlly) e.firstSee = IV.time; else if (!e.firstSee) e.firstSee = IV.time; + const dT = Math.hypot(tp.x - e.pos.x, tp.z - e.pos.z); + // officer: run for the alarm bell + if (e.kind === 'officer' && AI.alarm && !AI.alarmRung && !AI.alarm.off) { BEH.alarm(e, dt); return; } + // fixed posts (sniper, gunner) fight from where they are + if (e.fixed) { + faceTo(e, tp.x, tp.z, 6, dt); e.stance = e.o.stance || 'stand'; + e.actor.setUpper('aimIdle'); + e.shotT -= dt; + if (e.kind === 'gunner') { + // long bursts, also at your last known spot (suppression) + if (e.shotT <= 0 && (canShoot || (IV.time - (e.lkp ? e.lkp.t : 0) < 6))) { + if (e.burst <= 0) e.burst = 8 + (Math.random() * 10 | 0); + if (canShoot) shoot(e, tgt, dt); else suppressFire(e, e.lkp); + e.burst--; e.shotT = e.burst > 0 ? 0.075 : 1.4 + Math.random(); + } + } else if (e.shotT <= 0 && canShoot) { shoot(e, tgt, dt); e.shotT = e.kind === 'sniper' ? 3.6 + Math.random() : 1.8; } + if (!e.seeing && IV.time - (e.lkp ? e.lkp.t : 0) > 30) { e.aw = 0.8; e.setState('searching'); } + return; + } + // fall back when hurt and alone + const alone = !AI.list.some(q => q !== e && q.alive && q.state === 'combat' && Math.hypot(q.pos.x - e.pos.x, q.pos.z - e.pos.z) < 22); + if (e.hp < 50 && alone && !e.fellBack) { e.fellBack = true; const c = chooseCover(e, tp, false, true); if (c) { if (e.cover) e.cover.used = null; e.cover = c; c.used = e; AI.bark(e, 'fallback'); } } + // flank role: one of a pair swings wide + if (!e.cover || e.coverT > 14 || (e.cover && exposed(e.cover, tp))) { + if (e.cover) e.cover.used = null; + const flank = e.role === 'flank'; + e.cover = chooseCover(e, tp, flank, false); e.coverT = 0; + if (e.cover) { e.cover.used = e; if (flank) AI.bark(e, 'flank'); } + } + e.coverT += dt; + e.shotT -= dt; + if (e.cover && Math.hypot(e.cover.x - e.pos.x, e.cover.z - e.pos.z) > 0.6) { + // run to cover; snap-shoot only if very close + moveTo(e, e.cover.x, e.cover.z, A.runSpeed * (e.stagger > 0 ? 0.4 : 1), dt); + e.stance = 'stand'; e.peek = false; e.actor.setUpper(canShoot && dT < 15 ? 'aimIdle' : null); + if (canShoot && dT < 12 && e.shotT <= 0 && e.mag > 0) { shoot(e, tgt, dt); e.shotT = 1.1 + Math.random(); } + return; + } + e.speed = IV.damp(e.speed, 0, 10, dt); + faceTo(e, tp.x, tp.z, 7, dt); + // peek cycle: hidden, then exposed and firing + e.peekT = (e.peekT || 0) - dt; + if (e.peekT <= 0) { e.peek = !e.peek; e.peekT = e.peek ? 1.6 + Math.random() * 1.2 : (1.1 + Math.random() * 1.6) * (1 + e.suppr * 1.8); } + const low = e.cover ? e.cover.low : false; + e.stance = e.peek ? 'stand' : (low ? 'crouch' : 'stand'); + if (!e.cover) { e.stance = 'crouch'; e.peek = true; } + e.actor.setUpper(e.peek ? 'aimIdle' : null); + // tall cover (hedge, wall end): side-step out of it to peek + if (e.cover && !low) { const off = e.peek ? 0.9 : 0; const side = { x: -e.cover.nz, z: e.cover.nx }; e.peekOff = IV.damp(e.peekOff || 0, off, 6, dt); } + if (e.peek && e.mag > 0 && e.shotT <= 0) { + if (canShoot) { shoot(e, tgt, dt); e.shotT = (e.wkind === 'enemySmg' ? 0.12 : 0.9 + Math.random() * 0.8) * (1 + e.suppr); e.burst = (e.burst || 0) + 1; if (e.wkind === 'enemySmg' && e.burst % 5 === 0) e.shotT = 1.2; } + else if (e.lkp && IV.time - e.lkp.t < 5 && Math.random() < 0.3) { suppressFire(e, e.lkp); e.shotT = 1.5; } + } + if (e.mag <= 0) { e.mag = 10; e.shotT = 2.4; e.peek = false; e.peekT = 2.4; AI.bark(e, 'reload'); } + // grenade at a target that has been hiding behind cover for a while + AI.grenadeCool -= dt; + if (!e.seeing && e.lkp && AI.grenadeCool <= 0 && IV.time - e.lkp.t > 2 && IV.time - e.lkp.t < 10 && dT > 9 && dT < 30 && Math.random() < 0.004 * (1 + diff())) { + AI.grenadeCool = A.grenadeCooldown * (diff() === 0 ? 1.5 : 1); AI.bark(e, 'grenade'); + IV.weapons.enemyGrenade(e, e.lkp.x + (Math.random() - 0.5) * 3, e.lkp.z + (Math.random() - 0.5) * 3); + e.actor.setUpper('throw'); + } + // lost you for a long time: push to your last known position, then search + if (!e.seeing && !e.seeAlly && IV.time - (e.lkp ? e.lkp.t : 0) > 12) { + if (e.lkp && Math.hypot(e.lkp.x - e.pos.x, e.lkp.z - e.pos.z) > 4 && !e.noRoam) { if (e.cover) e.cover.used = null; e.cover = null; moveTo(e, e.lkp.x, e.lkp.z, A.searchSpeed, dt); e.stance = 'stand'; e.actor.setUpper('aimIdle'); } + if (IV.time - (e.lkp ? e.lkp.t : 0) > 26) { e.aw = 0.85; e.interest = e.lkp; e.setState('searching'); } + } + }, + alarm(e, dt) { + const al = AI.alarm; + e.actor.setUpper(null); e.stance = 'stand'; + if (Math.hypot(al.x - e.pos.x, al.z - e.pos.z) > 1.2) { moveTo(e, al.x, al.z, A.runSpeed * 1.05, dt); e.ringT = 0; return; } + e.speed = 0; faceTo(e, al.bx || al.x, al.bz || al.z, 6, dt); + e.ringT += dt; e.actor.play('salute', { fade: 0.15 }); e.ringUntil = IV.time + 0.25; + if (e.ringT > A.alarmDelay && !AI.alarmRung) { AI.ringAlarm(e); } + }, + dead() {} + }; + BEH.scripted = () => {}; + function exposed(c, tp) { + const dx = tp.x - c.x, dz = tp.z - c.z, d = Math.hypot(dx, dz); + return -(c.nx * dx / d + c.nz * dz / d) < 0.2; + } + function suppressFire(e, at) { + const fake = { pos: { x: at.x + (Math.random() - 0.5) * 3, y: W.height(at.x, at.z), z: at.z + (Math.random() - 0.5) * 3 }, chestH: () => 0.6 + Math.random(), isPlayer: false }; + const save = Math.random; shootAt(e, fake); + } + function shootAt(e, fake) { // fire at a point (no hit decision: the bullet just flies) + const muz = e.weapon.userData.muzzle.getWorldPosition(new THREE.Vector3()); + const tp = targetPoint(fake), dx = tp.x - muz.x, dy = tp.y - muz.y, dz = tp.z - muz.z, l = Math.hypot(dx, dy, dz), v = 720; + IV.weapons.spawnBullet({ x: muz.x, y: muz.y, z: muz.z, vx: dx / l * v, vy: dy / l * v, vz: dz / l * v, drag: 0, dmg: A.dmg[diff()], flat: true, owner: e, team: 'them', tracer: !W.day, enemy: true, life: 1.4 }); + IV.fx.muzzle(muz.x, muz.y, muz.z, dx / l, dy / l, dz / l, true); + if (IV.weapons.gunShot) IV.weapons.gunShot(e.weapon, e.wkind); e.lastShotT = IV.time; + IV.audio && IV.audio.play(e.kind === 'gunner' ? 'mg' : 'erifle', { x: muz.x, z: muz.z }); + } + AI.ringAlarm = function (by) { + if (AI.alarmRung) return; + AI.alarmRung = true; + IV.audio && IV.audio.alarm(true); + for (const q of AI.list) if (q.alive && q.state !== 'combat') { q.alerted = true; q.aw = Math.max(q.aw, 0.9); q.lkp = q.lkp || { x: P.pos.x + (Math.random() - 0.5) * 30, z: P.pos.z + (Math.random() - 0.5) * 30, t: IV.time }; q.setState('searching'); } + IV.emit('alarm', by); + }; + AI.spotted = function (e) { + AI.bark(e, 'spotted'); + if (IV.time - AI.lastSpotted > 8) { AI.spottedCount++; IV.emit('spotted', e); } + AI.lastSpotted = IV.time; + // the nearest friend becomes the flanker + let best = null, bd = 25; for (const q of AI.list) if (q !== e && q.alive && !q.fixed && q.role !== 'flank') { const d = Math.hypot(q.pos.x - e.pos.x, q.pos.z - e.pos.z); if (d < bd && q.state === 'combat') { bd = d; best = q; } } + if (best && !AI.list.some(q => q.alive && q.role === 'flank')) best.role = 'flank'; + AI.alertNear(e, 18, P.pos); + for (const q of AI.list) if (q !== e && q.alive && Math.hypot(q.pos.x - e.pos.x, q.pos.z - e.pos.z) < 18 && q.state !== 'combat') { q.aw = 1; q.lkp = { x: P.pos.x, z: P.pos.z, t: IV.time }; q.setState('combat'); } + }; + + // ---------------------------------------------------------------- animation + const DS = {}; + Enemy.prototype.drive = function (dt) { + const a = this.actor; if (this.busy || !this.alive) return; + if (IV.time < (this.ringUntil || 0)) return; // ringing the bell: the one-shot plays + if (this.pose) { if (this.state === 'unaware' && this.speed < 0.1) return; this.pose = null; } + const v = this.vel.lengthSq() > 0.01 ? this.vel : ZERO; + IV.driveState(DS, v, this.bodyYaw, { yawRate: this.yawRate || 0, stance: this.stance === 'prone' ? 'prone' : this.stance, aiming: IV.upperOf(a) === 'aimIdle', aimPitch: this._ap || 0, aimYawOffset: this._ay || 0, sprinting: this.speed > 4.5, grounded: true, fallSpeed: 0, slopeY: 1, weapon: this.wkind, dt }); + DS.speed = Math.min(DS.speed, this.speed + 0.01); + if (a.drive) { if (!this.cine) IV.releaseLoopPose(a); a.drive(DS); } + }; + // drawing cost: soldiers off screen (a 1.3 m sphere round the body) are not drawn and animate four times a second; + // on Low nobody past 140 m is drawn (the frustum is computed once per rendered frame) + const FR = new THREE.Frustum(), FM = new THREE.Matrix4(), FS = new THREE.Sphere(new THREE.Vector3(), 1.3); let frAt = -1; + function onScreen(p) { + if (frAt !== IV.frameNo) { frAt = IV.frameNo; const c = W.camera; c.updateMatrixWorld(); FM.multiplyMatrices(c.projectionMatrix, c.matrixWorldInverse); FR.setFromProjectionMatrix(FM); } + FS.center.set(p.x, p.y + 0.9, p.z); return FR.intersectsSphere(FS); + } + AI.drawStats = { drawn: 0, total: 0 }; + Enemy.prototype.frame = function (alpha, dt) { + const r = this.actor.root; + r.position.lerpVectors(this.prev, this.pos, alpha); + if (this.peekOff && this.cover && !this.cover.low) { r.position.x += -this.cover.nz * this.peekOff * 0; } + r.rotation.y = this.bodyPrev + IV.wrapA(this.bodyYaw - this.bodyPrev) * alpha + Math.PI; + if (this.alive) { + // aim at the target / look about + let ap = 0, ay = this.headYaw; + if (this.state === 'combat' && this.target) { const t = this.target.pos, d = Math.hypot(t.x - this.pos.x, t.z - this.pos.z); ap = Math.atan2(t.y + this.target.chestH() - this.eye(), d); ay = IV.clamp(IV.wrapA(IV.yawTo(t.x - this.pos.x, t.z - this.pos.z) - this.bodyYaw), -1, 1); } + this.actor.setAim(ap, ay); this._ap = ap; this._ay = ay; + } + // cull animation work for far soldiers (update every few frames) + const d = Math.hypot(this.pos.x - W.camera.position.x, this.pos.z - W.camera.position.z); + this.animAcc = (this.animAcc || 0) + dt; + const seen = onScreen(this.pos) && d < (W.quality === 0 ? 140 : 260); + const every = !seen && d > 6 ? 0.25 : d > 90 ? 0.15 : d > 50 ? 0.066 : 0; + this.yawRate = dt > 0 ? IV.wrapA(this.bodyYaw - (this.lastYaw == null ? this.bodyYaw : this.lastYaw)) / Math.max(dt, 1e-3) : 0; this.lastYaw = this.bodyYaw; + if (this.animAcc >= every) { + if (this.alive) this.drive(this.animAcc); + // gun parts (only close by): bolt kick, trigger, the gunner's bipod down while he is set up + if (d < 30 && IV.weapons.animateGun) IV.weapons.animateGun(this.weapon, this.wkind, this.animAcc || dt, { trigger: IV.time - (this.lastShotT || -9) < 0.15, deployed: this.wkind === 'mg' && (this.fixed || (this.state === 'combat' && this.speed < 0.2)) }); + this.actor.update(this.animAcc); this.animAcc = 0; + } + r.visible = seen || d <= 6; + // sniper glint: visible while he is aiming your way + if (this.glint) { + const aiming = this.alive && this.state === 'combat' && this.seeing; + const hp = this.actor.root.position; + this.glint.position.set(hp.x - Math.sin(this.bodyYaw) * 0.4, this.eye() + 0.02, hp.z - Math.cos(this.bodyYaw) * 0.4); + this.glint.material.opacity = aiming ? 0.6 + 0.4 * Math.sin(IV.time * 9) : (this.alive && this.state !== 'unaware' ? 0.15 : 0); + const gs = 0.5 + d * 0.012; this.glint.scale.set(gs, gs, 1); + } + }; + + // ---------------------------------------------------------------- the manager + AI.reset = function () { + for (const e of AI.list) { e.actor.dispose(); if (e.glint && e.glint.parent) e.glint.parent.remove(e.glint); } + AI.list = []; AI.bodies = []; AI.masks = []; AI.maskUntil = 0; AI.loud = false; AI.alarm = null; AI.alarmRung = false; AI.grenadeCool = 0; AI.lastSpotted = -99; AI.spottedCount = 0; AI.ignorePlayer = false; + }; + AI.spawn = function (o) { const e = new Enemy(o); AI.list.push(e); return e; }; + AI.step = function (dt) { + let loud = false; + for (const e of AI.list) { e.step(dt); if (e.alive && e.state === 'combat') loud = true; } + if (loud !== AI.loud) { AI.loud = loud; IV.emit('loud', loud); } + }; + AI.frame = function (alpha, dt) { for (const e of AI.list) e.frame(alpha, dt); }; + AI.alive = () => AI.list.filter(e => e.alive); + // the highest alert among soldiers (for music and HUD): 0 calm, 1 suspicious, 2 searching, 3 combat + AI.level = function () { + let l = 0; + for (const e of AI.list) { if (!e.alive) continue; if (e.state === 'combat') return 3; if (e.state === 'searching' || e.state === 'investigating') l = Math.max(l, 2); else if (e.state === 'suspicious' || e.aw > 0.25) l = Math.max(l, 1); } + return l; + }; + AI.Enemy = Enemy; +})(); diff --git a/e63334287a3deaa3/ironveil/js/ally.js b/e63334287a3deaa3/ironveil/js/ally.js new file mode 100644 index 00000000..3fd9621a --- /dev/null +++ b/e63334287a3deaa3/ironveil/js/ally.js @@ -0,0 +1,153 @@ +/* Ironveil squadmate: Cpl. Dunning. Follows a step behind your left shoulder, copies your stance, never gives you away + (guards don't notice him until the shooting starts, and he makes no noise they can hear), holds fire until you go + loud or order him (T cycles Follow / Hold here / Fire at will), and can't die on Recruit. Missions can script him: + go to a spot, stack on a door, say a line. */ +(function () { + 'use strict'; + const T = IV.TUNING, W = IV.world, F = IV.CF; + const AL = IV.ally = { ent: null, mode: 'follow', script: null }; + const P = IV.player; + const diff = () => (IV.mission && IV.mission.diff) || 0; + AL.NAME = 'Cpl. Dunning'; + + AL.spawn = function (x, z, yaw) { + AL.remove(); + const actor = IVChars.spawn('ally'), weapon = IVChars.weapon('smg'); + actor.attach(weapon, 'handR'); + actor.groundAt = (x, z) => W.groundAt(x, z, (AL.ent ? AL.ent.pos.y : 0) + 0.4); + const e = AL.ent = { + team: 'us', isAlly: true, actor, weapon, pos: new THREE.Vector3(x, W.height(x, z), z), prev: new THREE.Vector3(), bodyYaw: yaw || 0, bodyPrev: yaw || 0, + hp: 250, alive: true, stance: 'stand', speed: 0, vel: new THREE.Vector3(), path: null, pathI: 0, goal: null, repath: 0, shotT: 1, target: null, stanceDelay: 0, + stanceKey() { return this.stance; }, chestH() { return this.stance === 'crouch' ? 0.9 : this.stance === 'prone' ? 0.25 : 1.3; }, + hit(zone, dmg) { + if (!this.alive) return; + if (diff() === 0 || AL.god) { this.hp = Math.max(60, this.hp - dmg * 0.3); return; } + this.hp -= dmg * T.ally.dmgMul; this.hurtT = IV.time; + if (this.hp <= 0) { this.alive = false; actor.setUpper(null); actor.play('deathBack', { once: true, fade: 0.1 }); IV.emit('allyDied'); } + } + }; + e.prev.copy(e.pos); + actor.onFoot = (side, k) => { if (Math.hypot(e.pos.x - W.camera.position.x, e.pos.z - W.camera.position.z) < 32) IV.footFx(e.pos, e.stance === 'crouch' ? 'crouch' : e.stance === 'prone' ? 'prone' : e.speed > 3 ? 'run' : 'walk', k, false, 0.55); }; + actor.root.position.copy(e.pos); W.dynamic.add(actor.root); + AL.mode = 'follow'; AL.script = null; AL.held = null; AL.met = true; + return e; + }; + AL.remove = function () { if (AL.ent) { AL.ent.actor.dispose(); AL.ent = null; } }; + AL.order = function () { + const order = ['follow', 'hold', 'fire']; + AL.mode = order[(order.indexOf(AL.mode) + 1) % 3]; + if (AL.mode === 'hold' && AL.ent) AL.held = { x: AL.ent.pos.x, z: AL.ent.pos.z }; + const lines = { follow: 'On you.', hold: 'Holding here.', fire: 'Weapons free. Say the word, I shoot.' }; + IV.mission && IV.mission.radio(AL.NAME, IV.t(lines[AL.mode]), 2.2); + IV.emit('order', AL.mode); + }; + // scripted: go to a point (and optionally crouch / face a way). done() fires on arrival. + AL.goTo = function (x, z, o) { AL.script = Object.assign({ x, z, run: true }, o || {}); }; + AL.release = function () { AL.script = null; }; + AL.teleport = function (x, z, yaw) { const e = AL.ent; if (!e) return; e.pos.set(x, W.height(x, z), z); e.prev.copy(e.pos); e.bodyYaw = e.bodyPrev = yaw || e.bodyYaw; e.path = null; }; + + const o = { x: 0, z: 0 }; + function moveTo(e, tx, tz, speed, dt) { + if (!e.path || !e.goal || Math.hypot(e.goal.x - tx, e.goal.z - tz) > 1.2 || e.repath <= 0) { e.goal = { x: tx, z: tz }; e.path = IV.nav.path(e.pos.x, e.pos.z, tx, tz) || [{ x: tx, z: tz }]; e.pathI = 0; e.repath = 1.5; } + e.repath -= dt; + const p = e.path[e.pathI]; if (!p) { e.speed = IV.damp(e.speed, 0, 8, dt); return true; } + const dx = p.x - e.pos.x, dz = p.z - e.pos.z, d = Math.hypot(dx, dz); + if (d < 0.4) { e.pathI++; return e.pathI >= e.path.length; } + // turn first when the way on is behind him (no gliding round, no instant 180) + const off = Math.abs(IV.wrapA(IV.yawTo(dx, dz) - e.bodyYaw)); + e.speed = IV.damp(e.speed, off > 1.9 && !e.target ? 0.3 : speed, 7, dt); + if (off > 1.9 && !e.target) e.bodyYaw = IV.turnToward(e.bodyYaw, IV.yawTo(dx, dz), 5, dt); + const st = Math.min(d, e.speed * dt); + o.x = e.pos.x + dx / d * st; o.z = e.pos.z + dz / d * st; + // don't walk into the player + const px = o.x - P.pos.x, pz = o.z - P.pos.z, pd = Math.hypot(px, pz); if (pd < 0.9 && pd > 0.01) { o.x += px / pd * (0.9 - pd); o.z += pz / pd * (0.9 - pd); } + W.collide(o, 0.3, e.pos.y + 0.45, e.pos.y + 1.6); + e.vel.set((o.x - e.pos.x) / dt, 0, (o.z - e.pos.z) / dt); + e.pos.x = o.x; e.pos.z = o.z; e.pos.y = W.groundAt(o.x, o.z, e.pos.y); + if (!e.target) e.bodyYaw = IV.turnToward(e.bodyYaw, IV.yawTo(dx, dz), T.move.turnRate * 0.8, dt); + return false; + } + function visibleEnemy(e) { + let best = null, bd = 70; + const free = AL.mode === 'fire' || IV.ai.loud; + if (!free) return null; + for (const q of IV.ai.list) { + if (!q.alive) continue; + if (AL.mode !== 'fire' && q.state !== 'combat') continue; + const d = Math.hypot(q.pos.x - e.pos.x, q.pos.z - e.pos.z); if (d > bd) continue; + if (!W.clear(e.pos.x, e.pos.y + 1.45, e.pos.z, q.pos.x, q.pos.y + q.chestH(), q.pos.z, F.BULLET)) continue; + bd = d; best = q; + } + return best; + } + function shoot(e, q) { + const d = Math.hypot(q.pos.x - e.pos.x, q.pos.z - e.pos.z); + const p = T.ally.acc * IV.clamp(14 / Math.max(5, d), 0.25, 1.2) * (q.stance === 'crouch' ? 0.7 : 1); + const muz = e.weapon.userData.muzzle.getWorldPosition(new THREE.Vector3()); + const tp = { x: q.pos.x, y: q.pos.y + q.chestH() + (Math.random() - 0.5) * 0.3, z: q.pos.z }; + if (Math.random() > p) { const a = Math.random() * 6.28, r = 0.6 + Math.random() * 1.6; tp.x += Math.cos(a) * r; tp.y += 0.3 + Math.sin(a) * 0.5; tp.z += Math.sin(a) * r; } + const dx = tp.x - muz.x, dy = tp.y - muz.y, dz = tp.z - muz.z, l = Math.hypot(dx, dy, dz), v = 300; + IV.weapons.spawnBullet({ x: muz.x, y: muz.y, z: muz.z, vx: dx / l * v, vy: dy / l * v, vz: dz / l * v, drag: 0, dmg: 34, owner: e, team: 'us', tracer: !W.day, life: 1.2 }); if (IV.weapons.gunShot) IV.weapons.gunShot(e.weapon, 'smg'); e.lastShotT = IV.time; + IV.fx.muzzle(muz.x, muz.y, muz.z, dx / l, dy / l, dz / l, false); + IV.audio && IV.audio.play('smg', { x: muz.x, z: muz.z, vol: 0.8 }); + IV.ai.noise(e.pos.x, e.pos.z, 150, 'shot', e); + } + + AL.step = function (dt) { + const e = AL.ent; if (!e) return; + e.prev.copy(e.pos); e.bodyPrev = e.bodyYaw; + if (!e.alive) return; + if (e.hurtT && IV.time - e.hurtT > 6) e.hp = Math.min(250, e.hp + 15 * dt); + if (IV.input.pressed('order') && AL.met) AL.order(); + // combat first: anyone shooting at us? + const q = visibleEnemy(e); + e.shotT -= dt; + e.target = q; + const sc = AL.script; + let tx, tz, speed, wantStance = P.stance === 'prone' ? 'prone' : P.stance; + if (sc) { + tx = sc.x; tz = sc.z; speed = sc.run ? 4.3 : 1.9; + if (sc.stance) wantStance = sc.stance; + } else if (AL.mode === 'hold' && AL.held) { tx = AL.held.x; tz = AL.held.z; speed = 3.5; wantStance = 'crouch'; } + else { + // a step behind and to the left of you + const f = IV.fwd(P.bodyYaw), l = { x: f.z, z: -f.x }; + tx = P.pos.x - f.x * T.ally.followDist + l.x * 1.5; tz = P.pos.z - f.z * T.ally.followDist + l.z * 1.5; + const d = Math.hypot(tx - e.pos.x, tz - e.pos.z); + speed = P.stance === 'prone' ? 0.8 : P.stance === 'crouch' ? (d > 8 ? 3.2 : 2.0) : d > 10 ? 6 : Math.max(2, Math.min(4.6, P.speed + 0.4)); + // catch up out of sight if far behind + if (Math.hypot(P.pos.x - e.pos.x, P.pos.z - e.pos.z) > T.ally.catchUp && !onScreen(e.pos)) { const p = IV.nav.nearest(tx, tz, 4); if (p) AL.teleport(p.x, p.z, P.bodyYaw); } + } + if (q && !sc) wantStance = wantStance === 'prone' ? 'prone' : 'crouch'; + // stance follows a moment later + if (wantStance !== e.stance) { e.stanceDelay += dt; if (e.stanceDelay > 0.35) { e.stance = wantStance; e.stanceDelay = 0; } } else e.stanceDelay = 0; + const d = Math.hypot(tx - e.pos.x, tz - e.pos.z); + let arrived = d < (sc ? 0.5 : 1.2); + if (!arrived && !(q && !sc && d < 6)) { const sp = e.stance === 'prone' ? Math.min(speed, 0.8) : e.stance === 'crouch' ? Math.min(speed, 3.2) : speed; arrived = moveTo(e, tx, tz, sp, dt); } + else e.speed = IV.damp(e.speed, 0, 8, dt); + if (arrived && sc && !sc.arrived) { sc.arrived = true; if (sc.done) sc.done(); } + if (q) { + e.bodyYaw = IV.dampA(e.bodyYaw, IV.yawTo(q.pos.x - e.pos.x, q.pos.z - e.pos.z), 8, dt); + e.actor.setUpper('aimIdle'); + if (e.shotT <= 0) { shoot(e, q); e.burst = (e.burst || 0) + 1; e.shotT = e.burst % 4 === 0 ? 0.9 + Math.random() * 0.6 : 0.11; } + } else { + e.actor.setUpper(sc && sc.aim ? 'aimIdle' : null); + if (arrived && sc && sc.yaw != null) e.bodyYaw = IV.dampA(e.bodyYaw, sc.yaw, 6, dt); + else if (e.speed < 0.3 && !sc) e.bodyYaw = IV.dampA(e.bodyYaw, P.bodyYaw, 2, dt); + } + if (e.speed < 0.05) e.vel.set(0, 0, 0); else if (arrived) e.vel.multiplyScalar(Math.exp(-12 * dt)); + }; + const frus = new THREE.Frustum(), pm = new THREE.Matrix4(); + function onScreen(p) { const c = W.camera; pm.multiplyMatrices(c.projectionMatrix, c.matrixWorldInverse); frus.setFromProjectionMatrix(pm); return frus.containsPoint(new THREE.Vector3(p.x, p.y + 1, p.z)); } + const DS = {}; + AL.frame = function (alpha, dt) { + const e = AL.ent; if (!e) return; + const r = e.actor.root; r.position.lerpVectors(e.prev, e.pos, alpha); + r.rotation.y = e.bodyPrev + IV.wrapA(e.bodyYaw - e.bodyPrev) * alpha + Math.PI; + const ap = e.target && e.alive ? Math.atan2(e.target.pos.y + 1.2 - e.pos.y - 1.5, Math.hypot(e.target.pos.x - e.pos.x, e.target.pos.z - e.pos.z)) : 0; + e.yawRate = dt > 0 ? IV.wrapA(e.bodyYaw - (e.lastYaw == null ? e.bodyYaw : e.lastYaw)) / dt : 0; e.lastYaw = e.bodyYaw; + if (e.alive) { IV.driveState(DS, e.vel, e.bodyYaw, { yawRate: e.yawRate, stance: e.stance, aiming: !!e.target || IV.upperOf(e.actor) === 'aimIdle', aimPitch: ap, aimYawOffset: 0, sprinting: e.speed > 4.8, grounded: true, fallSpeed: 0, slopeY: 1, weapon: 'smg', dt }); DS.speed = Math.min(DS.speed, e.speed + 0.01); if (!e.cine) IV.releaseLoopPose(e.actor); e.actor.drive(DS); } + if (IV.weapons.animateGun) IV.weapons.animateGun(e.weapon, 'smg', dt, { trigger: IV.time - (e.lastShotT || -9) < 0.15 }); + e.actor.update(dt); + }; +})(); diff --git a/e63334287a3deaa3/ironveil/js/ambience.js b/e63334287a3deaa3/ironveil/js/ambience.js new file mode 100644 index 00000000..f03a9848 --- /dev/null +++ b/e63334287a3deaa3/ironveil/js/ambience.js @@ -0,0 +1,157 @@ +/* Midnight Ops: background life. Two things the environment kit and the missions can call: + + IV.ambience.event(kind, pos, opts) a one-off sound in the distance (and a flash where it has one) + kind: 'aa' anti-aircraft fire: a short burst of sharp cracks with flashes high in the sky + 'bomb' a bombing rumble: flash now, the rumble arrives later (distance / 343 m/s) + 'aircraft' a droning flight passing over (opts.dur seconds, default 14) + 'dog' a dog barking a few times + 'bell' a church bell, opts.strokes (default 3) + 'rangefire' distant range fire: a few rifle shots, rolled off by distance + 'wind' a gust through the trees (opts.dur, default 4 s) + pos: {x, y?, z} in world metres (y defaults to 30 m for 'aa', ground otherwise); omit for "somewhere far". + opts: {vol (0..2, default 1), dur, strokes, flash (false to skip the light)} + Returns the delay in seconds before the sound arrives. Far events (beyond 60 m) also travel at 343 m/s. + + IV.ambience.walker(spec) a distant soldier with no AI and no collisions, for background drill + spec: {kind: 'ally'|'rifleman'|..., path: [[x, z], ...], speed (m/s, default 1.5), loop (default true), + stance: 'stand'|'crouch', wait (s at each end, default 0), start (0..1 along the path)} + Animated through the same actor.drive() at 5 Hz (2 Hz past 80 m), feet on W.height, not drawn off screen. + Returns a handle {remove()}. IV.ambience.clear() removes them all (missions call it when they unload). + IV.ambience.squad(spec) a block of walkers in step: spec as walker plus rows, cols, spacing + + Both are no-ops before the world exists; the missions' own scripts and IVEnv's sky events may call them freely. */ +(function () { + 'use strict'; + const W = IV.world; + const AM = IV.ambience = { walkers: [] }; + const R = Math.random, V = (a, b) => a + R() * (b - a); + + // ---------------------------------------------------------------- distant sound events + function farPoint() { const c = W.camera ? W.camera.position : { x: 0, z: 0 }, a = R() * 6.28, d = V(250, 600); return { x: c.x + Math.cos(a) * d, z: c.z + Math.sin(a) * d }; } + function dist(p) { const c = W.camera ? W.camera.position : { x: 0, z: 0 }; return Math.hypot(p.x - c.x, p.z - c.z); } + AM.event = function (kind, pos, opts) { + opts = opts || {}; + const A = IV.audio; if (!A || !A.synth) return 0; + const p = pos || farPoint(), d = dist(p), delay = d > 60 ? d / 343 : 0, vol = (opts.vol == null ? 1 : opts.vol), roll = 1 / (1 + d / 120); + const later = (s, f) => setTimeout(() => { try { f(); } catch (e) {} }, s * 1000); + const flash = (y, r, i, dur, color) => { if (opts.flash === false || !W.flashes) return; W.flashes.push({ x: p.x, y: y, z: p.z, r, i, dur, until: IV.time + dur, color: color || 0xffd8a0 }); }; + switch (kind) { + case 'aa': { + const n = 4 + (R() * 5 | 0), y = p.y != null ? p.y : V(60, 140); + for (let k = 0; k < n; k++) later(k * V(0.12, 0.3), () => { flash(y + V(-15, 15), 40, 0.6, 0.08, 0xfff0c0); later(delay, () => A.synth.crack(Math.min(0.5, 0.35 * vol * roll + 0.04), Math.min(1, 160 / Math.max(d, 1)))); }); + break; + } + case 'bomb': flash(4, 90, 1.4, 0.25, 0xffb070); later(delay, () => A.distantBoom(Math.min(0.9, (0.25 + 0.6 * roll) * vol))); break; + case 'aircraft': A.aircraft(true, opts.dur || 14, Math.min(0.6, 0.35 * vol)); return 0; + case 'dog': later(delay, () => A.synth.bark(Math.min(0.4, 0.3 * vol * roll + 0.03), 2 + (R() * 3 | 0))); break; + case 'bell': later(delay, () => A.synth.bell(Math.min(0.4, 0.25 * vol * roll + 0.04), opts.strokes || 3)); break; + case 'rangefire': for (let k = 0, t = 0; k < 3 + (R() * 4 | 0); k++, t += V(0.6, 2.2)) later(delay + t, () => A.synth.pop(Math.min(0.35, 0.3 * vol * roll + 0.03))); break; + case 'wind': A.synth.gust(Math.min(0.5, 0.25 * vol), opts.dur || 4); return 0; + default: return 0; + } + return delay; + }; + + // ---------------------------------------------------------------- background walkers (no AI, no collisions) + const DS = { vx: 0, vz: 0, speed: 0, yawRate: 0, stance: 'stand', aiming: false, aimPitch: 0, aimYawOffset: 0, sprinting: false, grounded: true, fallSpeed: 0, slopeY: 1, weapon: 'rifle', dt: 0 }; + AM.walker = function (s) { + if (!window.IVChars || !W.dynamic) return null; + const actor = IVChars.spawn(s.kind || 'ally'); if (!actor) return null; + const gun = IVChars.weapon(s.weapon || 'enemyRifle', { lod: true }); if (gun) actor.attach(gun, 'handR'); + const pts = s.path.map(p => ({ x: p[0], z: p[1] })); + let len = 0; const seg = []; for (let i = 0; i < pts.length - 1; i++) { const l = Math.hypot(pts[i + 1].x - pts[i].x, pts[i + 1].z - pts[i].z); seg.push(l); len += l; } + const w = { actor, gun, pts, seg, len, u: (s.start || 0) * len, dir: 1, speed: s.speed || 1.5, loop: s.loop !== false, wait: s.wait || 0, waitT: 0, stance: s.stance || 'stand', acc: 0, yaw: 0, off: s.off || { x: 0, z: 0 } }; + W.dynamic.add(actor.root); + actor.update(0); + AM.walkers.push(w); + w.remove = () => { const i = AM.walkers.indexOf(w); if (i >= 0) AM.walkers.splice(i, 1); W.dynamic.remove(actor.root); try { actor.dispose(); } catch (e) {} }; + return w; + }; + // a block of walkers keeping step: rows x cols at spacing, all following the same path + AM.squad = function (s) { + const out = [], rows = s.rows || 2, cols = s.cols || 4, sp = s.spacing || 1.6; + for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) { const w = AM.walker(Object.assign({}, s, { off: { x: (c - (cols - 1) / 2) * sp, z: -r * sp } })); if (w) out.push(w); } + return { walkers: out, remove() { out.forEach(w => w.remove()); } }; + }; + AM.clear = function () { AM.walkers.slice().forEach(w => w.remove()); AM.reset && AM.reset(); }; + function at(w, u) { + let i = 0; while (i < w.seg.length - 1 && u > w.seg[i]) { u -= w.seg[i]; i++; } + const a = w.pts[i], b = w.pts[i + 1] || a, l = w.seg[i] || 1, k = Math.min(1, u / l); + const dx = b.x - a.x, dz = b.z - a.z, yaw = IV.yawTo(dx, dz), f = IV.fwd(yaw); + // the squad offset is in the path's own frame (x across, z along) + return { x: a.x + dx * k - f.z * w.off.x + f.x * w.off.z, z: a.z + dz * k + f.x * w.off.x + f.z * w.off.z, yaw }; + } + const FR = new THREE.Frustum(), FM = new THREE.Matrix4(), SPH = new THREE.Sphere(new THREE.Vector3(), 1.3); + // ---------------------------------------------------------------- the environment kit's hooks (war-look round three) + // sky and village sounds: IVEnv emits IV.emit('ambience', {kind, x, z, delay}) (or just 'thunder' from lightning) + IV.on('ambience', a => { + if (!a) return; if (typeof a === 'string') a = { kind: a }; + const pos = a.x != null ? { x: a.x, z: a.z } : null, A = IV.audio; + const after = (s, f) => setTimeout(() => { try { f(); } catch (e) {} }, Math.max(0, s || 0) * 1000); + switch (a.kind) { + case 'drone': AM.event('aircraft', pos, { dur: 16, vol: 0.8 }); break; + case 'rumble': after(a.delay, () => A && A.distantBoom && A.distantBoom(0.35)); break; + case 'thunder': after(a.delay, () => A && A.distantBoom && A.distantBoom(0.75)); break; + case 'dog': AM.event('dog', pos); break; + case 'bell': AM.event('bell', pos, { strokes: 2 }); break; + case 'rifle': AM.event('rangefire', pos, { vol: 0.6 }); break; + case 'owl': after(a.delay, () => A && A.synth && A.synth.owl && A.synth.owl(0.12)); break; + default: break; // 'shout': no voices in this game + } + }); + // per frame: far drill squads (Boot Camp), rain arriving part-way through Night Drop, fading tracked prints + let squadsFor = null, rainOn = false, fadeAcc = 0; + function envFrame(dt) { + const M = IV.mission, A = IV.audio, E = window.IVEnv; + if (IV.art && IV.art.squads !== squadsFor) { + squadsFor = IV.art.squads; + const lowQ = IV.settings && IV.settings.quality === 0; + for (const q of squadsFor || []) { + if (lowQ && q !== squadsFor[0]) continue; // Low: one squad + const n = q.n || 8, cols = q.kind === 'run' ? 2 : Math.min(5, n), rows = Math.ceil(n / cols); + AM.squad({ kind: 'ally', weapon: 'smg', path: q.path, loop: q.loop !== false, speed: q.kind === 'run' ? 3.4 : 1.35, rows, cols, spacing: q.kind === 'run' ? 1.3 : 1.7 }); + } + } + // Night Drop: the rain comes in once the telephone line is cut (instant when a checkpoint starts past that point) + const nd = M && M.def && M.def.id === 'nightdrop'; + if (nd && !rainOn && M.flags && (M.flags.wire || M.phase === 'hold' || M.phase === 'run' || M.phase === 'breach')) { + rainOn = true; const secs = M.time < 3 ? 0 : 90; + IV.art && IV.art.weather && IV.art.weather('night_rain', secs); + A && A.rain && A.rain(1, secs || 2); + } + if (!nd && rainOn) { rainOn = false; A && A.rain && A.rain(0, 1); } + // tracked mud prints fade (a whole-texture pass, so only every two seconds) + fadeAcc += dt; if (fadeAcc > 2) { if (E && E.marks && E.marks.fade) try { E.marks.fade(fadeAcc); } catch (e) {} fadeAcc = 0; } + } + AM.reset = function () { rainOn = false; squadsFor = null; IV.audio && IV.audio.rain && IV.audio.rain(0, 0.5); }; + AM.frame = function (dt) { + envFrame(dt); + if (!AM.walkers.length || !W.camera) return; + const c = W.camera; FM.multiplyMatrices(c.projectionMatrix, c.matrixWorldInverse); FR.setFromProjectionMatrix(FM); + for (const w of AM.walkers) { + // move along the path (ping-pong or loop), in the render frame: nothing here touches the simulation + let moving = true; + if (w.waitT > 0) { w.waitT -= dt; moving = false; } + else { + w.u += w.dir * w.speed * dt; + if (w.u >= w.len || w.u <= 0) { + if (w.loop && w.pts.length > 2 && Math.hypot(w.pts[0].x - w.pts[w.pts.length - 1].x, w.pts[0].z - w.pts[w.pts.length - 1].z) < 1) w.u = (w.u + w.len) % w.len; + else { w.dir = -w.dir; w.u = Math.max(0, Math.min(w.len, w.u)); w.waitT = w.wait; } + } + } + const p = at(w, w.u), yaw = w.dir > 0 ? p.yaw : p.yaw + Math.PI, y = W.height(p.x, p.z); + w.actor.root.position.set(p.x, y, p.z); w.actor.root.rotation.y = yaw + Math.PI; + const d = Math.hypot(p.x - c.position.x, p.z - c.position.z); + SPH.center.set(p.x, y + 0.9, p.z); + const vis = d < 320 && FR.intersectsSphere(SPH); w.actor.root.visible = vis; + w.acc += dt; + const every = !vis ? 1 : d > 80 ? 0.5 : 0.2; + if (w.acc >= every) { + const sp = moving ? w.speed : 0; + DS.vx = 0; DS.vz = sp; DS.speed = sp; DS.stance = w.stance; DS.sprinting = sp > 4.5; DS.dt = w.acc; + if (w.actor.drive) { IV.releaseLoopPose && IV.releaseLoopPose(w.actor); w.actor.drive(DS); } + w.actor.update(w.acc); w.acc = 0; + } + } + }; +})(); diff --git a/e63334287a3deaa3/ironveil/js/art.js b/e63334287a3deaa3/ironveil/js/art.js new file mode 100644 index 00000000..79ca1893 --- /dev/null +++ b/e63334287a3deaa3/ironveil/js/art.js @@ -0,0 +1,156 @@ +/* The art factory: the ONE place where the game asks for visuals. Missions lay out the world through IV.art.*; + collision, nav and cover always come from the game's own code (kit.js colliders), and the meshes come from + IVEnv (ironveil/env/, the environment kit) when it is loaded, otherwise from the code-made stand-ins in kit.js. + Swap points (each takes the same layout data either way): + IV.art.hedge(b, points, gaps, opts) IV.art.wall(b, points, height, gaps) IV.art.fence(b, points, height) + IV.art.tree(b, x, z, kind, rng, baseY) IV.art.building(b, spec) IV.art.prop(kind, b, ...args) + IV.art.pole(b, x, z, h) IV.art.crops(poly, density, h, color) IV.art.grass(count, radius, accept, tint) + IV.art.water(points, levelFn, width, fallback) IV.art.atmosphere(cfg) IV.art.ground(cfg) IV.art.flush() + IV.art.impact(surface, point, normal, dir) (every bullet hit on the world; decals plug in here) + When IVEnv draws a piece, kit.js still runs with K.noMesh = true so only its colliders are made. + Buildings: the kit still builds the farmhouse, barn and huts (the mission script uses their exact doors, rooms, + loft and windows), but with IVEnv loaded their outside shell (walls, roof, eaves, gutters, sills, lintels, quoins, + chimney, grime) is drawn with IVEnv materials around the same openings (kit.js, spec.envB). Boot Camp's huts with + no interior in play are whole IVEnv buildings (bootcamp.js hut()). */ +(function () { + 'use strict'; + const K = IV.kit, W = IV.world; + const A = IV.art = {}; + const env = () => window.IVEnv && window.IVEnv.ready ? window.IVEnv : null; + A.envOn = () => !!env(); + function collidersOnly(fn) { K.noMesh = true; try { return fn(); } finally { K.noMesh = false; } } + // everything IVEnv makes goes under one root, merged per 48 m cell at the end of the build (IV.art.flush) + function root() { if (!W.envRoot || !W.envRoot.parent) { W.envRoot = new THREE.Group(); W.statics.add(W.envRoot); } return W.envRoot; } + function place(obj, x, y, z, rot) { if (!obj) return obj; const g = obj.group || obj; if (!g || !g.isObject3D) return obj; g.position.set(x, y, z); if (rot) g.rotation.y = rot; root().add(g); return obj; } + // an IVEnv call that throws must not stop the game from loading: warn and carry on without that piece + const safe = (fn, what) => { try { return fn(); } catch (e) { console.warn('IVEnv ' + what, e); return null; } }; + function add(obj) { if (!obj) return obj; const g = obj.group || obj; if (g && g.isObject3D) root().add(g); return obj; } + let seedN = 1; const seed = () => seedN++; + const H = (x, z) => W.height(x, z); + + A.hedge = function (b, pts, gaps, o) { + const E = env(); if (E && E.hedge) { collidersOnly(() => K.hedgerow(b, pts, gaps, o)); return add(safe(() => E.hedge(pts, { h: (o && o.h != null ? o.h : 2.4) + (o && o.bank != null ? o.bank : 1.1), gaps: gaps || [], seed: seed(), heightFn: H }), 'hedge')); } + return K.hedgerow(b, pts, gaps, o); + }; + A.wall = function (b, pts, h, gaps, opts) { + const E = env(); if (E && E.wall) { collidersOnly(() => K.stoneWall(b, pts, h, gaps)); return add(safe(() => E.wall(pts, Object.assign({ type: 'stone', h: h || 1, gaps: gaps || [], seed: seed(), heightFn: H }, opts)), 'wall')); } + return K.stoneWall(b, pts, h, gaps); + }; + A.fence = function (b, pts, h) { + const E = env(); if (E && E.fence) { collidersOnly(() => K.fence(b, pts, h)); return add(safe(() => E.fence(pts, 'rail', { heightFn: H, seed: seed() }), 'fence')); } + return K.fence(b, pts, h); + }; + // trees are batched: IVEnv.trees() instances them with LOD (flushed once at the end of the build) + let pendingTrees = []; + A.tree = function (b, x, z, kind, R, baseY) { + const E = env(); if (E && E.trees) { const r = collidersOnly(() => K.tree(b, x, z, kind, R, baseY)); pendingTrees.push({ kind, x, y: baseY != null ? baseY : H(x, z), z, rot: (R ? R() : Math.random()) * 6.28, scale: 0.9 + (R ? R() : Math.random()) * 0.25, seed: seed() }); return r; } + return K.tree(b, x, z, kind, R, baseY); + }; + // The kit builds the building (colliders, openings, rooms, interior: the mission script relies on them); with IVEnv + // loaded the outside shell is drawn with IVEnv materials into one builder (kit.js reads spec.envB) + A.building = function (b, spec) { + const E = env(); + if (!E || !E.builder || K.noMesh || spec.envShell === false) return K.building(b, spec); + const EB = E.builder(seed()); let r; + spec.envB = EB; try { r = K.building(b, spec); } finally { delete spec.envB; } + if (E.ageMesh && r) safe(() => E.ageMesh(EB, { w: spec.w, d: spec.d, eave: (r.top - r.fy) * 0.62, seed: (spec.x * 7 + spec.z * 3) | 0, amount: spec.age != null ? spec.age : 1, cx: spec.x, cz: spec.z, rot: (spec.rot || 0) + (spec.roof && spec.roof.ridge === 'z' ? Math.PI / 2 : 0), y0: r.fy - 0.3 }), 'age'); + safe(() => { const g = EB.finish(); g.name = 'IVEnv.shell'; root().add(g); }, 'building shell'); + return r; + }; + // a settlement (hamlet, camp, far village): IVEnv shells always drawn, full buildings near the camera, one closed + // collider box per building; lit windows get visual-only lamps; chimney tops are kept for smoke (A.chimneys) + A.chimneys = []; + A.settle = function (b, specs, opts) { + opts = opts || {}; const E = env(); const F = IV.CF, flags = opts.flags != null ? opts.flags : F.SOLID | F.SIGHT | F.BULLET | F.NAV; + if (!E || !E.settle) { for (const sp of specs) if (sp.solid !== false && !opts.shellOnly) K.box(b, 'stone', sp.x, (opts.heightFn || H)(sp.x, sp.z) - 0.5, sp.z, sp.w || 8, 5, sp.d || 6, sp.rot || 0, 0xa09a90, flags, 'stone'); return null; } + const r = safe(() => E.settle(specs, Object.assign({ heightFn: H }, opts)), 'settle'); if (!r) return null; + W.scene.add(r.group); + if (opts.solid !== false) for (const c of r.colliders) W.addBox(c.x, c.z, c.hx, c.hz, c.y0, c.y1, c.rot, flags, 'stone', 'building'); + if (opts.lights !== false) for (const l of r.lights.slice(0, opts.maxLights || 6)) W.addLamp({ x: l.x, y: l.y, z: l.z, r: 5, i: 0, power: 1.1, color: 0xff9a48, flicker: true, los: false, visual: true }); + A.chimneys.push(...r.chimneys); + return r; + }; + // weather: IV.art.weather('night_moon' | 'night_rain' | 'dusty' | 'day_overcast' | 'dusk_rain' ..., seconds) eases the + // whole state (sky, fog, lights, wetness, wind, rain); seconds 0 = at once. Lightning raises IV.emit('ambience', 'thunder') + if (window.IVEnv) IVEnv.onAmbience = (a) => IV.emit('ambience', a); + A.weather = function (name, secs) { const a = W.atm; if (!a || !a.blendTo) return false; if (!secs) a.set(name); else a.blendTo(name, secs); return true; }; + // far-off life in the background (searchlights, flak, aircraft, fires, smoke, birds, a lorry...); visual only. + // Sound hooks arrive as IV.emit('ambience', { kind, x, z, delay }) for the game's audio. Follows Reduced motion. + A.backdrop = function (spec) { const E = env(); if (!E || !E.backdrop) return null; return safe(() => E.backdrop(W.scene, spec, { reduced: !!IV.settings.motion, heightAt: (x, z) => (Math.abs(x) < W.size / 2 && Math.abs(z) < W.size / 2) ? H(x, z) : (E.skirtHeightAt ? E.skirtHeightAt(x, z) : 0), emit: (a) => IV.emit('ambience', a) }), 'backdrop'); }; + // paths for distant squads (drilling, running) that the game may fill with far-LOD soldiers: [{ path, loop, n, kind }] + A.squads = []; + // props: positional args as kit.js takes them; IVEnv draws a matching prop at the same spot + const PROP = { crate: 'crate', barrel: 'barrel', hay: 'haybale', woodpile: 'logpile', cart: 'cart', sandbags: 'sandbags', lamp: 'lamppost' }; + A.prop = function (kind, b, ...a) { + const E = env(), ek = PROP[kind]; + if (!E || !E.prop || !ek) return K.props[kind](b, ...a); + const r = collidersOnly(() => K.props[kind](b, ...a)); + let o = null; + try { + if (kind === 'sandbags') { const [ax, az, bx, bz, layers, baseY] = a, len = Math.hypot(bx - ax, bz - az), cx = (ax + bx) / 2, cz = (az + bz) / 2; o = place(E.prop('sandbags', seed(), { length: len, rows: layers || 3 }), cx, baseY != null ? baseY : H(cx, cz), cz, Math.atan2(-(bz - az), bx - ax)); } + else if (kind === 'cart' || kind === 'woodpile') { const [x, z, rot] = a; o = place(E.prop(ek, seed()), x, H(x, z), z, rot || 0); } + else if (kind === 'lamp') { const [x, z] = a; o = place(E.prop('lamppost', seed()), x, H(x, z), z, 0); } + else if (kind === 'barrel') { const [x, y, z] = a; o = place(E.prop('barrel', seed()), x, y, z, 0); } + else { const [x, y, z, rot] = a; o = place(E.prop(ek, seed()), x, y, z, rot || 0); } + } catch (e) { console.warn('IVEnv prop', kind, e); } + return r; + }; + A.pole = function (b, x, z, h) { + const E = env(); if (E && E.prop) { const r = collidersOnly(() => K.pole(b, x, z, h)); try { place(E.prop('telegraph', seed()), x, H(x, z), z, 0); } catch (e) {} return r; } + return K.pole(b, x, z, h); + }; + A.crops = function (poly, density, h, color) { + const E = env(); + if (E && E.scatter) { let x0 = 1e9, z0 = 1e9, x1 = -1e9, z1 = -1e9; for (const p of poly) { x0 = Math.min(x0, p[0]); z0 = Math.min(z0, p[1]); x1 = Math.max(x1, p[0]); z1 = Math.max(z1, p[1]); } const o = safe(() => E.scatter('wheat', (x, z) => IV.inPoly(x, z, poly) ? 1 : 0, { heightFn: H, density, bounds: [x0, z0, x1, z1], seed: seed() }), 'wheat'); if (o) { add(o); return o; } } + return K.crops(poly, density, h, color); + }; + // IVEnv grass reads the ground kinds and the height itself; long grass is where the stealth cover is + A.grass = function (count, radius, accept, tint) { + const E = env(); + if (E && E.grass) { const g = safe(() => E.grass(W.surfaceAt, H, Object.assign({ longAt: (x, z) => W.surfaceAt(x, z) === 'meadow' ? 1 : 0 }, W.cfg && W.cfg.grass)), 'grass'); if (g) { W.scene.add(g.group || g); A.grassObj = g; return { update() {} }; } } + return K.grassSystem(count, radius, accept, tint); + }; + A.water = function (pts, levelFn, width, fallback) { const E = env(); if (E && E.stream) { const o = safe(() => E.stream(pts, { width, heightFn: H, waterY: levelFn }), 'stream'); if (o) return add(o); } return fallback && fallback(); }; + // the ground mesh (world.js asks first) + A.ground = function (cfg) { + const E = env(); if (!E || !E.ground) return null; + const g = E.ground(H, { surfaceAt: W.surfaceAt, size: W.size }); + // land, hills and woods beyond the map edge, so the world never ends in a line (cfg.skirt tunes the hills) + if (g && g.group && E.skirt) { const sk = safe(() => E.skirt(H, Object.assign({ half: W.size / 2, day: !!(cfg && cfg.day) }, cfg && cfg.skirt)), 'skirt'); if (sk) g.group.add(sk); } + return g; + }; + // sky, moon or sun, fog and mist (world.js asks first) + A.atmosphere = function (cfg) { + const E = env(); if (!E || !E.atmosphere) return null; + // flashes: lightning on dusk_rain; off when the player has asked for reduced effects (Settings, "Reduced motion") + const preset = cfg.rain ? 'dusk_rain' : cfg.day ? 'day_overcast' : 'night_moon'; + const a = E.atmosphere(W.scene, W.renderer, preset, { mistBase: 0, shadows: W.P.shadow > 0, fogMul: W.P.fogMul, flashes: !IV.settings.motion }); + if (a && a.sun) { W.moonDir.copy(a.sun.position).normalize(); } + return a; + }; + // after the build: instance the trees, merge the static pieces per 48 m cell + A.flush = function () { + const E = env(); if (!E) return; + // trees for IVEnv.surfaceAt ('leaves' under them): a 16 m grid of trunk positions + if (pendingTrees.length) { const grid = E._treeGrid = E._treeGrid || new Map(); for (const t of pendingTrees) { const k = Math.floor(t.x / 16) + ',' + Math.floor(t.z / 16); if (!grid.has(k)) grid.set(k, []); grid.get(k).push(t.x, t.z); } + E._treeNear = (x, z, r) => { for (let i = -1; i <= 1; i++) for (let j = -1; j <= 1; j++) { const a = grid.get((Math.floor(x / 16) + i) + ',' + (Math.floor(z / 16) + j)); if (a) for (let q = 0; q < a.length; q += 2) if ((a[q] - x) ** 2 + (a[q + 1] - z) ** 2 < r * r) return true; } return false; }; } + // leaf litter and twigs under every tree (ground decals), then the trees themselves + if (pendingTrees.length && E.builder && E.Q.name !== 'low') safe(() => { const LB = E.builder(515), R = E.rng(515); for (const t of pendingTrees) { const n = t.kind === 'poplar' ? 2 : 4; for (let i = 0; i < n; i++) { const a = R() * 6.28, r = R() * 3.2, x = t.x + Math.cos(a) * r, z = t.z + Math.sin(a) * r; LB.decal(R() < 0.65 ? 'leaves' : 'grime', [x, H(x, z) + 0.025, z], [0, 1, 0], 1.6 + R() * 2.2, 1.4 + R() * 2, R() * 6.28); } } root().add(LB.finish()); }, 'leaf litter'); + if (pendingTrees.length && E.trees) { const t = safe(() => E.trees(pendingTrees), 'trees'); add(t); pendingTrees = []; } + if (E.mergeStatic && W.envRoot) { const merged = safe(() => E.mergeStatic(W.envRoot, { cell: E.Q.name === 'high' ? 64 : 128 }), 'merge'); if (merged && merged !== W.envRoot) { if (E.Q.name !== 'high') merged.traverse(o => { if (o.isMesh && o.material && o.material.userData && /^(glass|canvas|straw|metal_painted|wood_painted|bottles)$/.test(o.material.userData.ivenv || '')) o.castShadow = false; }); // small trim casts no shadow on Low/Medium + W.statics.remove(W.envRoot); W.statics.add(merged); W.envRoot = merged; } } + }; + A.reset = function () { pendingTrees = []; seedN = 1; if (window.IVEnv) { IVEnv._treeGrid = null; IVEnv._treeNear = null; } W.envRoot = null; A.chimneys = []; A.squads = []; const E = env(); if (E && E.clearDecals) E.clearDecals(); }; + // every bullet hit on the world (not on people): effects by surface, and IVEnv's own decal for that material + A.impact = function (surface, p, n, dir) { + IV.fx.impact(p.x, p.y, p.z, n.x, n.y, n.z, surface, dir); + const E = env(); if (E && E.impact) { try { E.impact(surface, p, n); } catch (e) {} } + }; + A.frame = function (dt) { + W.updatePushers(); + const E = env(); if (!E) return; + if (E.setPushers) E.setPushers(W.pushers.map(p => ({ x: p.x, z: p.z, r: p.r, s: p.prone ? 1 : p.crouch ? 0.8 : 0.6 }))); + if (E.setWind && IV.weapons) { const w = IV.weapons.wind, l = Math.hypot(w.x, w.z) || 1; E.setWind(w.x / l, w.z / l, Math.min(1, l / 5)); } + if (E.update) E.update(dt, W.camera); + }; +})(); diff --git a/e63334287a3deaa3/ironveil/js/audio.js b/e63334287a3deaa3/ironveil/js/audio.js new file mode 100644 index 00000000..c361ac58 --- /dev/null +++ b/e63334287a3deaa3/ironveil/js/audio.js @@ -0,0 +1,261 @@ +/* Ironveil audio: everything synthesised with Web Audio (no sound files). Gunshots are layered (crack, body, low boom) + with a distance filter and a shared echo (a generated impulse response, like a report rolling over fields). + Footsteps by surface and gait, night ambience (crickets, wind), distant artillery and aircraft, the alarm bell, radio + squelch, awareness stingers and a low adaptive music bed (calm / suspicious / combat). One AudioContext, created on + the first click or key. Volumes in Settings; M mutes. */ +(function () { + 'use strict'; + const AU = IV.audio = { ctx: null, ready: false }; + let ctx, master, sfx, mus, amb, verb, noiseBuf, comp; + const S = () => IV.settings; + AU.init = function () { + if (ctx) { if (ctx.state !== 'running') ctx.resume(); return; } + const AC = window.AudioContext || window.webkitAudioContext; if (!AC) return; + ctx = AU.ctx = new AC(); + comp = ctx.createDynamicsCompressor(); comp.threshold.value = -14; comp.ratio.value = 4; comp.connect(ctx.destination); + // master -> deafen filter (a close blast muffles everything for a few seconds) -> compressor + AU.deaf = ctx.createBiquadFilter(); AU.deaf.type = 'lowpass'; AU.deaf.frequency.value = 20000; AU.deaf.connect(comp); + master = ctx.createGain(); master.connect(AU.deaf); + sfx = ctx.createGain(); sfx.connect(master); + mus = ctx.createGain(); mus.connect(master); + amb = ctx.createGain(); amb.connect(master); + // echo bus + verb = ctx.createConvolver(); verb.buffer = impulse(2.8, 2.2); const vg = ctx.createGain(); vg.gain.value = 0.55; verb.connect(vg); vg.connect(sfx); + noiseBuf = ctx.createBuffer(1, ctx.sampleRate * 2, ctx.sampleRate); const d = noiseBuf.getChannelData(0); for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1; + AU.ready = true; AU.apply(); + document.addEventListener('visibilitychange', () => { if (!ctx) return; if (document.hidden) ctx.suspend(); else ctx.resume(); }); + }; + function impulse(sec, decay) { + const n = ctx.sampleRate * sec, b = ctx.createBuffer(2, n, ctx.sampleRate); + for (let c = 0; c < 2; c++) { const d = b.getChannelData(c); for (let i = 0; i < n; i++) { const t = i / n; d[i] = (Math.random() * 2 - 1) * Math.pow(1 - t, decay) * (i < ctx.sampleRate * 0.04 ? 0.2 : 1) * (0.6 + 0.4 * Math.sin(i * 0.0007 + c)); } } + return b; + } + AU.apply = function () { + if (!ctx) return; const s = S(); + master.gain.value = s.mute ? 0 : s.vol; sfx.gain.value = s.sfx; mus.gain.value = s.mus * 0.5; amb.gain.value = s.sfx * 0.8; + }; + AU.toggleMute = function () { S().mute = !S().mute; IV.persist(); AU.apply(); }; + ['pointerdown', 'keydown', 'touchend'].forEach(ev => addEventListener(ev, () => AU.init(), { capture: true, passive: true })); + IV.on('mute', () => AU.toggleMute()); + + // ---------------------------------------------------------------- building blocks + const now = () => ctx.currentTime; + // spatial chain: returns the node to connect sources into + function chain(o, send) { + o = o || {}; + let g = ctx.createGain(), out = g; + let vol = o.vol == null ? 1 : o.vol, cut = 18000, pan = 0; + if (o.x != null && IV.world.camera) { + const c = IV.world.camera.position, dx = o.x - c.x, dz = o.z - c.z, d = Math.hypot(dx, dz); + vol *= 1 / (1 + d / (o.ref || 14)); cut = Math.max(500, 18000 / (1 + d / 25)); + const yaw = IV.player ? IV.player.yaw : 0, a = IV.wrapA(IV.yawTo(dx, dz) - yaw); + pan = IV.clamp(-Math.sin(a), -1, 1) * Math.min(1, d / 4) * 0.8; + } + g.gain.value = vol; + const f = ctx.createBiquadFilter(); f.type = 'lowpass'; f.frequency.value = cut; g.connect(f); out = f; + if (ctx.createStereoPanner) { const p = ctx.createStereoPanner(); p.pan.value = pan; out.connect(p); out = p; } + out.connect(sfx); + if (send) { const sg = ctx.createGain(); sg.gain.value = send * Math.min(1, 0.4 + (1 - vol)); out.connect(sg); sg.connect(verb); } + return g; + } + function noise(dest, t0, dur, type, freq, q, a0, a1, f1) { + const s = ctx.createBufferSource(); s.buffer = noiseBuf; s.loop = true; + const f = ctx.createBiquadFilter(); f.type = type || 'bandpass'; f.frequency.setValueAtTime(freq, t0); if (f1) f.frequency.exponentialRampToValueAtTime(f1, t0 + dur); f.Q.value = q || 1; + const g = ctx.createGain(); g.gain.setValueAtTime(0.0001, t0); g.gain.exponentialRampToValueAtTime(a0, t0 + 0.004); g.gain.exponentialRampToValueAtTime(a1 || 0.0001, t0 + dur); + s.connect(f); f.connect(g); g.connect(dest); s.start(t0, Math.random()); s.stop(t0 + dur + 0.05); + } + function tone(dest, t0, dur, type, f0, f1, a0) { + const o = ctx.createOscillator(); o.type = type; o.frequency.setValueAtTime(f0, t0); if (f1) o.frequency.exponentialRampToValueAtTime(f1, t0 + dur); + const g = ctx.createGain(); g.gain.setValueAtTime(0.0001, t0); g.gain.exponentialRampToValueAtTime(a0, t0 + 0.005); g.gain.exponentialRampToValueAtTime(0.0001, t0 + dur); + o.connect(g); g.connect(dest); o.start(t0); o.stop(t0 + dur + 0.05); + } + const lastPlay = {}; + const V = (a, b) => a + Math.random() * (b - a); + + // ---------------------------------------------------------------- sound table + const SND = { + rifle(o) { const d = chain(o, 1.1), t = now(); noise(d, t, 0.09, 'highpass', 2500, 0.7, 1.2); noise(d, t, 0.35, 'lowpass', 1800, 0.7, 1.4, 0, 200); tone(d, t, 0.32, 'sine', 120, 40, 1.2); noise(d, t + 0.02, 0.9, 'lowpass', 500, 0.5, 0.35, 0, 90); }, + smg(o) { const d = chain(o, 0.45), t = now(); if (!o || o.x == null || o.vol == null) noise(d, t + 0.03, 0.025, 'bandpass', 4200, 6, 0.25); /* the bolt slamming home */ noise(d, t, 0.05, 'highpass', 2000, 0.7, 0.7); noise(d, t, 0.14, 'lowpass', 1500, 0.8, 0.9, 0, 300); tone(d, t, 0.1, 'sine', 140, 60, 0.6); }, + pistol(o) { const d = chain(o, 0.3), t = now(); noise(d, t + 0.02, 0.02, 'bandpass', 5000, 7, 0.2); noise(d, t, 0.06, 'bandpass', 1800, 0.8, 0.8); noise(d, t, 0.14, 'lowpass', 1200, 0.7, 0.6, 0, 250); }, + erifle(o) { const d = chain(Object.assign({ ref: 20 }, o), 1), t = now(); noise(d, t, 0.08, 'highpass', 2200, 0.7, 0.9); noise(d, t, 0.3, 'lowpass', 1500, 0.7, 1.1, 0, 180); tone(d, t, 0.25, 'sine', 110, 40, 0.8); }, + esmg(o) { const d = chain(Object.assign({ ref: 18 }, o), 0.4), t = now(); noise(d, t, 0.05, 'highpass', 2600, 0.7, 0.6); noise(d, t, 0.12, 'lowpass', 1300, 0.8, 0.8, 0, 300); }, + mg(o) { const d = chain(Object.assign({ ref: 22 }, o), 0.5), t = now(); noise(d, t, 0.04, 'highpass', 2400, 0.7, 0.7); noise(d, t, 0.11, 'lowpass', 1100, 0.8, 0.9, 0, 250); tone(d, t, 0.08, 'square', 90, 50, 0.2); }, + epistol(o) { SND.pistol(o); }, + bolt() { const d = chain({ vol: 0.5 }), t = now(); noise(d, t, 0.05, 'bandpass', 3200, 4, 0.5); noise(d, t + 0.18, 0.05, 'bandpass', 2600, 4, 0.5); noise(d, t + 0.36, 0.06, 'bandpass', 3000, 5, 0.6); noise(d, t + 0.5, 0.04, 'bandpass', 4000, 6, 0.4); }, + reload(o) { const d = chain({ vol: 0.45 }), t = now(); noise(d, t + 0.2, 0.05, 'bandpass', 2500, 5, 0.5); noise(d, t + 0.9, 0.06, 'bandpass', 1800, 5, 0.6); noise(d, t + 1.4, 0.05, 'bandpass', 3000, 6, 0.5); }, + // first-person handling sounds, started by the arms' clip events (js/fp.js) + magOut() { const d = chain({ vol: 0.42 }), t = now(); noise(d, t, 0.05, 'bandpass', 2300, 5, 0.5); noise(d, t + 0.05, 0.08, 'bandpass', 900, 2, 0.3); }, + magIn() { const d = chain({ vol: 0.5 }), t = now(); noise(d, t, 0.04, 'bandpass', 1700, 4, 0.6); noise(d, t + 0.03, 0.03, 'bandpass', 3400, 7, 0.5); }, + click(o) { const d = chain({ vol: (o && o.vol) || 0.4 }), t = now(); noise(d, t, 0.035, 'bandpass', (o && o.f) || 3000, 6, 0.5); }, + dry() { const d = chain({ vol: 0.4 }), t = now(); noise(d, t, 0.03, 'bandpass', 3500, 8, 0.5); }, + equip() { const d = chain({ vol: 0.35 }), t = now(); noise(d, t, 0.12, 'bandpass', 900, 2, 0.4); noise(d, t + 0.15, 0.04, 'bandpass', 2800, 6, 0.4); }, + cloth(o) { const d = chain({ vol: (o && o.vol) || 0.35 }), t = now(); noise(d, t, 0.22, 'bandpass', V(700, 1100), 1.2, 0.3); }, + vault() { const d = chain({ vol: 0.5 }), t = now(); noise(d, t, 0.25, 'bandpass', 800, 1, 0.4); noise(d, t + 0.4, 0.12, 'lowpass', 400, 1, 0.6); }, + land(o) { const d = chain({ vol: 0.55 }), t = now(); noise(d, t, 0.14, 'lowpass', 500, 1, 0.8); }, + impact(o) { + if (!o || o.x == null) return; const d = chain(Object.assign({ ref: 8 }, o)), t = now(), s = o.surf; + if (s === 'metal') tone(d, t, 0.25, 'triangle', V(1800, 2600), 900, 0.3); + if (s === 'wood') noise(d, t, 0.08, 'bandpass', 900, 3, 0.6); else if (s === 'water') noise(d, t, 0.2, 'highpass', 1200, 1, 0.4); else noise(d, t, 0.07, 'bandpass', s === 'stone' ? 2400 : 700, 2, 0.6); + }, + whiz() { const d = chain({ vol: 0.6 }), t = now(); noise(d, t, 0.18, 'bandpass', 3800, 6, 0.7, 0, 1400); }, + hitThud() { const d = chain({ vol: 0.5 }), t = now(); tone(d, t, 0.06, 'sine', 380, 200, 0.4); }, + killThud() { const d = chain({ vol: 0.6 }), t = now(); tone(d, t, 0.09, 'sine', 300, 140, 0.5); noise(d, t, 0.06, 'bandpass', 1500, 3, 0.3); }, + throw() { const d = chain({ vol: 0.4 }), t = now(); noise(d, t, 0.25, 'bandpass', 1400, 2, 0.4, 0, 500); }, + pin() { const d = chain({ vol: 0.5 }), t = now(); noise(d, t, 0.04, 'bandpass', 4200, 8, 0.6); tone(d, t + 0.06, 0.15, 'triangle', 2600, 2000, 0.15); }, + clink(o) { const d = chain(o), t = now(); tone(d, t, 0.12, 'triangle', V(2000, 2600), 1500, 0.3); }, + rock(o) { const d = chain(Object.assign({ ref: 10 }, o)), t = now(); noise(d, t, 0.05, 'bandpass', o && o.surf === 'stone' ? 2500 : 900, 3, 0.8); noise(d, t + 0.09, 0.04, 'bandpass', 1500, 3, 0.4); }, + explosion(o) { const d = chain(Object.assign({ ref: 30 }, o), 1.4), t = now(), k = o && o.big ? 1.6 : 1; noise(d, t, 1.6 * k, 'lowpass', 900, 0.7, 1.6, 0, 60); tone(d, t, 0.8 * k, 'sine', 70, 25, 1.6); noise(d, t, 0.15, 'highpass', 1500, 0.7, 0.9); noise(d, t + 0.3, 2.5 * k, 'lowpass', 300, 0.5, 0.35, 0, 60); }, + bodyfall(o) { const d = chain(Object.assign({ ref: 8 }, o)), t = now(); noise(d, t, 0.18, 'lowpass', 300, 1, 0.7); noise(d, t + 0.12, 0.1, 'lowpass', 500, 1, 0.3); }, + takedown() { const d = chain({ vol: 0.5 }), t = now(); noise(d, t + 0.1, 0.3, 'bandpass', 600, 1, 0.4); noise(d, t + 0.4, 0.15, 'lowpass', 300, 1, 0.5); }, + squelch() { const d = chain({ vol: 0.3 }), t = now(); noise(d, t, 0.12, 'bandpass', 1800, 2, 0.4); noise(d, t + 0.12, 0.05, 'highpass', 3000, 1, 0.2); }, + squad() { const d = chain({ vol: 0.15 }), t = now(); noise(d, t, 0.06, 'bandpass', 1200, 3, 0.2); }, + objective() { const d = chain({ vol: 0.3 }), t = now(); tone(d, t, 0.5, 'triangle', 392, 0, 0.25); tone(d, t + 0.12, 0.6, 'triangle', 523, 0, 0.2); }, + objDone() { const d = chain({ vol: 0.3 }), t = now(); tone(d, t, 0.3, 'triangle', 523, 0, 0.2); tone(d, t + 0.1, 0.5, 'triangle', 659, 0, 0.2); tone(d, t + 0.2, 0.7, 'triangle', 784, 0, 0.2); }, + tag() { const d = chain({ vol: 0.25 }), t = now(); tone(d, t, 0.12, 'sine', 1200, 0, 0.2); tone(d, t + 0.08, 0.15, 'sine', 1600, 0, 0.15); }, + casing(o) { if (Math.random() < 0.5) return; const d = chain(Object.assign({ vol: 0.25, ref: 4 }, o)), t = now(); tone(d, t, 0.08, 'triangle', V(3200, 4200), 2600, 0.15); }, + sting1() { const d = chain({ vol: 0.25 }), t = now(); tone(d, t, 1.2, 'sine', 220, 233, 0.2); tone(d, t, 1.2, 'sine', 330, 311, 0.12); }, + sting2() { const d = chain({ vol: 0.45 }), t = now(); noise(d, t, 0.8, 'lowpass', 300, 1, 0.5); tone(d, t, 0.9, 'sawtooth', 110, 104, 0.18); tone(d, t, 0.9, 'sawtooth', 164, 155, 0.12); }, + ui() { const d = chain({ vol: 0.2 }), t = now(); tone(d, t, 0.06, 'triangle', 900, 0, 0.15); }, + uiOk() { const d = chain({ vol: 0.25 }), t = now(); tone(d, t, 0.08, 'triangle', 700, 0, 0.15); tone(d, t + 0.06, 0.1, 'triangle', 1050, 0, 0.15); }, + wire() { const d = chain({ vol: 0.6 }), t = now(); noise(d, t, 0.06, 'bandpass', 3500, 6, 0.7); tone(d, t, 0.4, 'triangle', 900, 300, 0.2); }, + charge() { const d = chain({ vol: 0.5 }), t = now(); for (let i = 0; i < 3; i++) noise(d, t + i * 0.25, 0.05, 'bandpass', 2000 + i * 300, 5, 0.4); }, + door() { const d = chain({ vol: 0.7 }), t = now(); noise(d, t, 0.18, 'lowpass', 400, 1, 1.0); noise(d, t + 0.05, 0.4, 'bandpass', 700, 2, 0.3); }, + truck(o) { const d = chain(Object.assign({ ref: 30 }, o)), t = now(); tone(d, t, 2.5, 'sawtooth', 55, 50, 0.25); noise(d, t, 2.5, 'lowpass', 200, 1, 0.3); } + }; + AU.play = function (name, o) { + if (!ctx || !AU.ready || ctx.state !== 'running') return; + const f = SND[name]; if (!f) return; + const t = performance.now(); if (lastPlay[name] && t - lastPlay[name] < (name === 'smg' || name === 'mg' || name === 'esmg' ? 25 : 35)) return; lastPlay[name] = t; + // sound travels at 343 m/s: far shots and blasts arrive after their flash + if (o && o.x != null && IV.world.camera && /rifle|smg|mg|pistol|explosion/.test(name)) { + const c = IV.world.camera.position, d = Math.hypot(o.x - c.x, o.z - c.z); + if (name === 'explosion' && d < 16) AU.deafen(1 - d / 16); + if (d > 20) { setTimeout(() => { try { f(o); } catch (e) {} }, d / 343 * 1000); return; } + } + try { f(o); } catch (e) {} + }; + // a blast right beside you: everything muffles and a high ring fades out over a few seconds + AU.deafen = function (k) { + if (!ctx || IV.settings.motion) return; + const t = now(); AU.deaf.frequency.cancelScheduledValues(t); AU.deaf.frequency.setValueAtTime(400 + (1 - k) * 2000, t); AU.deaf.frequency.exponentialRampToValueAtTime(20000, t + 3.5); + const o = ctx.createOscillator(), g = ctx.createGain(); o.frequency.value = 3400; g.gain.setValueAtTime(0.0001, t); g.gain.exponentialRampToValueAtTime(0.05 * k, t + 0.05); g.gain.exponentialRampToValueAtTime(0.0001, t + 3); + o.connect(g); g.connect(comp); o.start(t); o.stop(t + 3.1); + }; + // footsteps: surface sets the filter, gait the loudness + AU.step = function (surf, gait, vol, pos) { + if (!ctx || !AU.ready || ctx.state !== 'running') return; + const g = { sprint: 0.9, run: 0.7, walk: 0.45, crouchRun: 0.35, crouch: 0.22, prone: 0.18 }[gait] || 0.4; + const o = pos ? { x: pos.x, z: pos.z, ref: 6, vol: g * vol } : { vol: g * vol }; + const d = chain(o), t = now(); + if (surf === 'gravel') { noise(d, t, 0.09, 'bandpass', V(2500, 3500), 1.2, 0.6); noise(d, t + 0.02, 0.06, 'highpass', 4000, 1, 0.3); } + else if (surf === 'wood') { noise(d, t, 0.07, 'lowpass', 600, 2, 0.8); tone(d, t, 0.08, 'sine', V(130, 170), 90, 0.3); } + else if (surf === 'stone') noise(d, t, 0.05, 'bandpass', V(1300, 1800), 2, 0.6); + else if (surf === 'water') { noise(d, t, 0.25, 'bandpass', V(700, 1100), 1, 0.6, 0, 400); noise(d, t + 0.05, 0.15, 'highpass', 2500, 1, 0.3); } + else if (surf === 'mud') { noise(d, t, 0.12, 'lowpass', V(350, 500), 2, 0.7); noise(d, t + 0.05, 0.14, 'bandpass', V(700, 1000), 6, 0.25, 0, 300); /* the squelch as the boot comes out */ } + else if (surf === 'crops' || surf === 'tallgrass') { noise(d, t, 0.22, 'bandpass', V(2200, 3200), 0.8, 0.45); noise(d, t, 0.08, 'lowpass', 300, 1, 0.3); } + else { noise(d, t, 0.1, 'bandpass', V(500, 900), 0.9, 0.5); noise(d, t, 0.14, 'highpass', 3000, 0.8, 0.15); } + if (gait === 'prone' || gait === 'crouch') noise(d, t, 0.25, 'bandpass', 1000, 1, 0.12); + // kit: a quiet rattle of webbing and canteen on each running step + if (gait === 'run' || gait === 'sprint') { noise(d, t + 0.03, 0.06, 'bandpass', V(2600, 3400), 4, gait === 'sprint' ? 0.14 : 0.08); noise(d, t + 0.02, 0.12, 'bandpass', 900, 1.5, 0.06); } + }; + + // ---------------------------------------------------------------- ambience, artillery, aircraft, alarm, music + let ambNodes = null, bellT = null, aircraft = []; + AU.ambience = function (kind) { + if (!ctx) return; + AU.stopAmbience(); + const nodes = []; + // wind: brown-ish noise with a slow swell + const w = ctx.createBufferSource(); w.buffer = noiseBuf; w.loop = true; + const wf = ctx.createBiquadFilter(); wf.type = 'lowpass'; wf.frequency.value = 380; const wg = ctx.createGain(); wg.gain.value = kind === 'day' ? 0.12 : 0.16; + const lfo = ctx.createOscillator(); lfo.frequency.value = 0.07; const lg = ctx.createGain(); lg.gain.value = 0.08; lfo.connect(lg); lg.connect(wg.gain); + w.connect(wf); wf.connect(wg); wg.connect(amb); w.start(); lfo.start(); nodes.push(w, lfo); + if (kind === 'night') { // crickets: amplitude-modulated high tone bursts + for (let i = 0; i < 3; i++) { + const o = ctx.createOscillator(); o.type = 'sine'; o.frequency.value = 4200 + i * 380; + const am = ctx.createOscillator(); am.frequency.value = 28 + i * 6; const ag = ctx.createGain(); ag.gain.value = 0; + const amg = ctx.createGain(); amg.gain.value = 0.012; am.connect(amg); amg.connect(ag.gain); + const chirp = ctx.createOscillator(); chirp.frequency.value = 0.5 + i * 0.17; const cg = ctx.createGain(); cg.gain.value = 0.01; chirp.connect(cg); cg.connect(ag.gain); + o.connect(ag); ag.connect(amb); o.start(); am.start(); chirp.start(); nodes.push(o, am, chirp); + } + } else { // daytime: the odd bird + const birds = setInterval(() => { if (!ctx || document.hidden) return; const d = chain({ vol: 0.08 }), t = now(); for (let i = 0; i < 3; i++) tone(d, t + i * 0.12, 0.1, 'sine', V(2600, 3400), V(2000, 3800), 0.3); }, 5200); + nodes.push({ stop() { clearInterval(birds); } }); + } + // distant artillery now and then + const art = setInterval(() => { if (!ctx || document.hidden || !IV.playing()) return; if (Math.random() < 0.5) AU.distantBoom(V(0.15, 0.35)); }, 7000); + nodes.push({ stop() { clearInterval(art); } }); + ambNodes = nodes; + }; + AU.stopAmbience = function () { if (ambNodes) ambNodes.forEach(n => { try { n.stop(); } catch (e) {} }); ambNodes = null; AU.aircraft(false); AU.alarm(false); }; + AU.distantBoom = function (v) { if (!ctx) return; const d = chain({ vol: v || 0.3 }, 0.6), t = now(); noise(d, t, 2.2, 'lowpass', 160, 0.7, 0.9, 0, 40); tone(d, t, 1.2, 'sine', 50, 28, 0.6); }; + // aircraft passing over: a droning chord that swells and fades over dur seconds + // a rain bed: two noise layers (the hiss of the fall, the patter on leaves and roofs), eased to vol over secs + let rainN = null; + AU.rain = function (vol, secs) { + if (!ctx) return; + if (!rainN && vol > 0) { + const a = ctx.createBufferSource(); a.buffer = noiseBuf; a.loop = true; + const fa = ctx.createBiquadFilter(); fa.type = 'highpass'; fa.frequency.value = 1400; + const b = ctx.createBufferSource(); b.buffer = noiseBuf; b.loop = true; b.playbackRate.value = 0.7; + const fb = ctx.createBiquadFilter(); fb.type = 'bandpass'; fb.frequency.value = 520; fb.Q.value = 0.8; + const g = ctx.createGain(); g.gain.value = 0.0001; + a.connect(fa); fa.connect(g); b.connect(fb); fb.connect(g); g.connect(amb); a.start(); b.start(); + rainN = { a, b, g }; + } + if (!rainN) return; + const t = now(); rainN.g.gain.cancelScheduledValues(t); rainN.g.gain.setValueAtTime(Math.max(0.0001, rainN.g.gain.value), t); + rainN.g.gain.linearRampToValueAtTime(Math.max(0.0001, vol * 0.22), t + Math.max(0.05, secs || 0)); + }; + AU.rainStop = function () { if (rainN) { try { rainN.a.stop(); rainN.b.stop(); } catch (e) {} rainN = null; } }; + AU.aircraft = function (on, dur, vol) { + if (!ctx) return; + if (!on) { aircraft.forEach(n => { try { n.stop(); } catch (e) {} }); aircraft = []; return; } + const t = now(), g = ctx.createGain(); g.gain.setValueAtTime(0.0001, t); g.gain.exponentialRampToValueAtTime(vol || 0.4, t + dur * 0.4); g.gain.exponentialRampToValueAtTime(0.0001, t + dur); + const f = ctx.createBiquadFilter(); f.type = 'lowpass'; f.frequency.value = 420; g.connect(f); f.connect(amb); + for (const fr of [62, 63.5, 93, 124.6]) { const o = ctx.createOscillator(); o.type = 'sawtooth'; o.frequency.value = fr; const og = ctx.createGain(); og.gain.value = 0.18; o.connect(og); og.connect(g); o.start(t); o.stop(t + dur + 0.1); aircraft.push(o); } + }; + // the farm's alarm bell: clanging until stopped + AU.alarm = function (on) { + if (bellT) { clearInterval(bellT); bellT = null; } + if (!on || !ctx) return; + const ring = () => { if (!ctx || document.hidden) return; const d = chain({ vol: 0.35 }, 0.5), t = now(); for (const f of [880, 1320, 2216]) tone(d, t, 1.4, 'sine', f, f * 0.995, f === 880 ? 0.35 : 0.12); }; + ring(); bellT = setInterval(ring, 420); + }; + // adaptive music: three layers whose gains follow the alert level + let musLayers = null, musT = null, musLevel = 0, beat = 0; + AU.music = function (on) { + if (!ctx) return; + if (musT) { clearInterval(musT); musT = null; } + if (musLayers) { musLayers.forEach(l => { try { l.src.forEach(s => s.stop()); } catch (e) {} }); musLayers = null; } + if (!on) return; + const mk = (freqs, type, cut, vol) => { const g = ctx.createGain(); g.gain.value = 0; const f = ctx.createBiquadFilter(); f.type = 'lowpass'; f.frequency.value = cut; g.connect(f); f.connect(mus); const src = freqs.map(fr => { const o = ctx.createOscillator(); o.type = type; o.frequency.value = fr; o.detune.value = V(-6, 6); const og = ctx.createGain(); og.gain.value = vol; o.connect(og); og.connect(g); o.start(); return o; }); return { g, src, f }; }; + musLayers = [mk([73.4, 110, 146.8, 174.6], 'triangle', 600, 0.12), mk([77.8, 116.5], 'sawtooth', 420, 0.08), mk([55, 82.4], 'sawtooth', 300, 0.1)]; + // a slow pulse (suspicious) and drums (combat) scheduled on the audio clock + let next = now() + 0.1; + musT = setInterval(() => { + if (!ctx || document.hidden) return; + const lvl = IV.ai ? IV.ai.level() : 0; musLevel = lvl; + const tt = now(); + musLayers[0].g.gain.setTargetAtTime(IV.playing() ? 0.6 : 0.25, tt, 1.5); + musLayers[1].g.gain.setTargetAtTime(lvl >= 1 && lvl < 3 ? 0.5 : 0, tt, 1.2); + musLayers[2].g.gain.setTargetAtTime(lvl >= 3 ? 0.7 : 0, tt, 0.6); + while (next < tt + 0.2) { + beat++; + if (lvl === 2 && beat % 2 === 0) { const d = chain({ vol: 0.12 }); tone(d, next, 0.3, 'sine', 98, 90, 0.4); } + if (lvl >= 3) { const d = chain({ vol: 0.22 }); if (beat % 4 === 0 || beat % 8 === 3) { tone(d, next, 0.35, 'sine', 70, 40, 0.8); noise(d, next, 0.2, 'lowpass', 300, 1, 0.5); } if (beat % 4 === 2) noise(d, next, 0.1, 'bandpass', 1800, 2, 0.25); } + next += 0.3; + } + }, 50); + }; + AU.musicLevel = () => musLevel; + // small distant sounds for IV.ambience.event (all unpositioned, already rolled off by distance by the caller) + AU.synth = { + crack(v, bright) { if (!ctx) return; const d = chain({ vol: v }, 0.5), t = now(); noise(d, t, 0.25, 'bandpass', 600 + 1400 * (bright || 0.3), 0.8, 1, 0, 200); tone(d, t, 0.3, 'sine', 90, 45, 0.5); }, + pop(v) { if (!ctx) return; const d = chain({ vol: v }, 0.7), t = now(); noise(d, t, 0.5, 'lowpass', 700, 0.7, 0.9, 0, 120); }, + bark(v, n) { if (!ctx) return; for (let i = 0; i < n; i++) { const d = chain({ vol: v }, 0.4), t = now() + i * V(0.32, 0.5); tone(d, t, 0.14, 'sawtooth', V(420, 520), V(260, 320), 0.6); noise(d, t, 0.1, 'bandpass', 900, 2, 0.4, 0, 600); } }, + bell(v, n) { if (!ctx) return; for (let i = 0; i < n; i++) { const d = chain({ vol: v }, 0.8), t = now() + i * 1.6; for (const [f, a] of [[392, 0.4], [784, 0.18], [1175, 0.1], [523, 0.08]]) tone(d, t, 3.2, 'sine', f, f * 0.998, a); } }, + owl(v) { if (!ctx) return; const d = chain({ vol: v || 0.12 }), t = now(); tone(d, t, 0.32, 'sine', 390, 360, 0.6); tone(d, t + 0.55, 0.5, 'sine', 380, 340, 0.7); }, + gust(v, dur) { if (!ctx) return; const d = chain({ vol: 0.0001 }), t = now(), g = d; const src = ctx.createBufferSource(); src.buffer = noiseBuf; src.loop = true; const f = ctx.createBiquadFilter(); f.type = 'bandpass'; f.frequency.setValueAtTime(300, t); f.frequency.linearRampToValueAtTime(700, t + dur * 0.5); f.frequency.linearRampToValueAtTime(260, t + dur); const gg = ctx.createGain(); gg.gain.setValueAtTime(0.0001, t); gg.gain.exponentialRampToValueAtTime(v, t + dur * 0.4); gg.gain.exponentialRampToValueAtTime(0.0001, t + dur); src.connect(f); f.connect(gg); gg.connect(amb); src.start(t); src.stop(t + dur + 0.1); } + }; +})(); diff --git a/e63334287a3deaa3/ironveil/js/camera.js b/e63334287a3deaa3/ironveil/js/camera.js new file mode 100644 index 00000000..6659142d --- /dev/null +++ b/e63334287a3deaa3/ironveil/js/camera.js @@ -0,0 +1,198 @@ +/* Ironveil camera: first person by default (js/fp.js); over-the-shoulder third person as a Settings option (shoulder swap), a damped pivot that follows the interpolated player, + collision that pulls the camera in front of walls and hedges (fast in, slow out), aim zoom, the first-person scope + with sway and hold-breath, recoil kick, shake, and the aim assist that nudges the view onto enemies. */ +(function () { + 'use strict'; + const T = IV.TUNING, CT = T.cam, W = IV.world, F = IV.CF; + const C = IV.camera = { + pivot: new THREE.Vector3(), dist: CT.dist, side: 1, aimK: 0, scopeK: 0, trauma: 0, fov: 68, + swayX: 0, swayY: 0, breath: 1, holding: false, breathOut: 0, kickP: 0, kickY: 0, assist: null, mode: 'third', lookDir: new THREE.Vector3(), + override: null + }; + const P = IV.player; + let inited = false; + C.reset = function () { inited = false; C.dist = CT.dist; C.aimK = 0; C.scopeK = 0; C.trauma = 0; C.breath = 1; C.kickP = C.kickY = 0; C.assist = null; C.override = null; }; + C.shake = function (a) { if (IV.settings.motion) a *= 0.3; C.trauma = Math.min(1, C.trauma + a); }; + // recoil: the view kicks at once and a spring brings most of it back (a little climb stays, as with a real gun) + C.kick = function (p, y) { P.pitch += p; P.yaw += y; C.kickP += p * 0.72; C.kickY += y * 0.6; }; + // a very small bob on each foot contact (Settings: Camera bob), and a dip on landing + C.bobV = 0; C.bobY = 0; + C.footBob = function (k) { if (!IV.settings.bob || IV.settings.motion || (IV.weapons && (IV.weapons.aiming || IV.weapons.scoped))) return; C.bobV -= CT.bob * 9 * (k || 1); }; + C.landDip = function (k) { if (IV.settings.motion) return; C.bobV -= CT.landDip * 9 * (k || 1); }; + + // look input (mouse/touch), applied every render frame (raw, no smoothing) + C.look = function (dx, dy, touch) { + const S = IV.settings, W8 = IV.weapons, aimed = W8 && (W8.aiming || W8.scoped); + let k = CT.sens * (aimed ? S.aimSens : S.sens) * (touch ? 1.7 : 1) * (C.fov / 68); + // aim friction while hip-firing (and lightly while aimed) over a visible enemy + const fr = assistFriction(); k *= 1 - fr; + P.yaw -= dx * k; + P.pitch -= dy * k * (S.invert ? -1 : 1); + P.pitch = IV.clamp(P.pitch, CT.pitchMin, CT.pitchMax); + }; + + // ---------------------------------------------------------------- aim assist + const diff = () => (IV.mission && IV.mission.diff) || 0; + function assistScale() { return IV.settings.assist * (IV.touch ? T.assist.touchMul : 1); } + // the best enemy to snap toward: visible, alive, within the cone, closest to the centre of the view + C.findTarget = function (cone, maxRange) { + const AI = IV.ai; if (!AI) return null; + const cam = W.camera, cp = cam.position, fwd = C.lookDir; + let best = null, bs = cone; + const list = IV.targets && IV.targets.length ? AI.list.concat(IV.targets) : AI.list; + for (const e of list) { + if (!e.alive || e.noAssist) continue; + const tx = e.pos.x, ty = e.pos.y + e.chestH(), tz = e.pos.z; + const dx = tx - cp.x, dy = ty - cp.y, dz = tz - cp.z, d = Math.hypot(dx, dy, dz); + if (d > maxRange) continue; + const a = Math.acos(IV.clamp((dx * fwd.x + dy * fwd.y + dz * fwd.z) / d, -1, 1)); + if (a > bs) continue; + if (!W.clear(cp.x, cp.y, cp.z, tx, ty, tz, F.BULLET)) continue; + bs = a; best = { e, x: tx, y: ty, z: tz, d }; + } + return best; + }; + C.onAimStart = function (scoped) { + if (IV.fp && IV.fp.on()) return; // first person: no snap, only slowdown and a mild pull (console style) + const d = diff(), s = T.assist.snap[d] * assistScale(); + if (s <= 0) return; + const t = C.findTarget(T.assist.cone[d] * Math.min(1.4, assistScale()), scoped ? T.assist.scopeMaxRange : 120); + if (!t) return; + const cp = W.camera.position; + const wantYaw = IV.yawTo(t.x - cp.x, t.z - cp.z), wantPitch = Math.atan2(t.y - cp.y, Math.hypot(t.x - cp.x, t.z - cp.z)); + C.assist = { dy: IV.wrapA(wantYaw - P.yaw) * Math.min(1, s), dp: (wantPitch - P.pitch) * Math.min(1, s), t: 0 }; + }; + function assistFriction() { + const d = diff(), f = T.assist.friction[d] * Math.min(1, assistScale()); + if (f <= 0) return 0; + const W8 = IV.weapons; if (W8 && W8.scoped) { const t = C.findTarget(T.assist.frictionCone * 0.4, T.assist.scopeMaxRange); return t ? f * 0.5 : 0; } + const t = C.findTarget(T.assist.frictionCone, 80); + return t ? f : 0; + } + + // ---------------------------------------------------------------- per render frame + const want = new THREE.Vector3(), dir = new THREE.Vector3(), right = new THREE.Vector3(), tmp = new THREE.Vector3(); + C.frame = function (dt) { + const cam = W.camera, S = IV.settings, W8 = IV.weapons; + if (C.override) { C.override(cam, dt); C.lookDir.set(0, 0, -1).applyQuaternion(cam.quaternion); return; } + // assist snap (eased over snapTime) + if (C.assist) { + const a = C.assist, st = T.assist.snapTime, k0 = IV.smooth(Math.min(1, a.t / st)); a.t += dt; const k1 = IV.smooth(Math.min(1, a.t / st)); + P.yaw += a.dy * (k1 - k0); P.pitch += a.dp * (k1 - k0); + if (a.t >= st) C.assist = null; + } + // first person, console-style assist: while moving with a target near the centre, the view turns gently with it + if (IV.fp && IV.fp.on() && P.speed > 0.5 && assistScale() > 0 && T.assist.friction[diff()] > 0) { + const t = C.findTarget(0.1, 60); + if (t) { const cp = W.camera.position, wy = IV.yawTo(t.x - cp.x, t.z - cp.z); P.yaw += IV.wrapA(wy - P.yaw) * Math.min(1, 1.2 * assistScale() * dt); } + } + // recoil recovery (spring back toward where you were aiming) + const rk = 1 - Math.exp(-dt * 11); + P.pitch -= C.kickP * rk; P.yaw -= C.kickY * rk; C.kickP -= C.kickP * rk; C.kickY -= C.kickY * rk; + // bob spring (critically damped-ish) + C.bobV += (-C.bobY * 120 - C.bobV * 18) * dt; C.bobY += C.bobV * dt; if (Math.abs(C.bobY) < 1e-4 && Math.abs(C.bobV) < 1e-3) C.bobY = C.bobV = 0; + P.pitch = IV.clamp(P.pitch, CT.pitchMin, CT.pitchMax); + const aiming = W8 && W8.aiming; + // first person: the rifle comes up to the eye first (the viewmodel), and the scope view starts once it is there + const scoped = W8 && W8.scoped && !(IV.fp && IV.fp.on() && !IV.fp.scopeReady()); + C.scopeView = !!scoped; + const binoc = !!(W8 && W8.binoc) && !(IV.fp && IV.fp.on() && !IV.fp.binocReady()); // binoculars come up to the eyes first too + C.aimK = IV.damp(C.aimK, aiming || (W8 && (W8.binoc || W8.scoped)) ? 1 : 0, 14, dt); + C.scopeK = scoped ? 1 : 0; + W.grassClear.value.set(P.render.x, 0, P.render.z, scoped || binoc ? 3.2 : P.stance === 'prone' ? 1.8 : 0); + // pivot: at the shoulder, height by stance + const pr = P.render; + const ph = P.stance === 'stand' ? 1.55 : P.stance === 'crouch' ? 1.05 : 0.5; + want.set(pr.x, pr.y + ph + C.bobY, pr.z); + if (!inited) { C.pivot.copy(want); inited = true; } + C.pivot.x = IV.damp(C.pivot.x, want.x, CT.follow, dt); C.pivot.z = IV.damp(C.pivot.z, want.z, CT.follow, dt); + C.pivot.y = IV.damp(C.pivot.y, want.y, 11, dt) + (C.bobY - (C.lastBob || 0)); C.lastBob = C.bobY; + // shake + C.trauma = Math.max(0, C.trauma - dt * 1.6); + const sh = C.trauma * C.trauma, t = IV.time; + const shY = (IV.noise(t * 23, 1.7) - 0.5) * 0.06 * sh, shP = (IV.noise(t * 23, 9.1) - 0.5) * 0.06 * sh; + // sway (scope): stance-dependent figure-eight, much smaller while holding breath + let sw = 0; + if (scoped) { + const base = P.stance === 'prone' ? 0.0011 : P.stance === 'crouch' ? 0.0022 : 0.0042; + const holding = IV.input.held('breath') && C.breath > 0; + if (holding) { C.breath = Math.max(0, C.breath - dt / 6); } else C.breath = Math.min(1, C.breath + dt / 4); + C.holding = holding; + const tired = C.breath < 0.15 ? 2.2 : 1; + sw = base * (holding ? 0.12 : 1) * tired * (S.motion ? 0.6 : 1) * (1 + (P.speed > 0.3 ? 2 : 0)); + C.swayX = Math.sin(t * 0.9) * sw + Math.sin(t * 2.3 + 1) * sw * 0.35; + C.swayY = Math.sin(t * 1.8) * sw * 0.6 + Math.cos(t * 1.1) * sw * 0.3; + } else { C.swayX = C.swayY = 0; C.holding = false; C.breath = Math.min(1, C.breath + dt / 4); } + const yaw = P.yaw + shY + C.swayX, pitch = P.pitch + shP + C.swayY; + dir.set(-Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), -Math.cos(yaw) * Math.cos(pitch)); + C.lookDir.copy(dir); + right.set(Math.cos(yaw), 0, -Math.sin(yaw)); + // FOV + const sprintK = P.sprinting ? 1 : 0; + C._spr = IV.damp(C._spr || 0, sprintK, 6, dt); + let fov = S.fov + C._spr * CT.sprintFov; + fov = fov * (1 - C.aimK * (1 - CT.aimFov)); + if (binoc) fov = S.fov / 4.5; + if (scoped) fov = S.fov / T.weapons.rifle.zoom; + C.fov = IV.damp(C.fov, fov, scoped ? 40 : 12, dt); + if (Math.abs(cam.fov - C.fov) > 0.01) { cam.fov = C.fov; cam.updateProjectionMatrix(); } + if (!scoped && !binoc && IV.fp && IV.fp.on()) { IV.fp.frame(cam, dt, dir, yaw, pitch); return; } // the default view + IV.fp && IV.fp.off(); + if (scoped || binoc) { + // first person at the eye + P.actor && P.actor.setVisible(false); + cam.position.set(pr.x, pr.y + (P.eyeY() - P.pos.y), pr.z); + const f = IV.fwd(P.yaw); cam.position.x += f.x * 0.15; cam.position.z += f.z * 0.15; + // the eye at the real eyepiece of the rifle or binoculars (_scopeEye) when the model has one and it is + // where it should be (within 0.5 m of the body's eye); the direction stays the player's aim, so the drop marks hold + const WP = IV.weapons, eye = WP && WP.part && WP.part(WP.models && (W8.binoc ? WP.models.binoc : WP.models.rifle), W8.binoc ? 'binoculars_scopeEye' : 'rifleScoped_scopeEye'); + if (eye) { eye.getWorldPosition(tmp); if (tmp.distanceTo(cam.position) < 0.5) cam.position.copy(tmp); } + tmp.copy(cam.position).add(dir); cam.lookAt(tmp); + cam.near = 0.15; cam.updateProjectionMatrix(); + C.mode = 'scope'; + return; + } + P.actor && P.actor.setVisible(true); + C.mode = 'third'; + if (cam.near !== 0.08) { cam.near = 0.08; cam.updateProjectionMatrix(); } + // shoulder arm + const side = CT.side * (1 - C.aimK) + CT.aimSide * C.aimK, dist = CT.dist * (1 - C.aimK) + CT.aimDist * C.aimK, hgt = CT.height * (1 - C.aimK * 0.5); + const proneK = P.stance === 'prone' ? 0.8 : 1; + C.sideS = IV.damp(C.sideS == null ? C.side : C.sideS, C.side, 10, dt); + // lean: aiming with a wall or hedge end right in front of you, the view slides out past the corner (shoulder side) + let lean = 0; + if (C.aimK > 0.5) { + const ay = C.pivot.y + 0.1, fx = dir.x, fz = dir.z, fl = Math.hypot(fx, fz) || 1; + if (W.raycast(C.pivot.x, ay, C.pivot.z, fx / fl, 0, fz / fl, 1.1, F.SOLID | F.SIGHT, true)) { + const ox = C.pivot.x + right.x * 0.75 * C.side, oz = C.pivot.z + right.z * 0.75 * C.side; + if (!W.raycast(C.pivot.x, ay, C.pivot.z, right.x * C.side, 0, right.z * C.side, 0.8, F.SOLID, true) && !W.raycast(ox, ay, oz, fx / fl, 0, fz / fl, 3, F.SOLID | F.SIGHT, true)) lean = 0.7; + } + } + C.lean = IV.damp(C.lean || 0, lean, 8, dt); + const sx = right.x * (side + C.lean) * C.sideS, sz = right.z * (side + C.lean) * C.sideS; + // the camera's own anchor sits beside the pivot (shoulder); keep that inside walls too + const ax = C.pivot.x + sx, ay = C.pivot.y + hgt, az = C.pivot.z + sz; + let sideOk = 1; + { + const sl = Math.hypot(sx, sz) || 1, hit = W.raycast(C.pivot.x, C.pivot.y + hgt, C.pivot.z, sx / sl, 0, sz / sl, sl + 0.25, F.SOLID | F.SIGHT, true); + if (hit) sideOk = Math.max(0, (hit.t - 0.25) / sl); + } + const bx = C.pivot.x + sx * sideOk, by = ay, bz = C.pivot.z + sz * sideOk; + const dWant = dist * proneK; + // collision: a few rays from the anchor back along the view; nearest hit wins + let dHit = dWant; + const offs = [[0, 0], [0.18, 0.12], [-0.18, 0.12], [0.18, -0.12], [-0.18, -0.12]]; + for (const o of offs) { + const ox = bx + right.x * o[0], oy = by + o[1], oz = bz + right.z * o[0]; + const h = W.raycast(ox, oy, oz, -dir.x, -dir.y, -dir.z, dWant + 0.3, F.SOLID | F.SIGHT, false); + if (h && h.t - 0.3 < dHit) dHit = Math.max(0.35, h.t - 0.3); + } + if (dHit < C.dist) C.dist = IV.damp(C.dist, dHit, CT.pullIn, dt); else C.dist = IV.damp(C.dist, dHit, CT.easeOut, dt); + cam.position.set(bx - dir.x * C.dist, by - dir.y * C.dist, bz - dir.z * C.dist); + // never below the ground + const gh = W.height(cam.position.x, cam.position.z) + 0.25; if (cam.position.y < gh) cam.position.y = gh; + tmp.copy(cam.position).add(dir); cam.lookAt(tmp); + // fade the player out when the camera is pushed right against them + if (P.actor) P.actor.setVisible(C.dist > 0.55); + }; +})(); diff --git a/e63334287a3deaa3/ironveil/js/chars-standin.js b/e63334287a3deaa3/ironveil/js/chars-standin.js new file mode 100644 index 00000000..71d9c2e8 --- /dev/null +++ b/e63334287a3deaa3/ironveil/js/chars-standin.js @@ -0,0 +1,585 @@ +/* Ironveil character stand-in: the same window.IVChars API as chars.js (see README), made entirely in code, so the game + runs before (or without) the real rigged characters. Each soldier is ONE skinned mesh (one draw call) built from + smooth capsules on a 17-bone skeleton, with procedural clips (walk, run, crouch, prone, deaths...), an upper-body + layer, aim bending, and two-bone arm IK that puts both hands on whatever weapon is in the right hand. + 1 unit = 1 m, feet at the origin, facing +Z. */ +(function () { + 'use strict'; + if (window.IVChars && !window.IVChars.standin) return; + const V3 = THREE.Vector3, Q = THREE.Quaternion; + const PI = Math.PI; + + // ---------------------------------------------------------------- skeleton (bind positions, model space) + const BONES = [ + ['hips', -1, 0, 0.98, 0], ['spine', 0, 0, 1.10, 0], ['chest', 1, 0, 1.30, -0.01], ['neck', 2, 0, 1.50, 0], ['head', 3, 0, 1.585, 0.01], + ['upperArmL', 2, 0.195, 1.425, -0.01], ['foreArmL', 5, 0.205, 1.14, -0.01], ['handL', 6, 0.21, 0.885, 0.0], + ['upperArmR', 2, -0.195, 1.425, -0.01], ['foreArmR', 8, -0.205, 1.14, -0.01], ['handR', 9, -0.21, 0.885, 0.0], + ['thighL', 0, 0.098, 0.93, 0], ['shinL', 11, 0.1, 0.505, 0.0], ['footL', 12, 0.1, 0.085, -0.01], + ['thighR', 0, -0.098, 0.93, 0], ['shinR', 14, -0.1, 0.505, 0.0], ['footR', 15, -0.1, 0.085, -0.01] + ]; + const BI = {}; BONES.forEach((b, i) => BI[b[0]] = i); + const NB = BONES.length; + const UPPER = ['spine', 'chest', 'neck', 'head', 'upperArmL', 'foreArmL', 'handL', 'upperArmR', 'foreArmR', 'handR'].map(n => BI[n]); + + // ---------------------------------------------------------------- looks per kind + const LOOK = { + hero: { coat: 0x5f5d40, coat2: 0x56553a, trou: 0x5a5640, boot: 0x3b2a1d, legg: 0x9a8c68, helm: 0x4a4f33, web: 0x8a8158, skin: 0xc49a80, helmet: 'us', pack: true }, + ally: { coat: 0x625f42, coat2: 0x585639, trou: 0x5c5842, boot: 0x3b2a1d, legg: 0x9a8c68, helm: 0x4d5235, web: 0x8a8158, skin: 0xb88c70, helmet: 'us', pack: true }, + rifleman: { coat: 0x5c6155, coat2: 0x53584d, trou: 0x575a52, boot: 0x1c1a18, helm: 0x4a4f48, web: 0x1e1d1b, skin: 0xc29c86, helmet: 'de', canister: true }, + officer: { coat: 0x5a604f, coat2: 0x51574a, trou: 0x4f544a, boot: 0x141312, helm: 0x4d5347, web: 0x2a2420, skin: 0xc7a28a, helmet: 'cap', long: true }, + sniper: { coat: 0x5a5a42, coat2: 0x47492f, trou: 0x575a52, boot: 0x1c1a18, helm: 0x4a4f48, web: 0x1e1d1b, skin: 0xc29c86, helmet: 'de', camo: true }, + gunner: { coat: 0x5c6155, coat2: 0x53584d, trou: 0x575a52, boot: 0x1c1a18, helm: 0x4a4f48, web: 0x1e1d1b, skin: 0xbd967e, helmet: 'de', belt: true } + }; + + // ---------------------------------------------------------------- geometry building + const tmpM = new THREE.Matrix4(), tmpQ = new Q(), tmpV = new V3(), tmpV2 = new V3(), up = new V3(0, 1, 0); + // capsule along +Y from 0 to len, radii r0 (bottom) r1 (top) + function capsule(r0, r1, len, rs, hs) { + const pts = []; + rs = Math.min(rs || 8, 10); hs = Math.min(hs || 3, 3); + for (let i = 0; i <= hs; i++) { const a = -PI / 2 + (i / hs) * PI / 2; pts.push(new THREE.Vector2(Math.cos(a) * r0, Math.sin(a) * r0)); } + for (let i = 0; i <= hs; i++) { const a = (i / hs) * PI / 2; pts.push(new THREE.Vector2(Math.cos(a) * r1, len + Math.sin(a) * r1)); } + pts[0].x = 0.0001; pts[pts.length - 1].x = 0.0001; + return new THREE.LatheGeometry(pts, rs); + } + // a part: geometry placed with matrix, coloured, skinned to bone b (and optionally blended to bone b2 near y0) + const _lin = new THREE.Color(); + function Builder() { this.p = []; this.n = []; this.c = []; this.si = []; this.sw = []; this.uv = []; } + Builder.prototype.add = function (geo, m, color, b, blend, colorFn) { + const g = geo.index ? geo.toNonIndexed() : geo; + const pa = g.attributes.position, na = g.attributes.normal, nm = new THREE.Matrix3().getNormalMatrix(m), col = new THREE.Color(color); + for (let i = 0; i < pa.count; i++) { + tmpV.fromBufferAttribute(pa, i).applyMatrix4(m); tmpV2.fromBufferAttribute(na, i).applyMatrix3(nm).normalize(); + this.p.push(tmpV.x, tmpV.y, tmpV.z); this.n.push(tmpV2.x, tmpV2.y, tmpV2.z); + let cc = col; if (colorFn) cc = colorFn(tmpV, col); + _lin.copy(cc).convertSRGBToLinear(); + this.c.push(_lin.r, _lin.g, _lin.b); + // box-projected UVs for the cloth weave texture + const ax = Math.abs(tmpV2.x), ay = Math.abs(tmpV2.y); + if (ay > 0.7) this.uv.push(tmpV.x * 3, tmpV.z * 3); else if (ax > 0.7) this.uv.push(tmpV.z * 3, tmpV.y * 3); else this.uv.push(tmpV.x * 3, tmpV.y * 3); + let w2 = 0, b2 = 0; + // soft joint: vertices near the parent joint (y0) share their weight with the parent bone + if (blend) { w2 = IV.clamp(1 - Math.abs(blend.y0 - tmpV.y) / blend.r, 0, 1) * 0.5; b2 = blend.b; } + this.si.push(b, b2, 0, 0); this.sw.push(1 - w2, w2, 0, 0); + } + }; + // segment helper: place a capsule from point a to point b + function segMatrix(a, b) { + const d = tmpV.copy(b).sub(a), len = d.length(); + tmpQ.setFromUnitVectors(up, d.normalize()); + return { m: new THREE.Matrix4().compose(a.clone(), tmpQ.clone(), new V3(1, 1, 1)), len }; + } + const bp = n => { const b = BONES[BI[n]]; return new V3(b[2], b[3], b[4]); }; + const M = (x, y, z, sx, sy, sz, rx, ry, rz) => new THREE.Matrix4().compose(new V3(x, y, z), new Q().setFromEuler(new THREE.Euler(rx || 0, ry || 0, rz || 0)), new V3(sx || 1, sy || 1, sz || 1)); + + function buildBody(kind) { + const L = LOOK[kind] || LOOK.rifleman, B = new Builder(); + const sphere = new THREE.SphereGeometry(1, 10, 7), box = new THREE.BoxGeometry(1, 1, 1), cyl = new THREE.CylinderGeometry(1, 1, 1, 10, 1); + const camo = L.camo ? (p, c) => { const n = IV.noise(p.x * 9 + p.z * 4, p.y * 7); return n > 0.62 ? new THREE.Color(0x3a3d26) : n < 0.3 ? new THREE.Color(0x6a6544) : c; } : null; + const folds = (p, c) => { const k = 0.93 + 0.1 * IV.noise(p.x * 23, p.y * 31 + p.z * 17); return c.clone().multiplyScalar(k); }; + const cloth = camo || folds; + // torso: hips, belly, chest as elliptic capsules + B.add(capsule(0.16, 0.155, 0.12, 16, 4), M(0, 0.86, 0, 1.08, 1, 0.78), L.trou, BI.hips, null, cloth); + B.add(capsule(0.155, 0.17, 0.16, 16, 4), M(0, 1.0, 0.0, 1.06, 1, 0.74), L.coat, BI.spine, { y0: 1.02, r: 0.08, b: BI.hips }, cloth); + B.add(capsule(0.17, 0.155, 0.2, 16, 4), M(0, 1.2, -0.005, 1.18, 1, 0.78), L.coat, BI.chest, { y0: 1.2, r: 0.07, b: BI.spine }, cloth); + // shoulders: rounded yoke + B.add(sphere, M(0.15, 1.395, -0.01, 0.1, 0.085, 0.095), L.coat2, BI.chest, null, cloth); + B.add(sphere, M(-0.15, 1.395, -0.01, 0.1, 0.085, 0.095), L.coat2, BI.chest, null, cloth); + // jacket skirt below the belt + B.add(capsule(0.175, 0.17, 0.1, 16, 2), M(0, 0.86, 0, 1.07, 1, 0.8), L.coat2, BI.hips, null, cloth); + if (L.long) B.add(cyl, M(0, 0.7, 0, 0.19, 0.3, 0.15), L.coat2, BI.hips, null, cloth); + // collar + neck + head + B.add(cyl, M(0, 1.47, 0, 0.075, 0.06, 0.07), L.coat2, BI.chest); + B.add(capsule(0.052, 0.05, 0.09, 10, 2), M(0, 1.47, 0.005), L.skin, BI.neck); + B.add(sphere, M(0, 1.655, 0.012, 0.098, 0.118, 0.108), L.skin, BI.head); + B.add(sphere, M(0, 1.6, 0.04, 0.078, 0.06, 0.085), L.skin, BI.head); // jaw + B.add(box, M(0, 1.655, 0.118, 0.026, 0.05, 0.035, 0.2), L.skin, BI.head); // nose + B.add(sphere, M(0.098, 1.65, 0.0, 0.018, 0.032, 0.022), L.skin, BI.head); // ears + B.add(sphere, M(-0.098, 1.65, 0.0, 0.018, 0.032, 0.022), L.skin, BI.head); + B.add(box, M(0, 1.688, 0.103, 0.13, 0.016, 0.02), new THREE.Color(L.skin).multiplyScalar(0.55), BI.head); // brow shadow + for (const s of [-1, 1]) B.add(sphere, M(s * 0.035, 1.672, 0.1, 0.014, 0.008, 0.006), 0x1d1712, BI.head); // eyes + // headgear + if (L.helmet === 'us') { + B.add(new THREE.SphereGeometry(1, 16, 10, 0, PI * 2, 0, PI * 0.52), M(0, 1.675, 0.0, 0.142, 0.135, 0.152), L.helm, BI.head, null, (p, c) => c.clone().multiplyScalar(0.9 + 0.15 * IV.noise(p.x * 60, p.z * 60 + p.y * 40))); + B.add(cyl, M(0, 1.668, 0.0, 0.148, 0.012, 0.158), L.helm, BI.head); + B.add(box, M(0, 1.6, 0.06, 0.2, 0.012, 0.012, 0.4), 0x6a5c40, BI.head); // chin strap + } else if (L.helmet === 'de') { + B.add(new THREE.SphereGeometry(1, 16, 10, 0, PI * 2, 0, PI * 0.5), M(0, 1.68, -0.005, 0.135, 0.13, 0.145), L.helm, BI.head); + // the flared skirt: a short open cone around the back and sides + B.add(new THREE.CylinderGeometry(0.138, 0.168, 0.07, 18, 1, true), M(0, 1.645, -0.015, 1, 1, 1.04), L.helm, BI.head); + B.add(new THREE.CylinderGeometry(0.168, 0.172, 0.012, 18, 1), M(0, 1.61, -0.015, 1, 1, 1.04), L.helm, BI.head); + // plain invented unit marking: a small white chevron on the left side + B.add(box, M(0.137, 1.705, 0.0, 0.006, 0.012, 0.045, 0, 0, 0.0).multiply(new THREE.Matrix4().makeRotationX(0.6)), 0xd8d4c8, BI.head); + B.add(box, M(0.137, 1.705, 0.03, 0.006, 0.012, 0.045, 0, 0, 0.0).multiply(new THREE.Matrix4().makeRotationX(-0.6)), 0xd8d4c8, BI.head); + } else { // peaked field cap + B.add(cyl, M(0, 1.735, 0.0, 0.112, 0.07, 0.12), L.helm, BI.head); + B.add(cyl, M(0, 1.775, 0.01, 0.13, 0.03, 0.14), L.helm, BI.head); + B.add(box, M(0, 1.71, 0.12, 0.17, 0.012, 0.08, -0.2), 0x151515, BI.head); + } + // arms + for (const s of ['L', 'R']) { + const sg = s === 'L' ? 1 : -1; + const ua = bp('upperArm' + s), fa = bp('foreArm' + s), ha = bp('hand' + s); + let sm = segMatrix(fa, ua); B.add(capsule(0.048, 0.06, sm.len, 12, 3), sm.m, L.coat, BI['upperArm' + s], { y0: ua.y - 0.02, r: 0.06, b: BI.chest }, cloth); + sm = segMatrix(ha, fa); B.add(capsule(0.037, 0.047, sm.len, 12, 3), sm.m, L.coat, BI['foreArm' + s], { y0: fa.y, r: 0.05, b: BI['upperArm' + s] }, cloth); + B.add(cyl, M(ha.x, ha.y + 0.03, ha.z, 0.044, 0.04, 0.044), L.coat2, BI['foreArm' + s]); // cuff + // hand: palm + thumb, slightly cupped + B.add(sphere, M(ha.x, ha.y - 0.055, ha.z + 0.005, 0.034, 0.06, 0.02), L.skin, BI['hand' + s]); + B.add(sphere, M(ha.x - sg * 0.0, ha.y - 0.04, ha.z + 0.025, 0.012, 0.035, 0.012, 0.6), L.skin, BI['hand' + s]); + // legs + const th = bp('thigh' + s), sh = bp('shin' + s), ft = bp('foot' + s); + sm = segMatrix(sh, th); B.add(capsule(0.06, 0.088, sm.len, 12, 3), sm.m, L.trou, BI['thigh' + s], { y0: th.y - 0.03, r: 0.07, b: BI.hips }, cloth); + sm = segMatrix(ft, sh); B.add(capsule(0.044, 0.058, sm.len, 12, 3), sm.m, L.legg || L.boot, BI['shin' + s], { y0: sh.y, r: 0.06, b: BI['thigh' + s] }, L.legg ? null : (p, c) => p.y < 0.36 ? c : new THREE.Color(L.trou)); + // boot + B.add(capsule(0.045, 0.045, 0.2, 10, 3), M(ft.x, 0.045, ft.z - 0.05, 1.1, 1, 0.75).multiply(new THREE.Matrix4().makeRotationX(PI / 2)), L.boot, BI['foot' + s]); + B.add(box, M(ft.x, 0.012, ft.z + 0.05, 0.1, 0.024, 0.27), 0x161412, BI['foot' + s]); + } + // webbing, belt, pouches, packs + B.add(cyl, M(0, 1.02, 0, 0.172, 0.05, 0.125), L.web, BI.spine); + B.add(box, M(0, 1.02, 0.128, 0.05, 0.045, 0.012), 0x6a6a5a, BI.spine); // buckle + for (const s of [-1, 1]) { + B.add(box, M(s * 0.09, 1.02, 0.12, 0.07, 0.085, 0.05), L.web, BI.spine); // ammo pouches + B.add(box, M(s * 0.09, 1.25, 0.12, 0.028, 0.32, 0.012, 0, 0, s * 0.18), L.web, BI.chest); // suspenders + B.add(box, M(s * 0.09, 1.25, -0.125, 0.028, 0.32, 0.012, 0, 0, -s * 0.18), L.web, BI.chest); + } + if (L.pack) { B.add(box, M(0, 1.26, -0.15, 0.26, 0.28, 0.1), L.web, BI.chest); B.add(capsule(0.04, 0.04, 0.24, 8, 2), M(-0.12, 1.12, -0.12, 1, 1, 1, 0, 0, PI / 2), 0x52502f, BI.chest); } + if (L.canister) { B.add(cyl, M(0.11, 0.95, -0.14, 0.055, 0.26, 0.055, 0, 0, 0.12), 0x4a5048, BI.hips); B.add(box, M(-0.13, 0.95, -0.1, 0.1, 0.13, 0.06), 0x2b2a24, BI.hips); } + if (L.belt) B.add(box, M(0, 1.25, 0.13, 0.05, 0.42, 0.03, 0, 0, 0.7), 0x8a7a4a, BI.chest, null, (p, c) => (Math.floor(p.y * 60) % 2) ? c : new THREE.Color(0x5a4a2a)); + if (L.long) { B.add(box, M(0, 1.3, 0.13, 0.012, 0.36, 0.012), 0x8a8a7a, BI.chest); for (let k = 0; k < 4; k++) B.add(sphere, M(0, 1.42 - k * 0.1, 0.135, 0.008, 0.008, 0.006), 0xb0aa90, BI.chest); } + + const g = new THREE.BufferGeometry(); + g.setAttribute('position', new THREE.Float32BufferAttribute(B.p, 3)); + g.setAttribute('normal', new THREE.Float32BufferAttribute(B.n, 3)); + g.setAttribute('color', new THREE.Float32BufferAttribute(B.c, 3)); + g.setAttribute('uv', new THREE.Float32BufferAttribute(B.uv, 2)); + g.setAttribute('skinIndex', new THREE.Uint16BufferAttribute(B.si, 4)); + g.setAttribute('skinWeight', new THREE.Float32BufferAttribute(B.sw, 4)); + g.computeBoundingSphere(); + return g; + } + + // shared materials and body geometry per kind (characters of a kind share one geometry) + let clothTex = null; + function clothTexture() { + if (clothTex) return clothTex; + const c = document.createElement('canvas'); c.width = c.height = 128; const g = c.getContext('2d'); + g.fillStyle = '#808080'; g.fillRect(0, 0, 128, 128); + const R = IV.rng(9); + for (let i = 0; i < 128; i += 2) { g.fillStyle = `rgba(0,0,0,${0.05 + R() * 0.05})`; g.fillRect(0, i, 128, 1); g.fillStyle = `rgba(255,255,255,${0.03 + R() * 0.04})`; g.fillRect(i, 0, 1, 128); } + for (let i = 0; i < 400; i++) { g.fillStyle = `rgba(${R() < 0.5 ? '0,0,0' : '255,255,255'},.06)`; g.fillRect(R() * 128, R() * 128, 2, 2); } + clothTex = new THREE.CanvasTexture(c); clothTex.wrapS = clothTex.wrapT = THREE.RepeatWrapping; clothTex.encoding = THREE.LinearEncoding; + return clothTex; + } + const geoCache = {}, matCache = {}; + function bodyMat() { + if (matCache.body) return matCache.body; + const m = new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.88, metalness: 0, skinning: true, bumpMap: clothTexture(), bumpScale: 0.0025 }); + m.onBeforeCompile = sh => { // the cloth texture as a subtle detail multiply (keeps vertex colours as the hue) + sh.uniforms.tCloth = { value: clothTexture() }; + sh.fragmentShader = 'uniform sampler2D tCloth;\n' + sh.fragmentShader.replace('#include ', '#include \n diffuseColor.rgb *= 0.78 + texture2D(tCloth, vUv * 2.0).r * 0.44;'); + }; + m.defines = { USE_UV: '' }; + return (matCache.body = m); + } + + // ---------------------------------------------------------------- clips + // A pose is a Float32Array of NB*3 euler angles, plus [hy, hz, hp] (hips height offset, forward offset, whole-body pitch). + const PL = NB * 3 + 3, HY = NB * 3, HZ = NB * 3 + 1, HP = NB * 3 + 2; + function zero(p) { p.fill(0); return p; } + const set = (p, n, x, y, z) => { const i = BI[n] * 3; p[i] = x || 0; p[i + 1] = y || 0; p[i + 2] = z || 0; }; + const add = (p, n, x, y, z) => { const i = BI[n] * 3; p[i] += x || 0; p[i + 1] += y || 0; p[i + 2] += z || 0; }; + const sin = Math.sin, cos = Math.cos, max = Math.max; + function relaxedArms(p, t) { set(p, 'upperArmL', 0.05, 0, 0.1); set(p, 'upperArmR', 0.05, 0, -0.1); set(p, 'foreArmL', -0.25); set(p, 'foreArmR', -0.25); } + // gait: amp = thigh swing, knee = knee lift, bob, lean, arm swing; ph in radians + function gait(p, ph, amp, knee, bob, lean, arm) { + set(p, 'thighL', -amp * sin(ph)); set(p, 'thighR', amp * sin(ph)); + set(p, 'shinL', knee * max(0, sin(ph - 1.3)) + 0.12 + knee * 0.3 * max(0, -sin(ph))); set(p, 'shinR', knee * max(0, sin(ph + PI - 1.3)) + 0.12 + knee * 0.3 * max(0, sin(ph))); + set(p, 'footL', -0.25 * sin(ph - 0.6) * amp); set(p, 'footR', 0.25 * sin(ph - 0.6) * amp); + p[HY] = -bob * Math.abs(cos(ph)) - 0.01; + set(p, 'spine', lean * 0.5, 0.06 * sin(ph) * amp, 0); set(p, 'chest', lean * 0.5, -0.1 * sin(ph) * amp, 0); + set(p, 'hips', 0, -0.08 * sin(ph) * amp, 0.03 * cos(ph) * amp); + set(p, 'upperArmL', arm * sin(ph), 0, 0.1); set(p, 'upperArmR', -arm * sin(ph), 0, -0.1); + set(p, 'foreArmL', -0.35 - arm * 0.5 * max(0, -sin(ph))); set(p, 'foreArmR', -0.35 - arm * 0.5 * max(0, sin(ph))); + set(p, 'head', -lean * 0.6); + } + function kneel(p) { + p[HY] = -0.42; set(p, 'hips', 0, 0.1, 0); + set(p, 'thighR', -0.15, 0, -0.05); set(p, 'shinR', 1.62); set(p, 'footR', 0.9); + set(p, 'thighL', -1.38, 0, 0.06); set(p, 'shinL', 1.36); set(p, 'footL', 0.0); + set(p, 'spine', 0.12); set(p, 'chest', 0.08); set(p, 'head', -0.2); + } + function crouchBase(p, ph, amp) { + p[HY] = -0.3 - 0.015 * Math.abs(cos(ph)); + set(p, 'thighL', -1.0 - amp * sin(ph)); set(p, 'thighR', -1.0 + amp * sin(ph)); + set(p, 'shinL', 1.55 + amp * 0.8 * max(0, sin(ph - 1.2))); set(p, 'shinR', 1.55 + amp * 0.8 * max(0, sin(ph + PI - 1.2))); + set(p, 'footL', -0.55); set(p, 'footR', -0.55); + set(p, 'spine', 0.3); set(p, 'chest', 0.12); set(p, 'head', -0.38); + } + function proneBase(p, ph, amp) { + p[HY] = -0.8; p[HP] = PI / 2 - 0.04; p[HZ] = -0.05; + set(p, 'thighL', 0.0, 0, 0.12 + amp * max(0, sin(ph)) * 0.5); set(p, 'thighR', 0.0, 0, -0.12 - amp * max(0, -sin(ph)) * 0.5); + set(p, 'shinL', 0.1 + amp * 1.4 * max(0, sin(ph))); set(p, 'shinR', 0.1 + amp * 1.4 * max(0, -sin(ph))); + set(p, 'footL', 1.2); set(p, 'footR', 1.2); + set(p, 'spine', -0.08); set(p, 'chest', -0.12); set(p, 'neck', -0.45); set(p, 'head', -0.6); + set(p, 'upperArmL', -2.3 - amp * 0.4 * sin(ph), 0, 0.5); set(p, 'upperArmR', -2.3 + amp * 0.4 * sin(ph), 0, -0.5); + set(p, 'foreArmL', -1.2); set(p, 'foreArmR', -1.2); + p[HY] += 0.02 * amp * Math.abs(sin(ph)); + } + const ease = t => t < 0 ? 0 : t > 1 ? 1 : t * t * (3 - 2 * t); + const mix = (a, b, k) => a + (b - a) * k, cl01 = v => v < 0 ? 0 : v > 1 ? 1 : v; + // Driven locomotion: one shared phase per character (left foot down at 0, right at 0.5), advanced by ground speed + // over stride length, so the feet keep pace with the ground. Direction comes from the local velocity: the swing is + // split between forward/back (x) and sideways (z) so strafing and backpedalling step the right way. + function locoStand(p, a) { + const d = a.dp, s = d.speed, ph = (a.phase + 0.25) * PI * 2; + const k0 = cl01(s / 1.5), k1 = cl01((s - 1.5) / 2.3), k2 = cl01((s - 3.8) / 2.6); + let amp = mix(mix(0.42, 0.68, k1), 0.88, k2) * mix(0.35, 1, k0), knee = mix(mix(0.75, 1.3, k1), 1.7, k2) * mix(0.4, 1, k0); + const bob = mix(mix(0.022, 0.045, k1), 0.06, k2) * k0, lean = mix(mix(0.04, 0.14, k1), 0.28, k2), arm = d.aiming ? 0 : mix(mix(0.3, 0.52, k1), 0.75, k2) * k0; + let cf = 1, sf = 0; + if (s > 0.15) { const th = Math.atan2(-d.vx, d.vz); cf = Math.cos(th); sf = Math.sin(th); } // vx arrives +left; th is +right + else if (Math.abs(d.yawRate) > 0.5) { amp = 0.2; knee = 0.45; cf = 0.25; sf = -Math.sign(d.yawRate); } // stepping round on the spot + const sw = sin(ph); + set(p, 'thighL', -amp * sw * cf, 0, -amp * sw * sf * 0.6); set(p, 'thighR', amp * sw * cf, 0, amp * sw * sf * 0.6); + set(p, 'shinL', knee * max(0, sin(ph - 1.3)) + 0.12 + knee * 0.3 * max(0, -sw)); set(p, 'shinR', knee * max(0, sin(ph + PI - 1.3)) + 0.12 + knee * 0.3 * max(0, sw)); + set(p, 'footL', -0.25 * sin(ph - 0.6) * amp * cf); set(p, 'footR', 0.25 * sin(ph - 0.6) * amp * cf); + p[HY] = -bob * Math.abs(cos(ph)) - 0.01; + const twist = IV.clamp(sf * (cf >= 0 ? 1 : -1) * 0.35, -0.35, 0.35); // hips turn into a strafe, the chest stays on the aim + set(p, 'hips', 0, twist - 0.08 * sw * amp * cf, 0.03 * cos(ph) * amp); + set(p, 'spine', lean * 0.5 * cf, -twist * 0.5 + 0.06 * sw * amp, 0); set(p, 'chest', lean * 0.5 * cf, -twist * 0.5 - 0.1 * sw * amp, 0); + set(p, 'upperArmL', arm * sw, 0, 0.1); set(p, 'upperArmR', -arm * sw, 0, -0.1); + set(p, 'foreArmL', -0.35 - arm * 0.5 * max(0, -sw)); set(p, 'foreArmR', -0.35 - arm * 0.5 * max(0, sw)); + set(p, 'head', -lean * 0.6 * cf); + } + function locoCrouch(p, a) { + const d = a.dp, s = d.speed, ph = (a.phase + 0.25) * PI * 2, k0 = cl01(s / 1.3); + let cf = 1, sf = 0; if (s > 0.1) { const th = Math.atan2(-d.vx, d.vz); cf = Math.cos(th); sf = Math.sin(th); } + const amp = mix(0.15, 0.45, k0) * (s > 1.6 ? 1.15 : 1), sw = sin(ph); + p[HY] = -0.3 - 0.015 * Math.abs(cos(ph)); + set(p, 'thighL', -1.0 - amp * sw * cf, 0, -amp * sw * sf * 0.5); set(p, 'thighR', -1.0 + amp * sw * cf, 0, amp * sw * sf * 0.5); + set(p, 'shinL', 1.55 + amp * 0.8 * max(0, sin(ph - 1.2))); set(p, 'shinR', 1.55 + amp * 0.8 * max(0, sin(ph + PI - 1.2))); + set(p, 'footL', -0.55); set(p, 'footR', -0.55); + set(p, 'hips', 0, IV.clamp(sf * 0.3, -0.3, 0.3), 0); + set(p, 'spine', 0.3); set(p, 'chest', 0.12); set(p, 'head', -0.38); relaxedArms(p); + } + function stride(a) { const s = a.dp.speed, st = a.dp.stance; if (st === 'prone') return 0.84; if (st === 'crouch') return 0.95 + 0.3 * s; return s < 1.5 ? mix(1.2, 1.68, s / 1.5) : s < 3.8 ? mix(1.68, 2.74, (s - 1.5) / 2.3) : mix(2.74, 3.97, Math.min(1, (s - 3.8) / 2.6)); } + function death(p, t, front) { + const a = ease(t / 0.4), b = ease((t - 0.25) / 0.6); + // knees buckle, then the body goes over + p[HY] = -0.25 * a - 0.62 * b; p[HP] = (front ? 1 : -1) * (PI / 2 - 0.1) * b; p[HZ] = (front ? 0.25 : -0.3) * b; + set(p, 'thighL', -0.9 * a * (1 - b) + (front ? 0.05 : -0.2) * b, 0, 0.15 * b); set(p, 'thighR', -0.6 * a * (1 - b) + (front ? -0.1 : -0.35) * b, 0, -0.2 * b); + set(p, 'shinL', 1.2 * a * (1 - b) + 0.3 * b); set(p, 'shinR', 1.0 * a * (1 - b) + 0.6 * b); + set(p, 'spine', (front ? 0.3 : -0.25) * a, 0.2 * b); set(p, 'chest', (front ? 0.2 : -0.2) * a, 0.15 * b); set(p, 'head', (front ? -0.4 : 0.5) * b, 0.6 * b); + set(p, 'upperArmL', (front ? -1.4 : -0.6) * b, 0, 0.5 + 0.6 * b); set(p, 'upperArmR', (front ? -0.3 : 0.4) * b, 0, -0.4 - 0.9 * b); + set(p, 'foreArmL', -0.6 * b); set(p, 'foreArmR', -0.3 * b); + } + const CLIPS = { + idle: { len: 4, f: (p, t) => { relaxedArms(p); const b = sin(t * PI * 2); set(p, 'chest', 0.015 * b); set(p, 'head', -0.02 * b, 0.05 * sin(t * PI)); set(p, 'thighL', 0.02, 0, 0.03); set(p, 'thighR', -0.04, 0, -0.04); set(p, 'shinL', 0.05); set(p, 'shinR', 0.08); } }, + loco: { len: 1, f: (p, t, a) => locoStand(p, a) }, + crouchLoco: { len: 1, f: (p, t, a) => locoCrouch(p, a) }, + proneLoco: { len: 1, f: (p, t, a) => proneBase(p, (a.phase + 0.25) * PI * 2, 1) }, + walk: { len: 1.12, f: (p, t) => gait(p, t * PI * 2, 0.42, 0.75, 0.025, 0.04, 0.32) }, + run: { len: 0.72, f: (p, t) => gait(p, t * PI * 2, 0.7, 1.35, 0.05, 0.16, 0.55) }, + sprint: { len: 0.62, f: (p, t) => gait(p, t * PI * 2, 0.88, 1.7, 0.06, 0.3, 0.75) }, + crouchIdle: { len: 4, f: (p, t) => { kneel(p); relaxedArms(p); set(p, 'chest', 0.08 + 0.015 * sin(t * PI * 2)); } }, + crouchWalk: { len: 1.0, f: (p, t) => { crouchBase(p, t * PI * 2, 0.45); relaxedArms(p); } }, + proneIdle: { len: 4, f: (p, t) => proneBase(p, 0, 0) }, + proneCrawl: { len: 1.4, f: (p, t) => proneBase(p, t * PI * 2, 1) }, + aimIdle: { len: 4, f: (p, t) => { CLIPS.idle.f(p, t); set(p, 'thighL', -0.08, 0, 0.08); set(p, 'thighR', 0.1, 0, -0.06); set(p, 'shinL', 0.12); set(p, 'shinR', 0.1); set(p, 'hips', 0, 0.25); } }, + aimWalk: { len: 1.0, f: (p, t) => { gait(p, t * PI * 2, 0.32, 0.6, 0.02, 0.05, 0); set(p, 'hips', 0, 0.2); } }, + crouchAim: { len: 4, f: (p, t) => { kneel(p); } }, + proneAim: { len: 4, f: (p, t) => { proneBase(p, 0, 0); } }, + reload: { len: 2.4, upper: true, f: (p, t) => {} }, + boltCycle: { len: 1, upper: true, f: (p, t) => {} }, + throw: { len: 0.7, once: true, upper: true, f: (p, t) => { const a = ease(t / 0.45), b = ease((t - 0.45) / 0.3); set(p, 'upperArmR', -2.6 * a + 1.6 * b, 0, -0.4); set(p, 'foreArmR', -1.6 * a + 1.2 * b); set(p, 'chest', -0.2 * a + 0.35 * b, 0.5 * a - 0.7 * b); set(p, 'upperArmL', -1.0 * a + 0.6 * b, 0, 0.3); set(p, 'foreArmL', -0.8); } }, + melee: { len: 0.5, once: true, upper: true, f: (p, t) => { const a = sin(Math.min(1, t / 0.5) * PI); set(p, 'upperArmR', -1.2 - 0.6 * a, 0, -0.3); set(p, 'foreArmR', -1.4 + 1.0 * a); set(p, 'chest', 0.2 * a, 0.3 * a); } }, + takedown: { len: 1.3, once: true, f: (p, t) => { kneel(p); p[HY] = -0.2; set(p, 'upperArmL', -1.6, 0, 0.5); set(p, 'foreArmL', -1.6); set(p, 'upperArmR', -1.2 - 0.4 * sin(Math.min(1, t) * PI), 0, -0.2); set(p, 'foreArmR', -1.2); set(p, 'chest', 0.3); set(p, 'thighL', -0.8); set(p, 'shinL', 0.9); } }, + takedownVictim: { len: 1.3, once: true, f: (p, t) => { const k = ease((t - 0.5) / 0.8); if (t < 0.5) { relaxedArms(p); set(p, 'head', -0.5); set(p, 'chest', -0.25); set(p, 'upperArmL', -0.8, 0, 0.3); set(p, 'upperArmR', -0.8, 0, -0.3); set(p, 'foreArmL', -1.6); set(p, 'foreArmR', -1.6); } else death(p, k * 1.0, true); } }, + vault: { len: 0.62, once: true, f: (p, t) => { const a = sin(Math.min(1, t / 0.62) * PI); set(p, 'thighL', -1.4 * a, 0, 0.3 * a); set(p, 'thighR', -0.9 * a); set(p, 'shinL', 1.4 * a); set(p, 'shinR', 1.6 * a); set(p, 'spine', 0.35 * a); set(p, 'upperArmL', -0.9 * a, 0, 0.4); set(p, 'foreArmL', -0.2); set(p, 'upperArmR', -0.4, 0, -0.2); p[HY] = -0.1 * a; } }, + hit: { len: 0.45, once: true, upper: true, f: (p, t) => { const a = sin(Math.min(1, t / 0.45) * PI); set(p, 'chest', -0.3 * a, 0.25 * a); set(p, 'head', -0.25 * a, -0.2 * a); set(p, 'upperArmL', -0.9 * a, 0, 0.1); set(p, 'foreArmL', -1.9 * a); } }, + deathFront: { len: 1.1, once: true, f: (p, t) => death(p, t, true) }, + deathBack: { len: 1.1, once: true, f: (p, t) => death(p, t, false) }, + alert: { len: 3.2, f: (p, t) => { relaxedArms(p); set(p, 'head', 0, 0.55 * sin(t * PI * 2), 0); set(p, 'chest', 0, 0.25 * sin(t * PI * 2 - 0.4), 0); set(p, 'thighL', -0.05, 0, 0.05); set(p, 'shinL', 0.1); } }, + salute: { len: 2, f: (p, t) => { relaxedArms(p); set(p, 'upperArmR', -1.3, 0.3, -1.25); set(p, 'foreArmR', -2.3, 0, 0); } }, + sitIdle: { len: 4, f: (p, t) => { relaxedArms(p); p[HY] = -0.5; set(p, 'thighL', -1.5); set(p, 'thighR', -1.5); set(p, 'shinL', 1.5); set(p, 'shinR', 1.5); set(p, 'chest', 0.1 + 0.02 * sin(t * 6.28)); set(p, 'upperArmL', -0.5); set(p, 'upperArmR', -0.5); set(p, 'foreArmL', -1.0); set(p, 'foreArmR', -1.0); } } + }; + + // ---------------------------------------------------------------- weapon hold frames (in the aim frame, from the head) + // pos: grip (right hand) relative to the head, in the aim frame (x right? no: +x is the character's LEFT, +z forward) + const HOLD = { + rifle: { aim: { p: [-0.1, -0.13, 0.27], r: [0, 0, 0] }, low: { p: [-0.13, -0.5, 0.2], r: [-0.55, 0.45, 0.25] }, sprint: { p: [-0.05, -0.35, 0.22], r: [-0.2, 1.1, 0.6] }, eye: 0.09 }, + pistol: { aim: { p: [-0.04, -0.14, 0.48], r: [0, 0, 0] }, low: { p: [-0.18, -0.68, 0.16], r: [-1.1, 0.1, 0] }, sprint: { p: [-0.2, -0.7, 0.05], r: [-1.3, 0, 0] }, eye: 0.08, oneHandLow: true }, + mg: { aim: { p: [-0.1, -0.16, 0.25], r: [0, 0, 0] }, low: { p: [-0.12, -0.55, 0.22], r: [-0.25, 0.4, 0.2] }, sprint: { p: [-0.05, -0.4, 0.2], r: [-0.2, 1.0, 0.5] }, eye: 0.09 }, + tool: { aim: { p: [-0.03, -0.06, 0.16], r: [0, 0, 0] }, low: { p: [-0.18, -0.68, 0.12], r: [-1.2, 0, 0] }, sprint: { p: [-0.2, -0.7, 0.05], r: [-1.3, 0, 0] }, eye: 0, oneHandLow: true }, + knife: { aim: { p: [-0.12, -0.35, 0.4], r: [0.3, 0, 0] }, low: { p: [-0.18, -0.68, 0.12], r: [-0.5, 0, 0] }, sprint: { p: [-0.2, -0.7, 0.05], r: [-0.5, 0, 0] }, eye: 0, oneHandLow: true, oneHand: true } + }; + + // ---------------------------------------------------------------- the actor + const _a = new V3(), _b = new V3(), _c = new V3(), _d = new V3(), _q1 = new Q(), _q2 = new Q(), _e = new THREE.Euler(), _m4 = new THREE.Matrix4(); + const DOWN = new V3(0, -1, 0); + function Actor(kind) { + this.kind = kind; + const geo = geoCache[kind] || (geoCache[kind] = buildBody(kind)); + const bones = this.bones = []; + for (let i = 0; i < NB; i++) { + const b = new THREE.Bone(); b.name = BONES[i][0]; + const pi = BONES[i][1]; + if (pi < 0) b.position.set(BONES[i][2], BONES[i][3], BONES[i][4]); + else { b.position.set(BONES[i][2] - BONES[pi][2], BONES[i][3] - BONES[pi][3], BONES[i][4] - BONES[pi][4]); bones[pi].add(b); } + bones.push(b); + } + const mesh = this.mesh = new THREE.SkinnedMesh(geo, bodyMat()); + mesh.add(bones[0]); + mesh.bind(new THREE.Skeleton(bones)); + mesh.castShadow = true; mesh.receiveShadow = true; mesh.frustumCulled = false; + const root = this.root = new THREE.Group(); root.add(mesh); + this.height = 1.78; + this.cur = { name: 'idle', t: 0, speed: 1, once: false }; + this.prev = null; this.fade = 0; this.fadeLen = 0.2; + this.upper = null; this.upperT = 0; this.upperW = 0; + this.aimP = 0; this.aimY = 0; + this.pose = new Float32Array(PL); this.pa = new Float32Array(PL); this.pb = new Float32Array(PL); this.pu = new Float32Array(PL); + this.weapon = null; this.hold = 'rifle'; this.slots = {}; + this.rest = bones.map(b => b.position.clone()); + } + Actor.prototype.play = function (name, o) { + o = o || {}; + if (!CLIPS[name]) name = 'idle'; + const c = this.cur; + if (c.name === name && !o.restart) { c.speed = o.speed != null ? o.speed : c.speed; return; } + this.prev = { name: c.name, t: c.t, speed: c.speed, once: c.once }; + this.fade = 0; this.fadeLen = o.fade != null ? o.fade : 0.2; + this.cur = { name, t: 0, speed: o.speed != null ? o.speed : 1, once: !!(o.once || CLIPS[name].once) }; + }; + // drive(state): the one call per rendered frame (MOVEMENT.md). Picks the stance's driven loop, advances the shared + // foot phase by ground speed / stride, fires onFoot(side, strength) at contacts, leans, and sets the aim offsets. + // One-shot clips started with play() (vault, takedown, hit, death...) run to their end first. + Actor.prototype.drive = function (s) { + const c = this.cur; + if (c.once && (c.t < 1 || /death|Victim/.test(c.name))) { this.setAim(s.aimPitch || 0, s.aimYawOffset || 0); return; } + this.dp = s; + const dt = s.dt || 0, moving = s.speed > (s.stance === 'prone' ? 0.1 : 0.15), turning = !moving && Math.abs(s.yawRate || 0) > 0.5 && s.stance === 'stand'; + let name; + if (s.stance === 'prone') name = moving ? 'proneLoco' : s.aiming ? 'proneAim' : 'proneIdle'; + else if (s.stance === 'crouch') name = moving ? 'crouchLoco' : s.aiming ? 'crouchAim' : 'crouchIdle'; + else name = moving || turning ? 'loco' : s.aiming ? 'aimIdle' : 'idle'; + if (name !== c.name) this.play(name, { fade: name === 'loco' || c.name === 'loco' ? 0.2 : 0.28 }); + // the shared phase + const before = this.phase || 0; + const rate = moving ? s.speed / stride(this) : turning ? Math.abs(s.yawRate) * 0.28 : 0; + this.phase = (before + rate * dt) % 1; + if (moving || turning) { + const crossed = (a, b, m) => (a < m && b >= m) || (a > b && (m === 0 ? true : a < m || b >= m)); + if (crossed(before, this.phase, 0)) this.onFoot && this.onFoot('left', Math.min(1, s.speed / 4 + 0.3)); + if (crossed(before, this.phase, 0.5)) this.onFoot && this.onFoot('right', Math.min(1, s.speed / 4 + 0.3)); + } else if (this.phase > 0.02 && this.phase < 0.98) { + // finish the step so the feet come together instead of freezing mid-stride + this.phase = this.phase < 0.5 ? Math.max(0, this.phase - dt * 1.5) : Math.min(1, this.phase + dt * 1.5) % 1; + } + // lean: roll into turns (up to ~8 deg), pitch into acceleration and braking (up to ~6 deg) + const acc = dt > 0 ? ((s.speed - (this.lastSpeed || 0)) / dt) : 0; this.lastSpeed = s.speed; + const tr = IV.clamp(-(s.yawRate || 0) * s.speed * 0.025, -0.14, 0.14), tp = IV.clamp(acc * 0.012, -0.1, 0.1); + const k = 1 - Math.exp(-dt * 6); this.leanR = (this.leanR || 0) + (tr - (this.leanR || 0)) * k; this.leanP = (this.leanP || 0) + (tp - (this.leanP || 0)) * k; + this.setAim(s.aimPitch || 0, s.aimYawOffset || 0); + }; + Actor.prototype.setUpper = function (name) { if (name !== this.upper) { this.upper = name; this.upperT = 0; } }; + Actor.prototype.setAim = function (p, y) { this.aimP = p; this.aimY = y || 0; }; + Actor.prototype.bone = function (n) { return BI[n] != null ? this.bones[BI[n]] : null; }; + Actor.prototype.setVisible = function (v) { this.root.visible = v; }; + Actor.prototype.attach = function (obj, slot) { + const map = { handR: 'handR', handL: 'handL', back: 'chest', hip: 'hips', head: 'head' }; + const b = this.bones[BI[map[slot] || 'handR']]; + b.add(obj); this.slots[slot] = obj; + if (slot === 'handR') { + this.weapon = obj; const k = obj.userData.kind || ''; + this.hold = /pistol/.test(k) ? 'pistol' : k === 'mg' ? 'mg' : /binoc|grenade/.test(k) ? 'tool' : k === 'knife' ? 'knife' : 'rifle'; + obj.position.set(0, -0.075, 0.02); obj.quaternion.identity(); + } else if (slot === 'back') { obj.position.set(0.05, 0.1, -0.2); obj.rotation.set(0, 0, 0.9); obj.rotateX(PI / 2); } + else if (slot === 'hip') { obj.position.set(-0.19, -0.05, 0.02); obj.rotation.set(PI / 2, 0, 0); } + }; + Actor.prototype.detach = function (obj) { if (obj && obj.parent) obj.parent.remove(obj); for (const k in this.slots) if (this.slots[k] === obj) delete this.slots[k]; if (this.weapon === obj) this.weapon = null; }; + Actor.prototype.dispose = function () { if (this.root.parent) this.root.parent.remove(this.root); }; + Actor.prototype.tris = function () { return this.mesh.geometry.attributes.position.count / 3; }; + + function evalClip(name, t, out, a) { zero(out); const c = CLIPS[name]; c.f(out, t, a); return out; } + Actor.prototype.update = function (dt) { + const c = this.cur, C = CLIPS[c.name]; + c.t += dt * c.speed / C.len; if (c.once) c.t = Math.min(c.t, 1); else c.t %= 1; + evalClip(c.name, c.once ? c.t * C.len : c.t, this.pb, this); + const pose = this.pose; + if (this.prev && this.fade < 1) { + const p = this.prev, PC = CLIPS[p.name]; + p.t += dt * p.speed / PC.len; if (p.once) p.t = Math.min(p.t, 1); else p.t %= 1; + evalClip(p.name, p.once ? p.t * PC.len : p.t, this.pa, this); + this.fade = Math.min(1, this.fade + dt / Math.max(0.01, this.fadeLen)); + const w = ease(this.fade); + for (let i = 0; i < PL; i++) pose[i] = this.pa[i] + (this.pb[i] - this.pa[i]) * w; + } else pose.set(this.pb); + // upper layer clips (throw, melee, hit) override the upper bones + const U = this.upper && CLIPS[this.upper]; + if (U && U.upper && (this.upper === 'throw' || this.upper === 'melee' || this.upper === 'hit')) { + this.upperT = Math.min(1, this.upperT + dt / U.len); + evalClip(this.upper, this.upperT * U.len, this.pu); + const w = Math.min(1, Math.sin(this.upperT * PI) * 3); + for (const bi of UPPER) for (let k = 0; k < 3; k++) pose[bi * 3 + k] += (this.pu[bi * 3 + k] - pose[bi * 3 + k]) * w; + if (this.upperT >= 1) this.upper = null; + } else if (this.upper) this.upperT += dt; + const dead = /death|Victim/.test(c.name); + // aim bend: pitch spread over spine/chest/neck, yaw twist over spine/chest + if (!dead) { + const prone = pose[HP] > 1; + const ap = this.aimP * (prone ? 0.5 : 1), ay = this.aimY; + add(pose, 'spine', -ap * 0.25, ay * 0.3, 0); add(pose, 'chest', -ap * 0.3, ay * 0.35, 0); add(pose, 'neck', -ap * 0.2, ay * 0.15, 0); add(pose, 'head', -ap * 0.25, ay * 0.2, 0); + } + // lean into turns (roll) and into acceleration (pitch), eased + if (!dead && this.dp) { add(pose, 'spine', this.leanP, 0, this.leanR); add(pose, 'chest', this.leanP * 0.5, 0, this.leanR * 0.6); } + // apply + const B = this.bones; + for (let i = 0; i < NB; i++) { B[i].rotation.set(pose[i * 3], pose[i * 3 + 1], pose[i * 3 + 2]); } + B[0].position.set(this.rest[0].x, this.rest[0].y + pose[HY], this.rest[0].z + pose[HZ]); + if (pose[HP]) { _e.set(pose[HP], 0, 0); _q1.setFromEuler(_e); _q2.setFromEuler(B[0].rotation); B[0].quaternion.copy(_q1).multiply(_q2); } + this.root.updateMatrixWorld(true); + if (this.weapon && !dead && !/takedown|vault/.test(c.name)) this.holdWeapon(c.name); + }; + + // Put the weapon where it should be for the current upper mode, then reach both hands to it (two-bone IK). + Actor.prototype.holdWeapon = function (loco) { + const H = HOLD[this.hold] || HOLD.rifle, B = this.bones, head = B[BI.head], w = this.weapon; + const aiming = this.upper === 'aimIdle' || this.upper === 'fire' || this.upper === 'boltCycle' || this.upper === 'binoc'; + const sprint = loco === 'sprint' && !aiming; + const fr = aiming ? H.aim : sprint ? H.sprint : H.low; + // aim frame: root yaw + aim yaw, pitch = aim pitch (low ready keeps a little of it) + const rootQ = this.root.getWorldQuaternion(_q1); + _e.set(-(aiming ? this.aimP : this.aimP * 0.3), this.aimY, 0, 'YXZ'); + const aimQ = _q2.setFromEuler(_e).premultiply(rootQ); + head.getWorldPosition(_a); + const prone = this.pose[HP] > 1; + if (prone && !aiming) { fr.__p = fr.__p || [fr.p[0], fr.p[1] * 0.25, fr.p[2] + 0.2]; } + const pp = prone && !aiming ? fr.__p : fr.p; + _b.set(pp[0], pp[1], pp[2]).applyQuaternion(aimQ).add(_a); // grip world position + _e.set(fr.r[0], fr.r[1], fr.r[2], 'YXZ'); + const wq = new Q().setFromEuler(_e).premultiply(aimQ); // weapon world orientation + // reload / bolt: small weapon tilt and hand motions + let lOff = null, rOff = null; + const ut = this.upperT; + if (this.upper === 'reload') { const k = Math.sin(Math.min(1, ut / 2.2) * PI); wq.multiply(_q1.setFromEuler(_e.set(0.35 * k, 0, 0.5 * k))); lOff = new V3(0.02, -0.12 * k, -0.15 * k); } + if (this.upper === 'boltCycle') { const k = Math.sin(Math.min(1, ut / 0.8) * PI); rOff = new V3(-0.05 * k, 0.06 * k, -0.12 * k); } + // the hand bone is at the wrist; the weapon hangs in the palm (attach offset), so the wrist target is offset + const wristOff = _c.set(0, 0.075, -0.02).applyQuaternion(wq); + const rT = _d.copy(_b).add(wristOff); + if (rOff) rT.add(rOff.applyQuaternion(wq)); + this.ik('R', rT, _a.clone().add(new V3(-0.6, -0.5, -0.4).applyQuaternion(aimQ)), wq); + const g = w.userData.grip && w.userData.grip.l; + if (g && !(H.oneHandLow && !aiming) && !H.oneHand) { + const lt = g.clone().applyQuaternion(wq).add(_b); lt.add(new V3(0, 0.06, -0.02).applyQuaternion(wq)); + if (lOff) lt.add(lOff.applyQuaternion(wq)); + const lq = wq.clone().multiply(_q1.setFromEuler(_e.set(0, 0, 0.4))); + this.ik('L', lt, _a.clone().add(new V3(0.7, -0.6, -0.2).applyQuaternion(aimQ)), lq); + } + }; + // two-bone IK: put the wrist of arm s at target t, elbow toward pole, hand oriented wq (world) + const _s = new V3(), _el = new V3(), _dir = new V3(), _bend = new V3(), _pq = new Q(); + Actor.prototype.ik = function (s, t, pole, wq) { + const B = this.bones, ua = B[BI['upperArm' + s]], fa = B[BI['foreArm' + s]], ha = B[BI['hand' + s]]; + const la = fa.position.length(), lb = ha.position.length(); + ua.getWorldPosition(_s); + _dir.copy(t).sub(_s); let d = _dir.length(); _dir.normalize(); + d = IV.clamp(d, 0.05, la + lb - 0.002); + const ca = IV.clamp((la * la + d * d - lb * lb) / (2 * la * d), -1, 1), sa = Math.sqrt(1 - ca * ca); + _bend.copy(pole).sub(_s); _bend.addScaledVector(_dir, -_bend.dot(_dir)).normalize(); + _el.copy(_s).addScaledVector(_dir, la * ca).addScaledVector(_bend, la * sa); + // upper arm: rest direction is -Y in its parent frame + const restU = _a.copy(fa.position).normalize(); + ua.parent.getWorldQuaternion(_pq); + const wantU = _b.copy(_el).sub(_s).normalize().applyQuaternion(_pq.clone().invert()); + ua.quaternion.setFromUnitVectors(restU, wantU); + ua.updateMatrixWorld(true); + const restF = _a.copy(ha.position).normalize(); + fa.parent.getWorldQuaternion(_pq); + const tw = _c.copy(t).sub(_el); + const wantF = tw.normalize().applyQuaternion(_pq.clone().invert()); + fa.quaternion.setFromUnitVectors(restF, wantF); + fa.updateMatrixWorld(true); + if (wq) { fa.getWorldQuaternion(_pq); ha.quaternion.copy(_pq.invert().multiply(wq)); ha.updateMatrixWorld(true); } + }; + + // ---------------------------------------------------------------- weapons + function wbuild(parts) { // parts: [geo, matrix, color] + const p = [], n = [], c = []; + for (const [g0, m, col] of parts) { + const g = g0.index ? g0.toNonIndexed() : g0, nm = new THREE.Matrix3().getNormalMatrix(m), cc = new THREE.Color(col); + for (let i = 0; i < g.attributes.position.count; i++) { + _a.fromBufferAttribute(g.attributes.position, i).applyMatrix4(m); _b.fromBufferAttribute(g.attributes.normal, i).applyMatrix3(nm).normalize(); + p.push(_a.x, _a.y, _a.z); n.push(_b.x, _b.y, _b.z); _lin.copy(cc).convertSRGBToLinear(); c.push(_lin.r, _lin.g, _lin.b); + } + } + const g = new THREE.BufferGeometry(); + g.setAttribute('position', new THREE.Float32BufferAttribute(p, 3)); g.setAttribute('normal', new THREE.Float32BufferAttribute(n, 3)); g.setAttribute('color', new THREE.Float32BufferAttribute(c, 3)); + g.computeBoundingSphere(); + return g; + } + let wmat = null; + const WOOD = 0x6a4428, WOOD2 = 0x55361f, STEEL = 0x2c2e30, STEEL2 = 0x3c3e40, BLUE = 0x23262b; + const bx = (x, y, z, sx, sy, sz, rx, ry, rz) => M(x, y, z, sx, sy, sz, rx, ry, rz); + const BOXG = new THREE.BoxGeometry(1, 1, 1), CYLG = new THREE.CylinderGeometry(1, 1, 1, 12), CYLX = new THREE.CylinderGeometry(1, 1, 1, 12).rotateX(PI / 2); + const WEAPONS = { + rifleScoped: () => [ + [BOXG, bx(0, -0.02, -0.25, 0.045, 0.1, 0.42, 0.06), WOOD], [BOXG, bx(0, -0.065, -0.4, 0.04, 0.09, 0.2, 0.2), WOOD2], + [BOXG, bx(0, 0.0, 0.2, 0.05, 0.06, 0.62), WOOD], [CYLX, bx(0, 0.035, 0.12, 0.016, 0.016, 0.5), STEEL], + [CYLX, bx(0, 0.04, 0.55, 0.011, 0.011, 0.5), STEEL], [BOXG, bx(0, 0.035, -0.02, 0.04, 0.045, 0.2), STEEL2], + [CYLX, bx(-0.035, 0.04, -0.06, 0.008, 0.008, 0.05, 0, 0.9), STEEL], [new THREE.SphereGeometry(0.014, 8, 6), bx(-0.06, 0.03, -0.04), STEEL], + [CYLX, bx(0, 0.105, 0.03, 0.019, 0.019, 0.3), BLUE], [CYLX, bx(0, 0.105, 0.2, 0.024, 0.024, 0.06), BLUE], [CYLX, bx(0, 0.105, -0.13, 0.022, 0.022, 0.05), BLUE], + [BOXG, bx(0, 0.075, -0.04, 0.02, 0.04, 0.02), STEEL], [BOXG, bx(0, 0.075, 0.11, 0.02, 0.04, 0.02), STEEL], + [BOXG, bx(0, -0.04, 0.03, 0.012, 0.05, 0.04), STEEL] + ], + enemyRifle: () => [ + [BOXG, bx(0, -0.02, -0.25, 0.045, 0.1, 0.42, 0.06), WOOD], [BOXG, bx(0, -0.065, -0.4, 0.04, 0.09, 0.2, 0.2), WOOD2], + [BOXG, bx(0, 0.0, 0.22, 0.05, 0.06, 0.66), WOOD], [CYLX, bx(0, 0.035, 0.14, 0.016, 0.016, 0.5), STEEL], + [CYLX, bx(0, 0.04, 0.58, 0.011, 0.011, 0.5), STEEL], [BOXG, bx(0, 0.035, -0.02, 0.04, 0.045, 0.2), STEEL2], + [CYLX, bx(-0.035, 0.04, -0.06, 0.008, 0.008, 0.05, 0, 0.9), STEEL], [BOXG, bx(0, 0.06, 0.78, 0.01, 0.02, 0.01), STEEL] + ], + smg: () => [ + [BOXG, bx(0, -0.03, -0.25, 0.045, 0.09, 0.3, 0.1), WOOD], [BOXG, bx(0, 0.03, 0.06, 0.055, 0.07, 0.34), STEEL2], + [CYLX, bx(0, 0.04, 0.33, 0.017, 0.017, 0.22), STEEL], [CYLX, bx(0, 0.04, 0.3, 0.024, 0.024, 0.1), STEEL], + [BOXG, bx(0, -0.06, 0.1, 0.035, 0.18, 0.04, 0.05), STEEL], [BOXG, bx(0, -0.04, 0.24, 0.03, 0.09, 0.04, 0.3), WOOD], + [BOXG, bx(0, -0.04, -0.02, 0.03, 0.09, 0.04, 0.3), WOOD2] + ], + enemySmg: () => [ + [BOXG, bx(0, 0.0, -0.22, 0.012, 0.012, 0.3), STEEL], [CYLX, bx(0, 0.035, 0.05, 0.022, 0.022, 0.36), STEEL2], + [CYLX, bx(0, 0.035, 0.32, 0.012, 0.012, 0.2), STEEL], [BOXG, bx(0, -0.09, 0.14, 0.025, 0.2, 0.035), STEEL], + [BOXG, bx(0, -0.035, -0.01, 0.03, 0.08, 0.04, 0.3), 0x1a1a1a] + ], + pistol: () => [[BOXG, bx(0, 0.045, 0.06, 0.028, 0.032, 0.17), BLUE], [BOXG, bx(0, -0.01, 0.0, 0.03, 0.1, 0.045, 0.2), 0x3a2a1e], [CYLX, bx(0, 0.045, 0.17, 0.016, 0.016, 0.08), BLUE]], + mg: () => [ + [BOXG, bx(0, 0.0, -0.22, 0.04, 0.09, 0.3, 0.05), 0x1c1c1c], [BOXG, bx(0, 0.04, 0.12, 0.06, 0.08, 0.42), STEEL2], + [CYLX, bx(0, 0.045, 0.55, 0.026, 0.026, 0.5), STEEL], [CYLX, bx(0, 0.045, 0.85, 0.012, 0.012, 0.12), STEEL], + [BOXG, bx(0.06, 0.02, 0.1, 0.1, 0.1, 0.12), 0x4a4a3a], [BOXG, bx(0, -0.04, -0.03, 0.03, 0.09, 0.04, 0.3), 0x1c1c1c], + [CYLG, bx(0.05, -0.08, 0.6, 0.008, 0.28, 0.008, 0.4, 0, 0.3), STEEL], [CYLG, bx(-0.05, -0.08, 0.6, 0.008, 0.28, 0.008, 0.4, 0, -0.3), STEEL] + ], + knife: () => [[BOXG, bx(0, 0, 0.0, 0.025, 0.03, 0.11), 0x3a2a1e], [BOXG, bx(0, 0.005, 0.13, 0.006, 0.025, 0.16), 0x9aa0a4], [BOXG, bx(0, 0, 0.055, 0.05, 0.035, 0.012), STEEL]], + binoculars: () => [[CYLX, bx(0.035, 0.0, 0.05, 0.028, 0.028, 0.14), 0x22241e], [CYLX, bx(-0.035, 0.0, 0.05, 0.028, 0.028, 0.14), 0x22241e], [BOXG, bx(0, 0.0, 0.05, 0.05, 0.025, 0.05), 0x22241e]], + grenade: () => [[new THREE.SphereGeometry(1, 10, 8), bx(0, 0.0, 0.03, 0.03, 0.04, 0.03), 0x4a5030], [CYLX, bx(0, 0.045, 0.03, 0.01, 0.01, 0.02).multiply(new THREE.Matrix4().makeRotationX(PI / 2)), STEEL], [BOXG, bx(0.012, 0.025, 0.03, 0.006, 0.06, 0.012), STEEL]] + }; + const MUZ = { rifleScoped: [0, 0.04, 0.8], enemyRifle: [0, 0.04, 0.83], smg: [0, 0.04, 0.45], enemySmg: [0, 0.035, 0.42], pistol: [0, 0.045, 0.21], mg: [0, 0.045, 0.92], knife: [0, 0, 0.2], binoculars: [0, 0, 0.13], grenade: [0, 0, 0.05] }; + const LGRIP = { rifleScoped: [0, -0.02, 0.3], enemyRifle: [0, -0.02, 0.3], smg: [0, -0.06, 0.24], enemySmg: [0, -0.04, 0.12], pistol: [0.01, -0.03, 0.0], mg: [0, -0.02, 0.2], binoculars: [0.07, 0, 0.04] }; + const wgeo = {}; + function weapon(kind) { + if (!WEAPONS[kind]) kind = 'enemyRifle'; + if (!wmat) wmat = new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.5, metalness: 0.35 }); + const g = wgeo[kind] || (wgeo[kind] = wbuild(WEAPONS[kind]())); + const m = new THREE.Mesh(g, wmat); m.castShadow = true; + const o = new THREE.Group(); o.add(m); + const mz = new THREE.Object3D(); mz.position.fromArray(MUZ[kind]); o.add(mz); + o.userData = { kind, muzzle: mz, grip: { r: new V3(), l: LGRIP[kind] ? new V3().fromArray(LGRIP[kind]) : null }, eye: kind === 'rifleScoped' ? new V3(0, 0.105, -0.2) : null }; + return o; + } + + window.IVChars = { + standin: true, + info: { source: 'built-in stand-in (code-made skinned mannequins)', version: 1 }, + load(onProgress) { if (onProgress) onProgress(1); return Promise.resolve(); }, + spawn(kind) { return new Actor(kind); }, + weapon, + tris(kind) { const g = geoCache[kind] || (geoCache[kind] = buildBody(kind)); return g.attributes.position.count / 3; }, + clips: Object.keys(CLIPS) + }; +})(); diff --git a/e63334287a3deaa3/ironveil/js/core.js b/e63334287a3deaa3/ironveil/js/core.js new file mode 100644 index 00000000..407c55ad --- /dev/null +++ b/e63334287a3deaa3/ironveil/js/core.js @@ -0,0 +1,230 @@ +/* Ironveil core: the IV namespace, every tuned number (TUNING), small maths helpers, seeded noise, settings and the save. + Plain script, loaded first. 1 unit = 1 metre. North is -Z, east is +X. A yaw of 0 faces north. */ +(function () { + 'use strict'; + const IV = window.IV = { V: 1 }; + // The game's display name, in ONE place (the owner may still change it). The folder, the IVChars API and the + // 'ironveil:*' storage keys keep the working title on purpose. + IV.GAME_NAME = 'Midnight Ops'; + IV.applyName = function () { + const n = IV.GAME_NAME, words = n.toUpperCase().split(' '); + document.title = n; + document.querySelectorAll('[data-gname-logo]').forEach(el => { el.innerHTML = words.join('
'); el.setAttribute('aria-label', n); }); + document.querySelectorAll('[data-gname-line]').forEach(el => { el.textContent = n.toUpperCase(); }); + const g = document.getElementById('gateTx'); if (g) g.textContent = IV.t('{n} contains war violence and blood.', { n }); + const p = document.getElementById('portraitTx'); if (p) p.textContent = IV.t('Turn your phone sideways to play {n}.', { n }); + }; + + // ---------------------------------------------------------------- TUNING + // Every number that sets how the game feels, in one place, with units. Tuned by playing (see README). + IV.TUNING = { + step: 1 / 60, // s, fixed simulation step + move: { // MOVEMENT.md section 2 (a soldier with rifle and kit) + walk: 1.5, run: 3.8, sprint: 6.4, // m/s: walk is also the speed while aiming; run is the default jog + crouch: 1.3, crouchRun: 2.0, // m/s crouched (crouch-walk is quiet; Shift crouched = crouch-run) + prone: 0.6, // m/s crawling + strafeMul: 0.85, backMul: 0.7, // sideways and backward speed vs forward + accel: 12, // 1/s exponential approach: about 0.25 s to jog + sprintAccel: 5, // 1/s from jog up to sprint: about 0.6 s + decel: 14, airAccel: 2, // 1/s: stop in about 0.2 s (14, as the characters' test page; the stop's foot glide depends on the foot phase at release, 5-20 cm, not on this rate) + sprintDecel: 7, // 1/s: stopping or reversing from above a jog takes about 0.4 s (a braking step, not a skid) + plantTime: 0.12, plantSpeed: 2.5, // s the feet plant on a full reversal above this speed (m/s) + turnRate: 9.4, // rad/s body turn toward the movement (540 deg/s) + aimTurnRate: 12.5, // rad/s body toward the aim while aiming (720 deg/s) + sprintTurnRate: 2.1, // rad/s the sprint direction can swing (120 deg/s): no turning on the spot + turnInPlace: 1.05, turnInPlaceRate: 4.4, // rad past which a standing body turns in place, and how fast + gravity: 22, // m/s^2 (snappier than 9.8 for a character) + step: 0.35, snap: 0.5, // m: step-up height; ground snap reach (stays glued going downhill) + slopeCos: 0.766, slideAccel: 9, // cos(40 deg): steeper terrain can't be climbed and slides you back + radius: 0.32, // m, body radius + vaultMin: 0.45, vaultMax: 1.35, // m, heights you can vault over + vaultTime: 0.62, vaultTimeClip: 1.1, // s: stand-in vault; chars.js's vault clip (in place, root moved by us) + stanceTime: 0.28, // s, (see setStance: 0.25 / 0.6 / 0.9 s by how far the change goes) + sprintOut: 0.22, // s after a sprint before the weapon can fire or aim + waterMul: 0.55 // speed in the stream + }, + cam: { + dist: 3.1, height: 0.42, side: 1.0, // m, over-the-shoulder arm (from the shoulder pivot): far enough right that the rifle and both hands show + aimDist: 1.7, aimSide: 0.85, aimFov: 0.7, // aiming: closer arm, FOV multiplier + crouchDrop: 0.55, proneDrop: 1.05, // m the pivot drops by stance + follow: 13, // 1/s positional damping of the pivot (MOVEMENT.md: 10-15) + bob: 0.012, landDip: 0.09, // m: step bob (Settings can turn it off), dip on landing + pullIn: 30, easeOut: 4, // 1/s camera collision: snap in, ease back out + sprintFov: 6, // degrees added while sprinting + pitchMin: -1.25, pitchMax: 1.2, // rad + sens: 0.0023 // rad per mouse pixel at sensitivity 1 + }, + assist: { // aim assist (difficulty Recruit, Regular, Veteran) + snap: [0.85, 0.45, 0], // fraction of the angle to the target removed when aim is pressed + cone: [0.26, 0.17, 0], // rad, half-angle of the cone searched on aim + friction: [0.55, 0.35, 0], // look slowdown over a target while hip-firing (0..1) + frictionCone: 0.06, // rad + touchMul: 1.35, // stronger on touch screens + scopeMaxRange: 60, // m: no assist at all on the scoped rifle past this + snapTime: 0.12 // s, how long the snap takes (eased, not instant) + }, + health: { max: 100, regenDelay: 4.5, regenRate: 22 }, // hp, s, hp/s + ballistics: { + v0: 800, // m/s rifle muzzle velocity + drag: 0.00069, // 1/m, quadratic drag factor (k in dv/dt = -k|v|v): ~650 m/s left at 300 m + g: 9.81, // m/s^2 + zero: 100, // m, the rifle is zeroed here: the centre of the reticle hits at 100 m + sightHeight: 0.045, // m, scope above the bore + smgV0: 280, pistolV0: 250 + }, + weapons: { + rifle: { dmg: 140, rpm: 0, mag: 5, reserve: 30, reload: 2.6, bolt: 1.05, spread: 0.0004, hipSpread: 0.03, recoil: 0.065, noise: 260, zoom: 4 }, + smg: { dmg: 30, fall: [20, 45, 0.6], rpm: 600, mag: 30, reserve: 120, reload: 2.2, spread: 0.008, hipSpread: 0.03, bloom: 0.0025, bloomMax: 0.04, recoil: 0.012, noise: 180 }, + pistol: { dmg: 45, fall: [15, 35, 0.5], rpm: 300, mag: 8, reserve: 32, reload: 1.6, spread: 0.006, hipSpread: 0.018, recoil: 0.03, noise: 42 }, + headMul: 2.6, limbMul: 0.65, + grenade: { fuse: 4.0, radius: 7, dmg: 220, throwV: 16, count: 2 }, + rock: { throwV: 15, noise: 15, count: 99 }, + takedownRange: 2.0, takedownAngle: 1.9 // m, rad (|angle between enemy facing and you| must be > this behind them) + }, + noise: { // m, how far a sound carries in quiet night air + sprint: 16, run: 9.5, walk: 5, crouchRun: 4.5, crouch: 2.4, prone: 1.2, vault: 6, land: 7, + surface: { grass: 0.85, mud: 1.0, gravel: 1.35, wood: 1.25, stone: 1.1, water: 1.5, crops: 1.0 }, + bodyFall: 9, rockHit: 15, takedown: 3.5, maskedMul: 0.3 + }, + ai: { + fovH: 1.15, // rad half-angle of clear vision + fovPeriph: 1.75, // rad half-angle of peripheral vision (slower to notice) + sightRange: 75, // m, at full visibility (lit, standing, moving) + lightNight: 0.33, // ambient light value for a target in open moonlight + lightShadow: 0.17, // in moon shadow (behind a hedge, under trees, indoors) + stance: { stand: 1, crouch: 0.58, prone: 0.3 }, + move: { still: 0.8, walk: 1, run: 1.15, sprint: 1.3 }, + conceal: { stand: 0.85, crouch: 0.35, prone: 0.12 }, // in tall crops or grass + gain: [0.55, 0.85, 1.25], // awareness gained per second at point blank (difficulty) + decay: 0.12, // awareness lost per second when nothing is seen + suspicious: 0.3, investigate: 0.62, spotted: 1.0, + hearGain: 0.45, // awareness from one footstep heard at the edge + reaction: [0.9, 0.6, 0.35], // s before the first shot once spotted + accRamp: 1.1, // s of exposure to reach full accuracy + acc: [0.22, 0.38, 0.55], // hit chance per shot at full ramp, 15 m, standing (difficulty) + dmg: [9, 14, 22], // hp per enemy rifle/smg hit + sniperDmg: [45, 60, 85], + searchTime: 38, // s + runSpeed: 3.9, walkSpeed: 1.45, searchSpeed: 2.2, turnRate: 6.3, // m/s; rad/s body turn (360 deg/s) + grenadeCooldown: 24, // s, shared by all enemies + tokens: [2, 3, 4], // how many soldiers may shoot at you at once (difficulty) + alarmDelay: 2.2, // s ringing before the alarm counts + truckDelay: 28 // s after the alarm (or 60 when the telephone wire is cut) + }, + ally: { followDist: 3.2, catchUp: 38, acc: 0.5, dmgMul: 1 }, + blood: { decals: 40, decalLife: 45 } // capped decal count, seconds before they fade + }; + + // ---------------------------------------------------------------- maths + const clamp = IV.clamp = (v, a, b) => v < a ? a : v > b ? b : v; + IV.lerp = (a, b, t) => a + (b - a) * t; + IV.damp = (a, b, k, dt) => a + (b - a) * (1 - Math.exp(-k * dt)); + IV.wrapA = a => { while (a > Math.PI) a -= Math.PI * 2; while (a < -Math.PI) a += Math.PI * 2; return a; }; + IV.dampA = (a, b, k, dt) => a + IV.wrapA(b - a) * (1 - Math.exp(-k * dt)); + IV.smooth = t => t * t * (3 - 2 * t); + IV.dist2 = (ax, az, bx, bz) => { const dx = ax - bx, dz = az - bz; return Math.sqrt(dx * dx + dz * dz); }; + IV.fwd = yaw => ({ x: -Math.sin(yaw), z: -Math.cos(yaw) }); // facing for a yaw + IV.yawTo = (dx, dz) => Math.atan2(-dx, -dz); // yaw that faces (dx,dz) + IV.fmtTime = s => { s = Math.max(0, Math.round(s)); return Math.floor(s / 60) + ':' + String(s % 60).padStart(2, '0'); }; + + // Seeded random (mulberry32) so levels and tests repeat exactly. + IV.rng = function (seed) { + let a = seed >>> 0; + const f = function () { a |= 0; a = a + 0x6D2B79F5 | 0; let t = Math.imul(a ^ a >>> 15, 1 | a); t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296; }; + f.range = (a, b) => a + f() * (b - a); + f.pick = arr => arr[Math.floor(f() * arr.length)]; + return f; + }; + IV.R = IV.rng(1944); // gameplay randomness (reseeded per mission) + + // Value noise + fbm (deterministic, used for terrain, textures and scatter) + function hash2(x, y) { let h = Math.imul(x | 0, 374761393) + Math.imul(y | 0, 668265263); h = Math.imul(h ^ h >>> 13, 1274126177); return ((h ^ h >>> 16) >>> 0) / 4294967296; } + IV.hash2 = hash2; + IV.noise = function (x, y) { + const xi = Math.floor(x), yi = Math.floor(y), xf = x - xi, yf = y - yi; + const u = xf * xf * (3 - 2 * xf), v = yf * yf * (3 - 2 * yf); + const a = hash2(xi, yi), b = hash2(xi + 1, yi), c = hash2(xi, yi + 1), d = hash2(xi + 1, yi + 1); + return a + (b - a) * u + (c - a) * v + (a - b - c + d) * u * v; + }; + IV.fbm = function (x, y, oct) { + let s = 0, amp = 0.5, f = 1, n = 0; + for (let i = 0; i < (oct || 4); i++) { s += IV.noise(x * f + i * 17.3, y * f - i * 9.1) * amp; n += amp; amp *= 0.5; f *= 2.03; } + return s / n; + }; + // distance from point to segment, and the t along it + IV.segDist = function (px, pz, ax, az, bx, bz) { + const dx = bx - ax, dz = bz - az, l2 = dx * dx + dz * dz || 1; + const t = clamp(((px - ax) * dx + (pz - az) * dz) / l2, 0, 1); + const x = ax + dx * t - px, z = az + dz * t - pz; + return { d: Math.sqrt(x * x + z * z), t }; + }; + IV.polyDist = function (px, pz, pts) { // distance to a polyline [[x,z],...] + let best = 1e9, bt = 0, bi = 0; + for (let i = 0; i < pts.length - 1; i++) { const r = IV.segDist(px, pz, pts[i][0], pts[i][1], pts[i + 1][0], pts[i + 1][1]); if (r.d < best) { best = r.d; bt = r.t; bi = i; } } + return { d: best, i: bi, t: bt }; + }; + IV.inPoly = function (x, z, poly) { + let inside = false; + for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) { + const xi = poly[i][0], zi = poly[i][1], xj = poly[j][0], zj = poly[j][1]; + if (((zi > z) !== (zj > z)) && (x < (xj - xi) * (z - zi) / (zj - zi) + xi)) inside = !inside; + } + return inside; + }; + + // ---------------------------------------------------------------- events + const subs = {}; + IV.on = (n, f) => { (subs[n] = subs[n] || []).push(f); }; + IV.emit = (n, a) => { const l = subs[n]; if (l) for (let i = 0; i < l.length; i++) l[i](a); }; + + // ---------------------------------------------------------------- language + IV.t = (s, v) => window.BackRoomLang ? BackRoomLang.t(s, v) : String(s).replace(/\{(\w+)\}/g, (m, n) => v && v[n] != null ? v[n] : m); + + // ---------------------------------------------------------------- devices + IV.touch = matchMedia('(pointer: coarse)').matches && !matchMedia('(any-pointer: fine)').matches; + IV.reducedMotion = matchMedia('(prefers-reduced-motion: reduce)').matches; + IV.params = new URLSearchParams(location.search); + // the preview gate (index.html, window.IV_PREVIEW): while it is on, only Boot Camp can be played, by any route + IV.PREVIEW = !!window.IV_PREVIEW; + IV.playable = id => !IV.PREVIEW || id === 'bootcamp'; + IV.test = IV.params.has('test'); + + // ---------------------------------------------------------------- save + // localStorage 'ironveil:save' = { v: 1, diff, missions: { id: { done, medal, best, bestMedal } }, settings: {...}, + // cp: { mission, diff, idx, data } (the last checkpoint, so Continue resumes there), tut: boot camp finished once } + const KEY = 'ironveil:save'; + const DEF_SETTINGS = { sens: 1, aimSens: 0.75, invert: false, assist: IV.touch ? 1 : 0, auto: IV.touch, sub: 1, motion: IV.reducedMotion, blood: true, bob: true, + quality: IV.touch ? 0 : 1, view: 'first', fov: 74, bright: 1, vol: 0.8, sfx: 1, mus: 0.55, mute: false }; + function load() { + let s = null; + try { s = JSON.parse(localStorage.getItem(KEY) || 'null'); } catch (e) { s = null; } + if (!s || typeof s !== 'object' || s.v !== 1) s = { v: 1, diff: 0, missions: {}, settings: {}, cp: null, tut: false }; + s.settings = Object.assign({}, DEF_SETTINGS, s.settings || {}); + s.missions = s.missions || {}; + return s; + } + IV.save = load(); + IV.settings = IV.save.settings; + IV.persist = function () { try { localStorage.setItem(KEY, JSON.stringify(IV.save)); } catch (e) {} }; + IV.reloadSave = function () { IV.save = load(); IV.settings = IV.save.settings; }; + IV.DEF_SETTINGS = DEF_SETTINGS; + + // the upper-body clip an actor is playing, for either character set (stand-in: .upper string; chars.js: .curUpper) + IV.upperOf = a => a.curUpper ? a.curUpper.name : (typeof a.upper === 'string' ? a.upper : null); + // upper-body names the game uses that chars.js may not have: fall back to its nearest clip + // A looping clip started with actor.play() (an idle for a cut-scene or a spawn pose) stays at full weight in + // chars.js and mutes the drive() graph for good, so the soldier stops showing stance and movement. Call this just + // before drive() whenever no scripted pose is wanted: it fades any looping base clip out (one-shots are left to end). + IV.releaseLoopPose = function (a) { + if (!a || !a.driven || !a.base || !a.cur || !a.cur.full) return; + if (a.cur.full.loop === THREE.LoopOnce) return; + for (const b of a.base) { b.target = 0; b.rate = 1 / 0.25; } + a.cur = null; + }; + IV.setUpper = function (a, name) { + if (name && window.IVChars && !IVChars.standin && IVChars.clips && IVChars.clips.indexOf(name) < 0) name = name === 'binoc' ? 'aimIdle' : name === 'fire' ? 'aimIdle' : name; + a.setUpper(name); + }; + IV.$ = id => document.getElementById(id); + IV.err = function (msg) { const e = IV.$('err'); if (e) { e.hidden = false; e.textContent = msg; } console.error(msg); }; +})(); diff --git a/e63334287a3deaa3/ironveil/js/fp.js b/e63334287a3deaa3/ironveil/js/fp.js new file mode 100644 index 00000000..f24184e1 --- /dev/null +++ b/e63334287a3deaa3/ironveil/js/fp.js @@ -0,0 +1,601 @@ +/* Midnight Ops: the first-person view (the default; the over-the-shoulder camera stays in Settings as "View"). + + Camera: at the eye of the interpolated player, eye height eased by stance (1.62 / 1.05 / 0.32 m), one step phase + (the characters' own foot phase, so feet, sound and bob agree) driving head bob, a landing dip, a little strafe roll, + lean on Q and E (12 degrees of roll and 0.3 m sideways, stopped short of walls), sprint widening the FOV. + + Viewmodel: arms and the weapon in their own pass with their own camera (55 degree FOV, near 0.01) drawn after the + world with the depth cleared, so they never go into a wall. Until the characters' arms rig arrives it is a second + hero actor posed by the same clips (hold, aim, reload, bolt) with its legs and head collapsed, seen from its own eye. + Procedural layers on its root: idle breathing sway, step bob from the step phase, look sway and lag, recoil kick and + recovery, aim-down-sights that brings the sight line to the screen centre over about 0.2 s, sprint carry, lowering + near walls, landing dip, stance offsets. It is lit from the scene: the same environment map, a hemisphere and sun + copied from the world's, scaled by how lit the player is, and the muzzle and lamp light near him. + + Body: the world hero is drawn without his head and arms (a fragment mask on his own material copy), so looking down + shows legs, feet and torso that match the stance and steps, while his shadow is still the whole man and his gun. + + API: IV.fp.on() (first person in use this frame), IV.fp.frame(cam, dt, dir) from camera.js, IV.fp.draw() from + world.js after the world pass, IV.fp.muzzle(out) the world point the visible muzzle stands in front of. */ +(function () { + 'use strict'; + const W = IV.world, T = IV.TUNING, F = IV.CF; + // viewmodel placement (metres in the arms' frame: x is HIS left, so the gun to the right of the screen is -x) + const TUNE = { camFwd: 0.12, camUp: 0.0, hipX: -0.04, hipY: -0.06, hipZ: -0.02, alwaysShoulder: true }; + const FP = IV.fp = { tune: TUNE, eye: 1.62, lean: 0, leanTarget: 0, roll: 0, bobT: 0, lastPhase: 0, vmAim: 0, vmLower: 0, swayX: 0, swayY: 0, lagYaw: 0, lagPitch: 0, kick: 0, kickR: 0 }; + const P = IV.player; + const EYE = { stand: 1.62, crouch: 1.05, prone: 0.32 }; + FP.on = () => IV.settings.view !== 'third' && !(IV.camera && IV.camera.override); + + // ---------------------------------------------------------------- camera + const right = new THREE.Vector3(), tmp = new THREE.Vector3(), up = new THREE.Vector3(0, 1, 0), hv = new THREE.Vector3(); + FP.frame = function (cam, dt, dir, yaw, pitch) { + const S = IV.settings, W8 = IV.weapons, pr = P.render; + // eye height by stance, eased (a slight overshoot coming up) + const want = P.vault ? 1.4 : EYE[P.stance] || 1.62; + FP.eye = IV.damp(FP.eye, want, P.stance === 'prone' || want < FP.eye ? 7 : 9, dt); + // the body camera: for prone, stance changes, vaults and scripted moments the eye rides on the hero's own head + // (the head bone, a little up and forward to the eyes), so going prone pitches you forward onto your elbows and + // a vault carries you up and over with the body instead of a flat height ease + const A = P.actor, hb = A && A.bone && A.bone('Head'), fb = IV.fwd(P.bodyYaw); + const bodyWant = P.vault || P.stance === 'prone' || P.stanceT > 0 || P.cineClip ? 1 : 0; + FP.bodyK = IV.damp(FP.bodyK || 0, bodyWant, bodyWant ? 9 : 4, dt); + if (hb) { + hb.getWorldPosition(hv); + FP.hx = IV.damp(FP.hx == null ? hv.x - pr.x : FP.hx, hv.x - pr.x + fb.x * 0.1, 14, dt); + FP.hz = IV.damp(FP.hz == null ? hv.z - pr.z : FP.hz, hv.z - pr.z + fb.z * 0.1, 14, dt); + FP.hy = IV.damp(FP.hy == null ? hv.y - pr.y : FP.hy, hv.y - pr.y + 0.09, 14, dt); + } + // step phase: the characters' foot phase if there is one, else distance walked + const moving = P.grounded && P.speed > 0.3; + let ph = A && A.phase != null ? A.phase : (FP.bobT += P.speed * dt / 2.2) % 1; + const motion = S.motion ? 0.35 : 1, bobOn = S.bob === false ? 0 : 1; + const wade = P.inWater ? 1.6 : 1; + const amp = (P.stance === 'crouch' ? 0.01 : P.stance === 'prone' ? 0.006 : P.sprinting ? 0.05 : P.speed > 2.6 ? 0.03 : 0.015) * wade * IV.clamp(P.speed / 1.5, 0, 1) * bobOn * motion * (W8 && (W8.aiming || W8.scoped) ? 0.2 : 1); + FP.bobAmp = IV.damp(FP.bobAmp || 0, moving ? amp : 0, 8, dt); + const by = -Math.abs(Math.sin(ph * Math.PI * 2)) * FP.bobAmp, bx = Math.sin(ph * Math.PI * 2) * FP.bobAmp * 0.5; + FP.phase = ph; + // camera motion layers (pitch and roll added after the look direction): vault arc, stance-change nod, wading + // sway, the harness pendulum, and a spring nod on landing from a fall + const t = IV.time, M = IV.mission; + let mp = 0, mr = 0; + if (P.vault) { const k = Math.min(1, P.vault.t); mp = -0.2 * Math.sin(k * Math.PI); mr = 0.06 * Math.sin(k * Math.PI); } + else if (P.stanceT > 0) mp = P.stance === 'stand' ? 0.05 : -0.09; + if (P.inWater && P.grounded) { mr += Math.sin(t * 1.3) * 0.014 * motion; mp += Math.sin(t * 0.9 + 1) * 0.008 * motion; } + const hanging = P.cine && M && M.phase === 'harness'; + if (hanging) { mr += Math.sin(t * 0.9) * 0.05 * motion; mp += Math.cos(t * 0.7) * 0.025 * motion - 0.04; } + FP.mp = IV.damp(FP.mp || 0, mp * motion, 8, dt); FP.mr = IV.damp(FP.mr || 0, mr * motion, 8, dt); + // falls (the harness drop, a ledge): measured from the interpolated height so it works for scripted moves too + const vyR = FP.lastY == null || dt <= 0 ? 0 : (pr.y - FP.lastY) / dt; FP.lastY = pr.y; + if (vyR < -3) { FP.fallPeak = Math.min(FP.fallPeak || 0, vyR); FP.fallCine = FP.fallCine || !!P.cine; } + else if (FP.fallPeak) { + const k = Math.min(1, -FP.fallPeak / 9); FP.fallPeak = 0; + FP.nodV = (FP.nodV || 0) - 3.6 * k * motion; + if (FP.fallCine) IV.camera.landDip(k); // a scripted drop has no landing of its own in player.js + FP.fallCine = false; + } + FP.nodV = (FP.nodV || 0) + (-(FP.nod || 0) * 90 - (FP.nodV || 0) * 14) * dt; FP.nod = (FP.nod || 0) + FP.nodV * dt; + if (Math.abs(FP.nod) < 1e-4 && Math.abs(FP.nodV) < 1e-3) FP.nod = FP.nodV = 0; + // lean (Q / E): not sprinting or prone; stop short of walls + const I = IV.input; + let lt = (I.held('leanRight') ? 1 : 0) - (I.held('leanLeft') ? 1 : 0); + if (P.sprinting || P.stance === 'prone' || !P.alive) lt = 0; + right.set(Math.cos(yaw), 0, -Math.sin(yaw)); + const ey = pr.y + FP.eye; + if (lt) { const h = W.raycast(pr.x, ey, pr.z, right.x * lt, 0, right.z * lt, 0.55, F.SOLID | F.SIGHT, true); if (h) lt *= Math.max(0, (h.t - 0.2) / 0.35); } + FP.lean = IV.damp(FP.lean, lt, 11, dt); P.lean = FP.lean; + // strafe roll (a degree or so) and the lean roll + const sv = P.vel.x * right.x + P.vel.z * right.z; + FP.roll = IV.damp(FP.roll, -FP.lean * 0.21 - IV.clamp(sv / 6.4, -1, 1) * 0.017 * motion, 10, dt); + // position: eye, bob, landing dip (camera.js bobY spring), lean + const C = IV.camera, f = IV.fwd(yaw), bk = FP.bodyK || 0; + const exo = f.x * 0.08 * (1 - bk) + (FP.hx || 0) * bk, ezo = f.z * 0.08 * (1 - bk) + (FP.hz || 0) * bk, eyo = (ey - pr.y) * (1 - bk) + (FP.hy != null ? FP.hy : ey - pr.y) * bk; + cam.position.set(pr.x + right.x * (FP.lean * 0.3 + bx) + exo, pr.y + eyo + by + (C.bobY || 0) - Math.abs(FP.lean) * 0.04, pr.z + right.z * (FP.lean * 0.3 + bx) + ezo); + tmp.copy(cam.position).add(dir); cam.up.copy(up); cam.lookAt(tmp); + cam.rotateZ(FP.roll + FP.mr); + cam.rotateX(FP.mp + FP.nod); + if (cam.near !== 0.05) { cam.near = 0.05; cam.updateProjectionMatrix(); } + // guard: in first person nothing of the world body may be drawn near the eye unless its first-person mode is in + // force (head, neck and arms gone); if it is not (the first frame, a swap in progress), the body is hidden that frame + if (P.actor) { const ready = A && A.setFirstPerson ? FP._fpKey && FP._fpKey !== 'off' : fpHide.value > 0.5; P.actor.setVisible(!!ready); } + C.mode = 'first'; + bodyFirstPerson(true); + vmFrame(dt, yaw, pitch); + }; + FP.off = function () { bodyFirstPerson(false); if (VM) VM.root.visible = false; }; + + // ---------------------------------------------------------------- the body seen from inside, and its shadow + // The camera must not see the hero's head, hair, eyes or arms (the viewmodel shows the arms), but his shadow must be + // the whole man with his gun. three r128 tests shadow casters against the MAIN camera's layers, so layers can't split + // the two passes. Instead the player's body material gets its own copy whose fragment shader drops every fragment + // skinned mostly to the head, neck or arm bones while `fpHide` is on; the shadow pass uses three's own depth material, + // which knows nothing of that, so the shadow keeps them. Hair, eyes, the held gun and the slung gun get material copies + // that write neither colour nor depth (shadow only). + const HIDE_RE = /^(Head|neck|spine_0[23]|clavicle|upperarm|lowerarm|hand|thumb|index|middle|ring|pinky|eye|jaw|head)/i; // head, arms and the upper chest (its kit would fill the view looking down) + const fpHide = { value: 0 }; + let bodyFP = false, maskDone = null; + function bodyFirstPerson(on) { bodyFP = on; } + function hiddenCopy(m) { const c = m.clone(); c.colorWrite = false; c.depthWrite = false; return c; } + function shadowOnly(obj, on) { + if (!obj || obj.userData._fpSO === on) return; + obj.userData._fpSO = on; + obj.traverse(o => { + if (!o.isMesh) return; const u = o.userData; + if (on) { if (!u._fpMat) { u._mat0 = o.material; u._fpMat = Array.isArray(o.material) ? o.material.map(hiddenCopy) : hiddenCopy(o.material); } o.material = u._fpMat; o.castShadow = true; } + else if (u._mat0) o.material = u._mat0; + }); + } + FP.shadowOnly = shadowOnly; + // a copy of a skinned mesh's material that drops fragments skinned mostly (over 45 %) to bones `hide(bone)` picks, + // while the uniform `on` is 1. The shadow pass never sees it (three's own depth material), so shadows stay whole. + function maskedMaterial(o, hide, on, src) { + src = src || o.material; + if (Array.isArray(src)) return src.map(m => maskedMaterial(o, hide, on, m)); // multi-material meshes: each one masked + const bones = o.skeleton.bones, flags = new Float32Array(Math.max(1, bones.length)); + bones.forEach((b, i) => { flags[i] = hide(b) ? 1 : 0; }); + const m = src.clone(); + m.onBeforeCompile = function (sh) { + sh.uniforms.fpHide = on; sh.uniforms.fpBones = { value: flags }; + sh.vertexShader = sh.vertexShader.replace('#include ', '#include \nuniform float fpBones[' + flags.length + '];\nvarying float vFpHide;') + .replace('#include ', '#include \n vFpHide = fpBones[int(skinIndex.x)] * skinWeight.x + fpBones[int(skinIndex.y)] * skinWeight.y + fpBones[int(skinIndex.z)] * skinWeight.z + fpBones[int(skinIndex.w)] * skinWeight.w;'); + sh.fragmentShader = sh.fragmentShader.replace('#include ', '#include \nuniform float fpHide;\nvarying float vFpHide;') + .replace('void main() {', 'void main() {\n if (fpHide > 0.5 && vFpHide > 0.45) discard;'); + }; + let key = 'fpmask'; for (let i = 0; i < flags.length; i++) key += flags[i] ? '1' : '0'; + m.customProgramCacheKey = () => key; + return m; + } + FP.maskedMaterial = maskedMaterial; + function maskBody(A) { + if (maskDone === A) return; maskDone = A; + A.root.traverse(o => { + if (!o.isSkinnedMesh) return; + if (/Hair|Eyes/i.test(o.name)) { o.userData.fpPart = true; return; } + o.material = maskedMaterial(o, b => HIDE_RE.test(b.name), fpHide); + o.castShadow = true; + }); + } + // called by player.js after the actor's update + FP.afterBodyUpdate = function () { + const A = P.actor; if (!A || !A.bone) return; + // (not tied to WP.scoped: the rifle is raised in first person before the scope view starts, and turning the body + // back to full there put the camera inside his head. The scope view hides the whole actor itself.) + const on = bodyFP && P.alive; + const M = IV.weapons.models || {}; + if (A.setFirstPerson) { + // the characters' own first-person body (no head, neck or arms; eyes, hair and the gun in the hands shadow-only, + // a full-body shadow from an invisible copy). It treats what is attached at the call, so it is re-applied when + // the gun in the hands changes (weapons.js calls FP.beforeAttach first so the old gun gets its materials back). + const key = on ? 'on:' + (A.held ? A.held.uuid : '') : 'off'; + if (key !== FP._fpKey) { + A.setFirstPerson(false); if (on) A.setFirstPerson(true); FP._fpKey = key; + // the chest kit (pack, webbing on spine_02/03) still fills the view looking down: drop it too, camera only + A.root.traverse(o => { + if (!o.isSkinnedMesh || !o.userData.fullGeom || /_fpShadow$/.test(o.name)) return; const u = o.userData; + if (on) { if (o.material !== u._chestMat) { if (!u._chestMat || u._chestBase !== o.material) { u._chestBase = o.material; u._chestMat = maskedMaterial(o, b => /^(spine_0[123]|pelvis)$/.test(b.name), { value: 1 }); } o.material = u._chestMat; } } + else if (u._chestBase && o.material === u._chestMat) o.material = u._chestBase; + }); + } + } else { + maskBody(A); + fpHide.value = on ? 1 : 0; + A.root.traverse(o => { if (o.userData.fpPart) shadowOnly(o, on); }); + } + // the long gun slung on his back would cross the view looking down: shadow only in first person + for (const k in M) { const g = M[k]; if (!g) continue; const held = g === A.held; if (A.setFirstPerson && held) { shadowOnly(g, false); continue; } shadowOnly(g, on && !!g.parent); } // the holstered pistol too: with the hips masked it would float + }; + // weapons.js: before guns are moved between the hands, the sling and the holster + FP.beforeAttach = function () { const A = P.actor; if (A && A.setFirstPerson && FP._fpKey && FP._fpKey !== 'off') { A.setFirstPerson(false); FP._fpKey = null; } }; + // compile the arms' shaders (every gun, the props) and the body's first-person materials before play starts, so the + // first shot, weapon swap or look down does not hitch while the GPU compiles (main.js calls this as a mission starts) + FP.warm = function () { + const vm = vmBuild(); if (!vm || !FP.on()) return; + const r = W.renderer, rig = vm.rig, t0 = performance.now(); + if (!rig.standin) { const vis = []; for (const k of ['rifleScoped', 'smg', 'pistol']) { const v = rig.get(k); if (v) { vis.push([v.group, v.group.visible]); v.group.visible = true; v.group.traverse(o => { if (o.isMesh) { vis.push([o, o.visible]); o.visible = true; } }); } } vm.root.visible = true; try { r.compile(vm.scene, vm.cam); } catch (e) {} vis.forEach(([o, b]) => { o.visible = b; }); } + else { vm.root.visible = true; try { r.compile(vm.scene, vm.cam); } catch (e) {} } + FP.warmMs = Math.round(performance.now() - t0); + }; + // tests: advance the arms (clips, layers) by dt without drawing a frame + FP.vmTick = function (dt) { if (FP.on()) vmFrame(dt, P.yaw, P.pitch); }; + FP.scopeReady = () => (FP.vmAim || 0) >= 0.9; // the arms rig's adsRaise clip keeps the hand out of the eye during the raise + FP.binocReady = () => VM && !VM.rig.standin ? !!FP.atEye : (FP.vmAim || 0) >= 0.9; + // the old bone-scaling hide is gone: undo it if a previous frame left a bone collapsed + FP.HIDE_RE = HIDE_RE; + + // ---------------------------------------------------------------- viewmodel + // One shape for whichever rig draws the arms, so swapping the stand-in for the characters' rig is small: + // { group, drive(state, dt), play(name), clips, sockets, adsOffset, muzzle, ejection, scopeEye, gun } + // group sits in the viewmodel camera's frame (camera at the origin looking down -Z, x right, y up); at rest it shows + // the hip pose, and adsOffset ({p: Vector3, q: Quaternion}) is what moves it onto the sight line. + // The real rig: IVChars.viewmodel(kind). Until it exists: the stand-in below. + // + // Stand-in: a second hero actor driven in the aim pose (both hands on the gun, the left by the characters' IK), + // head, neck and legs collapsed. It is placed by the GUN, not by the head: each weapon has a sight point (rear sight + // or scope eye, metres in the gun's frame) and a hip pose (where that sight point sits in front of the eye, and how + // the gun is turned), and the body hangs off the gun. The gun's place in the body is taken once the pose has settled + // and then kept, so a reload or a bolt cycle moves the gun and the arms together instead of the body round the gun. + const SIGHT = { // per weapon kind: s = sight point in the gun's frame; hip = [x, y, z] of that point; rot = hip turn [pitch, yaw, roll] (rad); ads = eye relief (m) + rifleScoped: { s: [0, 0.075, -0.198], hip: [0.115, -0.125, -0.33], rot: [0.03, 0.06, -0.06], ads: 0.0 }, + smg: { s: [0, 0.062, -0.02], hip: [0.115, -0.118, -0.42], rot: [0.03, 0.07, -0.07], ads: 0.17 }, + pistol: { s: [0, 0.034, -0.045], hip: [0.1, -0.11, -0.42], rot: [0.02, 0.06, -0.05], ads: 0.36 }, + grenade: { s: [0, 0.07, 0], hip: [0.15, -0.16, -0.36], rot: [0.25, 0.25, -0.2], ads: 0.3 }, + binoculars: { s: [0, 0.012, -0.075], hip: [0.02, -0.16, -0.22], rot: [0.3, 0, 0], ads: 0.0 }, + knife: { s: [0, 0, 0], hip: [0.13, -0.17, -0.34], rot: [0.5, 0.3, -0.6], ads: 0.3 } + }; + FP.SIGHT = SIGHT; + const R0 = new THREE.Quaternion().setFromAxisAngle(up, Math.PI); // the gun's +Z (barrel) to the camera's -Z + const _m = new THREE.Matrix4(), _m2 = new THREE.Matrix4(), _q = new THREE.Quaternion(), _e = new THREE.Euler(), _v = new THREE.Vector3(), _s1 = new THREE.Vector3(1, 1, 1); + function standinRig() { + const actor = IVChars.spawn('hero'); if (!actor) return null; + const group = new THREE.Group(); group.add(actor.root); + // only the forearms, hands and fingers are drawn (sleeves above the elbow and the body would fill the screen + // this close to the eye); everything else of the second actor is dropped in the shader + const KEEP = /^(lowerarm|hand|thumb|index|middle|ring|pinky)/i, vmOn = { value: 1 }; + actor.root.traverse(o => { + if (!o.isMesh) return; + o.frustumCulled = false; o.castShadow = false; o.receiveShadow = false; + if (o.isSkinnedMesh) { if (/Hair|Eyes|LOD/i.test(o.name)) o.visible = false; else o.material = maskedMaterial(o, b => !KEEP.test(b.name), vmOn); } + }); + const models = {}, ref = {}; + const ds = { vx: 0, vz: 0, speed: 0, yawRate: 0, stance: 'stand', aiming: true, aimPitch: 0, aimYawOffset: 0, sprinting: false, grounded: true, fallSpeed: 0, slopeY: 1, weapon: '', dt: 0 }; + const HIDEB = ['Head', 'neck_01', 'thigh_l', 'thigh_r']; + const rig = { standin: true, group, actor, clips: IVChars.clips || [], sockets: {}, gun: null, kind: null, muzzle: null, ejection: null, scopeEye: null, + adsOffset: { p: new THREE.Vector3(), q: new THREE.Quaternion() }, hip: { p: new THREE.Vector3(), q: new THREE.Quaternion() }, settle: 0 }; + rig.setKind = function (kind) { + if (rig.kind === kind) return; + if (rig.gun) actor.detach(rig.gun); + rig.gun = models[kind] || (models[kind] = IVChars.weapon(kind)); + if (rig.gun) { actor.attach(rig.gun, 'handR'); rig.gun.traverse(o => { if (o.isMesh) { o.frustumCulled = false; o.castShadow = false; } }); } + rig.kind = kind; rig.settle = 0; + rig.muzzle = rig.gun && rig.gun.userData.muzzle; rig.ejection = rig.gun && rig.gun.getObjectByName(kind + '_ejection'); rig.scopeEye = rig.gun && rig.gun.getObjectByName(kind + '_scopeEye'); + }; + rig.play = function (name) { IV.setUpper(actor, name); }; + // state: { weapon kind, oneShot (upper clip to mirror), dt } + rig.drive = function (st, dt) { + ds.dt = dt; ds.weapon = st.weapon; ds.aiming = st.kind !== 'grenade'; + if (actor.drive) { IV.releaseLoopPose && IV.releaseLoopPose(actor); actor.drive(ds); } + const vu = IV.upperOf(actor); + if (st.oneShot && st.oneShot !== vu) IV.setUpper(actor, st.oneShot); + group.position.set(0, 0, 0); group.quaternion.identity(); group.updateMatrixWorld(true); + // chars.js picks the level of detail and its update rate by the distance to IVChars.camera: measure from the + // viewmodel's own camera (at the origin of this scene), or the arms drop to the far LOD + const c0 = IVChars.camera; IVChars.camera = rig.cam || c0; actor.update(dt); IVChars.camera = c0; + for (const n of HIDEB) { const b = actor.bone(n); if (b) b.scale.setScalar(0.001); } + group.updateMatrixWorld(true); + if (!rig.gun) return; + // the gun in the body's frame: kept from the settled aim pose (one-shots move the gun, not the body) + const busy = !!st.oneShot || (vu && /reload|bolt|throw|fire/i.test(vu)); + rig.settle += dt; + if (!ref[rig.kind] || (!busy && rig.settle < 0.6)) ref[rig.kind] = rig.gun.matrixWorld.clone(); + const T = SIGHT[rig.kind] || SIGHT.smg; + // hip pose and the ADS offset for this kind: gun = T(p) R(q) R0 T(-s) + rig.hip.p.fromArray(T.hip); rig.hip.q.setFromEuler(_e.set(T.rot[0], T.rot[1], T.rot[2])); + rig.adsOffset.p.set(-T.hip[0], -T.hip[1], -T.ads - T.hip[2]); rig.adsOffset.q.copy(rig.hip.q).invert(); + rig._ref = ref[rig.kind]; rig._s = T.s; + }; + // place the group so the gun sits at pose (p, q): group = T(p) R(q) R0 T(-s) * ref^-1 + rig.place = function (p, q) { + _m.makeTranslation(-rig._s[0], -rig._s[1], -rig._s[2]); + _q.copy(q).multiply(R0); _m2.compose(p, _q, _s1).multiply(_m); + _m.copy(rig._ref).invert(); _m2.multiply(_m); + _m2.decompose(group.position, group.quaternion, group.scale); + group.updateMatrixWorld(true); + }; + return rig; + } + // ---------------------------------------------------------------- the characters' arms rig (IVChars.viewmodel) + // One viewmodel per gun ('rifleScoped', 'smg', 'pistol'), made on first use, all in one group at the eye. Their clips + // carry the hip, ADS and sprint poses and every hand action (fire, bolt, reload with the magazine in the left hand, + // draw, grenade, melee, interact, binoculars), so this side adds only small procedural layers and starts the clips. + function realRig() { + if (!IVChars.viewmodel || !IVChars.fpClips || !IVChars.fpClips('smg').length) return null; + const group = new THREE.Group(), vms = {}; + const rig = { standin: false, group, vms, vm: null, kind: null, gun: null, muzzle: null, ejection: null, scopeEye: null, sockets: null, clips: [] }; + rig.get = function (kind) { + if (!(kind in vms)) { const v = IVChars.viewmodel(kind); vms[kind] = v; if (v) { v.group.visible = false; group.add(v.group); v.onEvent = (e, c) => { FP.lastEvent = { e, c, t: IV.time }; if (e === 'atEye') FP.atEye = true; onRigEvent(e, c, v); }; } } + return vms[kind]; + }; + rig.setKind = function (kind) { + if (rig.kind === kind) return false; + const v = rig.get(kind); if (!v) return false; + if (rig.vm) rig.vm.group.visible = false; + rig.vm = v; v.group.visible = true; rig.kind = kind; rig.gun = v.weapon; + rig.muzzle = v.muzzle; rig.ejection = v.ejection; rig.scopeEye = v.scopeEye; rig.sockets = v.sockets; rig.clips = v.clips; + return true; + }; + rig.play = (name, o) => rig.vm ? rig.vm.play(name, o) : 0; + rig.len = (name, kind) => { const v = kind ? rig.get(kind) : rig.vm; return v ? v.clipLength(name) : 0; }; + return rig; + } + const _o = new THREE.Vector3(), SHOULDER = new THREE.Vector3(); + // the arms shadow themselves and the gun (Medium and High): a small shadow map of its own, about 1.2 m across, from + // the moon or sun direction in the viewmodel's frame; the meshes are switched to cast and receive once + function vmShadows(vm, v) { + const want = (IV.settings.quality | 0) >= 1 && W.renderer.shadowMap.enabled; + if (want === !!v._sh) return; v._sh = want; + v.group.traverse(o => { if (o.isMesh) { o.castShadow = want; o.receiveShadow = want; } }); + const L = vm.sun; L.castShadow = want; + if (want) { L.shadow.mapSize.set(1024, 1024); Object.assign(L.shadow.camera, { left: -0.6, right: 0.6, top: 0.6, bottom: -0.6, near: 0.05, far: 3 }); L.shadow.camera.updateProjectionMatrix(); L.shadow.bias = -0.0006; L.shadow.normalBias = 0.004; L.shadow.radius = 2; } + } + // the clips' events run the gun: rounds go in at 'magIn', the reload ends at 'done', cases leave the port at 'shot' + // (SMG, pistol) or 'eject' (rifle bolt), and each handling sound plays when the hands make it + const _ed = new THREE.Vector3(), _ep = new THREE.Vector3(); + function caseFrom(v) { + const e = v.ejection; if (!e || !VM) return; + socketWorld(e, _ep); e.getWorldQuaternion(_q); _ed.set(0, 0, 1).applyQuaternion(_q).applyQuaternion(W.camera.quaternion); // viewmodel camera frame -> world + const sp = 2.2 + Math.random() * 0.8; + IV.fx.casing(_ep.x, _ep.y, _ep.z, _ed.x * sp + (Math.random() - 0.5) * 0.4, _ed.y * sp + 1.4 + Math.random() * 0.6, _ed.z * sp + (Math.random() - 0.5) * 0.4); + } + function onRigEvent(e, c, v) { + const A = IV.audio, WP = IV.weapons, rel = /^reload/.test(c); + if (e === 'magOut') A && A.play('magOut'); + else if (e === 'magIn') { A && A.play('magIn'); if (rel) WP.magIn && WP.magIn(); } + else if (e === 'done' && rel) WP.reloadDone && WP.reloadDone(); + else if (e === 'boltUp' || e === 'boltDown') A && A.play('click', { f: 2600, vol: 0.35 }); + else if (e === 'boltBack' || e === 'boltForward') A && A.play('click', { f: 3300, vol: 0.45 }); + else if (e === 'eject') caseFrom(v); + else if (e === 'shot' && v.kind !== 'rifleScoped') caseFrom(v); + else if (e === 'charge' || e === 'slide') A && A.play('click', { f: 2900, vol: 0.45 }); + else if (e === 'pin') A && A.play('pin'); + } + // a socket of the arms (viewmodel camera frame) as the world point in front of which it is drawn + function socketWorld(o, out) { o.getWorldPosition(out); out.applyMatrix4(VM.cam.matrixWorldInverse); out.z *= 0.9; return out.applyMatrix4(W.camera.matrixWorld); } + FP.realActive = () => !!(VM && !VM.rig.standin && FP.on() && VM.root.visible); + function realFrame(vm, dt, yaw, pitch) { + const W8 = IV.weapons, S = IV.settings, rig = vm.rig, M = IV.mission, I = IV.input, C = IV.camera; + const gunKind = KIND[W8.cur] || 'smg'; + const tdT = W8.takedownT != null ? IV.time - W8.takedownT : 99, inTakedown = P.cineClip && tdT < 3; + const harness = P.cine && M && M.phase === 'harness'; + const show = P.alive && !(W8.scoped && FP.scopeReady()) && !(W8.binoc && FP.atEye) && (!P.cineClip || inTakedown) && (!P.cine || harness); + vm.root.visible = show; + if (!show) { if (!W8.binoc) FP.atEye = false; return; } + if (rig.setKind(gunKind) && FP.vmShown) { const d = rig.play('draw'); if (d) W8.cool = Math.max(W8.cool, d * 0.7); } // a new gun comes up with its draw clip + FP.vmShown = true; + const v = rig.vm; if (!v) return; + // beats -> clips (each started once, on the change) + const beat = W8.busyThrow ? 'grenade' : W8.binoc ? 'binoculars' : inTakedown ? 'melee' : harness && M.interAt && I.held('use') ? 'cut' : (M && M.interAt && I.held('use') && M.interAt.prog > 0) ? 'interact' : null; + if (beat !== FP.beat) { + if (beat === 'grenade') { if (split(v)) { FP.pullT = IV.time; rig.play('grenadePull'); } else rig.play('grenade'); } + else if (beat === 'binoculars') { FP.atEye = false; rig.play('binoculars'); } + else if (beat === 'melee') rig.play('melee'); + else if (beat === 'cut') rig.play('interact', { loop: true }); + else if (beat === 'interact') rig.play('interact'); + if (FP.beat === 'binoculars') { FP.atEye = false; rig.play('binocularsLower'); } + else if (FP.beat === 'cut') v.stop(0.2); + FP.beat = beat; + } + // the rifle's bolt after the shot's own clip + if (FP.boltDue && !v.isPlaying('fire') && !v.isPlaying('fireAds')) { FP.boltDue = false; rig.play('boltCycle'); } + // base blend: ADS and sprint carry are the rig's own poses + const aiming = !!(W8.aiming || W8.scoped); + FP.vmAim = IV.damp(FP.vmAim, aiming ? 1 : 0, aiming ? 14 : 11, dt); + FP.vmSpr = IV.damp(FP.vmSpr || 0, P.sprinting ? 1 : 0, P.sprinting ? 7 : 10, dt); + if (W8.binoc && FP.lastEvent && FP.lastEvent.e === 'atEye') FP.atEye = true; + if (W8.binoc && !FP.atEye && v.current === 'binoculars' && FP.binocT == null) FP.binocT = IV.time; + if (W8.binoc && FP.binocT != null && IV.time - FP.binocT > rig.len('binoculars') + 0.05) FP.atEye = true; // no 'atEye' event: the end of the clip + if (!W8.binoc) FP.binocT = null; + v.drive({ ads: FP.vmAim, sprint: FP.vmSpr }, dt); + holdGrenade(v); + // small procedural layers: breathing, step bob, look lag, recoil, wall lowering, landing dip, lean roll + const motion = S.motion ? 0.4 : 1, t = IV.time, ph = FP.phase || 0, bobA = (FP.bobAmp || 0) * 0.9; + const dyaw = IV.wrapA(yaw - (FP.lastYaw == null ? yaw : FP.lastYaw)), dpit = pitch - (FP.lastPitch == null ? pitch : FP.lastPitch); + FP.lastYaw = yaw; FP.lastPitch = pitch; + const lagK = aiming ? 0.3 : 1; + FP.lagYaw = IV.clamp(IV.damp(FP.lagYaw, dyaw * 4 * lagK, 12, dt), -0.05, 0.05); FP.lagPitch = IV.clamp(IV.damp(FP.lagPitch, dpit * 4 * lagK, 12, dt), -0.04, 0.04); + FP.fatigue = IV.clamp((FP.fatigue || 0) + (P.sprinting ? dt / 4 : -dt / 7), 0, 1); + const breath = (aiming ? 0.1 : 1) * motion * (1 + FP.fatigue * 2.2); + FP.kick = IV.damp(FP.kick, 0, 13, dt); FP.kickR = IV.damp(FP.kickR, 0, 9, dt); + const cam = W.camera, look = C.lookDir, wall = W.raycast(cam.position.x, cam.position.y, cam.position.z, look.x, look.y, look.z, 0.9, F.SOLID | F.SIGHT, true); + FP.vmLower = IV.damp(FP.vmLower, wall && !aiming ? IV.clamp(1 - (wall.t - 0.3) / 0.6, 0, 1) : 0, 8, dt); + const a = IV.smooth(IV.clamp(FP.vmAim, 0, 1)), relax = 1 - a * 0.85; + const ox = (Math.sin(t * 1.1) * 0.0022 * breath + Math.sin(ph * Math.PI * 2) * bobA * 0.45 - FP.lagYaw * 0.35) * relax; + const oy = (-Math.abs(Math.sin(ph * Math.PI * 2)) * bobA * 0.7 + Math.sin(t * 1.7) * 0.0016 * breath + FP.lagPitch * 0.3) * (1 - a * 0.7) - FP.vmLower * 0.09 + (C.bobY || 0) * 0.45; + const oz = FP.kick * (aiming ? 0.02 : 0.03) + FP.vmLower * 0.05; + // the turn layers (recoil climb, look lag, wall lowering, lean roll) pivot about the right shoulder, behind and below + // the eye, so recoil travels back through the wrists and forearms instead of the gun spinning about the eye + // the rifle's sprint clip swings the muzzle up across the view: lower and cant it, about the shoulder + const rs = gunKind === 'rifleScoped' ? FP.vmSpr || 0 : 0; + _e.set(FP.kickR * 0.7 + FP.lagPitch * 0.5 * relax - FP.vmLower * 0.5 - rs * 0.12, FP.lagYaw * 0.7 * relax - rs * 0.06, -FP.roll * 0.5 + Math.sin(ph * Math.PI * 2) * bobA * 0.4 * relax + rs * 0.12); + v.group.quaternion.setFromEuler(_e); + SHOULDER.set(0.17, -0.3, 0.12); + v.group.position.copy(SHOULDER).negate().applyQuaternion(v.group.quaternion).add(SHOULDER).add(_o.set(ox, oy, oz - FP.vmTune.push * (1 - a))); // the push eases out in ADS so the sights stay exact + vmShadows(vm, v); + vm.gun = rig.gun; + vm.cam.position.set(0, 0, 0); vm.cam.quaternion.identity(); vm.cam.updateMatrixWorld(true); + vm.root.updateMatrixWorld(true); + vmLight(vm); + } + // the grenade, with the arms' split clips: grenadePull (pin out, holds its last frame), grenadeCook (a held loop while + // the key stays down, so cooking works; the fuse runs from the pin), grenadeThrow on key-up; weapons.js lets the + // grenade go when grenadeThrow reaches its 'release' event (capped wait). Without the split clips, the single + // 'grenade' clip plays and the throw is immediate. + const split = v => v && v.clipLength('grenadePull') > 0 && v.clipLength('grenadeThrow') > 0; + FP.throwSync = function (bt, force) { + if (force || !VM || VM.rig.standin || !FP.on() || !VM.root.visible) return false; + const v = VM.rig.vm; if (!split(v)) return false; + if (bt.relT == null) { bt.relT = IV.time; v.play('grenadeThrow', { fade: 0.08 }); } + if (FP.lastEvent && FP.lastEvent.e === 'release' && FP.lastEvent.c === 'grenadeThrow' && FP.lastEvent.t >= bt.relT - 1e-3) return false; + return IV.time - bt.relT < 0.6; + }; + function holdGrenade(v) { + const bt = IV.weapons.busyThrow; if (!bt || bt.relT != null || !split(v)) return; + if (v.current === 'grenadePull' && FP.pullT != null && IV.time - FP.pullT >= v.clipLength('grenadePull')) v.play('grenadeCook', { loop: true, fade: 0.12 }); + } + // shots, reloads and bolts from weapons.js start the rig's clips; the game's timings follow the clips' lengths + IV.on('shot', k => { const vm = VM; if (!vm || vm.rig.standin || !FP.on()) return; vm.rig.play('fire'); if (k === 'rifle') FP.boltDue = true; }); + FP.clipLen = function (name, cur) { const vm = vmBuild(); if (!vm || vm.rig.standin) return 0; return vm.rig.len(name, KIND[cur] || cur); }; + FP.onReload = function (empty) { const vm = VM; if (!vm || vm.rig.standin || !FP.on()) return 0; return vm.rig.play(empty && vm.rig.len('reloadEmpty') ? 'reloadEmpty' : 'reload'); }; + FP.cancelAction = function () { const vm = VM; if (vm && !vm.rig.standin && vm.rig.vm) vm.rig.vm.stop(0.15); }; + let VM = null; + function vmBuild() { + if (VM || !window.IVChars || !IVChars.spawn) return VM; + const scene = new THREE.Scene(), cam = new THREE.PerspectiveCamera(55, 1, 0.01, 20); + const rig = realRig() || standinRig(); if (!rig) return null; + scene.add(rig.group); scene.add(cam); + const hemi = new THREE.HemisphereLight(0xffffff, 0x404040, 0.6), sun = new THREE.DirectionalLight(0xffffff, 0.8), pt = new THREE.PointLight(0xffc880, 0, 6, 2); + scene.add(hemi); scene.add(sun); scene.add(sun.target); scene.add(pt); + rig.cam = cam; + VM = { scene, cam, rig, root: rig.group, hemi, sun, pt, kind: null }; + return VM; + } + FP.vm = () => VM; + // the arms pass: its own field of view (50-60, never the world's) and a small push of the whole rig away from the eye + FP.vmTune = { fov: 55, push: 0.03 }; // 50 was tried: a narrower view only enlarges the arms; 3 cm out sits them a little smaller at the hip + const KIND = { rifle: 'rifleScoped', smg: 'smg', pistol: 'pistol', binoc: 'binoculars', grenade: 'grenade', knife: 'knife' }; + const vst = { weapon: '', kind: '', oneShot: null, dt: 0 }; + const pose = { p: new THREE.Vector3(), q: new THREE.Quaternion() }, qa = new THREE.Quaternion(), qp = new THREE.Quaternion(), piv = new THREE.Vector3(); + function vmFrame(dt, yaw, pitch) { + const vm = vmBuild(); if (!vm) return; + if (!vm.rig.standin) return realFrame(vm, dt, yaw, pitch); + const W8 = IV.weapons, S = IV.settings, rig = vm.rig; + // what the hands hold this frame (scripted beats included; js/fp.js header lists how each beat plays) + const M = IV.mission, I = IV.input; + const tdT = W8.takedownT != null ? IV.time - W8.takedownT : 99, inTakedown = P.cineClip && tdT < 3; + const harness = P.cine && M && M.phase === 'harness'; + if (FP._throwing && !W8.busyThrow) FP.throwT = IV.time; // the grenade just left the hand + FP._throwing = !!W8.busyThrow; if (W8.busyThrow) FP.throwKind = W8.busyThrow.kind; + const throwK = FP.throwT != null ? (IV.time - FP.throwT) / 0.42 : 9; + let k = W8.busyThrow || throwK < 1 ? 'grenade' : W8.binoc ? 'binoc' : W8.cur; + if (inTakedown || harness) k = 'knife'; + const kind = KIND[k] || k; + const show = P.alive && !(W8.scoped && FP.vmAim > 0.92) && !(W8.binoc && FP.vmAim > 0.92) && (!P.cineClip || inTakedown) && (!P.cine || harness || inTakedown); + vm.root.visible = show; + if (!show) return; + if (rig.kind !== kind) { if (rig.kind) FP.drawK = 1; rig.setKind(kind); } // a new thing in the hands comes up from below + vm.gun = rig.gun; + if (rig.gun) rig.gun.visible = !(kind === 'grenade' && FP.throwKind === 'rock'); // a stone: the throwing hand, no model + if (rig.actor) rig.actor.leftHandIK = kind === 'knife' || kind === 'grenade' ? 0 : null; + // mirror the world actor's upper-body one-shots (reload, bolt) onto the arms + const wu = IV.upperOf(P.actor); + vst.weapon = k; vst.kind = kind; vst.dt = dt; vst.oneShot = /reload|bolt/i.test(wu || '') && kind !== 'knife' && kind !== 'grenade' ? wu : null; + rig.drive(vst, dt); + // procedural layers (viewmodel camera frame: x right, y up, z toward the camera) + const C = IV.camera, motion = S.motion ? 0.4 : 1; + const aiming = !!(W8.aiming || W8.scoped || (W8.binoc && k === 'binoc')); + // look lag: the gun trails the view a little and catches up + const dyaw = IV.wrapA(yaw - (FP.lastYaw == null ? yaw : FP.lastYaw)), dpit = pitch - (FP.lastPitch == null ? pitch : FP.lastPitch); + FP.lastYaw = yaw; FP.lastPitch = pitch; + const lagK = aiming ? 0.35 : 1; + FP.lagYaw = IV.clamp(IV.damp(FP.lagYaw, dyaw * 5 * lagK, 12, dt), -0.07, 0.07); FP.lagPitch = IV.clamp(IV.damp(FP.lagPitch, dpit * 5 * lagK, 12, dt), -0.06, 0.06); + const t = IV.time, ph = FP.phase || 0, bobA = (FP.bobAmp || 0) * 1.3; + // breathing: heavier for a few seconds after a sprint (first-person-body skill) + FP.fatigue = IV.clamp((FP.fatigue || 0) + (P.sprinting ? dt / 4 : -dt / 7), 0, 1); + const breath = (aiming ? 0.12 : 1) * motion * (1 + FP.fatigue * 2.2); + FP.kick = IV.damp(FP.kick, 0, 13, dt); FP.kickR = IV.damp(FP.kickR, 0, 9, dt); + FP.vmAim = IV.damp(FP.vmAim, aiming ? 1 : 0, aiming ? 16 : 12, dt); // about 0.2 s to the sights, a touch slower down + // sprint carry: the gun swings across the chest, muzzle low and left + FP.vmSpr = IV.damp(FP.vmSpr || 0, P.sprinting && k !== 'grenade' ? 1 : 0, P.sprinting ? 7 : 10, dt); + // lowering near walls: a short ray along the view + const cam = W.camera, look = IV.camera.lookDir, wall = W.raycast(cam.position.x, cam.position.y, cam.position.z, look.x, look.y, look.z, 0.9, F.SOLID | F.SIGHT, true); + FP.vmLower = IV.damp(FP.vmLower, wall && !aiming ? IV.clamp(1 - (wall.t - 0.3) / 0.6, 0, 1) : 0, 8, dt); + // stance: crouched the gun sits a little higher and tighter, prone it is pushed forward and tilted in + FP.vmPr = IV.damp(FP.vmPr || 0, P.stance === 'prone' ? 1 : 0, 6, dt); + const ox = Math.sin(t * 1.1) * 0.0025 * breath + Math.sin(ph * Math.PI * 2) * bobA * 0.55 - FP.lagYaw * 0.45 - FP.vmSpr * 0.02; + const oy = -Math.abs(Math.sin(ph * Math.PI * 2)) * bobA * 0.9 + Math.sin(t * 1.7) * 0.0018 * breath + FP.lagPitch * 0.35 - FP.vmLower * 0.1 + (C.bobY || 0) * 0.5 - FP.vmSpr * 0.045 + FP.vmPr * 0.02; + const oz = FP.kick * (aiming ? 0.035 : 0.05) + FP.vmLower * 0.06 - FP.vmPr * 0.03; + // beats: draw (a new item rises from below), using something (gun lowered), grenade cook and throw, knife stab + // (takedown) and the harness cut (knife up at the riser, sawing while Use is held) + FP.drawK = IV.damp(FP.drawK || 0, 0, 7, dt); + const using = !!(M && M.interAt && I.held('use') && M.interAt.prog > 0 && !harness); + FP.vmUse = IV.damp(FP.vmUse || 0, using ? 1 : 0, 8, dt); + let bx2 = 0, by2 = -FP.drawK * 0.22 - FP.vmUse * 0.14, bz2 = 0, bp = -FP.drawK * 0.6 - FP.vmUse * 0.6, byaw = FP.vmUse * 0.35, broll = 0; + if (kind === 'grenade') { + if (W8.busyThrow) { const c = Math.min(1, (IV.time - W8.busyThrow.t0) / 0.35); by2 += 0.06 * c; bp += 0.25 * c; bz2 += 0.05 * c; } // wound back by the shoulder + else { const e = IV.clamp(throwK, 0, 1); bz2 -= Math.sin(e * Math.PI * 0.8) * 0.35; by2 += Math.sin(e * Math.PI) * 0.08 - e * e * 0.35; bx2 -= e * 0.1; bp -= e * 1.1; } + } + if (kind === 'knife' && inTakedown) { + // grab and strike: up and back (0-0.35 s), thrust forward and down (0.35-0.6), hold, then lower away (2.0-2.6) + const a1 = IV.smooth(IV.clamp(tdT / 0.35, 0, 1)), a2 = IV.smooth(IV.clamp((tdT - 0.35) / 0.25, 0, 1)), a3 = IV.smooth(IV.clamp((tdT - 2.0) / 0.6, 0, 1)); + bx2 += -0.06 * a1; by2 += 0.12 * a1 - 0.08 * a2 - 0.3 * a3; bz2 += 0.08 * a1 - 0.3 * a2 + 0.1 * a3; bp += 0.5 * a1 - 1.2 * a2 - 0.4 * a3; broll += 0.4 * a1; + } + if (kind === 'knife' && harness) { + const cutting = !!(M.interAt && I.held('use')); + FP.saw = IV.damp(FP.saw || 0, cutting ? 1 : 0, 6, dt); + const sw = Math.sin(IV.time * 13) * FP.saw; + bx2 += -0.14 * FP.saw; by2 += 0.3 * FP.saw + sw * 0.03; bz2 += -0.05 * FP.saw + sw * 0.02; bp += 0.9 * FP.saw; broll += 0.5 * FP.saw; + } + // pose: hip blended to the sights, then the layers + const hip = rig.hip, ads = rig.adsOffset, a = IV.smooth(IV.clamp(FP.vmAim, 0, 1)); + pose.p.copy(hip.p).addScaledVector(ads.p, a); + qa.copy(hip.q).multiply(ads.q); pose.q.copy(hip.q).slerp(qa, a); + const relax = 1 - a * 0.85; + pose.p.x += ox * relax + bx2; pose.p.y += oy * (1 - a * 0.7) + by2; pose.p.z += oz + bz2; + _e.set(FP.kickR + FP.lagPitch * 0.6 * relax - FP.vmLower * 0.55 - FP.vmSpr * 0.35 + bp, FP.lagYaw * 0.8 * relax + FP.vmSpr * 0.75 + byaw, -FP.roll * 0.6 + FP.vmSpr * 0.5 + Math.sin(ph * Math.PI * 2) * bobA * 0.6 * relax + FP.vmPr * 0.12 + broll); + // the layers turn the gun about the right hand (its grip), not the sight point half a metre ahead of it + qp.setFromEuler(_e); + const sp0 = rig._s || [0, 0, 0]; + piv.set(-sp0[0], -sp0[1], -sp0[2]).applyQuaternion(_q.copy(pose.q).multiply(R0)).add(pose.p); + pose.p.sub(piv).applyQuaternion(qp).add(piv); pose.q.premultiply(qp); + if (rig.place) rig.place(pose.p, pose.q); + else { rig.group.position.copy(pose.p); rig.group.quaternion.copy(pose.q); } + vm.cam.position.set(0, 0, 0); vm.cam.quaternion.identity(); vm.cam.updateMatrixWorld(true); + vmLight(vm); + } + function vmLight(vm) { + const cam = W.camera; + // lighting copied from the world, scaled by how lit the player is + // how lit the player is (moon, moon shadow, lamps), never brighter than the world itself; the arms are drawn after the + // post stack, so at night they also take a share of its vignette and desaturation as a plain darkening + const E = window.IVEnv, grade = E && E.atmo && E.atmo.P && E.atmo.P.grade, night = !grade || grade === 'night' || grade === 'rain'; + const lit = (W.lightAt ? IV.clamp(0.2 + W.lightAt(P.render.x, P.render.y + 1.4, P.render.z) * 0.9, 0.2, 1) : 1) * (night ? 0.78 : 0.95); + if (W.hemi) { vm.hemi.color.copy(W.hemi.color); vm.hemi.groundColor.copy(W.hemi.groundColor); vm.hemi.intensity = W.hemi.intensity * lit; } + if (W.sun) { + // the sun or moon direction in the viewmodel camera's frame + vm.sun.color.copy(W.sun.color); vm.sun.intensity = W.sun.intensity * lit; + _v.set(W.moonDir.x, W.moonDir.y, W.moonDir.z).applyQuaternion(_q.copy(cam.quaternion).invert()); + vm.sun.target.position.set(0.12, -0.15, -0.4); vm.sun.position.copy(_v).normalize().multiplyScalar(1.5).add(vm.sun.target.position); vm.sun.target.updateMatrixWorld(); + // a weak cool rim from the sky side, up and behind, so the silhouette holds at night + if (!vm.rim) { vm.rim = new THREE.DirectionalLight(0x9fb4d8, 0); vm.scene.add(vm.rim); } + vm.rim.position.set(-0.4, 0.8, 0.6); vm.rim.intensity = night ? 0.35 * W.hemi.intensity : 0.12; + } + // the nearest lamp pools and the muzzle / explosion flash light the arms from where they really are: each world point + // light is copied into the viewmodel scene at its position relative to the eye (same colour, power, falloff) + _q.copy(cam.quaternion).invert(); + const src = [W.flashLight].concat(W.pointPool ? W.pointPool.slice(0, 2) : []); + if (!vm.lamps) { vm.lamps = src.map(() => { const l = new THREE.PointLight(0xffc880, 0, 10, 2); vm.scene.add(l); return l; }); vm.pt.intensity = 0; } + src.forEach((w, i) => { const l = vm.lamps[i]; if (!w || !l) return; l.color.copy(w.color); l.distance = w.distance; l.decay = w.decay; l.intensity = w.intensity * (night ? 0.9 : 1); l.position.copy(w.position).sub(cam.position).applyQuaternion(_q); }); + vm.scene.environment = W.scene.environment || null; + } + // where the gun and hands are on screen (0..1, top-left origin), for HUD layout checks: the gun's box and the hand + // and forearm bones, projected by the viewmodel camera + const _b3 = new THREE.Box3(), _pc = new THREE.Vector3(); + FP.screenBox = function () { + if (!VM || !VM.root.visible || !VM.rig.gun) return null; + const r = { x0: 1, y0: 1, x1: 0, y1: 0, pts: [] }, add = v => { if (v.z > -0.02) return; _pc.copy(v).project(VM.cam); const x = (_pc.x + 1) / 2, y = (1 - _pc.y) / 2; r.pts.push([+x.toFixed(3), +y.toFixed(3)]); r.x0 = Math.min(r.x0, x); r.x1 = Math.max(r.x1, x); r.y0 = Math.min(r.y0, y); r.y1 = Math.max(r.y1, y); }; + _b3.setFromObject(VM.rig.gun); + for (let i = 0; i < 8; i++) add(_v.set(i & 1 ? _b3.max.x : _b3.min.x, i & 2 ? _b3.max.y : _b3.min.y, i & 4 ? _b3.max.z : _b3.min.z)); + const A = VM.rig.actor; if (A) for (const n of ['hand_l', 'hand_r', 'lowerarm_l', 'lowerarm_r']) { const b = A.bone(n); if (b) add(b.getWorldPosition(_v)); } + const bs = VM.rig.vm && VM.rig.vm.bones; if (bs) for (const n of ['hand_l', 'hand_r', 'lowerarm_l', 'lowerarm_r']) if (bs[n]) add(bs[n].getWorldPosition(_v)); + for (const k of ['x0', 'y0', 'x1', 'y1']) r[k] = Math.round(IV.clamp(r[k], 0, 1) * 1000) / 1000; + return r; + }; + // a finished interaction: a small nod (a breach is a shoulder into the door: a harder lurch) + IV.on('interacted', o => { if (!FP.on()) return; FP.nodV = (FP.nodV || 0) - (o && o.id === 'breach' ? 3.2 : 1.2) * (IV.settings.motion ? 0.35 : 1); }); + // recoil from weapons.js: kick back and up + FP.recoil = function (k) { FP.kick = Math.min(1.5, FP.kick + k); FP.kickR = Math.min(0.25, FP.kickR + k * 0.06); }; + + // ---------------------------------------------------------------- the second pass + // world.js draws the world; the viewmodel goes on top of whatever it drew + const draw0 = W.draw; W.draw = function (dt) { draw0.call(W, dt); FP.draw(); }; + FP.draw = function () { + if (!VM || !VM.root.visible || !FP.on()) return; + const r = W.renderer, ac = r.autoClear, tm = r.toneMapping; + VM.cam.aspect = W.camera.aspect; VM.cam.fov = FP.vmTune.fov; VM.cam.updateProjectionMatrix(); // fixed: never follows the world FOV setting + r.autoClear = false; r.setRenderTarget(null); r.clearDepth(); + r.toneMapping = THREE.ACESFilmicToneMapping; // the post stack tone maps the world itself; the viewmodel is drawn after it + { const ri = r.info.render; FP.worldInfo = { calls: ri.calls, tris: ri.triangles }; } // the world pass just drawn (without the post stack this is all of it) + const t0 = performance.now(); + r.render(VM.scene, VM.cam); + FP.passMs = IV.damp(FP.passMs || 0, performance.now() - t0, 4, 0.016); + const ri = r.info.render; FP.vmInfo = { calls: ri.calls, tris: ri.triangles }; // this pass alone (info resets per render call) + r.autoClear = ac; r.toneMapping = tm; + }; + // the world point in front of which the visible muzzle sits (for muzzle flash and tracers) + FP.muzzle = function (out) { + if (!VM || !VM.rig.muzzle || !VM.root.visible) return null; + const m = VM.rig.muzzle.getWorldPosition(tmp); + m.applyMatrix4(VM.cam.matrixWorldInverse); // viewmodel camera space + m.z *= 0.9; // a touch in front of the world so it is not inside the near geometry + return out.copy(m).applyMatrix4(W.camera.matrixWorld); + }; +})(); diff --git a/e63334287a3deaa3/ironveil/js/fx.js b/e63334287a3deaa3/ironveil/js/fx.js new file mode 100644 index 00000000..c726358f --- /dev/null +++ b/e63334287a3deaa3/ironveil/js/fx.js @@ -0,0 +1,256 @@ +/* Ironveil effects: pooled particles (one additive and one normal system, one draw call each), tracers as camera-facing + quads, muzzle flashes, ejected casings, decals (bullet marks and blood, capped and fading), impacts by surface, + explosions with a shockwave ring and lingering fire, and drifting illumination flares. Blood follows the Settings + switch: off turns every blood effect into dust. */ +(function () { + 'use strict'; + const W = IV.world; + const FX = IV.fx = {}; + const V = new THREE.Vector3(), V2 = new THREE.Vector3(); + + // ---------------------------------------------------------------- particle systems + function PSys(cap, additive, tex) { + this.cap = cap; this.n = 0; + this.d = new Float32Array(cap * 16); // x y z vx vy vz life max s0 s1 r g b a drag grav + const g = this.geo = new THREE.BufferGeometry(); + this.pos = new Float32Array(cap * 3); this.col = new Float32Array(cap * 4); this.size = new Float32Array(cap); + g.setAttribute('position', new THREE.BufferAttribute(this.pos, 3).setUsage(THREE.DynamicDrawUsage)); + g.setAttribute('pcol', new THREE.BufferAttribute(this.col, 4).setUsage(THREE.DynamicDrawUsage)); + g.setAttribute('psize', new THREE.BufferAttribute(this.size, 1).setUsage(THREE.DynamicDrawUsage)); + g.setDrawRange(0, 0); + const m = this.mat = new THREE.ShaderMaterial({ + transparent: true, depthWrite: false, blending: additive ? THREE.AdditiveBlending : THREE.NormalBlending, + uniforms: { tex: { value: tex }, uScale: { value: 400 }, fogC: { value: new THREE.Color() }, fogD: { value: 0.01 } }, + vertexShader: 'attribute vec4 pcol; attribute float psize; uniform float uScale; varying vec4 vC; varying float vF;\n' + + 'void main(){ vec4 mv = modelViewMatrix * vec4(position,1.0); gl_Position = projectionMatrix * mv; gl_PointSize = min(psize * uScale / max(0.1, -mv.z), 220.0); vC = pcol; vF = -mv.z; }', + fragmentShader: 'uniform sampler2D tex; uniform vec3 fogC; uniform float fogD; varying vec4 vC; varying float vF;\n' + + 'void main(){ vec4 t = texture2D(tex, gl_PointCoord); float f = exp(-fogD*fogD*vF*vF); ' + + (additive ? 'gl_FragColor = vec4(vC.rgb * t.rgb * t.a * vC.a * f, 1.0);' : 'gl_FragColor = vec4(mix(fogC, vC.rgb, f), t.a * vC.a);') + ' }' + }); + this.pts = new THREE.Points(g, m); this.pts.frustumCulled = false; this.pts.renderOrder = additive ? 6 : 5; + } + PSys.prototype.emit = function (x, y, z, vx, vy, vz, life, s0, s1, r, g, b, a, drag, grav) { + let i = this.n; if (i >= this.cap) i = (Math.random() * this.cap) | 0; else this.n++; + const d = this.d, k = i * 16; + d[k] = x; d[k + 1] = y; d[k + 2] = z; d[k + 3] = vx; d[k + 4] = vy; d[k + 5] = vz; d[k + 6] = 0; d[k + 7] = life; + d[k + 8] = s0; d[k + 9] = s1; d[k + 10] = r; d[k + 11] = g; d[k + 12] = b; d[k + 13] = a; d[k + 14] = drag || 0; d[k + 15] = grav || 0; + }; + PSys.prototype.update = function (dt) { + const d = this.d; + for (let i = 0; i < this.n; i++) { + const k = i * 16; + d[k + 6] += dt; + if (d[k + 6] >= d[k + 7]) { // swap-remove + const last = (this.n - 1) * 16; for (let j = 0; j < 16; j++) d[k + j] = d[last + j]; this.n--; i--; continue; + } + const dr = Math.exp(-d[k + 14] * dt); + d[k + 3] *= dr; d[k + 5] *= dr; d[k + 4] = d[k + 4] * dr - d[k + 15] * dt; + d[k] += d[k + 3] * dt; d[k + 1] += d[k + 4] * dt; d[k + 2] += d[k + 5] * dt; + if (d[k + 15] > 0 && d[k + 1] < W.height(d[k], d[k + 2]) + 0.02) { d[k + 1] = W.height(d[k], d[k + 2]) + 0.02; d[k + 4] *= -0.25; d[k + 3] *= 0.5; d[k + 5] *= 0.5; } + } + const p = this.pos, c = this.col, s = this.size; + for (let i = 0; i < this.n; i++) { + const k = i * 16, t = d[k + 6] / d[k + 7]; + p[i * 3] = d[k]; p[i * 3 + 1] = d[k + 1]; p[i * 3 + 2] = d[k + 2]; + c[i * 4] = d[k + 10]; c[i * 4 + 1] = d[k + 11]; c[i * 4 + 2] = d[k + 12]; + c[i * 4 + 3] = d[k + 13] * (t < 0.1 ? t * 10 : 1 - (t - 0.1) / 0.9); + s[i] = d[k + 8] + (d[k + 9] - d[k + 8]) * t; + } + this.geo.attributes.position.needsUpdate = true; this.geo.attributes.pcol.needsUpdate = true; this.geo.attributes.psize.needsUpdate = true; + this.geo.setDrawRange(0, this.n); + }; + + let add, norm, tracerMesh, tracerPos, tracers = [], casings = [], casingIM, decals = [], decalIM, holes = [], holeIM, flashes = [], flashSprites = [], rings = [], fires = [], flares = []; + FX.init = function () { + // capped by quality: soft particles cost fill rate, the first thing a school laptop runs out of + add = new PSys([500, 800, 1100][W.quality], true, W.tex.glow()); + norm = new PSys([350, 700, 1000][W.quality], false, W.tex.smoke()); + W.scene.add(add.pts); W.scene.add(norm.pts); + // tracers: up to 48 quads in one dynamic mesh + const g = new THREE.BufferGeometry(); tracerPos = new Float32Array(48 * 6 * 3); + const tc = new Float32Array(48 * 6 * 3); + g.setAttribute('position', new THREE.BufferAttribute(tracerPos, 3).setUsage(THREE.DynamicDrawUsage)); + g.setAttribute('color', new THREE.BufferAttribute(tc, 3).setUsage(THREE.DynamicDrawUsage)); + tracerMesh = new THREE.Mesh(g, new THREE.MeshBasicMaterial({ vertexColors: true, transparent: true, blending: THREE.AdditiveBlending, depthWrite: false, side: THREE.DoubleSide, toneMapped: false, fog: false })); + tracerMesh.frustumCulled = false; tracerMesh.renderOrder = 7; W.scene.add(tracerMesh); + // casings + casingIM = new THREE.InstancedMesh(new THREE.CylinderGeometry(0.006, 0.006, 0.05, 6).rotateX(Math.PI / 2), new THREE.MeshStandardMaterial({ color: 0xb08a3a, metalness: 0.8, roughness: 0.35 }), 40); + casingIM.count = 0; casingIM.frustumCulled = false; W.scene.add(casingIM); + // decals: blood (soft red splat) and bullet marks (dark), each one instanced mesh + const splat = makeSplatTex(); + decalIM = new THREE.InstancedMesh(new THREE.PlaneGeometry(1, 1), new THREE.MeshStandardMaterial({ map: splat, transparent: true, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2, roughness: 0.4, color: 0x7a0c08 }), IV.TUNING.blood.decals); + decalIM.count = 0; decalIM.frustumCulled = false; decalIM.renderOrder = 2; W.scene.add(decalIM); + holeIM = new THREE.InstancedMesh(new THREE.PlaneGeometry(1, 1), new THREE.MeshBasicMaterial({ map: W.tex.glow(), transparent: true, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2, color: 0x000000, opacity: 0.8 }), 60); + holeIM.count = 0; holeIM.frustumCulled = false; holeIM.renderOrder = 2; W.scene.add(holeIM); + // muzzle flash sprites (pool of 8) + const ft = makeFlashTex(); + flashSprites = []; + for (let i = 0; i < 8; i++) { const s = new THREE.Sprite(new THREE.SpriteMaterial({ map: ft, color: 0xffd8a0, blending: THREE.AdditiveBlending, depthWrite: false, transparent: true, toneMapped: false })); s.visible = false; W.scene.add(s); flashSprites.push(s); } + tracers = []; casings = []; decals = []; holes = []; flashes = []; rings = []; fires = []; flares = []; + }; + function makeSplatTex() { + const c = document.createElement('canvas'); c.width = c.height = 64; const g = c.getContext('2d'), R = IV.rng(3); + for (let i = 0; i < 14; i++) { const a = R() * 6.28, r = R() * 18, x = 32 + Math.cos(a) * r, y = 32 + Math.sin(a) * r, s = R.range(4, 12); const gr = g.createRadialGradient(x, y, 0, x, y, s); gr.addColorStop(0, 'rgba(255,255,255,.95)'); gr.addColorStop(0.7, 'rgba(255,255,255,.7)'); gr.addColorStop(1, 'rgba(255,255,255,0)'); g.fillStyle = gr; g.fillRect(0, 0, 64, 64); } + const t = new THREE.CanvasTexture(c); return t; + } + function makeFlashTex() { + const c = document.createElement('canvas'); c.width = c.height = 64; const g = c.getContext('2d'); + const gr = g.createRadialGradient(32, 32, 0, 32, 32, 30); gr.addColorStop(0, 'rgba(255,255,240,1)'); gr.addColorStop(0.3, 'rgba(255,200,120,.8)'); gr.addColorStop(1, 'rgba(255,120,40,0)'); g.fillStyle = gr; g.fillRect(0, 0, 64, 64); + g.globalCompositeOperation = 'lighter'; g.strokeStyle = 'rgba(255,220,160,.8)'; g.lineWidth = 3; + for (let i = 0; i < 6; i++) { const a = i / 6 * 6.28 + 0.3; g.beginPath(); g.moveTo(32, 32); g.lineTo(32 + Math.cos(a) * 31, 32 + Math.sin(a) * 31); g.stroke(); } + return new THREE.CanvasTexture(c); + } + + // ---------------------------------------------------------------- emitters + const R = () => Math.random(), rr = (a, b) => a + Math.random() * (b - a); + FX.muzzle = function (x, y, z, dx, dy, dz, big) { + const s = flashSprites.find(s => !s.visible) || flashSprites[0]; + s.position.set(x + dx * 0.05, y + dy * 0.05, z + dz * 0.05); const k = big ? 0.7 : 0.45; s.scale.set(k * rr(0.8, 1.2), k * rr(0.8, 1.2), 1); s.material.rotation = R() * 6.28; s.visible = true; s.userData.t = 0.05; + flashes.push(s); + for (let i = 0; i < (big ? 6 : 3); i++) add.emit(x + dx * 0.1, y + dy * 0.1, z + dz * 0.1, dx * rr(2, 6) + rr(-0.5, 0.5), dy * rr(2, 6) + rr(-0.5, 0.5), dz * rr(2, 6) + rr(-0.5, 0.5), rr(0.04, 0.08), 0.12, 0.05, 1, 0.75, 0.4, 1, 3, 0); + for (let i = 0; i < (big ? 2 : 1); i++) norm.emit(x + dx * 0.15, y + dy * 0.15, z + dz * 0.15, dx * rr(0.5, 1.5) + rr(-0.2, 0.2), rr(0.2, 0.6), dz * rr(0.5, 1.5) + rr(-0.2, 0.2), rr(0.6, 1.2), 0.15, 0.6, 0.55, 0.55, 0.55, big ? 0.35 : 0.2, 1.5, -0.2); + W.flashAt(x, y, z, big ? 9 : 6, 1, 0.06); + }; + FX.tracer = function (b) { tracers.push(b); }; // reads b.x,y,z,vx,vy,vz each frame while b.alive + FX.casing = function (x, y, z, vx, vy, vz) { + if (casings.length >= 40) casings.shift(); + casings.push({ x, y, z, vx, vy, vz, rx: R() * 6, ry: R() * 6, life: 6, rest: false }); + }; + // surface impact. nx,ny,nz: surface normal. dir: bullet direction + FX.impact = function (x, y, z, nx, ny, nz, surf, dir) { + const n = 4; + if (surf === 'water') { for (let i = 0; i < 10; i++) norm.emit(x, y, z, rr(-0.6, 0.6), rr(2, 4), rr(-0.6, 0.6), rr(0.4, 0.7), 0.1, 0.25, 0.75, 0.8, 0.85, 0.6, 1, 9); return; } + let col = [0.42, 0.36, 0.27]; + if (surf === 'stone') col = [0.55, 0.53, 0.5]; else if (surf === 'wood') col = [0.45, 0.33, 0.2]; else if (surf === 'foliage') col = [0.18, 0.26, 0.1]; + else if (surf === 'gravel') col = [0.5, 0.48, 0.44]; else if (surf === 'cloth') col = [0.6, 0.55, 0.4]; + for (let i = 0; i < n; i++) norm.emit(x + nx * 0.05, y + ny * 0.05, z + nz * 0.05, nx * rr(0.5, 2) + rr(-0.6, 0.6), ny * rr(0.5, 2) + rr(0.2, 1.2), nz * rr(0.5, 2) + rr(-0.6, 0.6), rr(0.5, 1.1), 0.08, 0.5, col[0], col[1], col[2], 0.55, 2.2, 0.6); + // chunks with gravity + for (let i = 0; i < 3; i++) norm.emit(x, y, z, nx * rr(1, 3) + rr(-1, 1), rr(1.5, 3.5), nz * rr(1, 3) + rr(-1, 1), rr(0.4, 0.8), 0.04, 0.03, col[0] * 0.6, col[1] * 0.6, col[2] * 0.6, 0.9, 0.5, 9.8); + if (surf === 'stone' || surf === 'metal' || surf === 'gravel') for (let i = 0; i < (surf === 'metal' ? 8 : 3); i++) add.emit(x, y, z, nx * rr(2, 6) + rr(-2, 2), ny * rr(2, 6) + rr(-1, 3), nz * rr(2, 6) + rr(-2, 2), rr(0.08, 0.2), 0.05, 0.02, 1, 0.75, 0.4, 1, 1, 9.8); + if (surf === 'mud') for (let i = 0; i < 6; i++) norm.emit(x, y, z, nx * rr(0.5, 2) + rr(-1, 1), rr(2, 4), nz * rr(0.5, 2) + rr(-1, 1), rr(0.4, 0.7), 0.05, 0.04, 0.16, 0.12, 0.08, 1, 0.4, 9.8); // mud flecks + if (surf === 'foliage') for (let i = 0; i < 5; i++) norm.emit(x, y, z, rr(-1, 1), rr(0, 1), rr(-1, 1), rr(1.2, 2.2), 0.06, 0.06, 0.22, 0.3, 0.12, 0.9, 2.5, 1.2); + if (surf !== 'foliage' && surf !== 'cloth') FX.hole(x, y, z, nx, ny, nz, surf === 'wood' ? 0.07 : 0.09); + }; + // footsteps: mud clods kicked up behind the boot, and a small splash from a puddle (no decal, no hole) + FX.clods = function (x, y, z, n, dx, dz) { for (let i = 0; i < (n || 4); i++) norm.emit(x, y + 0.03, z, -(dx || 0) * rr(0.3, 1.2) + rr(-0.4, 0.4), rr(0.8, 1.8), -(dz || 0) * rr(0.3, 1.2) + rr(-0.4, 0.4), rr(0.35, 0.6), 0.025, 0.02, 0.17, 0.13, 0.09, 1, 0.5, 9); }; + FX.splash = function (x, y, z, k) { const n = Math.round(5 + 5 * (k || 1)); for (let i = 0; i < n; i++) norm.emit(x + rr(-0.1, 0.1), y + 0.04, z + rr(-0.1, 0.1), rr(-0.5, 0.5), rr(0.9, 2) * (k || 1), rr(-0.5, 0.5), rr(0.3, 0.5), 0.05, 0.12, 0.6, 0.65, 0.68, 0.5, 0.8, 9); }; + // blood: a hit puff, a short spray along the bullet, and a decal on what's behind (ground or a wall) within 3 m + FX.blood = function (x, y, z, dx, dy, dz, heavy) { + if (!IV.settings.blood) { FX.impact(x, y, z, -dx, -dy, -dz, 'cloth'); for (let i = 0; i < 6; i++) norm.emit(x, y, z, dx * rr(0.5, 2) + rr(-0.5, 0.5), rr(0.2, 1), dz * rr(0.5, 2) + rr(-0.5, 0.5), rr(0.5, 1), 0.1, 0.45, 0.5, 0.46, 0.4, 0.5, 2, 0.4); return; } + for (let i = 0; i < (heavy ? 10 : 6); i++) norm.emit(x, y, z, dx * rr(0.5, 2.5) + rr(-0.4, 0.4), dy * rr(0.5, 2) + rr(-0.2, 0.6), dz * rr(0.5, 2.5) + rr(-0.4, 0.4), rr(0.25, 0.5), 0.05, 0.3, 0.38, 0.02, 0.02, 0.85, 3, 2); + for (let i = 0; i < (heavy ? 12 : 7); i++) norm.emit(x, y, z, dx * rr(2, 5) + rr(-0.7, 0.7), dy * rr(1, 3) + rr(0, 1), dz * rr(2, 5) + rr(-0.7, 0.7), rr(0.3, 0.6), 0.025, 0.02, 0.3, 0.01, 0.01, 1, 0.6, 9.8); + // decal behind the target + const h = W.raycast(x, y, z, dx, dy - 0.35, dz, 3.2, IV.CF.BULLET); + if (h) FX.decal(h.x, h.y, h.z, h.nx, h.ny, h.nz, rr(0.3, 0.6)); + else { const gy = W.height(x + dx, z + dz); FX.decal(x + dx * 0.8, gy, z + dz * 0.8, 0, 1, 0, rr(0.3, 0.55)); } + }; + FX.bloodPool = function (x, z) { // a small stain under a fallen soldier (blood switch respected) + if (!IV.settings.blood) return; + FX.decal(x, W.height(x, z), z, 0, 1, 0, rr(0.6, 0.9)); + }; + const M4 = new THREE.Matrix4(), Q4 = new THREE.Quaternion(), S4 = new THREE.Vector3(), Z = new THREE.Vector3(0, 0, 1); + function placeDecal(im, list, cap, x, y, z, nx, ny, nz, s, life) { + if (list.length >= cap) list.shift(); + V.set(nx, ny, nz).normalize(); + Q4.setFromUnitVectors(Z, V); Q4.multiply(new THREE.Quaternion().setFromAxisAngle(Z, Math.random() * 6.28)); + list.push({ p: new THREE.Vector3(x + nx * 0.015, y + ny * 0.015, z + nz * 0.015), q: Q4.clone(), s, t: 0, life }); + } + FX.decal = (x, y, z, nx, ny, nz, s) => placeDecal(decalIM, decals, IV.TUNING.blood.decals, x, y, z, nx, ny, nz, s, IV.TUNING.blood.decalLife); + FX.hole = (x, y, z, nx, ny, nz, s) => placeDecal(holeIM, holes, 60, x, y, z, nx, ny, nz, s, 60); + FX.dust = function (x, y, z, n, s) { for (let i = 0; i < (n || 10); i++) norm.emit(x + rr(-0.4, 0.4), y + rr(0, 0.2), z + rr(-0.4, 0.4), rr(-0.8, 0.8), rr(0.1, 0.6), rr(-0.8, 0.8), rr(1, 2), (s || 0.4) * 0.6, (s || 0.4) * 2, 0.4, 0.37, 0.32, 0.4, 1.5, -0.05); }; + FX.smoke = function (x, y, z, n, s, dark) { for (let i = 0; i < n; i++) norm.emit(x + rr(-0.5, 0.5), y, z + rr(-0.5, 0.5), rr(-0.3, 0.3), rr(0.8, 2), rr(-0.3, 0.3), rr(3, 6), s, s * 4, dark ? 0.12 : 0.4, dark ? 0.11 : 0.39, dark ? 0.1 : 0.37, 0.5, 0.4, -0.15); }; + // big explosion: flash light, fireball, sparks, debris, smoke column, ground dust ring and a shockwave ring + FX.explosion = function (x, y, z, big) { + const k = big ? 1.8 : 1; + W.flashAt(x, y + 1, z, 40 * k, 3, big ? 1.2 : 0.5, 0xffb060); + for (let i = 0; i < 40 * k; i++) { const a = R() * 6.28, e = R() * 1.4, sp = rr(4, 14) * k; add.emit(x, y + 0.5, z, Math.cos(a) * Math.cos(e) * sp, Math.sin(e) * sp + 2, Math.sin(a) * Math.cos(e) * sp, rr(0.3, 0.8), rr(0.8, 1.6) * k, rr(2, 3.5) * k, 1, rr(0.45, 0.7), 0.2, 1, 3.5, -1); } + for (let i = 0; i < 30 * k; i++) add.emit(x, y + 0.5, z, rr(-18, 18), rr(4, 22), rr(-18, 18), rr(0.5, 1.5), 0.08, 0.04, 1, 0.7, 0.3, 1, 0.5, 9.8); + for (let i = 0; i < 26 * k; i++) norm.emit(x, y + 0.5, z, rr(-9, 9), rr(5, 16), rr(-9, 9), rr(1.2, 2.6), rr(0.06, 0.18), 0.1, 0.12, 0.1, 0.08, 1, 0.3, 9.8); + for (let i = 0; i < 30 * k; i++) norm.emit(x + rr(-1, 1), y + rr(0.5, 2), z + rr(-1, 1), rr(-2, 2), rr(2, 7), rr(-2, 2), rr(4, 9), rr(1, 2) * k, rr(5, 9) * k, 0.1, 0.09, 0.08, 0.75, 0.6, -0.2); + for (let i = 0; i < 36; i++) { const a = i / 36 * 6.28; norm.emit(x, W.height(x, z) + 0.3, z, Math.cos(a) * 12 * k, 0.3, Math.sin(a) * 12 * k, rr(1.5, 2.5), 0.8, 3.5 * k, 0.42, 0.38, 0.32, 0.5, 1.8, 0); } + // smoke lit from inside by the fireball, then the scorch left on the ground + for (let i = 0; i < 10 * k; i++) norm.emit(x + rr(-0.6, 0.6), y + rr(0.3, 1.2), z + rr(-0.6, 0.6), rr(-1.5, 1.5), rr(2, 5), rr(-1.5, 1.5), rr(1.2, 2.2), rr(0.8, 1.4) * k, rr(3, 5) * k, 0.42, 0.24, 0.11, 0.7, 0.8, -0.3); + FX.hole(x, W.height(x, z) + 0.02, z, 0, 1, 0, 2.6 * k); + // shockwave ring + const ring = new THREE.Mesh(new THREE.RingGeometry(0.8, 1, 48), new THREE.MeshBasicMaterial({ color: 0xffe6c0, transparent: true, opacity: 0.5, side: THREE.DoubleSide, depthWrite: false, blending: THREE.AdditiveBlending, toneMapped: false })); + ring.rotation.x = -Math.PI / 2; ring.position.set(x, W.height(x, z) + 0.4, z); W.scene.add(ring); rings.push({ m: ring, t: 0, k }); + }; + // a lingering fire: flickering light and embers + smoke for a while + FX.fire = function (x, y, z, dur, r) { + const lamp = W.addLamp({ x, y: y + 1.2, z, r: r || 16, i: 1, power: 4, color: 0xff8a30, flicker: true, los: false }); + fires.push({ x, y, z, t: dur || 60, lamp, acc: 0 }); + }; + // an illumination flare: drifts down slowly under its parachute, lighting a big pool (bad for stealth) + FX.flare = function (x, y, z) { + const s = new THREE.Sprite(new THREE.SpriteMaterial({ map: W.tex.glow(), color: 0xfff0d0, blending: THREE.AdditiveBlending, depthWrite: false, transparent: true, toneMapped: false })); + s.scale.set(6, 6, 1); s.position.set(x, y, z); W.scene.add(s); + const lamp = W.addLamp({ x, y, z, r: 60, i: 0.9, power: 7, color: 0xfff0d0, los: false }); + flares.push({ s, lamp, t: 25, vy: -1.1, vx: (Math.random() - 0.5) * 0.6 }); + }; + FX.clear = function () { + add.n = 0; norm.n = 0; tracers.length = 0; casings.length = 0; decals.length = 0; holes.length = 0; + for (const r of rings) W.scene.remove(r.m); rings.length = 0; + for (const f of flares) W.scene.remove(f.s); flares.length = 0; fires.length = 0; + }; + + // ---------------------------------------------------------------- per frame + const cam = () => W.camera; + FX.frame = function (dt) { + const c = cam(); + const scale = W.renderer.domElement.height / (2 * Math.tan(c.fov * Math.PI / 360)); + for (const s of [add, norm]) { s.mat.uniforms.uScale.value = scale; if (W.scene.fog) { s.mat.uniforms.fogC.value.copy(W.scene.fog.color); s.mat.uniforms.fogD.value = W.scene.fog.density || 0.01; } s.update(dt); } + for (let i = flashes.length - 1; i >= 0; i--) { const s = flashes[i]; s.userData.t -= dt; if (s.userData.t <= 0) { s.visible = false; flashes.splice(i, 1); } } + // tracers + let q = 0; const cp = c.position, tp = tracerPos, tcol = tracerMesh.geometry.attributes.color.array; + for (let i = tracers.length - 1; i >= 0; i--) { + const b = tracers[i]; if (!b.alive || q >= 48) { tracers.splice(i, 1); continue; } + const sp = Math.hypot(b.vx, b.vy, b.vz) || 1, len = Math.min(b.travelled, b.enemy ? 7 : 9); + const ax = b.x, ay = b.y, az = b.z, bx = ax - b.vx / sp * len, by = ay - b.vy / sp * len, bz = az - b.vz / sp * len; + // side vector: perpendicular to the segment and to the view + V.set(ax - bx, ay - by, az - bz); V2.set(ax - cp.x, ay - cp.y, az - cp.z); V.cross(V2).normalize().multiplyScalar(0.035 + 0.0012 * V2.length()); + const k = q * 18; + const P = [ax + V.x, ay + V.y, az + V.z, ax - V.x, ay - V.y, az - V.z, bx - V.x, by - V.y, bz - V.z, ax + V.x, ay + V.y, az + V.z, bx - V.x, by - V.y, bz - V.z, bx + V.x, by + V.y, bz + V.z]; + for (let j = 0; j < 18; j++) tp[k + j] = P[j]; + const cr = b.enemy ? [1.0, 0.55, 0.25] : [1.0, 0.8, 0.45], head = 1.2, tail = 0.05; + const C = [head, head, tail, head, tail, tail]; + for (let j = 0; j < 6; j++) { tcol[k + j * 3] = cr[0] * C[j]; tcol[k + j * 3 + 1] = cr[1] * C[j]; tcol[k + j * 3 + 2] = cr[2] * C[j]; } + q++; + } + tracerMesh.geometry.setDrawRange(0, q * 6); + tracerMesh.geometry.attributes.position.needsUpdate = true; tracerMesh.geometry.attributes.color.needsUpdate = true; + // casings + for (let i = casings.length - 1; i >= 0; i--) if (casings[i].life <= 0) casings.splice(i, 1); + for (let i = 0; i < casings.length; i++) { + const s = casings[i]; s.life -= dt; + if (!s.rest) { + s.vy -= 9.8 * dt; s.x += s.vx * dt; s.y += s.vy * dt; s.z += s.vz * dt; s.rx += dt * 18; s.ry += dt * 11; + const g = W.groundAt(s.x, s.z, s.y + 0.1, 0.2); + if (s.y < g + 0.006) { s.y = g + 0.006; if (Math.abs(s.vy) > 1.2) { s.vy *= -0.35; s.vx *= 0.5; s.vz *= 0.5; IV.audio && IV.audio.play('casing', { x: s.x, z: s.z }); } else { s.rest = true; s.rx = Math.PI / 2; } } + } + Q4.setFromEuler(new THREE.Euler(s.rx, s.ry, 0)); M4.compose(V.set(s.x, s.y, s.z), Q4, S4.set(1, 1, 1)); casingIM.setMatrixAt(i, M4); + } + casingIM.count = casings.length; casingIM.instanceMatrix.needsUpdate = true; + // decals fade at the end of their life + updDecals(decalIM, decals, dt); updDecals(holeIM, holes, dt); + for (let i = rings.length - 1; i >= 0; i--) { const r = rings[i]; r.t += dt; const s = 1 + r.t * 40 * r.k; r.m.scale.set(s, s, 1); r.m.material.opacity = Math.max(0, 0.5 * (1 - r.t / 0.55)); if (r.t > 0.55) { W.scene.remove(r.m); rings.splice(i, 1); } } + for (let i = fires.length - 1; i >= 0; i--) { + const f = fires[i]; f.t -= dt; f.acc += dt; + while (f.acc > 0.05) { f.acc -= 0.05; add.emit(f.x + rr(-1, 1), f.y + rr(0, 1), f.z + rr(-1, 1), rr(-0.3, 0.3), rr(1.5, 3.5), rr(-0.3, 0.3), rr(0.4, 0.9), rr(0.6, 1.2), 0.1, 1, rr(0.4, 0.6), 0.15, 1, 0.5, -0.5); if (Math.random() < 0.4) norm.emit(f.x + rr(-0.8, 0.8), f.y + 2, f.z + rr(-0.8, 0.8), rr(-0.3, 0.3), rr(1, 2.2), rr(-0.3, 0.3), rr(4, 7), 1, 5, 0.08, 0.08, 0.07, 0.55, 0.3, -0.1); } + f.lamp.power = 3 + Math.sin(IV.time * 13 + i) * 0.6 + Math.sin(IV.time * 31) * 0.4; + if (f.t <= 0) { f.lamp.on = false; fires.splice(i, 1); } + } + for (let i = flares.length - 1; i >= 0; i--) { + const f = flares[i]; f.t -= dt; f.s.position.y += f.vy * dt; f.s.position.x += f.vx * dt; + f.lamp.x = f.s.position.x; f.lamp.y = f.s.position.y; f.lamp.z = f.s.position.z; f.lamp.power = 7 * Math.min(1, f.t / 4) * (0.9 + 0.1 * Math.sin(IV.time * 20)); + f.lamp.i = 0.9 * Math.min(1, f.t / 4); + if (Math.random() < 0.3) norm.emit(f.s.position.x, f.s.position.y + 0.3, f.s.position.z, 0, 0.2, 0, 3, 0.3, 1.2, 0.5, 0.5, 0.5, 0.3, 0.2, 0); + if (f.t <= 0 || f.s.position.y < W.height(f.s.position.x, f.s.position.z) + 1) { W.scene.remove(f.s); f.lamp.on = false; flares.splice(i, 1); } + } + }; + function updDecals(im, list, dt) { + for (let i = list.length - 1; i >= 0; i--) { const d = list[i]; d.t += dt; if (d.t > d.life) list.splice(i, 1); } + for (let i = 0; i < list.length; i++) { const d = list[i], fade = Math.min(1, (d.life - d.t) / 5), grow = Math.min(1, d.t * 4 + 0.3); M4.compose(d.p, d.q, S4.set(d.s * grow * fade, d.s * grow * fade, 1)); im.setMatrixAt(i, M4); } + im.count = list.length; im.instanceMatrix.needsUpdate = true; + } + FX.counts = () => ({ add: add.n, norm: norm.n, tracers: tracers.length, decals: decals.length }); +})(); diff --git a/e63334287a3deaa3/ironveil/js/hud.js b/e63334287a3deaa3/ironveil/js/hud.js new file mode 100644 index 00000000..34c44019 --- /dev/null +++ b/e63334287a3deaa3/ironveil/js/hud.js @@ -0,0 +1,274 @@ +/* Ironveil HUD: DOM panels in the corners (objectives, weapon and ammo, stance and noise, squad order), subtitles, + prompts and toasts, and one canvas drawn each frame for the reticle, the awareness arcs (white -> yellow -> red), + the compass with objective and tagged-soldier markers, hit markers, damage direction, the scope (drop marks for + 100/200/300 m and the wind arrow), binoculars (range), and blood flecks at the screen edge when you're hit. */ +(function () { + 'use strict'; + const $ = IV.$, W = IV.world, T = IV.TUNING; + const H = IV.hud = {}; + let cv, g, dpr = 1, hitT = 0, hitKill = false, hitHead = false, dmgT = 0, sup = 0, barks = [], fleckT = 0, flecks = []; + const P = IV.player; + H.init = function () { + cv = $('hudc'); g = cv.getContext('2d'); + IV.on('hitmarker', h => { hitT = 0.28; hitKill = h.kill; hitHead = h.head; }); + IV.on('hurt', h => { dmgT = 1; fleckT = 1.2; makeFlecks(h.dmg); H.dmgDir = { a: P.hurtDir, x: h.from ? h.from.x : null, z: h.from ? h.from.z : null, t: 1.6 }; }); + IV.on('shot', k => { H.kickK = Math.min(1.6, (H.kickK || 0) + (k === 'rifle' ? 1.2 : k === 'pistol' ? 0.8 : 0.45)); }); + IV.on('suppressed', k => { sup = Math.min(1, sup + k * 0.6); }); + IV.on('objectives', () => H.objectives()); + IV.on('tagged', e => H.toast(IV.t('Soldier marked'))); + }; + H.show = function (on) { $('hud').hidden = !on; if (!on) { g && g.clearRect(0, 0, cv.width, cv.height); $('dmg').style.opacity = 0; } }; + + // ---------------------------------------------------------------- DOM parts + H.objectives = function () { + const M = IV.mission, box = $('obj'); + const list = M.objs.filter(o => o.state === 'active' || (o.state === 'done' && IV.time - o.t < 5)); + let html = list.length ? `
${IV.t('Objectives')}
` : ''; + for (const o of list) { + html += `
${esc(IV.t(o.text))}${o.optional ? ' (' + IV.t('optional') + ')' : ''}
`; + o.isNew = false; + } + box.innerHTML = html; + }; + const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + H.subtitle = function (who, text) { + const el = $('sub'); + if (!who) { el.hidden = true; return; } + el.hidden = false; el.innerHTML = `${esc(IV.t(who))}:${esc(text)}`; + }; + let toastT = null; + H.toast = function (t) { const el = $('toast'); el.textContent = t; el.classList.add('on'); clearTimeout(toastT); toastT = setTimeout(() => el.classList.remove('on'), 2600); }; + H.bark = function (e, text) { barks.push({ e, text, t: 2.6 }); if (barks.length > 4) barks.shift(); }; + const STANCE_SVG = { + stand: '', + crouch: '', + prone: '' + }; + let lastStance = '', lastW = '', lastNoise = -1, lastSquad = ''; + function dom() { + const WP = IV.weapons; + if (P.stance !== lastStance) { lastStance = P.stance; $('stanceIc').innerHTML = STANCE_SVG[P.stance]; $('stanceTx').textContent = IV.t(P.stance === 'stand' ? 'Standing' : P.stance === 'crouch' ? 'Crouched' : 'Prone'); } + const n = Math.round(IV.clamp(P.noise / 3.5, 0, 5)); + if (n !== lastNoise) { lastNoise = n; const is = $('noise').children; for (let i = 0; i < 5; i++) { is[i].className = i < n ? (n >= 4 ? 'on hi' : 'on') : ''; } } + const inv = WP.inv && WP.inv[WP.cur]; + const ws = WP.binoc ? 'binoc' : WP.busyThrow ? WP.busyThrow.kind + (WP.busyThrow.kind === 'grenade' ? Math.ceil(T.weapons.grenade.fuse - (IV.time - WP.busyThrow.t0)) : '') : WP.cur + (inv ? inv.mag + '/' + inv.res : '') + (WP.reloadT > 0 ? 'r' : '') + WP.inv.grenades; + if (ws !== lastW) { + lastW = ws; + if (WP.binoc) { $('wName').textContent = IV.t('Binoculars'); $('wAmmo').innerHTML = ''; } + else if (WP.busyThrow) { $('wName').textContent = IV.t(WP.busyThrow.kind === 'grenade' ? 'Grenade' : 'Rock'); $('wAmmo').innerHTML = WP.busyThrow.kind === 'grenade' ? `${Math.max(0, Math.ceil(T.weapons.grenade.fuse - (IV.time - WP.busyThrow.t0)))} ${IV.t('s fuse')}` : ''; } + else { $('wName').textContent = WP.name(WP.cur); const low = inv.mag <= Math.ceil(T.weapons[WP.cur].mag * 0.25); $('wAmmo').innerHTML = WP.reloadT > 0 ? `${IV.t('Reloading')}` : `${inv.mag} / ${inv.res}`; } + $('wGear').innerHTML = `${IV.t('Grenades')} ${WP.inv.grenades}${IV.t('Rocks')} ∞`; + } + const AL = IV.ally; + const sq = AL.ent && AL.met ? (AL.ent.alive ? AL.mode : 'down') : ''; + if (sq !== lastSquad) { lastSquad = sq; $('squad').innerHTML = sq ? `${esc(AL.NAME)}: ${IV.t(sq === 'follow' ? 'Following' : sq === 'hold' ? 'Holding' : sq === 'fire' ? 'Fire at will' : 'Down')} [${esc(IV.input.label('order'))}]` : ''; } + // prompt: interactable or takedown + const pr = $('prompt'), M = IV.mission; + let ptxt = null, prog = 0, key = ''; + if (IV.weapons.takedownTarget && !P.frozen) { ptxt = IV.t('Takedown'); key = IV.touch ? IV.t('Use') : IV.input.label('knife'); } + else if (M.interAt) { ptxt = IV.t(M.interAt.text); prog = M.interAt.prog; key = IV.touch ? IV.t('Use') : IV.input.label('use'); } + else if (H.hint) { ptxt = H.hint.text; key = H.hint.key || ''; } + else if (WP.inv && WP.inv[WP.cur] && WP.inv[WP.cur].mag === 0 && WP.inv[WP.cur].res > 0 && WP.reloadT <= 0) { ptxt = IV.t('Reload'); key = IV.touch ? '' : IV.input.label('reload'); } + if (ptxt) { + pr.hidden = false; + const html = `${key ? `${esc(key)}` : ''}${esc(ptxt)}${M.interAt && M.interAt.hold > 0.3 && !IV.weapons.takedownTarget ? `` : ''}`; + if (pr._h !== html) { pr.innerHTML = html; pr._h = html; } + } else pr.hidden = true; + // damage vignette + const hp = P.hp / T.health.max; + $('dmg').style.opacity = String(Math.max(dmgT * 0.7, (1 - hp) * 0.85, sup * 0.35)); + // badly hurt: the colour drains out of the world until you recover + const lowK = IV.clamp((0.45 - hp) / 0.35, 0, 1); if (Math.abs(lowK - (H._lowK || 0)) > 0.02) { H._lowK = lowK; $('view').style.filter = lowK > 0 ? `saturate(${1 - lowK * 0.7}) contrast(${1 + lowK * 0.1})` : ''; } + } + function makeFlecks(dmg) { + if (!IV.settings.blood) { flecks = []; return; } + const R = Math.random, n = 5 + Math.min(10, dmg / 3 | 0); + flecks = []; + for (let i = 0; i < n; i++) { const side = R() < 0.5 ? 0 : 1, a = R(); flecks.push({ x: side ? 0.88 + R() * 0.12 : R() * 0.12, y: a, r: 6 + R() * 22, o: 0.5 + R() * 0.5 }); } + } + + // ---------------------------------------------------------------- canvas + const v = new THREE.Vector3(); + function project(x, y, z) { v.set(x, y, z).project(W.camera); return { x: (v.x + 1) / 2 * cv.width, y: (1 - v.y) / 2 * cv.height, behind: v.z > 1 }; } + H.frame = function (dt) { + if (!cv || $('hud').hidden) return; + dom(); + hitT = Math.max(0, hitT - dt); dmgT = Math.max(0, dmgT - dt * 1.4); sup = Math.max(0, sup - dt * 0.6); fleckT = Math.max(0, fleckT - dt * 0.5); + const w = cv.width, h = cv.height; dpr = w / innerWidth; + g.clearRect(0, 0, w, h); + const WP = IV.weapons, C = IV.camera, cx = w / 2, cy = h / 2, u = dpr; + if (C.mode === 'scope' && WP.scoped) drawScope(w, h, u); + else if (WP.binoc && C.mode === 'scope') drawBinoc(w, h, u); + else if (P.alive && !P.cine && !P.sprinting && !(WP.reloadT > 0) && !(C.mode === 'first' && (WP.aiming || WP.scoped))) drawReticle(cx, cy, u, dt); // no crosshair while sprinting, reloading or looking down the sights + if (C.mode !== 'scope') drawHit(cx, cy, u); + drawGrenadeWarn(cx, cy, u); + drawAwareness(cx, cy, u); + drawCompass(w, u); + drawMarkers(u); + drawBarks(u, dt); + if (H.dmgDir && H.dmgDir.t > 0) { H.dmgDir.t -= dt; const a = H.dmgDir.x != null ? IV.wrapA(IV.yawTo(H.dmgDir.x - P.pos.x, H.dmgDir.z - P.pos.z) - P.yaw) : H.dmgDir.a, r = 120 * u; g.save(); g.translate(cx, cy); g.rotate(-a); g.fillStyle = `rgba(200,30,20,${Math.min(0.8, H.dmgDir.t)})`; g.beginPath(); g.moveTo(-26 * u, -r); g.quadraticCurveTo(0, -r - 16 * u, 26 * u, -r); g.lineTo(0, -r + 10 * u); g.closePath(); g.fill(); g.restore(); } + if (fleckT > 0 && flecks.length) { for (const f of flecks) { g.fillStyle = `rgba(110,8,4,${f.o * Math.min(1, fleckT)})`; g.beginPath(); g.ellipse(f.x * w, f.y * h, f.r * u, f.r * 0.7 * u, f.x, 0, 6.29); g.fill(); } } + }; + // an enemy grenade within lethal range: an icon by the crosshair with an arrow toward it + function drawGrenadeWarn(cx, cy, u) { + const g = IV.weapons.throws.find(g => g.kind === 'grenade' && g.enemy && Math.hypot(g.x - P.pos.x, g.z - P.pos.z) < IV.TUNING.weapons.grenade.radius + 2); + if (!g) return; + const a = IV.wrapA(IV.yawTo(g.x - P.pos.x, g.z - P.pos.z) - P.yaw), r = 92 * u, x = cx - Math.sin(a) * r, y = cy - Math.cos(a) * r, k = 0.6 + 0.4 * Math.sin(IV.time * 14); + g2(x, y, u, k, a); + } + function g2(x, y, u, k, a) { + g.save(); g.translate(x, y); g.globalAlpha = k; + g.fillStyle = 'rgba(10,8,6,.7)'; g.beginPath(); g.arc(0, 0, 15 * u, 0, 6.29); g.fill(); + g.fillStyle = '#cf4630'; g.beginPath(); g.ellipse(0, 2 * u, 6 * u, 8 * u, 0, 0, 6.29); g.fill(); g.fillRect(-2 * u, -9 * u, 4 * u, 4 * u); + g.rotate(-a); g.beginPath(); g.moveTo(0, -24 * u); g.lineTo(-6 * u, -16 * u); g.lineTo(6 * u, -16 * u); g.closePath(); g.fill(); + g.restore(); + } + // the crosshair: four marks whose gap is the real spread cone at this field of view (it opens while you move, crouch + // and prone tighten it, the SMG blooms as it fires), eased so it breathes instead of jumping, plus a kick on every + // shot. In first person it goes away while you look down the sights (the sights are the crosshair then). + function drawReticle(cx, cy, u, dt) { + const WP = IV.weapons; + const ppr = (cv.height / 2) / Math.tan(W.camera.fov * Math.PI / 360), want = Math.tan(WP.currentSpread()) * ppr / u + 3; + H.kickK = Math.max(0, (H.kickK || 0) - dt * 5); + H.gap = H.gap == null ? want : H.gap + (want - H.gap) * (1 - Math.exp(-dt * 14)); + const sp = H.gap + H.kickK * 9; + g.strokeStyle = 'rgba(240,232,210,.88)'; g.lineWidth = 2 * u; g.shadowColor = 'rgba(0,0,0,.8)'; g.shadowBlur = 3 * u; + if (WP.busyThrow) { g.beginPath(); g.arc(cx, cy, 3 * u, 0, 6.29); g.stroke(); } + else { + const s = sp * u, l = 8 * u; + g.beginPath(); g.moveTo(cx - s - l, cy); g.lineTo(cx - s, cy); g.moveTo(cx + s, cy); g.lineTo(cx + s + l, cy); g.moveTo(cx, cy + s); g.lineTo(cx, cy + s + l); g.moveTo(cx, cy - s - l); g.lineTo(cx, cy - s); g.stroke(); + g.fillStyle = 'rgba(240,232,210,.9)'; g.fillRect(cx - u, cy - u, 2 * u, 2 * u); + } + g.shadowBlur = 0; + } + // hit marker: four ticks round the centre, white on a hit, warm on a kill, red on a head kill; shown in ADS too + function drawHit(cx, cy, u) { + if (hitT <= 0) return; + const k = 6 * u + (0.28 - hitT) * 20 * u, c = hitKill ? (hitHead ? '#ff5a3c' : '#f2e2c0') : '#fff'; + g.strokeStyle = c; g.lineWidth = (hitKill ? 3 : 2) * u; g.shadowColor = 'rgba(0,0,0,.8)'; g.shadowBlur = 3 * u; + g.beginPath(); for (const [a, b] of [[-1, -1], [1, -1], [-1, 1], [1, 1]]) { g.moveTo(cx + a * k, cy + b * k); g.lineTo(cx + a * (k + 8 * u), cy + b * (k + 8 * u)); } g.stroke(); + g.shadowBlur = 0; + } + // awareness: one arc per soldier who has noticed something, placed round the reticle in his direction + function drawAwareness(cx, cy, u) { + if (!IV.ai) return; + const R = 64 * u; + for (const e of IV.ai.list) { + if (!e.alive) continue; + const aw = e.state === 'combat' ? 1 : Math.min(1, e.aw); + if (aw < 0.04 && e.state === 'unaware') continue; + const a = IV.wrapA(IV.yawTo(e.pos.x - P.pos.x, e.pos.z - P.pos.z) - P.yaw); + const ang = -Math.PI / 2 - a, span = 0.38; + const col = e.state === 'combat' ? '207,70,48' : aw >= T.ai.investigate || e.state === 'searching' || e.state === 'investigating' ? '232,197,71' : '240,232,210'; + g.lineCap = 'round'; + g.strokeStyle = 'rgba(0,0,0,.35)'; g.lineWidth = 6 * u; g.beginPath(); g.arc(cx, cy, R, ang - span / 2, ang + span / 2); g.stroke(); + g.strokeStyle = `rgba(${col},${0.35 + aw * 0.65})`; g.lineWidth = 4 * u; g.beginPath(); g.arc(cx, cy, R, ang - span / 2, ang - span / 2 + span * Math.max(0.08, aw)); g.stroke(); + // the stinger when someone first gets suspicious / spots you + const lvl = e.state === 'combat' ? 3 : aw >= T.ai.suspicious ? 1 : 0; + if (lvl > (e._hudL || 0)) IV.audio.play(lvl >= 3 ? 'sting2' : 'sting1'); + e._hudL = lvl; + } + g.lineCap = 'butt'; + } + function drawCompass(w, u) { + const cw = Math.min(460 * u, w * 0.5), x0 = (w - cw) / 2, y = 22 * u, span = Math.PI * 0.9; + g.fillStyle = 'rgba(10,11,8,.35)'; g.fillRect(x0, y - 12 * u, cw, 26 * u); + g.font = `600 ${13 * u}px "Barlow Condensed", sans-serif`; g.textAlign = 'center'; g.textBaseline = 'middle'; + const labels = { 0: 'N', 45: 'NW', 90: 'W', 135: 'SW', 180: 'S', 225: 'SE', 270: 'E', 315: 'NE' }; + for (let d = 0; d < 360; d += 15) { + const a = IV.wrapA(d * Math.PI / 180 - P.yaw); if (Math.abs(a) > span / 2) continue; + const x = w / 2 - a / span * cw; + if (labels[d] != null) { g.fillStyle = labels[d].length === 1 ? '#ece3cc' : 'rgba(236,227,204,.6)'; g.fillText(IV.t(labels[d]), x, y); } + else { g.fillStyle = 'rgba(236,227,204,.35)'; g.fillRect(x - 0.5 * u, y - 3 * u, u, 6 * u); } + } + const pin = (wx, wz, col, shape) => { + const a = IV.wrapA(IV.yawTo(wx - P.pos.x, wz - P.pos.z) - P.yaw), cl = IV.clamp(a, -span / 2, span / 2), x = w / 2 - cl / span * cw; + g.fillStyle = col; + if (shape === 'dia') { g.beginPath(); g.moveTo(x, y + 6 * u); g.lineTo(x + 6 * u, y + 12 * u); g.lineTo(x, y + 18 * u); g.lineTo(x - 6 * u, y + 12 * u); g.fill(); } + else { g.beginPath(); g.arc(x, y + 12 * u, 3 * u, 0, 6.29); g.fill(); } + }; + for (const o of IV.mission.objs) if (o.state === 'active' && o.marker) pin(o.marker.x, o.marker.z, o.optional ? '#c3b091' : '#d0a84c', 'dia'); + for (const e of IV.ai.list) if (e.alive && e.tagged) pin(e.pos.x, e.pos.z, '#e8c547'); + if (IV.ally.ent && IV.ally.ent.alive) pin(IV.ally.ent.pos.x, IV.ally.ent.pos.z, '#9fbf8a'); + g.fillStyle = '#ece3cc'; g.fillRect(w / 2 - u, y - 14 * u, 2 * u, 6 * u); + } + function drawMarkers(u) { + g.textAlign = 'center'; g.textBaseline = 'bottom'; g.font = `600 ${13 * u}px "Barlow Condensed", sans-serif`; + // tagged soldiers: a small chevron over the head, through walls, with the range + for (const e of IV.ai.list) { + if (!e.alive || !e.tagged) continue; + const p = project(e.pos.x, e.pos.y + 2.05, e.pos.z); if (p.behind) continue; + const d = Math.round(Math.hypot(e.pos.x - P.pos.x, e.pos.z - P.pos.z)); + const col = e.state === 'combat' ? '#cf4630' : e.state === 'unaware' ? '#ece3cc' : '#e8c547'; + g.fillStyle = col; g.beginPath(); g.moveTo(p.x - 6 * u, p.y - 8 * u); g.lineTo(p.x, p.y); g.lineTo(p.x + 6 * u, p.y - 8 * u); g.lineTo(p.x, p.y - 4 * u); g.fill(); + if (d < 200) { g.fillStyle = 'rgba(236,227,204,.75)'; g.fillText(d + ' m', p.x, p.y - 10 * u); } + } + // objective marker in the world (only active, with a marker, within 400 m, faded when close) + for (const o of IV.mission.objs) { + if (o.state !== 'active' || !o.marker || o.noWorld) continue; + const m = o.marker, d = Math.hypot(m.x - P.pos.x, m.z - P.pos.z); if (d < 4) continue; + const p = project(m.x, m.y != null ? m.y : W.height(m.x, m.z) + 1.5, m.z); if (p.behind) continue; + g.globalAlpha = IV.clamp((d - 4) / 10, 0.2, 0.9); + g.strokeStyle = o.optional ? '#c3b091' : '#d0a84c'; g.lineWidth = 2 * u; + g.beginPath(); g.moveTo(p.x, p.y - 9 * u); g.lineTo(p.x + 7 * u, p.y - 2 * u); g.lineTo(p.x, p.y + 5 * u); g.lineTo(p.x - 7 * u, p.y - 2 * u); g.closePath(); g.stroke(); + g.fillStyle = '#ece3cc'; g.fillText(Math.round(d) + ' m', p.x, p.y - 12 * u); + g.globalAlpha = 1; + } + } + function drawBarks(u, dt) { + g.font = `italic 500 ${15 * u}px "Barlow Condensed", sans-serif`; g.textAlign = 'center'; g.textBaseline = 'bottom'; + for (let i = barks.length - 1; i >= 0; i--) { + const b = barks[i]; b.t -= dt; if (b.t <= 0) { barks.splice(i, 1); continue; } + const p = project(b.e.pos.x, b.e.pos.y + 2.2, b.e.pos.z); if (p.behind) continue; + g.globalAlpha = Math.min(1, b.t); + g.fillStyle = 'rgba(0,0,0,.6)'; const tw = g.measureText(b.text).width + 10 * u; g.fillRect(p.x - tw / 2, p.y - 20 * u, tw, 20 * u); + g.fillStyle = '#f0e6c8'; g.fillText(b.text, p.x, p.y - 3 * u); + g.globalAlpha = 1; + } + } + // scope: black surround, fine crosshair, drop marks for 100/200/300 m, wind arrow, breath meter + function drawScope(w, h, u) { + const cx = w / 2, cy = h / 2, r = Math.min(w, h) * 0.46; + g.fillStyle = '#000'; g.beginPath(); g.rect(0, 0, w, h); g.moveTo(cx + r, cy); g.arc(cx, cy, r, 0, 6.29, true); g.fill(); // moveTo: without it the arc joins (0,0) with a thin diagonal sliver + const grd = g.createRadialGradient(cx, cy, r * 0.82, cx, cy, r); grd.addColorStop(0, 'rgba(0,0,0,0)'); grd.addColorStop(1, 'rgba(0,0,0,.85)'); g.fillStyle = grd; g.beginPath(); g.arc(cx, cy, r, 0, 6.29); g.fill(); + // pixels per radian at the current fov + const fov = W.camera.fov * Math.PI / 180, ppr = (h / 2) / Math.tan(fov / 2); + g.strokeStyle = 'rgba(10,10,10,.95)'; g.lineWidth = 1.6 * u; + g.beginPath(); g.moveTo(cx - r, cy); g.lineTo(cx - 14 * u, cy); g.moveTo(cx + 14 * u, cy); g.lineTo(cx + r, cy); g.moveTo(cx, cy - r); g.lineTo(cx, cy - 10 * u); g.moveTo(cx, cy + 6 * u); g.lineTo(cx, cy + r); g.stroke(); + g.lineWidth = 4 * u; g.beginPath(); g.moveTo(cx - r, cy); g.lineTo(cx - r * 0.55, cy); g.moveTo(cx + r * 0.55, cy); g.lineTo(cx + r, cy); g.moveTo(cx, cy + r * 0.55); g.lineTo(cx, cy + r); g.stroke(); + g.fillStyle = 'rgba(10,10,10,.95)'; g.font = `600 ${12 * u}px "Barlow Condensed", sans-serif`; g.textAlign = 'left'; g.textBaseline = 'middle'; + for (const m of IV.weapons.marks) { + if (m.d === 100) continue; + const y = cy + Math.tan(m.ang - 0) * ppr; + g.fillRect(cx - 9 * u, y - 0.8 * u, 18 * u, 1.6 * u); + g.fillText(String(m.d / 100), cx + 12 * u, y); + } + g.fillText('1', cx + 12 * u, cy - 7 * u); + // the soldier under the reticle: range (rangefinding by the marks is the skill; this helps on Recruit) + const wind = IV.weapons.wind, wy = IV.wrapA(Math.atan2(-wind.x, -wind.z) - P.yaw), ws = Math.hypot(wind.x, wind.z); + const bx = cx + r * 0.62, by = cy + r * 0.62; + g.save(); g.translate(bx, by); g.fillStyle = 'rgba(236,227,204,.9)'; g.font = `600 ${13 * u}px "Barlow Condensed", sans-serif`; g.textAlign = 'center'; + g.fillText(IV.t('Wind {s} m/s', { s: ws.toFixed(1) }), 0, 26 * u); + g.rotate(-wy + Math.PI); g.strokeStyle = 'rgba(236,227,204,.9)'; g.lineWidth = 2 * u; g.beginPath(); g.moveTo(0, -14 * u); g.lineTo(0, 14 * u); g.moveTo(-6 * u, 7 * u); g.lineTo(0, 14 * u); g.lineTo(6 * u, 7 * u); g.stroke(); g.restore(); + if (IV.mission.diff === 0) { const pt = IV.weapons.camRayPoint(); const d = Math.hypot(pt.x - W.camera.position.x, pt.z - W.camera.position.z); g.fillStyle = 'rgba(236,227,204,.85)'; g.textAlign = 'center'; g.fillText(d > 590 ? '---' : Math.round(d) + ' m', cx - r * 0.62, cy + r * 0.62 + 26 * u); } + // breath + const C = IV.camera; g.fillStyle = 'rgba(236,227,204,.25)'; g.fillRect(cx - 60 * u, cy + r + 10 * u > h - 20 * u ? h - 24 * u : cy + r * 0.88, 120 * u, 4 * u); + g.fillStyle = C.breath < 0.2 ? '#cf4630' : '#ece3cc'; g.fillRect(cx - 60 * u, cy + r + 10 * u > h - 20 * u ? h - 24 * u : cy + r * 0.88, 120 * u * C.breath, 4 * u); + if (hitT > 0) { g.strokeStyle = hitKill ? '#ff5a3c' : '#fff'; g.lineWidth = 2 * u; const k = 10 * u; g.beginPath(); for (const [a, b] of [[-1, -1], [1, -1], [-1, 1], [1, 1]]) { g.moveTo(cx + a * k, cy + b * k); g.lineTo(cx + a * (k + 8 * u), cy + b * (k + 8 * u)); } g.stroke(); } + } + function drawBinoc(w, h, u) { + const cx = w / 2, cy = h / 2, r = Math.min(w * 0.27, h * 0.44); + g.fillStyle = '#000'; g.beginPath(); g.rect(0, 0, w, h); g.arc(cx - r * 0.82, cy, r, 0, 6.29, true); g.arc(cx + r * 0.82, cy, r, 0, 6.29, true); g.fill('evenodd'); + g.fillStyle = '#000'; g.beginPath(); g.rect(0, 0, w, h); g.fill(); // repaint with holes properly + g.globalCompositeOperation = 'destination-out'; g.beginPath(); g.arc(cx - r * 0.82, cy, r, 0, 6.29); g.arc(cx + r * 0.82, cy, r, 0, 6.29); g.fill(); g.globalCompositeOperation = 'source-over'; + g.strokeStyle = 'rgba(236,227,204,.7)'; g.lineWidth = 1.2 * u; + for (let i = -4; i <= 4; i++) { g.beginPath(); g.moveTo(cx + i * 22 * u, cy - (i % 2 ? 5 : 9) * u); g.lineTo(cx + i * 22 * u, cy); g.stroke(); } + g.beginPath(); g.moveTo(cx - 90 * u, cy); g.lineTo(cx + 90 * u, cy); g.stroke(); + const pt = IV.weapons.camRayPoint(), d = Math.hypot(pt.x - W.camera.position.x, pt.z - W.camera.position.z); + g.fillStyle = 'rgba(236,227,204,.9)'; g.font = `600 ${16 * u}px "Barlow Condensed", sans-serif`; g.textAlign = 'center'; + g.fillText(IV.t('Range') + ' ' + (d > 590 ? '---' : Math.round(d) + ' m'), cx, cy + 30 * u); + g.font = `500 ${14 * u}px "Barlow Condensed", sans-serif`; g.fillStyle = 'rgba(236,227,204,.7)'; + g.fillText(IV.touch ? IV.t('Tap Fire to mark the soldier in the middle') : IV.t('{k} marks the soldier in the middle', { k: IV.input.label('fire') }), cx, cy + r * 0.8); + } + H.reset = function () { barks = []; flecks = []; fleckT = 0; dmgT = 0; sup = 0; lastStance = lastW = lastSquad = ''; lastNoise = -1; H.hint = null; }; +})(); diff --git a/e63334287a3deaa3/ironveil/js/input.js b/e63334287a3deaa3/ironveil/js/input.js new file mode 100644 index 00000000..99242139 --- /dev/null +++ b/e63334287a3deaa3/ironveil/js/input.js @@ -0,0 +1,101 @@ +/* Ironveil input: rebindable keys (keybinds.js), mouse look with pointer lock, and one action map that keyboard, mouse + and the touch controls all feed. Game code asks IV.input.held('aim'), .pressed('fire') (this step only), etc. */ +(function () { + 'use strict'; + const I = IV.input = { dx: 0, dy: 0, wheel: 0, locked: false, everLocked: false, fallback: false, moveX: 0, moveY: 0 }; + const KB = I.KB = Keybinds.create({ + game: 'ironveil', mouse: true, + actions: [ + { id: 'forward', label: 'Move forward', group: 'Move', keys: ['KeyW', 'ArrowUp'] }, + { id: 'back', label: 'Move back', group: 'Move', keys: ['KeyS', 'ArrowDown'] }, + { id: 'left', label: 'Move left', group: 'Move', keys: ['KeyA', 'ArrowLeft'] }, + { id: 'right', label: 'Move right', group: 'Move', keys: ['KeyD', 'ArrowRight'] }, + { id: 'sprint', label: 'Sprint', note: 'Hold', group: 'Move', keys: ['ShiftLeft'] }, + { id: 'crouch', label: 'Crouch', group: 'Move', keys: ['KeyC', 'ControlLeft'] }, + { id: 'prone', label: 'Go prone', group: 'Move', keys: ['KeyZ'] }, + { id: 'vault', label: 'Vault over / stand up', group: 'Move', keys: ['Space'] }, + { id: 'leanLeft', label: 'Lean left', note: 'Hold', group: 'Move', keys: ['KeyQ'] }, + { id: 'leanRight', label: 'Lean right', note: 'Hold', group: 'Move', keys: ['KeyE'] }, + { id: 'fire', label: 'Fire', group: 'Fight', keys: ['Mouse0'] }, + { id: 'aim', label: 'Aim', note: 'Hold. The rifle goes to its scope', group: 'Fight', keys: ['Mouse2'] }, + { id: 'breath', label: 'Hold breath (scoped)', group: 'Fight', ctx: 'scope', keys: ['ShiftLeft'] }, + { id: 'reload', label: 'Reload', group: 'Fight', keys: ['KeyR'] }, + { id: 'rifle', label: 'Scoped rifle', group: 'Fight', keys: ['Digit1'] }, + { id: 'smg', label: 'Submachine gun', group: 'Fight', keys: ['Digit2'] }, + { id: 'pistol', label: 'Pistol', group: 'Fight', keys: ['Digit3'] }, + { id: 'grenade', label: 'Grenade', note: 'Hold to cook and aim, let go to throw', group: 'Fight', keys: ['KeyG'] }, + { id: 'rock', label: 'Throw a rock', note: 'Hold to aim, let go to throw. Guards go to look', group: 'Fight', keys: ['KeyX'] }, + { id: 'knife', label: 'Knife takedown', note: 'From behind, close up', group: 'Fight', keys: ['KeyV'] }, + { id: 'binoc', label: 'Binoculars', note: 'Hold. Fire tags the soldier in the middle', group: 'Fight', keys: ['KeyB'] }, + { id: 'use', label: 'Use / interact', note: 'Hold for longer jobs', group: 'Other', keys: ['KeyF'] }, + { id: 'order', label: 'Squad order', note: 'Follow, hold, fire at will', group: 'Other', keys: ['KeyT'] }, + { id: 'shoulder', label: 'Swap shoulder (over-the-shoulder view)', group: 'Other', keys: ['KeyH'] }, + { id: 'mute', label: 'Mute', group: 'Other', keys: ['KeyM'] }, + { id: 'pause', label: 'Pause', group: 'Other', keys: ['KeyP'], lock: ['Escape'] } + ], + classes: { button: 'btn', primary: 'cta' } + }); + const keys = new Set(), edgesDown = new Set(), edgesUp = new Set(); + const stepDown = new Set(), stepUp = new Set(); + I.tAct = {}; // touch actions held + I.tEdge = new Set(); I.tEdgeUp = new Set(); + I.held = id => !!I.tAct[id] || KB.held(id, keys); + I.pressed = id => stepDown.has(id); + I.released = id => stepUp.has(id); + I.label = id => KB.short ? KB.short(id) : KB.label(id); + // called at the start of each simulation step: move this frame's edges into the step's sets + I.beginStep = function () { + stepDown.clear(); stepUp.clear(); + edgesDown.forEach(c => KB.actionsFor(c).forEach(a => stepDown.add(a))); + edgesUp.forEach(c => KB.actionsFor(c).forEach(a => stepUp.add(a))); + I.tEdge.forEach(a => stepDown.add(a)); I.tEdgeUp.forEach(a => stepUp.add(a)); + edgesDown.clear(); edgesUp.clear(); I.tEdge.clear(); I.tEdgeUp.clear(); + // movement axes + let x = (I.held('right') ? 1 : 0) - (I.held('left') ? 1 : 0), y = (I.held('forward') ? 1 : 0) - (I.held('back') ? 1 : 0); + if (I.stick && (I.stick.x || I.stick.y)) { x = I.stick.x; y = I.stick.y; } + const l = Math.hypot(x, y); if (l > 1) { x /= l; y /= l; } + I.moveX = x; I.moveY = y; + }; + // test hook: press/release an action by name + I.sim = function (id, on) { if (on) { if (!I.tAct[id]) I.tEdge.add(id); I.tAct[id] = true; } else { if (I.tAct[id]) I.tEdgeUp.add(id); I.tAct[id] = false; } }; + I.clear = function () { keys.clear(); for (const k in I.tAct) I.tAct[k] = false; I.dx = I.dy = 0; }; + + const gameKey = c => KB.actionsFor(c).length > 0; + addEventListener('keydown', e => { + if (KB.busy()) return; + if (e.code === 'Escape') { IV.emit('escape'); return; } + if (!IV.playing()) { if (e.code === 'KeyM') IV.emit('mute'); return; } + if (gameKey(e.code) || e.code === 'Tab') e.preventDefault(); + if (!e.repeat && !keys.has(e.code)) { keys.add(e.code); edgesDown.add(e.code); } + }); + addEventListener('keyup', e => { if (keys.has(e.code)) { keys.delete(e.code); edgesUp.add(e.code); } }); + addEventListener('blur', () => { keys.forEach(c => edgesUp.add(c)); keys.clear(); }); + const view = IV.$('view'); + view.addEventListener('mousedown', e => { + if (!IV.playing() || IV.touch) return; + if (!I.locked && !I.fallback) { I.requestLock(true); return; } + const c = 'Mouse' + e.button; if (!keys.has(c)) { keys.add(c); edgesDown.add(c); } + e.preventDefault(); + }); + addEventListener('mouseup', e => { const c = 'Mouse' + e.button; if (keys.has(c)) { keys.delete(c); edgesUp.add(c); } }); + view.addEventListener('contextmenu', e => e.preventDefault()); + addEventListener('wheel', e => { if (IV.playing()) I.wheel += Math.sign(e.deltaY); }, { passive: true }); + document.addEventListener('mousemove', e => { + if (!IV.playing()) return; + if (!I.locked && !(I.fallback && e.buttons)) return; + I.dx += e.movementX || 0; I.dy += e.movementY || 0; + }); + I.requestLock = function (fromClick) { + if (I.fallback || I.locked || IV.touch || IV.test) return; + I._fromClick = !!fromClick; + try { const r = view.requestPointerLock(); if (r && r.catch) r.catch(onLockError); } catch (e) { onLockError(); } + }; + function onLockError() { if (!I.everLocked && I._fromClick) I.fallback = true; } + document.addEventListener('pointerlockerror', onLockError); + document.addEventListener('pointerlockchange', () => { + I.locked = document.pointerLockElement === view; + if (I.locked) I.everLocked = true; + else if (IV.playing() && !IV.test) IV.emit('lostlock'); + }); + I.unlock = function () { if (document.pointerLockElement) document.exitPointerLock(); }; +})(); diff --git a/e63334287a3deaa3/ironveil/js/kit.js b/e63334287a3deaa3/ironveil/js/kit.js new file mode 100644 index 00000000..44625bb8 --- /dev/null +++ b/e63334287a3deaa3/ironveil/js/kit.js @@ -0,0 +1,537 @@ +/* Ironveil kit: builds the static world. Everything static is merged into one mesh per material (world-space box UVs so + texel density stays the same on every wall), and adds its colliders as it goes. Vegetation is instanced. + Builder use: const b = K.begin(); K.box(b, 'stone', ...); ... K.finish(b); */ +(function () { + 'use strict'; + const W = IV.world, F = IV.CF; + const K = IV.kit = {}; + // metres per texture repeat, per material + const UVS = { stone: 2.2, plaster: 2.6, wood: 1.6, roof: 2.4, metal: 1.2, cloth: 1.0, earth: 3, bark: 1.2, plain: 1, foliage: 2.5 }; + const _m = new THREE.Matrix4(), _q = new THREE.Quaternion(), _e = new THREE.Euler(), _v = new THREE.Vector3(), _s = new THREE.Vector3(), _n = new THREE.Matrix3(); + const _c = new THREE.Color(); + const GEO = { + box: new THREE.BoxGeometry(1, 1, 1).toNonIndexed(), + cyl8: new THREE.CylinderGeometry(0.5, 0.5, 1, 8, 1).toNonIndexed(), + cyl12: new THREE.CylinderGeometry(0.5, 0.5, 1, 12, 1).toNonIndexed(), + cone8: new THREE.CylinderGeometry(0, 0.5, 1, 8, 1).toNonIndexed(), + sph: new THREE.SphereGeometry(0.5, 10, 7).toNonIndexed(), + prism: (() => { // a triangular prism (gable ends, roof ridges): base on y=0 from x -0.5..0.5, apex at y=1, depth z -0.5..0.5 + const g = new THREE.BufferGeometry(); + const p = [-.5, 0, .5, .5, 0, .5, 0, 1, .5, .5, 0, -.5, -.5, 0, -.5, 0, 1, -.5, + -.5, 0, -.5, -.5, 0, .5, 0, 1, .5, -.5, 0, -.5, 0, 1, .5, 0, 1, -.5, + .5, 0, .5, .5, 0, -.5, 0, 1, -.5, .5, 0, .5, 0, 1, -.5, 0, 1, .5, + -.5, 0, .5, -.5, 0, -.5, .5, 0, -.5, -.5, 0, .5, .5, 0, -.5, .5, 0, .5]; + g.setAttribute('position', new THREE.Float32BufferAttribute(p, 3)); g.computeVertexNormals(); return g; + })() + }; + K.GEO = GEO; + + const ALBEDO = { plain: 1, foliage: 1, lit: 1, litDim: 1, dark: 1 }; + K.begin = function () { return { buckets: {}, foliage: [], trunks: [], cards: [] }; }; + function bucket(b, mat) { return b.buckets[mat] || (b.buckets[mat] = { p: [], n: [], u: [], c: [] }); } + + // Add a (non-indexed) geometry with a transform. color: hex or THREE.Color. ao: darken toward the bottom (0..1) + K.noMesh = false; // set by art.js when IVEnv draws the piece: only colliders are made + K.add = function (b, mat, geo, px, py, pz, sx, sy, sz, rx, ry, rz, color, ao) { + if (K.noMesh) return; + _e.set(rx || 0, ry || 0, rz || 0); _q.setFromEuler(_e); _v.set(px, py, pz); _s.set(sx, sy, sz); + _m.compose(_v, _q, _s); _n.getNormalMatrix(_m); + const B = bucket(b, mat), pa = geo.attributes.position.array, na = geo.attributes.normal.array, sc = 1 / (UVS[mat] || 2); + // untextured buckets take the colour as albedo (sRGB -> linear); textured ones as a tint over the sRGB texture + _c.set(color == null ? 0xffffff : color); if (ALBEDO[mat]) _c.convertSRGBToLinear(); else _c.multiplyScalar(1.25); + const n = pa.length / 3, e = _m.elements, ne = _n.elements; + let ymin = 1e9, ymax = -1e9; + if (ao) for (let i = 0; i < n; i++) { const y = e[1] * pa[i * 3] + e[5] * pa[i * 3 + 1] + e[9] * pa[i * 3 + 2] + e[13]; if (y < ymin) ymin = y; if (y > ymax) ymax = y; } + for (let i = 0; i < n; i++) { + const x = pa[i * 3], y = pa[i * 3 + 1], z = pa[i * 3 + 2]; + const wx = e[0] * x + e[4] * y + e[8] * z + e[12], wy = e[1] * x + e[5] * y + e[9] * z + e[13], wz = e[2] * x + e[6] * y + e[10] * z + e[14]; + let nx = ne[0] * na[i * 3] + ne[3] * na[i * 3 + 1] + ne[6] * na[i * 3 + 2], ny = ne[1] * na[i * 3] + ne[4] * na[i * 3 + 1] + ne[7] * na[i * 3 + 2], nz = ne[2] * na[i * 3] + ne[5] * na[i * 3 + 1] + ne[8] * na[i * 3 + 2]; + const l = Math.sqrt(nx * nx + ny * ny + nz * nz) || 1; nx /= l; ny /= l; nz /= l; + B.p.push(wx, wy, wz); B.n.push(nx, ny, nz); + const ax = Math.abs(nx), ay = Math.abs(ny), az = Math.abs(nz); + if (ay >= ax && ay >= az) B.u.push(wx * sc, wz * sc); else if (ax >= az) B.u.push(wz * sc, wy * sc); else B.u.push(wx * sc, wy * sc); + let k = 1; + if (ao) { const t = (wy - ymin) / Math.max(0.01, ymax - ymin); k = 1 - ao * (1 - Math.min(1, t * 3)) ; } + B.c.push(_c.r * k, _c.g * k, _c.b * k); + } + }; + // Box: centre x, bottom y0, centre z, size sx (width), sy (height), sz (depth), turned rot about Y. + // col: collider flags (0/undefined = none). surf: footstep/impact surface. + K.box = function (b, mat, x, y0, z, sx, sy, sz, rot, color, col, surf, ao) { + if (mat) K.add(b, mat, GEO.box, x, y0 + sy / 2, z, sx, sy, sz, 0, rot || 0, 0, color, ao); + if (col) return W.addBox(x, z, sx / 2, sz / 2, y0, y0 + sy, rot || 0, col, surf || (mat === 'wood' ? 'wood' : mat === 'metal' ? 'metal' : mat === 'cloth' ? 'cloth' : 'stone')); + }; + K.cyl = function (b, mat, x, y0, z, r, h, color, col, seg) { + K.add(b, mat, seg === 12 ? GEO.cyl12 : GEO.cyl8, x, y0 + h / 2, z, r * 2, h, r * 2, 0, 0, 0, color); + if (col) return W.addBox(x, z, r * 0.8, r * 0.8, y0, y0 + h, 0, col, mat === 'bark' ? 'wood' : 'metal'); + }; + + K.finish = function (b, parent) { + parent = parent || W.statics; + const out = []; + for (const k in b.buckets) { + const B = b.buckets[k]; if (!B.p.length) continue; + const g = new THREE.BufferGeometry(); + g.setAttribute('position', new THREE.Float32BufferAttribute(B.p, 3)); + g.setAttribute('normal', new THREE.Float32BufferAttribute(B.n, 3)); + g.setAttribute('uv', new THREE.Float32BufferAttribute(B.u, 2)); + g.setAttribute('color', new THREE.Float32BufferAttribute(B.c, 3)); + g.computeBoundingSphere(); + const m = new THREE.Mesh(g, W.mats[k] || W.mats.plain); + m.castShadow = k !== 'lit' && k !== 'litDim' && k !== 'dark'; m.receiveShadow = true; + m.matrixAutoUpdate = false; m.updateMatrix(); + parent.add(m); out.push(m); + } + // vegetation in 96 m chunks so whole chunks behind you or deep in the fog are skipped (W.frame culls them) + const chunks = (list, make) => { const m = new Map(); for (const f of list) { const k = Math.floor(f[0] / 96) * 100 + Math.floor(f[2] / 96); let a = m.get(k); if (!a) m.set(k, a = []); a.push(f); } for (const a of m.values()) { const im = make(a, parent); let cx = 0, cz = 0; for (const f of a) { cx += f[0]; cz += f[2]; } cx /= a.length; cz /= a.length; let r = 0; for (const f of a) r = Math.max(r, Math.hypot(f[0] - cx, f[2] - cz)); im.userData.cull = new THREE.Sphere(new THREE.Vector3(cx, W.height(cx, cz) + 4, cz), r + 8); im.frustumCulled = false; W.cullList.push(im); out.push(im); } }; + if (b.foliage.length) chunks(b.foliage, K.foliageMesh); + if (b.cards.length && W.quality > 0) chunks(b.cards, K.cardMesh); // Low: no leaf cards + return out; + }; + + // ---------------------------------------------------------------- vegetation (instanced) + let clumpGeo = null; + function makeClump() { // a lumpy, slightly flattened ball of leaves with darker, occluded underside + // High: a subdivided icosahedron (80 tris); Low/Medium: an octahedron (32 tris). Spherical normals hide the facets. + const g = W.quality >= 2 ? new THREE.IcosahedronGeometry(0.5, 1) : W.quality === 1 ? new THREE.OctahedronGeometry(0.5, 1) : new THREE.IcosahedronGeometry(0.5, 0), p = g.attributes.position, R = IV.rng(5); + const col = new Float32Array(p.count * 3); + const seen = new Map(); + for (let i = 0; i < p.count; i++) { + const x = p.getX(i), y = p.getY(i), z = p.getZ(i), key = x.toFixed(3) + y.toFixed(3) + z.toFixed(3); + let k = seen.get(key); if (k == null) { k = 0.82 + R() * 0.36; seen.set(key, k); } + p.setXYZ(i, x * k, y * k * 0.85 + 0.42, z * k); + const shade = 0.42 + 0.58 * IV.clamp((y + 0.5), 0, 1); + col[i * 3] = col[i * 3 + 1] = col[i * 3 + 2] = shade; + } + g.setAttribute('color', new THREE.BufferAttribute(col, 3)); + g.computeVertexNormals(); + // push normals outward (spherical) so lighting reads as a soft volume rather than facets + const n = g.attributes.normal; + for (let i = 0; i < n.count; i++) { _v.set(p.getX(i), p.getY(i) - 0.42, p.getZ(i)).normalize(); n.setXYZ(i, _v.x * 0.7 + n.getX(i) * 0.3, _v.y * 0.7 + n.getY(i) * 0.3, _v.z * 0.7 + n.getZ(i) * 0.3); } + g.userData.keep = true; + return g; + } + // clumps: [x,y,z,sx,sy,sz,rot,hex] + K.foliageMesh = function (list, parent) { + clumpGeo = clumpGeo || makeClump(); + const im = new THREE.InstancedMesh(clumpGeo, W.mats.foliage, list.length); + im.userData.keepGeo = true; + for (let i = 0; i < list.length; i++) { + const f = list[i]; _e.set(0, f[6], 0); _q.setFromEuler(_e); _v.set(f[0], f[1], f[2]); _s.set(f[3], f[4], f[5]); + _m.compose(_v, _q, _s); im.setMatrixAt(i, _m); _c.set(f[7]).convertSRGBToLinear(); im.setColorAt(i, _c); + } + im.castShadow = true; im.receiveShadow = true; + im.instanceMatrix.needsUpdate = true; + parent.add(im); return im; + }; + // leaf cards: crossed quads that break the outline of trees and hedges. [x,y,z,size,rot,hex] + let cardGeo = null; + K.cardMesh = function (list, parent) { + if (!cardGeo) { + const a = new THREE.PlaneGeometry(1, 1).toNonIndexed(), b2 = a.clone(); b2.rotateY(Math.PI / 2); + const c3 = a.clone(); c3.rotateX(Math.PI / 2); + const pos = [].concat(Array.from(a.attributes.position.array), Array.from(b2.attributes.position.array), Array.from(c3.attributes.position.array)); + const uv = [].concat(Array.from(a.attributes.uv.array), Array.from(b2.attributes.uv.array), Array.from(c3.attributes.uv.array)); + cardGeo = new THREE.BufferGeometry(); cardGeo.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3)); cardGeo.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2)); + const col = new Float32Array(pos.length); for (let i = 0; i < pos.length / 3; i++) { const y = pos[i * 3 + 1]; col[i * 3] = col[i * 3 + 1] = col[i * 3 + 2] = 0.6 + 0.4 * (y + 0.5); } + cardGeo.setAttribute('color', new THREE.BufferAttribute(col, 3)); + cardGeo.computeVertexNormals(); + // normals pointing up-ish so cards light like the canopy instead of flipping dark + const n = cardGeo.attributes.normal; for (let i = 0; i < n.count; i++) n.setXYZ(i, 0, 1, 0); + } + const im = new THREE.InstancedMesh(cardGeo, W.mats.leafCard, list.length); + im.userData.keepGeo = true; + for (let i = 0; i < list.length; i++) { + const f = list[i]; _e.set(0, f[4], 0); _q.setFromEuler(_e); _v.set(f[0], f[1], f[2]); _s.set(f[3], f[3], f[3]); + _m.compose(_v, _q, _s); im.setMatrixAt(i, _m); _c.set(f[5]).convertSRGBToLinear(); im.setColorAt(i, _c); + } + im.castShadow = true; im.receiveShadow = true; + parent.add(im); return im; + }; + const leafCols = [0x2f3d1f, 0x34431f, 0x2b3a1c, 0x3a4724, 0x283518, 0x3d4a26]; + // A Norman hedgerow: an earth bank (blocks sight and bullets, can't be vaulted) with dense shrubs and the odd tree on top. + // pts: [[x,z],...]. gaps: [[from m, to m], ...] measured along the line. o: {bank, h, trees} + K.hedgerow = function (b, pts, gaps, o) { + o = o || {}; gaps = gaps || []; + const bankH = o.bank != null ? o.bank : 1.1, topH = o.h != null ? o.h : 2.4, R = IV.rng(Math.round(pts[0][0] * 13 + pts[0][1] * 7)); + let acc = 0; + const inGap = s => gaps.some(g => s > g[0] && s < g[1]); + for (let i = 0; i < pts.length - 1; i++) { + const ax = pts[i][0], az = pts[i][1], bx = pts[i + 1][0], bz = pts[i + 1][1], dx = bx - ax, dz = bz - az, len = Math.hypot(dx, dz), rot = Math.atan2(-dz, dx); + // segments of up to 3 m so gaps cut cleanly + const nseg = Math.ceil(len / 3); + for (let k = 0; k < nseg; k++) { + const s0 = acc + len * k / nseg, s1 = acc + len * (k + 1) / nseg, sm = (s0 + s1) / 2; + if (inGap(sm)) continue; + const t = (k + 0.5) / nseg, cx = ax + dx * t, cz = az + dz * t, sl = len / nseg; + const gy = Math.min(W.height(cx, cz), W.height(cx - dz / len, cz + dx / len), W.height(cx + dz / len, cz - dx / len)); + // the bank: a wide low box, slightly sunk, earth material + K.add(b, 'earth', GEO.box, cx, gy + bankH / 2 - 0.2, cz, sl + 0.4, bankH + 0.4, 2.0, 0, rot, 0, 0x6a5a40, 0.5); + K.add(b, 'earth', GEO.box, cx, gy + bankH - 0.05, cz, sl + 0.4, 0.25, 1.5, 0, rot, 0, 0x4d4a30); + W.addBox(cx, cz, sl / 2 + 0.1, 1.0, gy - 1, gy + bankH + topH, rot, F.SOLID | F.SIGHT | F.BULLET | F.NAV, 'foliage', 'hedge'); + // shrubs along the top: two staggered rows of clumps + for (let m = 0; m < Math.max(1, Math.round(sl / 1.8)); m++) { + const tt = (m + R()) / Math.max(1, Math.round(sl / 1.8)), x = cx + (dx / len) * (tt - 0.5) * sl, z = cz + (dz / len) * (tt - 0.5) * sl; + const off = R.range(-0.45, 0.45), px = x + (-dz / len) * off, pz = z + (dx / len) * off; + const s = R.range(1.9, 2.7), hh = topH * R.range(0.75, 1.15); + K.noMesh || b.foliage.push([px, gy + bankH - 0.3, pz, s, hh, s, R() * 6.28, R.pick(leafCols)]); + // leaf cards on the crown and the flanks break up the blob outline + K.noMesh || b.cards.push([px + R.range(-0.4, 0.4), gy + bankH + hh * R.range(0.55, 0.85), pz + R.range(-0.4, 0.4), R.range(1.3, 1.9), R() * 6.28, R.pick(leafCols)]); + if (R() < 0.6) { const sd = R() < 0.5 ? -1 : 1; K.noMesh || b.cards.push([px + (-dz / len) * sd * s * 0.42, gy + bankH + hh * R.range(0.15, 0.45), pz + (dx / len) * sd * s * 0.42, R.range(1.1, 1.6), R() * 6.28, R.pick(leafCols)]); } + } + if (o.trees !== false && R() < (o.treeChance || 0.07)) K.tree(b, cx + R.range(-0.3, 0.3), cz + R.range(-0.3, 0.3), 'oak', R, gy + bankH - 0.2); + } + acc += len; + } + }; + // Low dry-stone wall (vaultable, you can see over it crouched? no: it hides you crouched, not standing) + K.stoneWall = function (b, pts, h, gaps) { + h = h || 1.0; gaps = gaps || []; + let acc = 0; + for (let i = 0; i < pts.length - 1; i++) { + const ax = pts[i][0], az = pts[i][1], bx = pts[i + 1][0], bz = pts[i + 1][1], dx = bx - ax, dz = bz - az, len = Math.hypot(dx, dz), rot = Math.atan2(-dz, dx); + const nseg = Math.ceil(len / 2.5); + for (let k = 0; k < nseg; k++) { + const sm = acc + len * (k + 0.5) / nseg; if (gaps.some(g => sm > g[0] && sm < g[1])) continue; + const t = (k + 0.5) / nseg, cx = ax + dx * t, cz = az + dz * t, sl = len / nseg, gy = W.height(cx, cz); + K.add(b, 'stone', GEO.box, cx, gy + h / 2 - 0.15, cz, sl + 0.02, h + 0.3, 0.55, 0, rot, 0, 0x9a968a, 0.35); + K.add(b, 'stone', GEO.box, cx, gy + h + 0.06, cz, sl + 0.04, 0.12, 0.62, 0, rot, 0, 0x7e7a70); + W.addBox(cx, cz, sl / 2, 0.3, gy - 0.5, gy + h + 0.12, rot, F.SOLID | F.BULLET | F.NAV | F.VAULT | F.LOW | (h > 1.4 ? F.SIGHT : 0), 'stone', 'wall'); + } + acc += len; + } + }; + K.fence = function (b, pts, h) { + h = h || 1.1; + for (let i = 0; i < pts.length - 1; i++) { + const ax = pts[i][0], az = pts[i][1], bx = pts[i + 1][0], bz = pts[i + 1][1], dx = bx - ax, dz = bz - az, len = Math.hypot(dx, dz), rot = Math.atan2(-dz, dx); + const n = Math.max(1, Math.round(len / 2.4)); + for (let k = 0; k <= n; k++) { const x = ax + dx * k / n, z = az + dz * k / n, gy = W.height(x, z); K.add(b, 'wood', GEO.box, x, gy + h / 2 - 0.1, z, 0.12, h + 0.2, 0.12, 0, rot, 0, 0x8a7a64); } + for (let r = 0; r < 2; r++) for (let k = 0; k < n; k++) { + const t = (k + 0.5) / n, x = ax + dx * t, z = az + dz * t, gy = W.height(x, z); + K.add(b, 'wood', GEO.box, x, gy + h * (0.45 + r * 0.42), z, len / n, 0.1, 0.05, 0, rot, (k % 2 ? 0.02 : -0.02), 0x9a8a70); + } + const cx = (ax + bx) / 2, cz = (az + bz) / 2; + W.addBox(cx, cz, len / 2, 0.12, W.height(cx, cz) - 0.3, W.height(cx, cz) + h, rot, F.SOLID | F.NAV | F.VAULT | F.LOW, 'wood', 'fence'); + } + }; + // Trees. kind 'oak' (big, along hedges), 'apple' (orchard), 'poplar' + K.tree = function (b, x, z, kind, R, baseY) { + R = R || IV.rng(Math.round(x * 31 + z * 17)); + const gy = baseY != null ? baseY : W.height(x, z); + const big = kind === 'oak', apple = kind === 'apple', poplar = kind === 'poplar'; + const th = big ? R.range(4, 5.5) : apple ? R.range(1.4, 1.9) : R.range(7, 9), tr = big ? R.range(0.28, 0.4) : apple ? 0.13 : 0.22; + K.add(b, 'bark', GEO.cyl8, x, gy + th / 2, z, tr * 2, th, tr * 2, R.range(-0.05, 0.05), 0, R.range(-0.05, 0.05), 0x8a7a68); + // a couple of limbs + const limbs = big ? 3 : apple ? 3 : 0; + for (let i = 0; i < limbs; i++) { const a = R() * 6.28, l = big ? 2.4 : 1.1; K.add(b, 'bark', GEO.cyl8, x + Math.cos(a) * l * 0.35, gy + th * 0.9 + l * 0.3, z + Math.sin(a) * l * 0.35, tr * 0.9, l, tr * 0.9, Math.sin(a) * 0.9, 0, -Math.cos(a) * 0.9, 0x7a6a58); } + W.addBox(x, z, tr, tr, gy - 0.5, gy + th + 1, R() * 3, F.SOLID | F.BULLET | F.NAV, 'wood', 'tree'); + const cols = apple ? [0x34421f, 0x3b4a22, 0x2f3c1c] : leafCols; + const n = big ? 9 : apple ? 6 : 7, cr = big ? 3.4 : apple ? 1.7 : 1.3, cy = gy + th + (big ? 1.8 : apple ? 0.9 : 1.2); + for (let i = 0; i < n; i++) { + const a = R() * 6.28, rr = R() * cr * 0.7, s = R.range(0.8, 1.15) * (big ? 3.2 : apple ? 1.9 : 1.6); + const yy = poplar ? cy + (i / n) * 7 - 1 : cy + R.range(-0.6, 1.0) * (big ? 1.2 : 0.6); + K.noMesh || b.foliage.push([x + Math.cos(a) * rr, yy - s * 0.4, z + Math.sin(a) * rr, s, s * (poplar ? 1.3 : 0.9), s, R() * 6.28, R.pick(cols)]); + if (R() < 0.7) K.noMesh || b.cards.push([x + Math.cos(a) * (rr + s * 0.4), yy + R.range(-0.5, 0.5), z + Math.sin(a) * (rr + s * 0.4), s * 0.9, R() * 6.28, R.pick(cols)]); + } + return { x, z, top: cy + 1.5 }; + }; + // A telegraph pole (the field-telephone line). Returns the top insulator position. + K.pole = function (b, x, z, h) { + h = h || 6.5; const gy = W.height(x, z); + K.add(b, 'wood', GEO.cyl8, x, gy + h / 2, z, 0.24, h, 0.24, 0, 0, 0, 0x6e5e4c); + K.add(b, 'wood', GEO.box, x, gy + h - 0.5, z, 1.1, 0.1, 0.1, 0, 0, 0, 0x6e5e4c); + W.addBox(x, z, 0.14, 0.14, gy - 0.3, gy + h, 0, F.SOLID | F.BULLET, 'wood', 'pole'); + return { x, y: gy + h - 0.42, z }; + }; + // Sagging wire between points (a thin dark line mesh, one per call) + K.wire = function (parent, pts) { + const p = []; + for (let i = 0; i < pts.length - 1; i++) { + const a = pts[i], c = pts[i + 1]; + for (let k = 0; k < 10; k++) { + const t0 = k / 10, t1 = (k + 1) / 10; + const y0 = a.y + (c.y - a.y) * t0 - Math.sin(Math.PI * t0) * 0.7, y1 = a.y + (c.y - a.y) * t1 - Math.sin(Math.PI * t1) * 0.7; + p.push(a.x + (c.x - a.x) * t0, y0, a.z + (c.z - a.z) * t0, a.x + (c.x - a.x) * t1, y1, a.z + (c.z - a.z) * t1); + } + } + const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.Float32BufferAttribute(p, 3)); + const l = new THREE.LineSegments(g, new THREE.LineBasicMaterial({ color: 0x15171a })); + parent.add(l); return l; + }; + + // ---------------------------------------------------------------- buildings + // A rectangular building. o: {x,z,w,d,rot,h,floor (y of floor above local ground), mat, sides:{n,s,e,w:[{t:'door'|'win',at,w}]}, + // inner:[{a:[lx,lz], b:[lx,lz], doors:[{at,w}]}], roof:{pitch,over,mat,ridge:'x'|'z'}, lit:[...window ids lit], ceiling} + // Local frame: x across width (east when rot=0), z across depth (south when rot=0). Sides: n = -z, s = +z, w = -x, e = +x. + K.building = function (b, o) { + const c = Math.cos(o.rot || 0), s = Math.sin(o.rot || 0); + const gy = o.y != null ? o.y : W.height(o.x, o.z); + const fy = gy + (o.floor || 0.25), h = o.h || 3.0, t = o.thick || 0.5, mat = o.mat || 'stone', wallCol = o.color || 0xb3ad9f; + const L2W = (lx, lz) => [o.x + lx * c + lz * s, o.z - lx * s + lz * c]; + const box = (m, lx, y0, lz, sx, sy, sz, col, flags, surf, ao) => { const p = L2W(lx, lz); return K.box(b, m, p[0], y0, p[1], sx, sy, sz, o.rot || 0, col, flags, surf, ao); }; + const hw = o.w / 2, hd = o.d / 2; + // IVEnv shell (art.js passes o.envB, an IVEnv builder, when the photo materials are loaded): the outside of the + // building (walls, plinth, quoins, sills, lintels, glazing bars, shutters, gables, roof, eaves, gutters, chimney, + // grime at the foot) is drawn with IVEnv materials; every collider, opening, room and the interior stay the kit's. + const EB = (!K.noMesh && o.envB) || null, wallM = mat === 'wood' ? 'planks' : mat === 'plaster' ? 'plaster' : 'fieldstone'; + const wallT = mat === 'wood' ? new THREE.Color(0.55, 0.45, 0.36) : null; // weathered brown boards, not bleached grey + const vb = (m, lx, y0, lz, sx, sy, sz, op) => { const p = L2W(lx, lz); op = Object.assign({ foot: gy }, op); EB.box(m, p[0], y0, p[1], sx, sy, sz, o.rot || 0, op); }; // foot: damp and grime measured from the real ground + const wn = (nx, nz) => [nx * c + nz * s, -nx * s + nz * c]; + const TT = (r, g, bl) => new THREE.Color(r, g, bl); + // foundation plinth and floor + if (EB) vb('fieldstone', 0, gy - 0.6, 0, o.w + 0.25, fy - gy + 0.6, o.d + 0.25, { tint: TT(0.62, 0.6, 0.56) }); + else box('stone', 0, gy - 0.6, 0, o.w + 0.25, fy - gy + 0.6, o.d + 0.25, 0x8e8a80, 0, 0, 0.3); + box(o.floorMat || 'wood', 0, fy - 0.08, 0, o.w - t * 2 + 0.02, 0.08, o.d - t * 2 + 0.02, o.floorCol || 0x8a7058, F.SOLID, o.floorMat === 'stone' ? 'stone' : 'wood'); + W.addBox(o.x, o.z, hw, hd, gy - 0.6, fy - 0.08, o.rot || 0, F.SOLID, 'stone', 'plinth'); + const wins = []; + const SOL = F.SOLID | F.SIGHT | F.BULLET | F.NAV; + // an outer wall along one side with openings + function side(name) { + const ops = (o.sides && o.sides[name]) || []; + const along = (name === 'n' || name === 's') ? o.w : o.d, sgn = (name === 'n' || name === 'w') ? -1 : 1; + // wall runs from -along/2 to along/2; local axis u + const piece = (u0, u1, y0, y1, flags, m, col) => { + if (u1 - u0 < 0.01 || y1 - y0 < 0.01) return; + const um = (u0 + u1) / 2, len = u1 - u0; + if (EB) { + if (name === 'n' || name === 's') { if (flags) box(null, um, y0, sgn * (hd - t / 2), len, y1 - y0, t, 0, flags, mat === 'wood' ? 'wood' : 'stone'); vb(wallM, um, y0, sgn * (hd - t / 2), len, y1 - y0, t, { tint: wallT, uvOff: [name === 's' ? um : -um, (y0 + y1) / 2] }); } // world-aligned: no seam between pieces + else { if (flags) box(null, sgn * (hw - t / 2), y0, um, t, y1 - y0, len, 0, flags, mat === 'wood' ? 'wood' : 'stone'); vb(wallM, sgn * (hw - t / 2), y0, um, t, y1 - y0, len, { tint: wallT, uvOff: [name === 'w' ? um : -um, (y0 + y1) / 2] }); } + return; + } + if (name === 'n' || name === 's') box(m || mat, um, y0, sgn * (hd - t / 2), len, y1 - y0, t, col || wallCol, flags, mat === 'wood' ? 'wood' : 'stone', 0.25); + else box(m || mat, sgn * (hw - t / 2), y0, um, t, y1 - y0, len, col || wallCol, flags, mat === 'wood' ? 'wood' : 'stone', 0.25); + }; + const sorted = ops.slice().sort((a, b) => a.at - b.at); + let u = -along / 2; + for (const op of sorted) { + const u0 = op.at - op.w / 2, u1 = op.at + op.w / 2; + piece(u, u0, fy - 0.1, fy + h, SOL); + const sill = op.sill != null ? op.sill : 0.9, top = op.t === 'door' ? fy + (op.h || 2.15) : fy + sill + (op.oh || 1.15), bot = op.t === 'door' ? fy - 0.1 : fy + sill; + piece(u0, u1, top, fy + h, SOL); // lintel + if (op.t === 'win') { + piece(u0, u1, fy - 0.1, bot, SOL); // under the sill + // window: frame, glass set back, sill stone + const lit = !!op.lit; + const pu = op.at, inset = sgn * (hd - t * 0.65), insetX = sgn * (hw - t * 0.65); + const glassMat = lit ? 'lit' : 'dark'; + if (name === 'n' || name === 's') { + if (!op.open) box(glassMat, pu, bot, inset, op.w - 0.1, top - bot, 0.04, 0xffffff); + box('wood', pu, bot, sgn * (hd - t * 0.55), 0.06, top - bot, 0.08, 0x5a4a38); box('wood', pu, (bot + top) / 2, sgn * (hd - t * 0.55), op.w, 0.06, 0.08, 0x5a4a38); + if (EB) { + vb('ashlar', pu, bot - 0.08, sgn * (hd + 0.02), op.w + 0.24, 0.09, t * 0.4 + 0.12, { tint: TT(0.7, 0.7, 0.7) }); if (mat !== 'wood') vb('ashlar', pu, top, sgn * (hd + 0.012), op.w + 0.4, 0.24, t * 0.32, { tint: TT(0.72, 0.71, 0.7) }); + for (const k of [-1, 1]) vb('timber', pu + k * op.w / 4, bot, sgn * (hd - t * 0.55), 0.035, top - bot, 0.05, { noFoot: true, tint: TT(0.6, 0.58, 0.52) }); + if (op.shut) for (const k of [-1, 1]) vb('wood_painted', pu + k * (op.w / 2 + 0.3), bot, sgn * (hd + 0.04), 0.55, top - bot, 0.05, { noFoot: true, tint: TT(0.75, 0.95, 0.8) }); + } else box('stone', pu, bot - 0.06, sgn * (hd + 0.04), op.w + 0.2, 0.08, 0.2, 0x8a867c); + if (op.shut && !EB) { box('wood', pu - op.w / 2 - 0.3, bot, sgn * (hd + 0.04), 0.55, top - bot, 0.05, 0x4c5a48); box('wood', pu + op.w / 2 + 0.3, bot, sgn * (hd + 0.04), 0.55, top - bot, 0.05, 0x4c5a48); } + } else { + if (!op.open) box(glassMat, insetX, bot, pu, 0.04, top - bot, op.w - 0.1, 0xffffff); + box('wood', sgn * (hw - t * 0.55), bot, pu, 0.08, top - bot, 0.06, 0x5a4a38); box('wood', sgn * (hw - t * 0.55), (bot + top) / 2, pu, 0.08, 0.06, op.w, 0x5a4a38); + if (EB) { + vb('ashlar', sgn * (hw + 0.02), bot - 0.08, pu, t * 0.4 + 0.12, 0.09, op.w + 0.24, { tint: TT(0.7, 0.7, 0.7) }); if (mat !== 'wood') vb('ashlar', sgn * (hw + 0.012), top, pu, t * 0.32, 0.24, op.w + 0.4, { tint: TT(0.72, 0.71, 0.7) }); + for (const k of [-1, 1]) vb('timber', sgn * (hw - t * 0.55), bot, pu + k * op.w / 4, 0.05, top - bot, 0.035, { noFoot: true, tint: TT(0.6, 0.58, 0.52) }); + if (op.shut) for (const k of [-1, 1]) vb('wood_painted', sgn * (hw + 0.04), bot, pu + k * (op.w / 2 + 0.3), 0.05, top - bot, 0.55, { noFoot: true, tint: TT(0.75, 0.95, 0.8) }); + } else box('stone', sgn * (hw + 0.04), bot - 0.06, pu, 0.2, 0.08, op.w + 0.2, 0x8a867c); + if (op.shut && !EB) { box('wood', sgn * (hw + 0.04), bot, pu - op.w / 2 - 0.3, 0.05, top - bot, 0.55, 0x4c5a48); box('wood', sgn * (hw + 0.04), bot, pu + op.w / 2 + 0.3, 0.05, top - bot, 0.55, 0x4c5a48); } + } + // blocks movement, not sight or bullets + if (name === 'n' || name === 's') box(null, pu, bot, sgn * (hd - t / 2), op.w, top - bot, t, 0, F.SOLID | F.NAV, 'glass'); + else box(null, sgn * (hw - t / 2), bot, pu, t, top - bot, op.w, 0, F.SOLID | F.NAV, 'glass'); + const wp = name === 'n' || name === 's' ? L2W(pu, sgn * (hd + 0.6)) : L2W(sgn * (hw + 0.6), pu); + wins.push({ x: wp[0], y: fy + 1.4, z: wp[1], lit }); + } else { + // door frame + if (name === 'n' || name === 's') { box('wood', u0 - 0.06, fy, sgn * (hd - t / 2), 0.12, top - fy, t + 0.06, 0x4a3a2a); box('wood', u1 + 0.06, fy, sgn * (hd - t / 2), 0.12, top - fy, t + 0.06, 0x4a3a2a); } + else { box('wood', sgn * (hw - t / 2), fy, u0 - 0.06, t + 0.06, top - fy, 0.12, 0x4a3a2a); box('wood', sgn * (hw - t / 2), fy, u1 + 0.06, t + 0.06, top - fy, 0.12, 0x4a3a2a); } + if (EB) { if (name === 'n' || name === 's') vb(mat === 'wood' ? 'timber' : 'ashlar', op.at, top, sgn * (hd + 0.01), op.w + 0.5, 0.24, t * 0.35); else vb(mat === 'wood' ? 'timber' : 'ashlar', sgn * (hw + 0.01), top, op.at, t * 0.35, 0.24, op.w + 0.5); } + // a step outside + const sp = name === 'n' || name === 's' ? [op.at, sgn * (hd + 0.4)] : [sgn * (hw + 0.4), op.at]; + const sp0 = L2W(sp[0], sp[1]); + if (fy - W.height(sp0[0], sp0[1]) > 0.18) { const stepTop = (fy + W.height(sp0[0], sp0[1])) / 2; if (name === 'n' || name === 's') box('stone', sp[0], gy - 0.3, sp[1], op.w + 0.4, stepTop - gy + 0.3, 0.6, 0x8a867c, F.SOLID, 'stone'); else box('stone', sp[0], gy - 0.3, sp[1], 0.6, stepTop - gy + 0.3, op.w + 0.4, 0x8a867c, F.SOLID, 'stone'); } + } + u = u1; + } + piece(u, along / 2, fy - 0.1, fy + h, SOL); + } + ['n', 's', 'e', 'w'].forEach(side); + // corner quoins (dressed stone at the corners breaks the box look) + if (mat !== 'wood') for (const cx of [-1, 1]) for (const cz of [-1, 1]) for (let k = 0; k < Math.floor(h / 0.5); k++) { + const big = k % 2 === 0; if (EB) vb(wallM, cx * (hw - (big ? 0.28 : 0.2) + 0.015), fy + k * 0.5 - 0.1, cz * (hd - (big ? 0.2 : 0.28) + 0.015), big ? 0.58 : 0.43, 0.49, big ? 0.43 : 0.58, { tint: TT(1.05, 1.04, 1.02) }); else box('stone', cx * (hw - (big ? 0.28 : 0.2) + 0.03), fy + k * 0.5 - 0.1, cz * (hd - (big ? 0.2 : 0.28) + 0.03), big ? 0.6 : 0.45, 0.48, big ? 0.45 : 0.6, 0xc4beb0); + } + // inner walls + for (const iw of (o.inner || [])) { + const ax = iw.a[0], az = iw.a[1], bx = iw.b[0], bz = iw.b[1], len = Math.hypot(bx - ax, bz - az), ux = (bx - ax) / len, uz = (bz - az) / len; + const ds = (iw.doors || []).slice().sort((p, q) => p.at - q.at); + let u = 0; + const seg = (u0, u1, y0, y1) => { if (u1 - u0 < 0.02) return; const m = (u0 + u1) / 2, lx = ax + ux * m, lz = az + uz * m; if (Math.abs(ux) > 0.5) box('plaster', lx, y0, lz, u1 - u0, y1 - y0, 0.16, 0xd8d0be, SOL, 'stone'); else box('plaster', lx, y0, lz, 0.16, y1 - y0, u1 - u0, 0xd8d0be, SOL, 'stone'); }; + for (const d of ds) { seg(u, d.at - d.w / 2, fy, fy + h); seg(d.at - d.w / 2, d.at + d.w / 2, fy + 2.1, fy + h); u = d.at + d.w / 2; } + seg(u, len, fy, fy + h); + } + // ceiling + roof + box('wood', 0, fy + h, 0, o.w, 0.12, o.d, 0x5e4a38, F.SOLID | F.SIGHT | F.BULLET, 'wood'); + if (o.beams !== false) for (let k = -hw + 1; k < hw - 0.5; k += 1.4) box('wood', k, fy + h - 0.18, 0, 0.16, 0.18, o.d - t * 2, 0x4a3828); + const rf = o.roof || {}, over = rf.over != null ? rf.over : 0.45, pitch = rf.pitch || 0.75, ridgeX = (rf.ridge || 'x') === 'x'; + const span = ridgeX ? o.d : o.w, run = ridgeX ? o.w : o.d, rise = span / 2 * pitch; + const ry = fy + h + 0.12; + // gable ends (wall material triangle), and two roof slabs + const gable = (px, pz, sx, ry2) => { const mm = new THREE.Matrix4().compose(new THREE.Vector3(px, ry, pz), new THREE.Quaternion().setFromEuler(new THREE.Euler(0, ry2, 0)), new THREE.Vector3(sx, rise, t)); EB.geo(wallM, GEO.prism, mm, { tint: wallT }); }; + if (EB && ridgeX) { for (const e of [-1, 1]) { const p = L2W(e * (hw - t / 2), 0); gable(p[0], p[1], o.d, (o.rot || 0) + Math.PI / 2); } } + else if (EB) { for (const e of [-1, 1]) { const p = L2W(0, e * (hd - t / 2)); gable(p[0], p[1], o.w, o.rot || 0); } } + else if (ridgeX) { + for (const e of [-1, 1]) { const p = L2W(e * (hw - t / 2), 0); K.add(b, mat, GEO.prism, p[0], ry, p[1], o.d, rise, t, 0, (o.rot || 0) + Math.PI / 2, 0, wallCol); } + } else { + for (const e of [-1, 1]) { const p = L2W(0, e * (hd - t / 2)); K.add(b, mat, GEO.prism, p[0], ry, p[1], o.w, rise, t, 0, o.rot || 0, 0, wallCol); } + } + const slabLen = Math.hypot(span / 2 + over, rise + over * pitch), ang = Math.atan(pitch); + const roofM = rf.mat === 'metal' ? 'metal_rust' : mat === 'wood' ? 'roof_tile' : 'slate'; + for (const e of [-1, 1]) { + const off = (span / 4 + over / 2) * e, yy = ry + rise / 2 - over * pitch / 2; + if (EB) { + // a roof that has settled: one sheet per slope that sags between the gables and dips mid-slope, slate rows + // slightly uneven, boarded soffit underneath, barge boards on the gable edges + { const L = run + 0.3, S2 = slabLen - Math.max(0, over - 0.35), nx = 8, nz = Math.max(10, Math.ceil(S2 / 0.1)), gS = new THREE.PlaneGeometry(ridgeX ? L : S2, ridgeX ? S2 : L, ridgeX ? nx : nz, ridgeX ? nz : nx), pa = gS.attributes.position, sd = (o.x * 7 + o.z * 3) | 0; + for (let i = 0; i < pa.count; i++) { const px = pa.getX(i), py = pa.getY(i), ua = ridgeX ? px / L : py / L, ub = ridgeX ? py / S2 : px / S2, row = Math.floor((ub + 0.5) * S2 / 0.3); + const rowF = (ub + 0.5) * S2 / 0.3 - row, sag = 0.09 * Math.cos(Math.PI * ua) * (0.35 + 0.65 * Math.cos(Math.PI * ub * 0.9)) + 0.015 * Math.sin(row * 12.9898 + sd) - 0.022 * rowF; // each course's lower edge stands proud + pa.setZ(i, -sag); } + gS.computeVertexNormals(); gS.rotateX(-Math.PI / 2); gS.translate(0, 0.07, 0); + const p = ridgeX ? L2W(0, off) : L2W(off, 0), q = new THREE.Quaternion().setFromEuler(new THREE.Euler(ridgeX ? -e * ang : 0, o.rot || 0, ridgeX ? 0 : e * ang, 'YXZ')); + const M = new THREE.Matrix4().compose(new THREE.Vector3(p[0], yy, p[1]), q, new THREE.Vector3(1, 1, 1)); + EB.geo(roofM, gS, M, { keepUv: true, uvW: ridgeX ? L : S2, uvH: ridgeX ? S2 : L, noFoot: true }); + const gU = gS.clone(); gU.scale(1, -1, 1); gU.translate(0, 0.07, 0); const ix = gU.index; if (ix) { const a = ix.array; for (let k = 0; k < a.length; k += 3) { const t2 = a[k]; a[k] = a[k + 1]; a[k + 1] = t2; } } gU.computeVertexNormals(); + EB.geo('planks', gU, M, { keepUv: true, uvW: ridgeX ? L : S2, uvH: ridgeX ? S2 : L, noFoot: true, tint: TT(0.45, 0.4, 0.36) }); + for (const g2 of [-1, 1]) { if (ridgeX) vb('timber', g2 * (L / 2 - 0.02), yy - 0.12, off, 0.05, 0.22, S2, { rx: -e * ang, noFoot: true, tint: TT(0.6, 0.55, 0.5) }); else vb('timber', off, yy - 0.12, g2 * (L / 2 - 0.02), S2, 0.22, 0.05, { rz: e * ang, noFoot: true, tint: TT(0.6, 0.55, 0.5) }); } + } + // eaves: fascia board, a cast-iron gutter, a downpipe at each end of the eave + const eY = ry - over * pitch, eo = span / 2 + over - Math.max(0, over - 0.35) / 2, L = run + 0.3; + if (ridgeX) { vb('timber', 0, eY - 0.2, e * (eo - 0.02), L, 0.2, 0.04, { noFoot: true, grain: 'long' }); vb('metal_painted', 0, eY - 0.24, e * (eo + 0.05), L, 0.1, 0.11, { noFoot: true, tint: TT(0.35, 0.36, 0.35) }); for (const k of [-1, 1]) vb('metal_painted', k * (hw - 0.25), gy, e * (hd + 0.07), 0.08, eY - gy - 0.2, 0.08, { tint: TT(0.35, 0.36, 0.35) }); } + else { vb('timber', e * (eo - 0.02), eY - 0.2, 0, 0.04, 0.2, L, { noFoot: true, grain: 'long' }); vb('metal_painted', e * (eo + 0.05), eY - 0.24, 0, 0.11, 0.1, L, { noFoot: true, tint: TT(0.35, 0.36, 0.35) }); for (const k of [-1, 1]) vb('metal_painted', e * (hw + 0.07), gy, k * (hd - 0.25), 0.08, eY - gy - 0.2, 0.08, { tint: TT(0.35, 0.36, 0.35) }); } + continue; + } + if (ridgeX) { const p = L2W(0, off); K.add(b, rf.mat || 'roof', GEO.box, p[0], yy, p[1], run + over * 2, 0.14, slabLen, -e * ang, o.rot || 0, 0, rf.col || 0xb0a8a4, 0); } + else { const p = L2W(off, 0); K.add(b, rf.mat || 'roof', GEO.box, p[0], yy, p[1], slabLen, 0.14, run + over * 2, 0, o.rot || 0, e * ang, rf.col || 0xb0a8a4, 0); } + } + // ridge cap and a chimney + if (EB) { const p = L2W(0, 0); EB.decal('moss', [p[0], ry + rise + 0.12, p[1]], [0, 1, 0], ridgeX ? run : 1.2, ridgeX ? 1.2 : run, o.rot || 0); } + if (EB) vb(mat === 'wood' ? 'roof_tile' : 'roof_tile', 0, ry + rise - 0.06, 0, ridgeX ? run + over * 2 : 0.32, 0.16, ridgeX ? 0.32 : run + over * 2, { noFoot: true, tint: mat === 'wood' ? undefined : TT(0.55, 0.5, 0.48) }); + else { const p = L2W(0, 0); K.add(b, 'roof', GEO.box, p[0], ry + rise + 0.02, p[1], ridgeX ? run + over * 2 : 0.3, 0.16, ridgeX ? 0.3 : run + over * 2, 0, o.rot || 0, 0, 0x6a6262); } + if (o.chimney && EB) { + const [cx0, cz0] = o.chimney; vb('brick_sooty', cx0, ry, cz0, 0.8, rise + 1.3, 0.7); vb('ashlar', cx0, ry + rise + 1.3, cz0, 0.92, 0.1, 0.82, { noFoot: true }); + for (const k of [-0.18, 0.18]) { const p = L2W(cx0 + k, cz0); EB.geo('roof_tile', new THREE.CylinderGeometry(0.1, 0.12, 0.4, 8), new THREE.Matrix4().makeTranslation(p[0], ry + rise + 1.6, p[1]), { noFoot: true }); } + } else if (o.chimney) { const p = L2W(o.chimney[0], o.chimney[1]); K.box(b, 'stone', p[0], ry, p[1], 0.8, rise + 1.3, 0.7, o.rot || 0, 0x9a948a); } + // weathering where it happens: splash grime and green along the foot of every wall, moss on the north face + if (EB) for (const [nx, nz, len] of [[0, -1, o.w], [0, 1, o.w], [-1, 0, o.d], [1, 0, o.d]]) { + const p = L2W(nx * (hw + 0.13), nz * (hd + 0.13)), n = wn(nx, nz); + EB.decal('grime', [p[0], fy + 0.15, p[1]], [n[0], 0, n[1]], len, 0.9, 0); + if (nz < 0 || nx < 0) EB.decal('moss', [p[0], gy + 0.25, p[1]], [n[0], 0, n[1]], len * 0.7, 0.5, 0); + EB.decal('waterstain', [p[0], fy + h - 0.4, p[1]], [n[0], 0, n[1]], len * 0.9, 0.8, 0); + } + // a roof as a sight blocker from above and a shade zone for the moon + W.addBox(o.x, o.z, hw + over, hd + over, ry, ry + rise, o.rot || 0, F.SIGHT | F.BULLET, 'roof', 'roof'); + const ex = Math.abs(hw * c) + Math.abs(hd * s), ez = Math.abs(hw * s) + Math.abs(hd * c); + W.roofs.push([o.x - ex, o.z - ez, o.x + ex, o.z + ez, ry]); + return { fy, L2W, wins, box, top: ry + rise }; + }; + + // ---------------------------------------------------------------- props (all merged into the static builder) + K.props = { + table(b, x, y, z, rot, w, d) { w = w || 1.4; d = d || 0.8; const c = Math.cos(rot), s = Math.sin(rot); K.box(b, 'wood', x, y + 0.72, z, w, 0.06, d, rot, 0x7a5a3e, F.SOLID | F.BULLET, 'wood'); for (const i of [-1, 1]) for (const j of [-1, 1]) { const lx = i * (w / 2 - 0.08), lz = j * (d / 2 - 0.08); K.box(b, 'wood', x + lx * c + lz * s, y, z - lx * s + lz * c, 0.07, 0.72, 0.07, rot, 0x5e4430); } }, + chair(b, x, y, z, rot) { const c = Math.cos(rot), s = Math.sin(rot); K.box(b, 'wood', x, y + 0.44, z, 0.44, 0.05, 0.44, rot, 0x6e5038); for (const i of [-1, 1]) for (const j of [-1, 1]) K.box(b, 'wood', x + i * 0.18 * c + j * 0.18 * s, y, z - i * 0.18 * s + j * 0.18 * c, 0.04, 0.44, 0.04, rot, 0x5a4030); K.box(b, 'wood', x - 0.2 * s, y + 0.46, z - 0.2 * c, 0.44, 0.5, 0.05, rot, 0x6e5038); W.addBox(x, z, 0.22, 0.22, y, y + 0.9, rot, F.SOLID, 'wood'); }, + bed(b, x, y, z, rot) { K.box(b, 'wood', x, y, z, 1.0, 0.45, 2.0, rot, 0x5a4030, F.SOLID | F.BULLET, 'wood'); K.box(b, 'cloth', x, y + 0.45, z, 0.92, 0.16, 1.9, rot, 0xd8d0b8); const c = Math.cos(rot), s = Math.sin(rot); K.box(b, 'cloth', x - 0.75 * s, y + 0.6, z - 0.75 * c, 0.7, 0.12, 0.35, rot, 0xeee8d8); K.box(b, 'wood', x - 1.0 * s, y, z - 1.0 * c, 1.0, 1.0, 0.08, rot, 0x5a4030); }, + shelf(b, x, y, z, rot, w) { w = w || 1.2; K.box(b, 'wood', x, y, z, w, 1.9, 0.35, rot, 0x5e4630, F.SOLID | F.SIGHT | F.BULLET, 'wood'); const c = Math.cos(rot), s = Math.sin(rot); const R = IV.rng(Math.round(x * 9 + z)); for (let k = 0; k < 3; k++) for (let i = 0; i < 4; i++) { const lx = -w / 2 + 0.15 + i * (w - 0.3) / 3 + R.range(-0.05, 0.05); K.box(b, 'plain', x + lx * c + 0.2 * s, y + 0.45 + k * 0.55, z - lx * s + 0.2 * c, R.range(0.12, 0.22), R.range(0.18, 0.3), 0.18, rot, R.pick([0x8a3a2a, 0x3a4a6a, 0xc8b890, 0x4a6a3a, 0x6a5a3a])); } }, + stove(b, x, y, z, rot) { K.box(b, 'metal', x, y, z, 0.9, 0.85, 0.6, rot, 0x2a2a2a, F.SOLID | F.BULLET, 'metal'); K.cyl(b, 'metal', x, y + 0.85, z, 0.08, 2.2, 0x222222); }, + crate(b, x, y, z, rot, s2) { s2 = s2 || 0.8; K.box(b, 'wood', x, y, z, s2, s2, s2, rot, 0x8a7656, F.SOLID | F.BULLET | F.NAV | F.LOW | F.VAULT, 'wood', 0.2); K.box(b, 'wood', x, y + s2 * 0.45, z, s2 + 0.02, 0.08, s2 + 0.02, rot, 0x6a5a40); }, + barrel(b, x, y, z) { K.cyl(b, 'wood', x, y, z, 0.32, 0.95, 0x6a5038, F.SOLID | F.BULLET | F.NAV, 12); K.cyl(b, 'metal', x, y + 0.2, z, 0.335, 0.06, 0x3a3a3a, 0, 12); K.cyl(b, 'metal', x, y + 0.72, z, 0.335, 0.06, 0x3a3a3a, 0, 12); }, + hay(b, x, y, z, rot) { K.box(b, 'cloth', x, y, z, 1.1, 0.55, 0.6, rot, 0xc8b070, F.SOLID | F.NAV | F.LOW | F.VAULT | F.BULLET, 'cloth', 0.25); }, + sandbags(b, ax, az, bx, bz, layers, baseY) { // a sandbag wall from a to b + const len = Math.hypot(bx - ax, bz - az), rot = Math.atan2(-(bz - az), bx - ax), n = Math.max(1, Math.round(len / 0.62)); layers = layers || 3; + for (let l = 0; l < layers; l++) for (let k = 0; k < n - (l % 2); k++) { + const t = (k + 0.5 + (l % 2) * 0.5) / n, x = ax + (bx - ax) * t, z = az + (bz - az) * t, gy = baseY != null ? baseY : W.height(x, z); + K.add(b, 'cloth', GEO.sph, x, gy + 0.13 + l * 0.24, z, 0.62, 0.28, 0.42, 0, rot + (k % 2 ? 0.05 : -0.05), 0, 0xa49770); + } + const cx = (ax + bx) / 2, cz = (az + bz) / 2, gy = baseY != null ? baseY : W.height(cx, cz); + W.addBox(cx, cz, len / 2, 0.24, gy - 0.3, gy + layers * 0.24 + 0.05, rot, F.SOLID | F.BULLET | F.NAV | F.LOW | F.VAULT | (layers > 4 ? F.SIGHT : 0), 'cloth', 'sandbags'); + }, + cart(b, x, z, rot) { const gy = W.height(x, z), c = Math.cos(rot), s = Math.sin(rot); K.box(b, 'wood', x, gy + 0.6, z, 1.4, 0.5, 2.4, rot, 0x6e5a40, F.SOLID | F.BULLET | F.NAV | F.SIGHT, 'wood', 0.3); for (const i of [-1, 1]) K.add(b, 'wood', GEO.cyl12, x + i * 0.78 * c, gy + 0.55, z - i * 0.78 * s, 1.1, 0.1, 1.1, 0, rot, Math.PI / 2, 0x4a3a28); K.box(b, 'wood', x - 1.8 * s, gy + 0.55, z - 1.8 * c, 0.08, 0.08, 1.8, rot, 0x5a4a34); }, + woodpile(b, x, z, rot) { const gy = W.height(x, z); for (let l = 0; l < 4; l++) for (let k = 0; k < 6 - l; k++) { const c = Math.cos(rot), s = Math.sin(rot), u = (k - (5 - l) / 2) * 0.2; K.add(b, 'bark', GEO.cyl8, x + u * c, gy + 0.1 + l * 0.18, z - u * s, 0.2, 1.1, 0.2, Math.PI / 2, rot, 0, 0x8a7a60); } W.addBox(x, z, 0.65, 0.6, gy, gy + 0.75, rot, F.SOLID | F.BULLET | F.NAV | F.LOW | F.VAULT, 'wood'); }, + lamp(b, x, z, h, parent) { // a lamp on a post with its own pool of light + const gy = W.height(x, z); h = h || 3.2; + K.add(b, 'wood', GEO.cyl8, x, gy + h / 2, z, 0.14, h, 0.14, 0, 0, 0, 0x4a3a2a); + K.add(b, 'metal', GEO.box, x + 0.3, gy + h - 0.05, z, 0.6, 0.06, 0.06, 0, 0, 0, 0x2a2a2a); + K.add(b, 'lit', GEO.sph, x + 0.55, gy + h - 0.3, z, 0.18, 0.24, 0.18, 0, 0, 0, 0xffffff); + K.add(b, 'metal', GEO.cone8, x + 0.55, gy + h - 0.12, z, 0.4, 0.15, 0.4, 0, 0, 0, 0x2a2a2a); + W.addBox(x, z, 0.1, 0.1, gy, gy + h, 0, F.SOLID | F.BULLET, 'wood'); + const glow = new THREE.Sprite(new THREE.SpriteMaterial({ map: W.tex.glow(), color: 0xffb060, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, opacity: 0.65, toneMapped: false })); + glow.position.set(x + 0.55, gy + h - 0.3, z); glow.scale.set(1.6, 1.6, 1); if (!K.noMesh) (parent || W.statics).add(glow); + return W.addLamp({ x: x + 0.55, y: gy + h - 0.35, z, r: 13, i: 0.9, power: 2.2, flicker: true }); + } + }; + // ---------------------------------------------------------------- grass and crops + // Crossed alpha cards. Grass is re-scattered round the camera as it moves (deterministic per 1.3 m cell), shrinking + // to nothing at the edge so it doesn't pop. accept(x,z) -> 0 (none) .. 1 (full height), tint(x,z,color). + function cardGeo2(w, h) { + const a = new THREE.PlaneGeometry(w, h, 1, 2).toNonIndexed(); a.translate(0, h / 2, 0); + const b2 = a.clone(); b2.rotateY(Math.PI / 2); + const pos = Array.from(a.attributes.position.array).concat(Array.from(b2.attributes.position.array)); + const uv = Array.from(a.attributes.uv.array).concat(Array.from(b2.attributes.uv.array)); + const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3)); g.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2)); + const n = new Float32Array(pos.length), col = new Float32Array(pos.length); + for (let i = 0; i < pos.length / 3; i++) { n[i * 3 + 1] = 1; const k = 0.45 + 0.55 * (pos[i * 3 + 1] / h); col[i * 3] = col[i * 3 + 1] = col[i * 3 + 2] = k; } + g.setAttribute('normal', new THREE.BufferAttribute(n, 3)); g.setAttribute('color', new THREE.BufferAttribute(col, 3)); + return g; + } + K.grassSystem = function (count, radius, accept, tint) { + const mat = new THREE.MeshStandardMaterial({ map: W.tex.grassCard(), alphaTest: 0.45, side: THREE.DoubleSide, vertexColors: true, roughness: 1 }); + const wind = W.windPatch(0.12, 1.7); + // grass right round you flattens away while you're prone or using a scope, so it never fills the view + mat.onBeforeCompile = sh => { wind(sh); sh.uniforms.uClear = W.grassClear; sh.vertexShader = 'uniform vec4 uClear;\n' + sh.vertexShader.replace('#include ', 'if (uClear.w > 0.0) { float dc = distance(ip.xz, uClear.xz); transformed *= mix(1.0, smoothstep(uClear.w * 0.6, uClear.w, dc), 1.0); }\n#include '); }; + const im = new THREE.InstancedMesh(cardGeo2(0.9, 0.55), mat, count); + im.setColorAt(count - 1, new THREE.Color(1, 1, 1)); // allocate the colour buffer at full size first + im.count = 0; im.frustumCulled = false; im.receiveShadow = true; + W.statics.add(im); + let lx = 1e9, lz = 1e9; + const cell = 1.3, col = new THREE.Color(); + const sys = { im, update(cx, cz) { + if (Math.hypot(cx - lx, cz - lz) < 3) return; lx = cx; lz = cz; + let n = 0; const r = Math.ceil(radius / cell); + const i0 = Math.floor(cx / cell), j0 = Math.floor(cz / cell); + // spiral-ish: near cells first so the count cap trims the far edge + const cells = sys.order || (sys.order = (() => { const a = []; for (let i = -r; i <= r; i++) for (let j = -r; j <= r; j++) { const d = Math.hypot(i, j) * cell; if (d <= radius) a.push([i, j, d]); } return a.sort((p, q) => p[2] - q[2]); })()); + for (const [di, dj, d] of cells) { + if (n >= count) break; + const i = i0 + di, j = j0 + dj, h1 = IV.hash2(i, j), h2 = IV.hash2(i + 71, j - 13), h3 = IV.hash2(i - 5, j + 37); + const x = (i + h1) * cell, z = (j + h2) * cell, k = accept(x, z); + if (k <= 0.05) continue; + const edge = IV.clamp((radius - Math.hypot(x - cx, z - cz)) / 6, 0, 1), s = (0.7 + h3 * 0.7) * k * edge; + if (s < 0.05) continue; + _e.set(0, h1 * 6.28, 0); _q.setFromEuler(_e); _v.set(x, W.height(x, z) - 0.03, z); _s.set(s, s * (0.8 + h2 * 0.6), s); + _m.compose(_v, _q, _s); im.setMatrixAt(n, _m); + tint(x, z, col); col.multiplyScalar(0.85 + h3 * 0.3).convertSRGBToLinear(); im.setColorAt(n, col); n++; + } + im.count = n; im.instanceMatrix.needsUpdate = true; if (im.instanceColor) im.instanceColor.needsUpdate = true; + } }; + return sys; + }; + // A field of crops (static): clumps of tall stalk cards over a polygon. Hides a crouched or prone soldier. + K.crops = function (poly, density, h, color) { + let minx = 1e9, maxx = -1e9, minz = 1e9, maxz = -1e9; + for (const p of poly) { minx = Math.min(minx, p[0]); maxx = Math.max(maxx, p[0]); minz = Math.min(minz, p[1]); maxz = Math.max(maxz, p[1]); } + const step = 1 / Math.sqrt(density), list = []; + for (let x = minx; x < maxx; x += step) for (let z = minz; z < maxz; z += step) { + const jx = x + (IV.hash2(x * 10 | 0, z * 10 | 0) - 0.5) * step, jz = z + (IV.hash2(z * 10 | 0, x * 10 | 0) - 0.5) * step; + if (!IV.inPoly(jx, jz, poly)) continue; + list.push([jx, jz]); + } + const mat = new THREE.MeshStandardMaterial({ map: W.tex.wheat(), alphaTest: 0.5, side: THREE.DoubleSide, vertexColors: true, roughness: 1, color: color || 0xb0a070 }); + mat.onBeforeCompile = W.windPatch(0.09, 1.3); + const im = new THREE.InstancedMesh(cardGeo2(1.2, h || 1.15), mat, list.length); + const c = new THREE.Color(); + list.forEach((p, i) => { + const r = IV.hash2(p[0] * 7 | 0, p[1] * 7 | 0); + _e.set(0, r * 6.28, 0); _q.setFromEuler(_e); _v.set(p[0], W.height(p[0], p[1]) - 0.05, p[1]); _s.set(1, 0.85 + r * 0.3, 1); + _m.compose(_v, _q, _s); im.setMatrixAt(i, _m); c.setRGB(0.9 + r * 0.2, 0.9 + r * 0.15, 0.85 + r * 0.1).convertSRGBToLinear(); im.setColorAt(i, c); + }); + im.receiveShadow = true; im.castShadow = false; + W.statics.add(im); + return im; + }; +})(); diff --git a/e63334287a3deaa3/ironveil/js/main.js b/e63334287a3deaa3/ironveil/js/main.js new file mode 100644 index 00000000..df530428 --- /dev/null +++ b/e63334287a3deaa3/ironveil/js/main.js @@ -0,0 +1,224 @@ +/* Ironveil main: boot (characters: chars.js if present, else the built-in stand-in), the fixed-timestep loop with + interpolation, the app state (menu / loading / play / paused / results) and the test hooks (window.__IV__ with ?test). */ +(function () { + 'use strict'; + const $ = IV.$, W = IV.world, T = IV.TUNING, UI = IV.menus, M = IV.mission; + IV.time = 0; + let state = 'boot'; + IV.playing = () => state === 'play'; + IV.state = () => state; + + // ---------------------------------------------------------------- boot + function loadScript(src) { return new Promise((res, rej) => { const s = document.createElement('script'); s.src = src; s.onload = res; s.onerror = rej; document.head.appendChild(s); }); } + function progress(k, txt) { $('loadBar').style.width = Math.round(k * 100) + '%'; if (txt != null) $('loadTx').textContent = IV.t(txt); } + async function boot() { + IV.applyName(); document.addEventListener('backroom:lang', IV.applyName); + progress(0.05, 'Loading soldiers…'); + if (!IV.params.has('standin')) { try { await loadScript('chars.js'); } catch (e) { /* not there yet: use the stand-in */ } } + if (!window.IVChars || window.IVChars.standin === undefined && !window.IVChars.spawn) await loadScript('js/chars-standin.js'); + if (!window.IVChars) await loadScript('js/chars-standin.js'); + try { await IVChars.load(k => progress(0.05 + k * 0.4, 'Loading soldiers…')); } + catch (e) { console.warn('chars.js failed, using the stand-in', e); window.IVChars = null; await loadScript('js/chars-standin.js'); await IVChars.load(); } + W.init($('view')); + if (window.IVChars) IVChars.camera = W.camera; // chars.js uses it for LOD and far-actor throttling + // Workaround for older chars.js builds (reported to its helper, fixed in its own update() since 0b524c1): three r128's mixer only writes a bone when its animated value + // changes, so the aim offset and IK that chars.js applies after mixer.update() pile up frame after frame while a + // pose is still (the body folds forward). Each frame we put the bones back to last frame's mixer result before + // update() runs, so the post-mixer passes always start from the animation. + if (window.IVChars && !IVChars.standin && !IVChars.__noAccum) { + const spawn0 = IVChars.spawn.bind(IVChars); + IVChars.spawn = function (kind) { + const a = spawn0(kind); if (!a || a.fb) return a; + if (/_accuIndex/.test(String(a.update))) return a; // chars.js now fixes this itself (since war-chars 0b524c1) + const bones = []; a.root.traverse(o => { if (o.isBone) bones.push(o); }); + const snap = bones.map(() => [new THREE.Quaternion(), new THREE.Vector3()]); let have = false, taken = false; + const take = () => { if (taken) return; taken = true; have = true; for (let i = 0; i < bones.length; i++) { snap[i][0].copy(bones[i].quaternion); snap[i][1].copy(bones[i].position); } }; + for (const k of ['_applyAim', '_post']) if (typeof a[k] === 'function') { const f = a[k]; a[k] = function () { take(); return f.apply(this, arguments); }; } + const up0 = a.update; + a.update = function (dt) { + if (have) for (let i = 0; i < bones.length; i++) { bones[i].quaternion.copy(snap[i][0]); bones[i].position.copy(snap[i][1]); } + taken = false; return up0.call(this, dt); + }; + return a; + }; + } + // the environment art (ironveil/env/env.js, window.IVEnv) if it is there; the code-made stand-ins otherwise + // the environment kit (?noenv keeps the code-made stand-ins, for comparison) + if (window.IVEnv && IVEnv.init && !IV.params.has('noenv')) { + try { IVEnv.init(W.renderer, ['low', 'medium', 'high'][W.quality]); if (IVEnv.load) await IVEnv.load(k => progress(0.45 + k * 0.1, 'Loading the countryside…')); IVEnv.ready = true; } + catch (e) { console.warn('env failed, using stand-ins', e); IVEnv.ready = false; } + } + IV.hud.init(); + UI.applySettings(); + // the title backdrop: Night Drop's farmland at night, a slow drifting camera + const nd = IV.missions.byId.nightdrop; + await M.loadWorld(nd, (k, t) => progress(0.45 + k * 0.5, t)); + if (nd.backdrop) nd.backdrop(M); + W.linearize(W.scene); + progress(1, ''); + state = 'menu'; + if (UI.needsGate()) UI.show('gate'); else UI.title(); + requestAnimationFrame(frame); + } + + // ---------------------------------------------------------------- app control + const app = IV.app = {}; + app.start = async function (id, cpIdx) { + const def = IV.missions.byId[id]; if (!def) return; + if (!IV.playable(id)) { UI.campaign(); return; } // preview build: Boot Camp only, whatever asked for this + state = 'loading'; UI.show('loading'); progress(0, 'Loading…'); IV.hud.show(false); + M.setDiff(IV.save.diff | 0); + if (M.worldId !== id) await M.loadWorld(def, progress); + const cp = IV.save.cp; + const data = cpIdx && cp && cp.mission === id ? cp.data : null; + if (!cpIdx && cp && cp.mission === id) { IV.save.cp = null; IV.persist(); } + if (cp && cp.mission === id && cpIdx) M.setDiff(cp.diff | 0); + M.begin(data ? cpIdx : 0, data); + play(); + }; + app.continueGame = function () { + const cp = IV.save.cp; + if (cp && IV.missions.byId[cp.mission] && IV.playable(cp.mission)) { IV.save.diff = cp.diff | 0; app.start(cp.mission, cp.idx); return; } + const next = IV.missions.list.find(d => !(IV.save.missions[d.id] || {}).done && IV.playable(d.id)); + if (next) UI.briefing(next); else UI.campaign(); + }; + app.retry = function (fromCp) { + UI.hideAll(); M.restoreCheckpoint(); play(); + }; + function play() { + UI.hideAll(); IV.hud.reset(); IV.hud.show(true); IV.hud.objectives(); + IV.touchUI.reset(); + state = 'play'; IV.input.clear(); acc = 0; + IV.fp && IV.fp.warm && IV.fp.warm(); // the first-person arms' shaders compiled now, not on the first shot + if (!IV.touch) IV.input.requestLock(false); + IV.audio.ambience(W.day ? 'day' : 'night'); IV.audio.music(true); + $('fade').style.opacity = 0; + } + app.pause = function () { + if (state !== 'play') return; + state = 'paused'; IV.input.clear(); IV.input.unlock(); + const a = M.objs.filter(o => o.state === 'active' && !o.optional)[0]; + $('pauseObj').textContent = a ? IV.t(a.text) : ''; + $('pauseMsg').textContent = ''; + UI.show('pause'); + }; + app.resume = function () { + if (state !== 'paused') return; + UI.hideAll(); state = 'play'; acc = 0; + if (!IV.touch) IV.input.requestLock(true); + }; + app.quit = function () { + state = 'menu'; IV.hud.show(false); IV.input.unlock(); IV.audio.stopAmbience(); IV.audio.music(false); + const nd = IV.missions.byId.nightdrop; + if (M.worldId === 'nightdrop' && nd.backdrop) { IV.ai.reset(); IV.ally.remove(); nd.backdrop(M); UI.campaign(); } + else { state = 'loading'; UI.show('loading'); M.loadWorld(nd, progress).then(() => { nd.backdrop(M); state = 'menu'; UI.campaign(); }); } + }; + IV.on('escape', () => { + if (IV.input.KB.busy()) return; + if (state === 'play') app.pause(); + else if (state === 'paused' && UI.cur === 'pause') app.resume(); + else if (UI.cur === 'settings') document.querySelector('#settings [data-go="back"]').click(); + else if (UI.cur === 'campaign' || UI.cur === 'briefing') UI.show(UI.cur === 'briefing' ? 'campaign' : 'title'); + }); + IV.on('lostlock', () => { if (state === 'play' && !IV.touch) app.pause(); }); + IV.on('missionComplete', s => { setTimeout(() => { if (!M.finished) return; state = 'results'; IV.hud.show(false); IV.input.unlock(); IV.audio.music(false); UI.results(s); }, 1600); }); + // killed: a short fade and straight back to the last checkpoint (a campaign keeps you playing); other failures show why + IV.on('missionFailed', r => { + if (r === 'You were killed.' && !IV.test) { $('fade').style.opacity = 1; IV.hud.toast(IV.t('Killed. Back to the last checkpoint.')); setTimeout(() => { if (!M.failed) return; app.retry(true); $('fade').style.opacity = 0; }, 1400); return; } + setTimeout(() => { if (!M.failed) return; state = 'results'; IV.hud.show(false); IV.input.unlock(); UI.failed(r); }, 900); }); + document.addEventListener('visibilitychange', () => { if (document.hidden && state === 'play' && !IV.test) app.pause(); }); + + // ---------------------------------------------------------------- the loop + const STEP = T.step; + let acc = 0, last = 0, alpha = 0, paused = false; + IV.timeScale = 1; + function simulate(dt) { + IV.time += dt; + IV.input.beginStep(); + if (IV.input.pressed('mute')) IV.audio.toggleMute(); + if (IV.input.pressed('shoulder')) IV.camera.side *= -1; + if (IV.input.pressed('pause')) { app.pause(); return; } + IV.player.step(dt); + IV.weapons.step(dt); + IV.ally.step(dt); + IV.ai.step(dt); + M.step(dt); + } + // First thing to go when frames are slow: the environment's parallax occlusion on brick, stone and tile (it more than + // doubled a wall-filling frame in a software test). After about two seconds averaging under 30 fps it is compiled + // out of every material for the rest of the visit (one short hitch while shaders rebuild). Low never has it. + let pomAvg = 1 / 60, pomSlow = 0; + function dropParallax(why) { + const E = window.IVEnv; if (!E || !E.Q || !E.Q.pom) return false; + E.Q.pom = false; let n = 0; + W.scene.traverse(o => { const ms = o.material ? (Array.isArray(o.material) ? o.material : [o.material]) : []; for (const m of ms) if (m.defines && 'ENV_POM' in m.defines) { delete m.defines.ENV_POM; delete m.defines.ENV_POM_STEPS; delete m.defines.ENV_POM_FAR; m.needsUpdate = true; n++; } }); + IV.pomDropped = { why, materials: n, t: IV.time }; return true; + } + IV.dropParallax = dropParallax; + function watchFrames(dt) { + if (IV.test || !window.IVEnv || !IVEnv.Q || !IVEnv.Q.pom) return; + pomAvg += (dt - pomAvg) * 0.05; + pomSlow = pomAvg > 1 / 30 ? pomSlow + dt : 0; + if (pomSlow > 2) dropParallax('slow frames'); + } + function render(dt) { + watchFrames(dt); + IV.frameNo = (IV.frameNo || 0) + 1; + IV.player.frame(alpha, dt); + IV.ai.frame(alpha, dt); + IV.ally.frame(alpha, dt); + IV.ambience && IV.ambience.frame(dt); + const I = IV.input; + if (I.dx || I.dy) { IV.camera.look(I.dx, I.dy, false); I.dx = I.dy = 0; } + IV.camera.frame(dt); + IV.weapons.frame(); + IV.fx.frame(dt); + IV.art.frame(dt); + W.frame(dt, IV.player.render); + if (M.def && M.def.frame) M.def.frame(M, dt); + IV.hud.frame(dt); + IV.touchUI.frame(); + W.draw(dt); + } + function frame(now) { + requestAnimationFrame(frame); + if (paused) return; + const dt = Math.min(0.1, (now - (last || now)) / 1000); last = now; + if (state === 'play') { + acc += dt * IV.timeScale; + let n = 0; + while (acc >= STEP && n < 6) { simulate(STEP); acc -= STEP; n++; if (state !== 'play') break; } + if (n === 6) acc = 0; + alpha = acc / STEP; + render(dt); + } else if (state === 'menu' || state === 'paused' || state === 'results') { + IV.time += dt * (state === 'paused' ? 0 : 1); + if (state === 'menu' && M.def && M.def.backdropFrame) M.def.backdropFrame(M, dt); + if (state !== 'paused') { IV.ai.frame(1, dt); IV.ally.frame(1, dt); if (IV.player.actor && IV.player.actor.root.parent) IV.player.frame(1, dt); } + IV.fx.frame(dt); W.frame(dt, W.camera.position); + if (state === 'menu' && IV.camera.override) IV.camera.frame(dt); + IV.art.frame(dt); + W.draw(dt); + } + } + + // ---------------------------------------------------------------- test hooks (?test) + if (IV.test) { + window.__IV__ = { + IV, state: () => state, + pauseLoop(on) { paused = on; }, + step(n) { for (let i = 0; i < (n || 1); i++) { if (state !== 'play') break; simulate(STEP); } alpha = 1; }, + render() { render(STEP); }, + press(id, on) { IV.input.sim(id, on); }, + look(yaw, pitch) { IV.player.yaw = yaw; if (pitch != null) IV.player.pitch = pitch; }, + navRebuild() { return IV.nav.rebuild(); }, + ambience(kind, pos, o) { return IV.ambience.event(kind, pos, o); }, + teleport(x, z, yaw) { IV.player.pos.set(x, W.groundAt(x, z, 50), z); IV.player.prev.copy(IV.player.pos); if (yaw != null) IV.player.yaw = IV.player.bodyYaw = yaw; }, + info() { const r = W.renderer.info; return { calls: r.render.calls, tris: r.render.triangles, geos: r.memory.geometries, tex: r.memory.textures }; }, + start: (id, cp) => app.start(id, cp || 0), + snapshot() { const P = IV.player; return { state, mission: M.def && M.def.id, phase: M.phase, time: M.time, p: { x: +P.pos.x.toFixed(2), y: +P.pos.y.toFixed(2), z: +P.pos.z.toFixed(2), hp: Math.round(P.hp), stance: P.stance, alive: P.alive }, objs: M.objs.map(o => o.id + ':' + o.state), enemies: IV.ai.list.map(e => ({ k: e.kind, s: e.state, aw: +e.aw.toFixed(2), x: +e.pos.x.toFixed(1), z: +e.pos.z.toFixed(1), alive: e.alive })), flags: M.flags, done: M.finished, failed: M.failed }; } + }; + } + addEventListener('error', e => { if (IV.test) IV.err('Error: ' + e.message + ' ' + (e.filename || '').split('/').pop() + ':' + e.lineno); }); + boot().catch(e => { IV.err(IV.GAME_NAME + ' could not start: ' + e.message); console.error(e); }); +})(); diff --git a/e63334287a3deaa3/ironveil/js/menus.js b/e63334287a3deaa3/ironveil/js/menus.js new file mode 100644 index 00000000..e9fb88fd --- /dev/null +++ b/e63334287a3deaa3/ironveil/js/menus.js @@ -0,0 +1,174 @@ +/* Ironveil menus: the content note (first launch), title, the map table (campaign list, difficulty), the briefing + dossier with its sketch map, pause, settings, results and the failure screen. Screens are plain DOM over the live + scene; IV.app (main.js) does the starting and stopping. */ +(function () { + 'use strict'; + const $ = IV.$; + const UI = IV.menus = { stack: [] }; + const SCREENS = ['gate', 'title', 'campaign', 'briefing', 'pause', 'settings', 'results', 'loading']; + UI.show = function (id) { + SCREENS.forEach(s => { $(s).hidden = s !== id; }); + UI.cur = id; + const first = $(id) && $(id).querySelector('button:not([disabled]):not([hidden])'); + if (first && !IV.touch) setTimeout(() => first.focus({ preventScroll: true }), 30); + }; + UI.hideAll = function () { SCREENS.forEach(s => { $(s).hidden = true; }); UI.cur = null; }; + + // ---------------------------------------------------------------- campaign data (missions 2-8 are planned) + UI.COMING = [ + { num: 2, title: 'The Radio Mast', line: 'A signals compound with three ways in. Silence the transmitter before it calls in the guns.' }, + { num: 3, title: 'Bridge at Dawn', line: 'Take the river bridge with the platoon, then hold it through three counter-attacks.' }, + { num: 4, title: 'The Clocktower', line: 'Sniper overwatch over an occupied town while a courier crosses the square.' }, + { num: 5, title: 'Rail Yard', line: 'Charges on a fuel train, a fuse already burning, and a truck out of the yard.' }, + { num: 6, title: 'The Chateau', line: 'Lift the plans from an officers\' dinner. If the alarm goes, out through the cellars.' }, + { num: 7, title: 'The Bunker Line', line: 'Trenches, pillboxes and machine-gun nests, with the whole company behind you.' }, + { num: 8, title: 'Last Light', line: 'A mountain research site, a prototype to wreck and a long shot at a fleeing convoy.' } + ]; + UI.campaign = function () { + const box = $('missionList'); box.innerHTML = ''; + const S = IV.save; + for (const def of IV.missions.list) { + const rec = S.missions[def.id] || {}; + const preview = !IV.playable(def.id); // preview build: shown, locked, 'In progress' + const locked = preview || def.num > 0 && !(S.missions[IV.missions.list[def.num - 1] && IV.missions.list[def.num - 1].id] || {}).done && !IV.params.has('unlock'); + const b = document.createElement('button'); b.className = 'ms'; b.disabled = locked; + b.innerHTML = `${def.num === 0 ? '0' : def.num}${IV.t(def.title)}${IV.t(def.line)}${rec.done ? IV.t('Done') + (rec.medal ? `` : '') + (rec.best ? `
${IV.fmtTime(rec.best)}` : '') : preview ? IV.t('In progress') : locked ? IV.t('Locked') : IV.t('New')}
`; + b.addEventListener('click', () => { if (!IV.playable(def.id)) return; IV.audio.play('uiOk'); UI.briefing(def); }); + box.appendChild(b); + } + for (const c of UI.COMING) { + const b = document.createElement('button'); b.className = 'ms'; b.disabled = true; + b.innerHTML = `${c.num}${IV.t(c.title)}${IV.t(c.line)}${IV.t('Coming soon')}`; + box.appendChild(b); + } + document.querySelectorAll('#diffPick button').forEach(b => b.setAttribute('aria-pressed', String(+b.dataset.d === S.diff))); + UI.show('campaign'); + }; + document.querySelectorAll('#diffPick button').forEach(b => b.addEventListener('click', () => { IV.save.diff = +b.dataset.d; IV.persist(); IV.audio.play('ui'); document.querySelectorAll('#diffPick button').forEach(x => x.setAttribute('aria-pressed', String(x === b))); })); + + // ---------------------------------------------------------------- briefing + UI.briefing = function (def) { + if (!IV.playable(def.id)) { UI.campaign(); return; } // preview build + UI.cur_def = def; + $('bTitle').textContent = IV.t(def.title); + $('bStamp').textContent = IV.t(def.num === 0 ? 'Training' : 'Secret'); + $('bBody').innerHTML = def.briefing.map(p => `

${IV.t(p)}

`).join(''); + $('bObj').innerHTML = def.preview.map(o => `${IV.t(o.text)}${o.opt ? ' (' + IV.t('optional') + ')' : ''}`).join(''); + $('bSkip').hidden = !(def.id === 'bootcamp' && IV.save.tut); + const c = $('sketch'), g = c.getContext('2d'); + paper(g, c.width, c.height); + def.sketch && def.sketch(g, c.width, c.height, sk); + UI.show('briefing'); + }; + $('bGo').addEventListener('click', () => { IV.audio.play('uiOk'); IV.app.start(UI.cur_def.id, 0); }); + $('bSkip').addEventListener('click', () => { const nd = IV.missions.byId.nightdrop; if (nd) UI.briefing(nd); }); + // pencil-sketch helpers for the briefing maps (a wobbly hand-drawn line, hatching, labels) + function paper(g, w, h) { + g.fillStyle = '#ddd0b2'; g.fillRect(0, 0, w, h); + const R = IV.rng(11); + for (let i = 0; i < 2500; i++) { g.fillStyle = `rgba(${R() < 0.5 ? '120,100,60' : '255,250,230'},${0.04 + R() * 0.05})`; g.fillRect(R() * w, R() * h, 2, 2); } + g.strokeStyle = 'rgba(80,90,120,.15)'; g.lineWidth = 1; for (let x = 0; x < w; x += 45) { g.beginPath(); g.moveTo(x, 0); g.lineTo(x, h); g.stroke(); } for (let y = 0; y < h; y += 45) { g.beginPath(); g.moveTo(0, y); g.lineTo(w, y); g.stroke(); } + } + const sk = { + line(g, pts, o) { o = o || {}; g.strokeStyle = o.c || 'rgba(40,36,24,.85)'; g.lineWidth = o.w || 2.2; g.lineCap = 'round'; g.lineJoin = 'round'; if (o.dash) g.setLineDash(o.dash); const R = IV.rng(pts.length * 31 + (pts[0][0] | 0)); + for (let pass = 0; pass < (o.passes || 2); pass++) { g.beginPath(); pts.forEach((p, i) => { const x = p[0] + (R() - 0.5) * 2.2, y = p[1] + (R() - 0.5) * 2.2; i ? g.lineTo(x, y) : g.moveTo(x, y); }); g.stroke(); } g.setLineDash([]); }, + hatch(g, poly, o) { o = o || {}; g.save(); g.beginPath(); poly.forEach((p, i) => i ? g.lineTo(p[0], p[1]) : g.moveTo(p[0], p[1])); g.closePath(); g.clip(); g.strokeStyle = o.c || 'rgba(60,50,30,.35)'; g.lineWidth = 1.2; const s = o.s || 9; for (let k = -1000; k < 2000; k += s) { g.beginPath(); g.moveTo(k, 0); g.lineTo(k + (o.slope || 600), 900); g.stroke(); } g.restore(); sk.line(g, poly.concat([poly[0]]), { w: 1.6, passes: 1, c: o.edge }); }, + text(g, t, x, y, o) { o = o || {}; g.save(); g.translate(x, y); g.rotate(o.rot || -0.03); g.font = `${o.size || 22}px "Special Elite", monospace`; g.fillStyle = o.c || 'rgba(40,36,24,.9)'; g.textAlign = o.align || 'left'; g.fillText(IV.t(t), 0, 0); g.restore(); }, + x(g, x, y, s, c) { sk.line(g, [[x - s, y - s], [x + s, y + s]], { c: c || '#8a2a1c', w: 3 }); sk.line(g, [[x + s, y - s], [x - s, y + s]], { c: c || '#8a2a1c', w: 3 }); }, + circle(g, x, y, r, c) { const pts = []; for (let i = 0; i <= 24; i++) pts.push([x + Math.cos(i / 24 * 6.283) * r, y + Math.sin(i / 24 * 6.283) * r]); sk.line(g, pts, { c: c || '#8a2a1c', w: 2.4 }); }, + arrow(g, pts, c) { sk.line(g, pts, { c: c || '#2f4a7a', w: 2.6, dash: [10, 7] }); const a = pts[pts.length - 1], b = pts[pts.length - 2], ang = Math.atan2(a[1] - b[1], a[0] - b[0]); sk.line(g, [[a[0] - Math.cos(ang - 0.5) * 16, a[1] - Math.sin(ang - 0.5) * 16], a, [a[0] - Math.cos(ang + 0.5) * 16, a[1] - Math.sin(ang + 0.5) * 16]], { c: c || '#2f4a7a', w: 2.6 }); } + }; + UI.sk = sk; + + // ---------------------------------------------------------------- results / failure + UI.results = function (s) { + const def = IV.mission.def; + $('rTitle').textContent = IV.t(def.num === 0 ? 'Training complete' : 'Mission complete'); + const m = $('rMedal'); m.style.background = s.medal === 'gold' ? '#d9b44a' : s.medal === 'silver' ? '#b9bec4' : '#b0763f'; m.textContent = s.medal === 'gold' ? 'I' : s.medal === 'silver' ? 'II' : 'III'; + $('rMedalTx').textContent = IV.t(s.medal === 'gold' ? 'Gold' : s.medal === 'silver' ? 'Silver' : 'Bronze'); + $('rDiff').textContent = IV.t(IV.mission.DIFF[s.diff].name); + $('rCrit').innerHTML = s.crit.map(c => `
  • ${c.text}
  • `).join(''); + const rows = [['Time', IV.fmtTime(s.time)], ['Accuracy', s.shots ? s.acc + '%' : '—'], ['Times spotted', s.spotted], ['Enemies down', s.kills], ['Takedowns', s.takedowns], ['Optional objectives', s.optional + ' / ' + s.optionalTotal]]; + $('rStats').innerHTML = rows.map(r => `${IV.t(r[0])}${r[1]}`).join(''); + const next = IV.missions.list.find(d => d.num === def.num + 1 && IV.playable(d.id)); + $('rNext').hidden = false; + $('rNext').textContent = IV.t(next ? 'Next: {t}' : 'Map table', { t: next ? IV.t(next.title) : '' }); + $('rNext').onclick = () => { IV.audio.play('uiOk'); if (next) UI.briefing(next); else UI.campaign(); }; + $('rRetry').textContent = IV.t('Replay'); $('rRetry').onclick = () => { IV.audio.play('uiOk'); IV.app.start(def.id, 0); }; + UI.show('results'); + }; + UI.failed = function (reason) { + const def = IV.mission.def; + $('rTitle').textContent = IV.t('Mission failed'); + const m = $('rMedal'); m.style.background = '#5a2018'; m.textContent = '✕'; + $('rMedalTx').textContent = IV.t(reason || 'Mission failed'); $('rDiff').textContent = ''; + $('rCrit').innerHTML = ''; $('rStats').innerHTML = ''; + const hasCp = IV.save.cp && IV.save.cp.mission === def.id && IV.save.cp.idx > 0; + $('rNext').textContent = IV.t(hasCp ? 'Retry from checkpoint' : 'Retry'); + $('rNext').onclick = () => { IV.audio.play('uiOk'); IV.app.retry(true); }; + $('rRetry').textContent = IV.t('Restart mission'); $('rRetry').onclick = () => { IV.audio.play('uiOk'); IV.app.start(def.id, 0); }; + UI.show('results'); + }; + + // ---------------------------------------------------------------- settings + const S = () => IV.settings; + const binds = [['sSens', 'sens', 'range'], ['sAimSens', 'aimSens', 'range'], ['sInvert', 'invert', 'check'], ['sAssist', 'assist', 'range'], ['sAuto', 'auto', 'check'], ['sSub', 'sub', 'select'], ['sMotion', 'motion', 'check'], ['sView', 'view', 'select'], ['sBob', 'bob', 'check'], ['sBlood', 'blood', 'check'], + ['sQual', 'quality', 'select'], ['sFov', 'fov', 'range'], ['sBright', 'bright', 'range'], ['sVol', 'vol', 'range'], ['sSfx', 'sfx', 'range'], ['sMus', 'mus', 'range'], ['sMute', 'mute', 'check']]; + UI.settings = function (from) { + UI.settingsFrom = from || UI.cur; + for (const [id, k, t] of binds) { const el = $(id); if (t === 'check') el.checked = !!S()[k]; else el.value = S()[k]; } + UI.show('settings'); + }; + for (const [id, k, t] of binds) { + $(id).addEventListener(t === 'range' ? 'input' : 'change', e => { + const el = e.target; S()[k] = t === 'check' ? el.checked : t === 'select' ? (k === 'sub' ? parseFloat(el.value) : k === 'view' ? el.value : +el.value) : parseFloat(el.value); + IV.persist(); UI.applySettings(); + if (k === 'quality') IV.hud.toast(IV.t('Quality changes apply when the page reloads')); + }); + } + UI.applySettings = function () { + const s = S(); + document.documentElement.style.setProperty('--subscale', s.sub); + IV.audio.apply(); + if (IV.world.atm && IV.world.atm.setBrightness) IV.world.atm.setBrightness(s.bright); + else if (IV.world.renderer) IV.world.renderer.toneMappingExposure = 0.92 * s.bright; + // one grading path: with the environment kit's post stack on, it does the grain and vignette (the page's own CSS + // grain and vignette are for Low only); Reduced motion turns its film grain down + document.body.classList.toggle('envpost', !!IV.world.post); + if (IV.world.atm && IV.world.atm.setFlashes) IV.world.atm.setFlashes(!s.motion); // lightning on rainy skies + if (window.IVChars && !IVChars.standin) { IVChars.lodDistances = [[8, 22], [12, 30], [14, 40]][s.quality] || [12, 30]; IVChars.weaponLodDistance = s.quality === 0 ? 4 : 6; } // mid and far character LODs, sooner on Low + const G = window.IVEnv && IVEnv.GRADES; + if (G) for (const k in G) { const g = G[k]; if (g._grain == null) g._grain = g.grain; g.grain = g._grain * (s.motion ? 0.35 : 1); } + }; + document.querySelectorAll('.tabs [data-tab]').forEach(b => b.addEventListener('click', () => { + document.querySelectorAll('.tabs [data-tab]').forEach(x => x.setAttribute('aria-selected', String(x === b))); + document.querySelectorAll('.set[data-pane]').forEach(p => { p.hidden = p.dataset.pane !== b.dataset.tab; }); + })); + + // ---------------------------------------------------------------- buttons with data-go + document.addEventListener('click', e => { + const b = e.target.closest('[data-go]'); if (!b) return; + const go = b.dataset.go; IV.audio.play('ui'); + if (go === 'campaign') UI.campaign(); + else if (go === 'settings') UI.settings(); + else if (go === 'controls') IV.input.KB.open(); + else if (go === 'continue') IV.app.continueGame(); + else if (go === 'back') { if (UI.cur === 'settings') { UI.show(UI.settingsFrom === 'pause' ? 'pause' : UI.settingsFrom === 'campaign' ? 'campaign' : 'title'); } else UI.show('title'); } + else if (go === 'resume') IV.app.resume(); + else if (go === 'checkpoint') IV.app.retry(true); + else if (go === 'restart') IV.app.start(IV.mission.def.id, 0); + else if (go === 'quit') IV.app.quit(); + }); + $('gateOk').addEventListener('click', () => { + try { localStorage.setItem('ironveil:terms', '1'); } catch (e) {} + IV.settings.blood = true; IV.persist(); IV.audio.play('uiOk'); UI.title(); + }); + UI.title = function () { + const cp = IV.save.cp, def = cp && IV.playable(cp.mission) && IV.missions.byId[cp.mission]; + const next = IV.missions.list.find(d => !(IV.save.missions[d.id] || {}).done && IV.playable(d.id)); + $('miContinue').hidden = !(def || (IV.save.tut && next)); + $('contTx').textContent = def ? IV.t(def.title) + ' · ' + IV.t('checkpoint') : next ? IV.t(next.title) : ''; + UI.show('title'); + }; + UI.needsGate = function () { try { return localStorage.getItem('ironveil:terms') !== '1'; } catch (e) { return true; } }; +})(); diff --git a/e63334287a3deaa3/ironveil/js/mission.js b/e63334287a3deaa3/ironveil/js/mission.js new file mode 100644 index 00000000..9451b892 --- /dev/null +++ b/e63334287a3deaa3/ironveil/js/mission.js @@ -0,0 +1,175 @@ +/* Ironveil missions: a mission is data plus a few script functions (see missions/*.js and the README). This file runs + them: objectives that appear, complete and change mid-mission, triggers (enter an area, kill, interact, timer, any + condition), timed and chained script beats, radio lines as subtitles, interactables with hold-to-use, checkpoints that + restore the dynamic world (soldiers, squadmate, flags, objectives, loadout), fail states and the results/medals. */ +(function () { + 'use strict'; + const W = IV.world, T = IV.TUNING; + IV.missions = { list: [], byId: {} }; + IV.missions.register = function (def) { IV.missions.list.push(def); IV.missions.byId[def.id] = def; IV.missions.list.sort((a, b) => a.num - b.num); }; + const DIFF = [ + { name: 'Recruit', taken: 0.6, aware: 0.8, acc: 0.85 }, + { name: 'Regular', taken: 1, aware: 1, acc: 1 }, + { name: 'Veteran', taken: 1.45, aware: 1.25, acc: 1.15 } + ]; + const M = IV.mission = { def: null, diff: 0, diffMul: DIFF[0], on: false, time: 0, objs: [], flags: {}, trigs: [], timers: [], inter: [], radioQ: [], cpIdx: 0, group: null, phase: '', failed: false, finished: false, noWeapons: false }; + M.DIFF = DIFF; + + // ---------------------------------------------------------------- objectives + M.obj = function (id, text, o) { + o = o || {}; + let ob = M.objs.find(x => x.id === id); + if (!ob) { ob = { id, text, state: 'active', optional: !!o.optional, t: IV.time }; M.objs.push(ob); } + else { ob.text = text || ob.text; ob.state = 'active'; ob.t = IV.time; } + if (o.marker) ob.marker = o.marker; // {x,y,z} shown on the compass and in the world + ob.isNew = true; + if (!o.quiet) IV.audio && IV.audio.play('objective'); + IV.emit('objectives'); + return ob; + }; + M.done = function (id) { const ob = M.objs.find(x => x.id === id); if (ob && ob.state === 'active') { ob.state = 'done'; ob.t = IV.time; IV.emit('objectives'); IV.audio && IV.audio.play('objDone'); } }; + M.drop = function (id) { const ob = M.objs.find(x => x.id === id); if (ob) { ob.state = 'gone'; IV.emit('objectives'); } }; + M.isDone = id => { const ob = M.objs.find(x => x.id === id); return !!ob && ob.state === 'done'; }; + M.active = () => M.objs.filter(o => o.state === 'active' || (o.state === 'done' && IV.time - o.t < 4)); + M.setMarker = function (id, m) { const ob = M.objs.find(x => x.id === id); if (ob) ob.marker = m; }; + + // ---------------------------------------------------------------- triggers, timers, interactables, radio + // when: () => bool, checked every step until it fires (once unless repeat) + M.when = function (when, fn, o) { const t = Object.assign({ when, fn, once: true, on: true }, o || {}); M.trigs.push(t); return t; }; + M.after = function (sec, fn) { const t = { at: M.time + sec, fn }; M.timers.push(t); return t; }; + M.area = function (x, z, r) { return () => Math.hypot(IV.player.pos.x - x, IV.player.pos.z - z) < r; }; + M.box = function (x0, z0, x1, z1) { return () => { const p = IV.player.pos; return p.x > x0 && p.x < x1 && p.z > z0 && p.z < z1; }; }; + // a thing to use: {id, x,y,z, r, text, hold (s), on (bool or fn), done(fn)} + M.interact = function (o) { o.prog = 0; if (o.on == null) o.on = true; M.inter.push(o); return o; }; + M.interAt = null; + // radio / squad lines as subtitles, queued, each shown for dur seconds (default by length) + M.radio = function (who, text, dur, o) { + M.radioQ.push({ who, text, dur: dur || Math.max(2.2, text.length * 0.055), o: o || {} }); + }; + M.say = (text, dur) => M.radio(IV.ally.NAME, text, dur); + M.hq = (text, dur) => M.radio('Radio', text, dur, { squelch: true }); + let radioCur = null; + function stepRadio(dt) { + if (radioCur) { radioCur.t -= dt; if (radioCur.t <= 0) { radioCur = null; IV.hud && IV.hud.subtitle(null); } } + if (!radioCur && M.radioQ.length) { + radioCur = M.radioQ.shift(); radioCur.t = radioCur.dur; + IV.hud && IV.hud.subtitle(radioCur.who, radioCur.text); + IV.audio && IV.audio.play(radioCur.o.squelch ? 'squelch' : 'squad'); + } + } + M.radioBusy = () => !!radioCur || M.radioQ.length > 0; + + // ---------------------------------------------------------------- lifecycle + // build the static world for a mission (kept while replaying the same mission) + M.loadWorld = async function (def, progress) { + M.def = def; M.worldId = null; + IV.R = IV.rng(1944 + def.num); + progress && progress(0.1, 'Laying out the country…'); + await tick(); + W.setupLevel(def.world); + progress && progress(0.35, 'Planting hedgerows…'); + await tick(); + def.build(M); + IV.art.flush(); + IV.menus && IV.menus.applySettings(); + W.lamps.forEach(l => { l.static = true; }); + progress && progress(0.7, 'Walking the lanes…'); + await tick(); + IV.nav.build(); + IV.fx.init(); + W.linearize(W.scene); + progress && progress(0.95, 'Briefing the squad…'); + await tick(); + M.worldId = def.id; + }; + M.setDiff = function (diff) { M.diff = diff; M.diffMul = DIFF[diff]; M.awareMul = DIFF[diff].aware; M.enemyAccMul = DIFF[diff].acc; }; + const tick = () => new Promise(r => setTimeout(r, 16)); + // (re)start the dynamic part from a checkpoint index (0 = mission start). data = saved state for that checkpoint. + M.begin = function (cpIdx, data) { + M.on = true; M.failed = false; M.finished = false; M.cpIdx = cpIdx; M.phase = ''; + M.objs = []; M.trigs = []; M.timers = []; M.inter = []; M.radioQ = []; radioCur = null; IV.hud && IV.hud.subtitle(null); + M.flags = data ? JSON.parse(JSON.stringify(data.flags || {})) : {}; + M.time = data ? data.time : 0; + M.noWeapons = false; IV.camera.reset(); IV.ai.reset(); IV.ally.remove(); IV.ambience && IV.ambience.clear(); IV.fx.clear && IV.fx.clear(); + if (M.group) W.scene.remove(M.group); + M.group = new THREE.Group(); W.scene.add(M.group); + W.lamps = W.lamps.filter(l => l.static); + IV.audio && IV.audio.alarm(false); + IV.weapons.bullets.length = 0; IV.weapons.throws.length = 0; IV.targets = []; + M.def.setup(M, cpIdx, data); + if (data && data.stats) { IV.weapons.stats = Object.assign({}, data.stats); IV.ai.spottedCount = data.spotted || 0; } + if (data && data.objs) for (const o of data.objs) { const ob = M.objs.find(x => x.id === o.id); if (ob) { ob.state = o.state; ob.text = o.text; } else M.objs.push(Object.assign({}, o, { isNew: false })); } + if (data && data.inv) Object.assign(IV.weapons.inv, JSON.parse(JSON.stringify(data.inv))); + W.linearize(W.scene); + try { W.renderer.compile(W.scene, W.camera); } catch (e) {} // compile shaders now, not on the first shot + IV.emit('objectives'); IV.emit('missionBegin', cpIdx); + }; + M.checkpoint = function (idx) { + if (idx <= M.cpIdx && idx !== 0) return; + M.cpIdx = idx; + const data = { flags: JSON.parse(JSON.stringify(M.flags)), time: M.time, stats: Object.assign({}, IV.weapons.stats), spotted: IV.ai.spottedCount, + objs: M.objs.filter(o => o.state !== 'gone').map(o => ({ id: o.id, text: o.text, state: o.state, optional: o.optional })), inv: JSON.parse(JSON.stringify(IV.weapons.inv)) }; + IV.save.cp = { mission: M.def.id, diff: M.diff, idx, data, v: 1 }; + IV.persist(); + IV.hud && IV.hud.toast(IV.t('Checkpoint reached')); + IV.emit('checkpoint', idx); + }; + M.restoreCheckpoint = function () { + const cp = IV.save.cp; + if (cp && cp.mission === M.def.id && cp.idx > 0) M.begin(cp.idx, cp.data); else M.begin(0, null); + }; + M.fail = function (reason) { + if (M.failed || M.finished) return; + M.failed = true; M.on = false; + IV.emit('missionFailed', reason); + }; + M.complete = function () { + if (M.finished || M.failed) return; + M.finished = true; M.on = false; + const st = IV.weapons.stats, def = M.def; + const s = { time: M.time, shots: st.shots, hits: st.hits, acc: st.shots ? Math.round(st.hits / st.shots * 100) : 0, kills: st.kills, heads: st.heads, takedowns: st.takedowns, spotted: IV.ai.spottedCount, + optional: M.objs.filter(o => o.optional && o.state === 'done').length, optionalTotal: def.optionalTotal || M.objs.filter(o => o.optional).length, diff: M.diff }; + const crit = (def.medals || []).map(c => ({ text: IV.t(c.text, c.vars), ok: !!c.ok(s, M) })); + const n = crit.filter(c => c.ok).length; + s.medal = n >= 3 ? 'gold' : n >= 2 ? 'silver' : 'bronze'; s.crit = crit; + const rec = IV.save.missions[def.id] = IV.save.missions[def.id] || {}; + const rank = { bronze: 1, silver: 2, gold: 3 }; + rec.done = true; rec.last = s.medal; + if (!rec.medal || rank[s.medal] > rank[rec.medal]) rec.medal = s.medal; + if (!rec.best || s.time < rec.best) rec.best = Math.round(s.time); + if (def.id === 'bootcamp') IV.save.tut = true; + if (IV.save.cp && IV.save.cp.mission === def.id) IV.save.cp = null; + IV.persist(); + window.BackRoomStats && BackRoomStats.add('missions', 1); + window.BackRoomStats && BackRoomStats.min('time:' + def.id, Math.round(s.time)); + IV.emit('missionComplete', s); + }; + + M.step = function (dt) { + if (!M.on) { stepRadio(dt); return; } + M.time += dt; + for (let i = M.timers.length - 1; i >= 0; i--) { const t = M.timers[i]; if (M.time >= t.at) { M.timers.splice(i, 1); t.fn(); if (!M.on) return; } } + for (const t of M.trigs) { if (!t.on) continue; if (t.when()) { if (t.once) t.on = false; t.fn(); if (!M.on) return; } } + if (M.trigs.length > 60) M.trigs = M.trigs.filter(t => t.on); + // interactables: the nearest usable one in front of you + const P = IV.player, I = IV.input; + let best = null, bd = 9; + if (P.alive && !P.frozen) for (const o of M.inter) { + const on = typeof o.on === 'function' ? o.on() : o.on; if (!on || (P.cine && !o.cine)) continue; + const d = Math.hypot(P.pos.x - o.x, P.pos.z - o.z); if (d > (o.r || 1.6) || Math.abs((o.y != null ? o.y : P.pos.y) - P.pos.y - 0.8) > 2) continue; + if (d < bd) { bd = d; best = o; } + } + M.interAt = best; + for (const o of M.inter) if (o !== best) o.prog = 0; + if (best) { + if (I.held('use')) { + best.prog += dt / (best.hold || 0.01); + if (best.prog >= 1) { best.prog = 0; best.on = false; IV.emit('interacted', best); best.done && best.done(); } + } else best.prog = 0; + } + if (M.def.step) M.def.step(M, dt); + stepRadio(dt); + if (!P.alive && !M.failed) { M.deadT = (M.deadT || 0) + dt; if (M.deadT > 2.6) { M.deadT = 0; M.fail('You were killed.'); } } else M.deadT = 0; + if (IV.ally.ent && !IV.ally.ent.alive && !M.failed && M.def.needAlly) { M.allyT = (M.allyT || 0) + dt; if (M.allyT > 2) { M.allyT = 0; M.fail(IV.t('{n} is down.', { n: IV.ally.NAME })); } } + }; +})(); diff --git a/e63334287a3deaa3/ironveil/js/missions/bootcamp.js b/e63334287a3deaa3/ironveil/js/missions/bootcamp.js new file mode 100644 index 00000000..c00ceea4 --- /dev/null +++ b/e63334287a3deaa3/ironveil/js/missions/bootcamp.js @@ -0,0 +1,373 @@ +/* Mission 0: BOOT CAMP. A training range in daylight, one idea at a time, each step waiting until you have done it. + Prompts show your own key bindings (or the touch buttons). Stations run north along the course: + move -> sprint -> crouch under the beam -> crawl under the wire -> vault the wall -> SMG pop-ups (aim assist) -> + scoped rifle at 100 / 200 / 300 m (drop marks, wind flag, hold breath) -> a rock to draw the "guard" off, then a + takedown from behind -> binoculars (mark three dummies) -> a grenade into the pit. About five minutes. */ +(function () { + 'use strict'; + const W = IV.world, K = IV.kit, F = IV.CF, S = IV.S, P = IV.player; + const RANGE_Z = 20; // the rifle firing point + // gentle downland relief outside the course (|x| > 55 or beyond the ends), the course itself unchanged + const smoothEdge = (v, a, b) => { const t = IV.clamp((v - a) / (b - a), 0, 1); return t * t * (3 - 2 * t); }; + function height(x, z) { + const base = 0.6 * IV.fbm(x / 60 + 5, z / 60, 3) + (Math.abs(x) > 40 ? (Math.abs(x) - 40) * 0.05 : 0) + (z < -320 ? (-320 - z) * 0.2 : 0); + const out = Math.max(smoothEdge(Math.abs(x), 58, 130), smoothEdge(z, 185, 260)); + // the range butts are cut into a bank: a 2.6 m earth bank rises behind the target frames (z -300 and beyond) + const butts = smoothEdge(-z, 299, 306) * (1 - smoothEdge(Math.abs(x), 30, 44)) * 2.6; + return base + butts + out * (7 * IV.fbm(x / 95 + 11, z / 95 - 4, 4) + 3 * IV.fbm(x / 33, z / 33 + 7, 3) - 2) + campRoll(x, z) * (1 - out); + } + // gentle rolls inside the camp (up to about a metre), flat where things stand: the course and the ranges, the + // stations, every building, tent and the parade square keep the ground they had + const FLAT = [[-6, 170, 6, -310], [-26, 50, -10, 26], [18, 12, 44, -16], [2, 26, 30, 4], [-26, 4, -10, -8], [-41, 170, -13, 140], [-40, 120, -28, 112], [-40, 88, -28, 80], [-38, 73, -28, 64], + [10, 145, 22, 115], [-26, 136, -10, 124], [23, 140, 42, 116], [24, 104, 42, 78], [26, 74, 42, 63], [26, 170, 40, 153], [-34, 106, -24, 94], [45, 172, 55, 160], [45, 124, 55, 112], [-15, 28, -7, 22], [36, 180, 52, 170]]; + function campRoll(x, z) { + let d = 99; + for (const r of FLAT) { const dx = Math.max(r[0] - x, 0, x - r[2]), dz = Math.max(r[3] - z, 0, z - r[1]); d = Math.min(d, Math.hypot(dx, dz)); } + const k = smoothEdge(d, 2, 12); + return k * (2.7 * (IV.fbm(x / 38 + 3, z / 38 - 6, 3) - 0.5) + 0.6 * (IV.fbm(x / 10, z / 10 + 2, 2) - 0.5)); // rolling 1-2 m (grades under ~9 deg) + } + function surface(x, z) { if (Math.abs(x) < 2.2 && z > 0) return S.gravel; if (Math.abs(x + 18) < 5 && Math.abs(z + 2) < 5) return S.mud; return S.grass; } + // what grows where (IVEnv ground and grass; see world.js W.surfaceAt). Long grass at fence feet, hut walls and posts + // is 'verge', which is NOT stealth cover, so the takedown step plays exactly as before; 'meadow' is not used here. + // [x, z, r]: things that stand in the turf and get a collar of long grass (rope posts, beam and wire posts, the + // water tower legs, mast, notice board, wash line, wind flags, target frames) + const POSTS = []; + for (let z = 160; z > 0; z -= 6) for (const sx of [-1, 1]) POSTS.push([sx * 2.6, z, 0.45]); + for (const sx of [-1, 1]) { POSTS.push([sx * 2.7, 88, 0.5]); for (let k = 0; k < 4; k++) POSTS.push([sx * 2.7, 67 + k * 2, 0.4]); } + for (const a of [-1, 1]) for (const b of [-1, 1]) POSTS.push([-30 + a * 1.6 * Math.cos(0.2) + b * 1.6 * Math.sin(0.2), 100 - a * 1.6 * Math.sin(0.2) + b * 1.6 * Math.cos(0.2), 0.7]); + POSTS.push([-9.5, 145, 1.5], [-4.2, 153.2, 0.5], [-4.2, 154.8, 0.5], [38.5, 155.5, 0.5], [38.5, 161.5, 0.5], [4.2, 22, 0.5], [7, -130, 0.5]); + for (const x of [-15, -12, 12, 15.5]) POSTS.push([x, -295.5, 1.0]); + const TRACK = [[2.4, 163], [18, 170], [32, 172.5], [44, 175.5]], ROADOUT = [[44, 176], [46, 215], [36, 262], [12, 330]]; + const HUTS = [[16, 140, 5, 3], [16, 120, 5, 3], [-18, 130, 7, 3.5]]; + const MUD = [[10.6, 140, 1.8], [10.6, 120, 1.8], [-10.4, 130, 1.8], [0, 88, 3.0], [0, 70, 3.2], [0, 66, 2.6], [0, 53.5, 2.4], [-1, 37, 2.6], [0, 22, 2.8], [30, 8.6, 2.6], [-26.5, 97, 2.2], [3.4, 120, 1.4], [-3.6, 104, 1.3], [3.3, 76, 1.5]]; + function surfaceKind(x, z) { + const n = IV.noise(x / 1.7 + 3, z / 1.7), ax = Math.abs(x); + for (const m of MUD) { const d = Math.hypot(x - m[0], z - m[1]); if (d < m[2] * (0.75 + 0.5 * n)) return 'mud'; if (d < m[2] * 1.7) return 'worn'; } + if (surface(x, z) !== S.grass) return null; // gravel course, grenade pit: the world's own kind + if (x > -40 && x < -14 && z > 142 && z < 168) return 'gravel'; // the parade square + if (IV.polyDist(x, z, TRACK).d < 1.6 + 0.4 * n) return 'lane'; // the track to the gate and the road out + if (z > 176 && IV.polyDist(x, z, ROADOUT).d < 2.4) return 'road'; + for (const p of POSTS) if (Math.abs(x - p[0]) < p[2] && Math.abs(z - p[1]) < p[2] && Math.hypot(x - p[0], z - p[1]) < p[2]) return 'verge'; + if (ax < 3.5 && z > 0 && z < 166) return ax < 2.6 + 0.9 * n ? 'worn' : 'lawn'; // trodden edge beside the gravel + // worn paths from the barrack hut doors to the camp track, and across the grass between the hut rows + for (const [x0, x1, zz] of [[-29, -14, 116], [-29, -14, 84], [-28, -17, 100]]) if (x > x0 && x < x1 && Math.abs(z - zz - 0.6 * Math.sin(x * 0.4)) < 0.5 + 0.35 * n) return 'worn'; + for (const h of HUTS) { const dx = Math.abs(x - h[0]) - h[2], dz = Math.abs(z - h[1]) - h[3]; if (dx < 0.9 + 0.5 * n && dz < 0.9 + 0.5 * n && (dx > -0.2 || dz > -0.2)) return 'verge'; } + if (Math.abs(ax - 44) < 0.8 + 0.6 * n && z > 58 && z < 162) return 'verge'; // fence lines + if ((Math.abs(ax - 56) < 2.6 + n || Math.abs(z - 175) < 2.2 + n || Math.abs(z + 330) < 2.6 + n) && ax < 60) return 'verge'; // hedge feet + if (((ax > 21.5 && ax < 22.5) || (x > 39.5 && x < 40.5)) && z > -12.5 && z < 8.5) return 'verge'; // takedown pen fence + if ((x > 21.5 && x < 40.5) && (Math.abs(z - 8) < 0.6 || Math.abs(z + 12) < 0.6)) return 'verge'; + if (ax < 6 && z < RANGE_Z && z > -300) return 'pasture'; // mown firing lanes + if (ax > 46) { const f = IV.fbm(x / 26, z / 26, 2); return f > 0.62 ? 'tussock' : f > 0.5 ? 'verge' : 'lawn'; } // rough ground beyond the camp + return IV.fbm(x / 18 + 4, z / 18, 2) > 0.66 ? 'pasture' : 'lawn'; + } + function groundColor(x, z, y, n, c) { + const v = IV.fbm(x / 20, z / 20, 3); c.setRGB(0.38 + v * 0.1, 0.46 + v * 0.06, 0.24); + const s = surface(x, z); + if (s === S.gravel) { c.setRGB(0.6, 0.56, 0.48); return 2; } + if (s === S.mud) { c.setRGB(0.42, 0.34, 0.24); return 1; } + // mown firing lanes + if (Math.abs(x) < 6 && z < RANGE_Z && z > -300) { c.setRGB(0.4, 0.48, 0.26); } + return 0; + } + const key = id => IV.touch ? IV.t({ forward: 'the left stick', sprint: 'Run', crouch: 'Crouch', prone: 'Prone', vault: 'Vault', aim: 'Aim', fire: 'Fire', breath: 'Breath', rock: 'Rock', grenade: 'Nade', binoc: 'Bino', knife: 'Use', use: 'Use', rifle: 'Swap', smg: 'Swap', order: 'Order', leanLeft: 'Lean L', leanRight: 'Lean R' }[id] || id) : IV.input.label(id); + const moveKeys = () => IV.touch ? IV.t('the left stick') : [IV.input.label('forward'), IV.input.label('left'), IV.input.label('back'), IV.input.label('right')].join(' '); + + // ---------------------------------------------------------------- build + // huts: the kit makes the colliders (the script and the bots know them), IVEnv draws the building: brick or + // timber walls, a roof that sits on them, glazed windows, a door, wear + function hut(kitFn, spec, x, z, rot) { + if (!IV.art.envOn() || !IVEnv.building) return kitFn(); + IV.kit.noMesh = true; let r; try { r = kitFn(); } finally { IV.kit.noMesh = false; } + try { const bd = IVEnv.building(spec); bd.group.position.set(x, W.height(x, z), z); bd.group.rotation.y = rot; (W.envRoot && W.envRoot.parent ? W.envRoot : W.statics).add(bd.group); } catch (e) { console.warn('hut', e); } + return r; + } + // camp dressing drawn by IVEnv, with its colliders handed to the world (the nav grid is built after this) + function dress(kind, x, z, rot, opts, flags) { + if (!IV.art.envOn() || !IVEnv.prop) return null; + try { + const o = IVEnv.prop(kind, (x * 73 + z * 31) | 0 || 1, opts), y = W.height(x, z), c = Math.cos(rot || 0), s = Math.sin(rot || 0); + o.group.position.set(x, y, z); o.group.rotation.y = rot || 0; (W.envRoot && W.envRoot.parent ? W.envRoot : W.statics).add(o.group); + for (const k of o.colliders) W.addBox(x + k.x * c + k.z * s, z - k.x * s + k.z * c, k.hx, k.hz, y + k.y0, y + k.y1, (rot || 0) + k.rot, flags == null ? F.SOLID | F.BULLET | F.NAV : flags, k.surf === 'cloth' ? 'wood' : k.surf, k.kind); + return o; + } catch (e) { console.warn('dress', kind, e); return null; } + } + function build(M) { + const b = K.begin(); + // course edging: rope posts along the gravel path + for (let z = 160; z > 0; z -= 6) for (const s of [-1, 1]) K.add(b, 'wood', K.GEO.box, s * 2.6, W.height(s * 2.6, z) + 0.4, z, 0.1, 0.8, 0.1, 0, 0, 0, 0x8a7458); + // the crouch beam (a log at 1.3 m on two posts) and the crawl wire (0.65 m, six metres long) + const gy = W.height(0, 88); + K.box(b, 'bark', 0, gy + 1.25, 88, 5.6, 0.25, 0.25, 0, 0x8a7458, F.SOLID | F.BULLET, 'wood'); + for (const s of [-1, 1]) K.box(b, 'wood', s * 2.7, gy, 88, 0.2, 1.5, 0.2, 0, 0x6e5a44, F.SOLID, 'wood'); + W.addBox(0, 88, 2.6, 0.15, gy + 1.25, gy + 3, 0, F.SOLID, 'wood'); + const wy = W.height(0, 70); + for (let k = 0; k < 4; k++) { K.box(b, 'metal', 0, wy + 0.62, 67 + k * 2, 5.4, 0.04, 0.04, 0, 0x55534e); for (const s of [-1, 1]) K.box(b, 'wood', s * 2.7, wy, 67 + k * 2, 0.1, 0.75, 0.1, 0, 0x6e5a44); } + W.addBox(0, 70, 2.6, 3.2, wy + 0.6, wy + 2.2, 0, F.SOLID, 'metal'); + // the vault wall + IV.art.wall(b, [[-3, 55], [3, 55]], 1.0); + // SMG bay: sandbag counter, pop-up targets off to the west + IV.art.prop('sandbags', b, -3, 40, -3, 34, 3); + // rifle firing point: sandbag rest, the wind flags + IV.art.prop('sandbags', b, -2.5, RANGE_Z + 1.5, 2.5, RANGE_Z + 1.5, 2); + M.flags_ = {}; + // the takedown pen: a fenced square with a post for the "guard" + IV.art.fence(b, [[22, 8], [27.5, 8]]); IV.art.fence(b, [[32.5, 8], [40, 8], [40, -12], [22, -12], [22, 8]]); // a gate gap on the south side + IV.art.prop('crate', b, 26, W.height(26, -2), -2, 0.2, 0.9); IV.art.prop('crate', b, 34, W.height(34, 4), 4, 0.6, 0.9); + IV.art.prop('hay', b, 29, W.height(29, -8), -8, 0.3); IV.art.prop('hay', b, 36, W.height(36, -5), -5, 1.2); + // the grenade pit + const py = W.height(-18, -2); + for (let i = 0; i < 10; i++) { const a = i / 10 * 6.283, a1 = (i + 1) / 10 * 6.283; IV.art.prop('sandbags', b, -18 + Math.cos(a) * 4.5, -2 + Math.sin(a) * 4.5, -18 + Math.cos(a1) * 4.5, -2 + Math.sin(a1) * 4.5, 2); } + // huts and a water tower so it reads as a camp + hut(() => IV.art.building(b, { x: 16, z: 140, w: 10, d: 6, h: 2.8, floor: 0.2, mat: 'wood', color: 0x7e7058, sides: { w: [{ t: 'door', at: 0, w: 1.0 }], s: [{ t: 'win', at: -2.5, w: 1 }, { t: 'win', at: 2.5, w: 1 }] }, roof: { pitch: 0.4, mat: 'metal', col: 0x6a6e66 } }), { kind: 'hut', w: 10, d: 6, floors: 1, seed: 156, damage: 0.05, lit: 0, num: 3 }, 16, 140, Math.PI); + hut(() => IV.art.building(b, { x: 16, z: 120, w: 10, d: 6, h: 2.8, floor: 0.2, mat: 'wood', color: 0x7e7058, sides: { w: [{ t: 'door', at: 0, w: 1.0 }], s: [{ t: 'win', at: -2.5, w: 1 }, { t: 'win', at: 2.5, w: 1 }] }, roof: { pitch: 0.4, mat: 'metal', col: 0x6a6e66 } }), { kind: 'hut', w: 10, d: 6, floors: 1, seed: 136, damage: 0.05, lit: 0, num: 4 }, 16, 120, Math.PI); + hut(() => IV.art.building(b, { x: -18, z: 130, w: 14, d: 7, h: 3, floor: 0.2, mat: 'plaster', color: 0xcfc6b0, sides: { e: [{ t: 'door', at: 0, w: 1.2 }], n: [{ t: 'win', at: -3, w: 1.2 }, { t: 'win', at: 3, w: 1.2 }] }, roof: { pitch: 0.6 } }), { kind: 'office', w: 14, d: 7, doorEnd: true, seed: 148, damage: 0.05, lit: 0 }, -18, 130, 0); // a long, low rendered office hut + if (!dress('watertower', -30, 100, 0.2)) { + for (const s of [-1, 1]) for (const t of [-1, 1]) K.add(b, 'wood', K.GEO.box, -30 + s * 1.5, W.height(-30, 100) + 4, 100 + t * 1.5, 0.25, 8, 0.25, 0, 0, 0, 0x6e5a44); + K.add(b, 'wood', K.GEO.cyl12, -30, W.height(-30, 100) + 9.2, 100, 4.2, 2.6, 4.2, 0, 0, 0, 0x7a6450); + } + // the lived-in camp: parade mast and notice board by the start, duckboards to the hut doors, tent lines with + // a wash line, fuel drums and stores by the tower, sandbagged bays by the SMG point, spare frames at the butts + dress('flagpole', -9.5, 145, 0); dress('noticeboard', -4.2, 154, Math.PI / 2 + 0.1); + dress('duckboards', 7, 140, 0, { length: 7 }, 0); dress('duckboards', 7, 120, 0, { length: 7 }, 0); dress('duckboards', -7.5, 130, 0, { length: 6 }, 0); + for (let k = 0; k < 4; k++) dress('tent', 30 + (k % 2) * 6, 166 - (k >> 1) * 6.5 + (k % 2) * 0.4, Math.PI / 2 + (k * 0.05 - 0.07)); + dress('washline', 38.5, 158.5, Math.PI / 2 + 0.05, { length: 6 }, F.SOLID); + if (IV.art.envOn()) { + IV.art.prop('barrel', b, -26.5, W.height(-26.5, 96.5), 96.5); IV.art.prop('barrel', b, -25.9, W.height(-25.9, 97.2), 97.2); + IV.art.prop('crate', b, 21.5, W.height(21.5, 129), 129, 0.3, 1); IV.art.prop('crate', b, 22.4, W.height(22.4, 130), 130, -0.2, 0.9); + dress('drums', -27, 104.5, 0.6); dress('tarp', -35.5, 97, 1.2); dress('ammo', 6.5, RANGE_Z + 2.6, 0.3); dress('crates', 13.8, 33.5, 0.4); + IV.art.prop('sandbags', b, 8, 36, 8, 30, 3); IV.art.prop('sandbags', b, 8, 36, 12, 36, 3); IV.art.prop('sandbags', b, 8, 30, 12, 30, 3); + for (const x of [-15, -12, 12, 15.5]) dress('targetframe', x, -295.5, Math.PI + (x > 0 ? 0.08 : -0.08)); + dress('targetframe', 9.5, RANGE_Z + 5, 2.6); dress('targetframe', 9.9, RANGE_Z + 5.6, 2.7); + } + // tree lines either side of the range + const R = IV.rng(7); + for (let z = 170; z > -320; z -= 9) { IV.art.tree(b, -48 + R.range(-3, 3), z, R() < 0.3 ? 'poplar' : 'oak', R); IV.art.tree(b, 48 + R.range(-3, 3), z + 4, R() < 0.3 ? 'poplar' : 'oak', R); } + IV.art.hedge(b, [[-44, 175], [44, 175]], [[40, 48]]); + // the training ground is enclosed: hedgerows along both sides and across the far end, woods on the downs beyond, + // so the horizon is never a ruler line and the edge of the world is never seen + IV.art.hedge(b, [[-56, 190], [-56, -330]], [[-56, 60, 6]]); + IV.art.hedge(b, [[56, 190], [56, -330]], [[56, -40, 6]]); + IV.art.hedge(b, [[-56, -330], [56, -330]], [[0, -330, 8]]); + IV.art.fence(b, [[-44, 160], [-44, 60]]); IV.art.fence(b, [[44, 160], [44, 60]]); + { const RW = IV.rng(19); + for (let i = 0; i < 70; i++) { const side = i % 2 ? 1 : -1, x = side * RW.range(75, 300), z = RW.range(-340, 300); IV.art.tree(b, x, z, RW() < 0.55 ? 'oak' : RW() < 0.6 ? 'ash' : 'poplar', RW); } + for (let c = 0; c < 6; c++) { const cx = (c % 2 ? 1 : -1) * RW.range(110, 260), cz = RW.range(-300, 260); for (let i = 0; i < 14; i++) IV.art.tree(b, cx + RW.range(-22, 22), cz + RW.range(-22, 22), RW() < 0.6 ? 'oak' : 'ash', RW); } + for (let i = 0; i < 30; i++) IV.art.tree(b, RW.range(-300, 300), RW.range(270, 320), RW() < 0.6 ? 'oak' : 'ash', RW); } + // ---- the rest of the camp: barrack huts in rows, mess hall and cookhouse, the motor pool with parked vehicles, fuel + // store, ablution block, guardroom at the gate, a sentry tower, a firing-point shelter, the parade square (ground + // kind), a track out to the gate, the road leading away with telegraph poles, a wire perimeter, and an assault + // course beyond the west hedge. All clear of the course, the ranges and the takedown pen. + { + const H2 = Math.PI / 2; + IV.art.settle(b, [ + { kind: 'hut', w: 10, d: 6, x: -34, z: 116, rot: 0, num: 1 }, + { kind: 'hut', w: 10, d: 6, x: -34, z: 84, rot: 0.02, num: 2 }, + { kind: 'office', w: 9, d: 5, x: -33, z: 68, rot: 0, out: 'brick_sooty' }, // ablutions + { kind: 'office', w: 16, d: 8, x: 32, z: 134, rot: 0 }, // mess hall + { kind: 'cottage', w: 8, d: 5, floors: 1, x: 32, z: 120, rot: Math.PI, roof: 'tile' }, // cookhouse + { kind: 'barn', w: 10, d: 16, x: 33, z: 96, rot: 0 }, // motor pool shed + { kind: 'office', w: 6, d: 4, x: 33, z: 69, rot: 0, out: 'brick_red' }, // fuel store + { kind: 'office', w: 6, d: 4.5, x: 50, z: 166, rot: -H2 } // guardroom + ], { seed: 909 }); + if (IV.art.envOn()) { + dress('truck', 26.5, 83.5, 0.15); dress('truck', 37, 82.5, -0.1); dress('car', 23.5, 106, 1.45); + dress('drums', 28.5, 66.5, 0.4); dress('drums', 38.5, 66, 2.1); dress('guardtower', 50, 118, 0.1); + dress('shelter', -11, 25.5, 0); dress('crates', 41, 99, 0.2); dress('tarp', 41.5, 92, 1.5); + for (const [x, z, r] of [[-82, 70, 0.1], [-95, 92, -0.2], [-80, 118, 0.3]]) dress('aframe', x, z, r, null, 0); + for (const [x, z] of [[-88, 80], [-100, 108], [-86, 132]]) IV.art.wall(b, [[x - 2, z], [x + 2, z]], 1.8); + for (const [x, z] of [[-92, 64], [-84, 102]]) dress('logpile', x, z, 0.3, null, 0); + // the gate: a striped barrier arm across the track where it leaves through the hedge gap + const gy = W.height(41, 175.5); K.box(b, 'wood', 40.6, gy, 175.5, 0.3, 1.1, 0.3, 0, 0x5a4a3a, F.SOLID | F.BULLET, 'wood'); + for (let k = 0; k < 6; k++) K.box(b, 'wood', 41.4 + k * 1.05, gy + 0.95, 175.5, 1.05, 0.12, 0.12, 0, k % 2 ? 0xc03a2a : 0xe8e4da); + W.addBox(44.6, 175.5, 3.4, 0.12, gy + 0.85, gy + 1.1, 0, F.SOLID, 'wood'); + // the road out and its telegraph line, a wire perimeter outside the hedges + const road = [[44, 176], [46, 215], [36, 262], [12, 330]]; + let prev = null; const wires = []; + for (let i = 0; i < road.length - 1; i++) { const [ax, az] = road[i], [bx, bz] = road[i + 1], L = Math.hypot(bx - ax, bz - az); + for (let t = 0; t < L; t += 34) { const x = ax + (bx - ax) * t / L + 5, z = az + (bz - az) * t / L; try { const p = IVEnv.prop('telegraph', (x * 7) | 0), y = W.height(x, z); p.group.position.set(x, y, z); (W.envRoot && W.envRoot.parent ? W.envRoot : W.statics).add(p.group); const tops = (p.group.userData.wireTop || []).map(q => [x + q[0], y + q[1], z + q[2]]); if (prev) for (let k = 0; k < Math.min(prev.length, tops.length); k++) wires.push([...prev[k], ...tops[k]]); prev = tops; } catch (e) {} } } + if (wires.length && IVEnv.wireMesh) W.scene.add(IVEnv.wireMesh(wires, 0.006, 0.35)); + if (IVEnv.fence && IVEnv.Q.name !== 'low') for (const pts of [[[-64, 192], [38, 192]], [[50, 192], [64, 192], [64, -334]], [[-64, 192], [-64, -334]]]) { try { const f = IVEnv.fence(pts, 'barbed', { heightFn: W.height, seed: 33 }); (W.envRoot && W.envRoot.parent ? W.envRoot : W.statics).add(f.group); } catch (e) { console.warn('wire', e); } } + } + } + // life around the camp: a lorry on the far road, the camp pennant, cookhouse smoke, birds over the woods, rain + // squalls hanging on the far downs, rifle fire from the next range (sound hook); squads drilling on the parade + // square and a running party on the road out, as paths for the game's far soldiers + IV.art.backdrop({ truck: { path: [[44, 176], [46, 215], [36, 262], [12, 330], [-40, 430]], speed: 7 }, pennant: { x: -9.45, y: W.height(-9.5, 145) + 8.4, z: 145 }, + smoke: [[28.4, W.height(32, 120) + 6.6, 120, false]], birds: [[-140, 80, 45, 28, 14], [120, -60, 55, 32, 12]], squalls: [[-380, -150], [320, 120]], + leaves: 'day', sounds: [{ kind: 'rifle', every: [2, 8], x: -220, z: -150 }, { kind: 'shout', every: [25, 60], x: -27, z: 155 }] }); + IV.art.squads.push({ kind: 'drill', loop: true, n: 10, path: [[-36, 146], [-18, 146], [-18, 165], [-36, 165]] }, { kind: 'run', loop: true, n: 8, path: [[44, 180], [46, 215], [36, 262], [46, 215]] }); + // the backstop berm behind the 300 m target + K.box(b, 'earth', 0, W.height(0, -300) - 1, -300, 40, 6, 6, 0, 0x7a6a50, F.SOLID | F.BULLET | F.SIGHT, 'mud', 0.3); + K.finish(b); + M.grass = IV.art.grass(W.P.grass, W.P.grassR, (x, z) => { const s = W.surfAt(x, z); if (s !== S.grass) return 0; if (Math.abs(x) < 6 && z < RANGE_Z && z > -300) return 0.3; return 0.6 + IV.noise(x / 5, z / 5) * 0.6; }, (x, z, c) => c.setRGB(0.36 + IV.noise(x / 9, z / 9) * 0.12, 0.5, 0.22)); + } + + // ---------------------------------------------------------------- dynamic: targets, flags + // A target board on a post. It falls back when hit. Counts as a target for aim assist while standing. + function board(M, x, z, rot, w, h, steel) { + const gy = W.height(x, z), g = new THREE.Group(); + const plate = new THREE.Mesh(new THREE.BoxGeometry(w, h, 0.05), new THREE.MeshStandardMaterial({ color: steel ? 0x8a8e90 : 0xc8b890, roughness: steel ? 0.4 : 0.9, metalness: steel ? 0.6 : 0 })); + // a plain silhouette mark: dark circle + rings painted on + const face = new THREE.Mesh(new THREE.CircleGeometry(Math.min(w, h) * 0.32, 20), new THREE.MeshBasicMaterial({ color: 0x2a2620 })); + face.position.z = 0.03; plate.add(face); + const ring = new THREE.Mesh(new THREE.RingGeometry(Math.min(w, h) * 0.12, Math.min(w, h) * 0.16, 20), new THREE.MeshBasicMaterial({ color: 0xd8d0c0 })); ring.position.z = 0.035; plate.add(ring); + const pivot = new THREE.Group(); pivot.position.set(0, 0.25, 0); plate.position.y = h / 2 + 0.05; pivot.add(plate); g.add(pivot); + const post = new THREE.Mesh(new THREE.BoxGeometry(0.1, 0.3, 0.1), new THREE.MeshStandardMaterial({ color: 0x5a4a38 })); post.position.y = 0.15; g.add(post); + g.position.set(x, gy, z); g.rotation.y = rot; g.traverse(o => { o.castShadow = true; }); + M.group.add(g); + const c = Math.cos(rot), s = Math.sin(rot); + const col = W.addBox(x, z, w / 2, 0.06, gy + 0.3, gy + 0.3 + h, rot, F.BULLET, steel ? 'metal' : 'wood', 'target'); + const t = { alive: true, pos: { x, y: gy, z }, chestH: () => 0.3 + h * 0.55, col, pivot, hits: 0, steel }; + col.onHit = () => { + if (!t.alive) return; t.hits++; + if (steel) { IV.audio.play('clink', { x, z }); t.alive = false; t.flash = 0.4; plate.material.color.setHex(0xd8b048); setTimeout(() => plate.material.color.setHex(0xc89a38), 400); } + else { t.alive = false; col.on = false; t.fall = 0; IV.audio.play('hitThud'); } + IV.emit('hitmarker', { kill: true }); IV.weapons.stats.hits++; + IV.emit('targetHit', t); + }; + IV.targets.push(t); + return t; + } + function windFlag(M, x, z) { + const gy = W.height(x, z), g = new THREE.Group(); + const pole = new THREE.Mesh(new THREE.CylinderGeometry(0.04, 0.05, 5, 8), new THREE.MeshStandardMaterial({ color: 0xd0ccc0 })); pole.position.y = 2.5; g.add(pole); + const geo = new THREE.PlaneGeometry(1.4, 0.7, 8, 2); geo.translate(0.7, 0, 0); + const flag = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ color: 0xd8552c, side: THREE.DoubleSide, roughness: 0.9 })); + flag.position.y = 4.6; g.add(flag); g.position.set(x, gy, z); M.group.add(g); + M.flags3d = M.flags3d || []; M.flags3d.push({ flag, base: geo.attributes.position.array.slice() }); + } + + // ---------------------------------------------------------------- steps + function setup(M, cp) { + const t = IV.t, WP = IV.weapons; + M.noWeapons = false; + P.spawn(0, 158, 0, 'stand'); + WP.reset({ start: 'smg', rifleRes: 40, smgRes: 150, grenades: 3 }); + WP.wind = { x: 2.2, z: 0.3 }; + windFlag(M, 4.2, RANGE_Z + 2); windFlag(M, 7, -130); + IV.ai.ignorePlayer = false; + const steps = []; + let i = -1; + const hint = (txt) => { IV.hud.hint = { text: txt }; }; + function next() { + i++; + if (i >= steps.length) { IV.hud.hint = null; M.radio('Sgt. Okafor', t('That\'s the course. You\'ll do. Get some sleep, you jump tomorrow night.')); M.after(3, () => M.complete()); return; } + steps[i](); + } + const go = (cond, done) => M.when(cond, () => { IV.audio.play('objDone'); done && done(); M.after(0.8, next); }); + const sarge = (line) => M.radio('Sgt. Okafor', t(line)); + const at = (x, z, r) => () => Math.hypot(P.pos.x - x, P.pos.z - z) < (r || 2.5); + const mark = (id, text, x, z) => M.obj(id, text, { marker: { x, z, y: W.height(x, z) + 1.4 } }); + + steps.push(() => { sarge('Morning. One thing at a time. Walk up to the first post.'); mark('s1', 'Walk to the first post', 0, 132); hint(t('Move with {k}. Look with the mouse.', { k: moveKeys() }).replace('the mouse', IV.touch ? t('a finger on the right side') : t('the mouse'))); go(at(0, 132, 3), () => M.done('s1')); }); + steps.push(() => { let ran = false; M.when(() => P.sprinting, () => { ran = true; }); sarge('Now run. Hold sprint all the way to the flag.'); mark('s2', 'Sprint to the next post', 0, 98); hint(t('Hold {k} to sprint', { k: key('sprint') })); go(() => ran && at(0, 98, 3)(), () => M.done('s2')); }); + steps.push(() => { sarge('Under the log. Crouch and go through.'); mark('s3', 'Crouch under the log', 0, 84); hint(t('{k} crouches (and stands up again)', { k: key('crouch') })); go(() => P.pos.z < 85.5 && Math.abs(P.pos.x) < 3, () => M.done('s3')); }); + steps.push(() => { sarge('Wire\'s low. On your belly and crawl.'); mark('s4', 'Crawl under the wire', 0, 63); hint(t('{k} goes prone. Crouched or prone, you are quieter and harder to see.', { k: key('prone') })); go(() => P.pos.z < 64.5 && Math.abs(P.pos.x) < 3, () => M.done('s4')); }); + steps.push(() => { let v = false; const off = IV.on('vault', () => { v = true; }); sarge('Wall. Over it, don\'t walk round it.'); mark('s5', 'Vault the wall', 0, 50); hint(t('Run at it and press {k} to vault', { k: key('vault') })); go(() => v && P.pos.z < 53, () => M.done('s5')); }); + // lean: first person only teaches it properly, but the station accepts the keys in either view + steps.push(() => { + let l = 0, r = 0; + sarge('Good. Now get your head round cover without stepping out. Lean left, then right.'); + M.obj('s5b', 'Lean out to the left and to the right'); + hint(t('Hold {l} to lean left and {r} to lean right. You can aim and fire while leaning.', { l: key('leanLeft'), r: key('leanRight') })); + go(() => { if (IV.input.held('leanLeft') || P.lean < -0.6) l = 1; if (IV.input.held('leanRight') || P.lean > 0.6) r = 1; return l && r; }, () => M.done('s5b')); + }); + // SMG pop-ups with aim assist + steps.push(() => { + WP.equip('smg'); + const ts = [[-18, 42, Math.PI / 2], [-22, 36, Math.PI / 2 + 0.2], [-15, 31, Math.PI / 2 - 0.3]].map(p => board(M, p[0], p[1], p[2], 0.55, 1.0)); + sarge('Pop-ups to your left. Bring the gun up, look down the sights, then squeeze.'); + M.obj('s6', 'Hit the three pop-up targets'); hint(t('Hold {a} to look down the sights, {f} to fire. From the hip the crosshair opens up while you move. Your aim slows over a target: that is the aim assist.', { a: key('aim'), f: key('fire') })); + go(() => ts.every(x => !x.alive), () => M.done('s6')); + }); + // rifle at range + steps.push(() => { + const ts = [[-4, RANGE_Z - 100], [0, RANGE_Z - 200], [4.5, RANGE_Z - 300]].map(p => board(M, p[0], p[1], 0, 1.0, 1.5, true)); + let shots0 = WP.stats.shots; + M.flags.rifleStart = WP.stats.shots; + sarge('Rifle. Plates at one, two and three hundred yards. Well, metres. Close enough.'); + sarge('Middle of the scope hits at one hundred. The marks under it are for two and three hundred. Wind\'s from the west, so lean into it.'); + mark('s7a', 'Go to the rifle bench', 0, RANGE_Z + 0.5); + hint(t('Press {k} for the rifle', { k: key('rifle') })); + M.when(at(0, RANGE_Z + 0.5, 3), () => { + M.done('s7a'); + M.obj('s7', 'Hit the 100, 200 and 300 m plates'); + hint(t('Hold {a} to put your eye to the scope. Hold {b} to steady your breath. Lie down for the steadiest shot.', { a: key('aim'), b: key('breath') })); + }); + M.when(() => ts.every(x => !x.alive), () => { M.flags.rifleShots = WP.stats.shots - M.flags.rifleStart; }); + go(() => ts.every(x => !x.alive), () => M.done('s7')); + }); + // rock + takedown on a sparring sergeant + steps.push(() => { + WP.equip('smg'); + const spawnGuard = () => { const e = IV.ai.spawn({ kind: 'ally', weapon: 'smg', x: 31, z: -2, yaw: Math.PI, scan: [0.2, -0.2], noShoot: true, name: 'guard' }); e.hp = 9999; e.sightMul = 0.35; e.lookTime = 9; M.guard = e; return e; }; // a training guard: looks round the stone for 9 s, not 5 + spawnGuard(); + sarge('Corporal Hale is playing the guard in the pen. He\'s watching the gate. Draw him off with a stone, get behind him, and put him down. Gently.'); + M.obj('s8', 'Throw a rock to distract the guard', { marker: { x: 31, z: -2, y: W.height(31, -2) + 2.2 } }); + hint(t('Hold {k} to aim a rock, let go to throw. Land it away from where you want to go.', { k: key('rock') })); + let distracted = false; + M.when(() => M.guard && (M.guard.state === 'investigating'), () => { distracted = true; M.done('s8'); M.obj('s9', 'Sneak up behind him and take him down'); hint(t('Behind him and close: {k} for the knife', { k: key('knife') })); }); + // seen: one reset at a time (the condition stays true until the new guard is in, so guard against queueing a reset every step) + let resetting = false; + M.when(() => !resetting && M.guard && M.guard.alive && M.guard.state === 'combat', () => { resetting = true; M.radio('Cpl. Hale', t('Seen you! Back out and try again.')); M.after(2.5, () => { resetting = false; if (M.guard && M.guard.alive) { M.guard.actor.dispose(); IV.ai.list.splice(IV.ai.list.indexOf(M.guard), 1); spawnGuard(); P.pos.set(26, W.height(26, 14), 14); P.prev.copy(P.pos); } }); }, { once: false }); + go(() => M.guard && !M.guard.alive, () => { M.done('s9'); M.radio('Cpl. Hale', t('Ow. Alright, that\'ll do.')); }); + }); + // binoculars + steps.push(() => { + const d = [[-6, -60], [5, -95], [-3, -140]].map(p => { const e = IV.ai.spawn({ x: p[0], z: p[1], yaw: 0, noShoot: true, fixed: true }); e.hp = 9999; return e; }); + IV.ai.ignorePlayer = true; + sarge('Dummies downrange, dressed like the other side. Binoculars up and mark all three.'); + M.obj('s10', 'Mark the three dummies with the binoculars'); hint(t('Hold {b} for binoculars, then {f} marks the one in the middle. Marked soldiers stay on your compass.', { b: key('binoc'), f: key('fire') })); + go(() => d.every(e => e.tagged), () => { M.done('s10'); }); + }); + // grenade + steps.push(() => { + IV.ai.ignorePlayer = false; + sarge('Last one. Grenade into the pit. The fuse starts when you pull the pin, so don\'t hang on to it.'); + M.obj('s11', 'Throw a grenade into the pit', { marker: { x: -18, z: -2, y: W.height(-18, -2) + 1 } }); + hint(t('Hold {g} to pull the pin and aim (the line shows where it lands), let go to throw.', { g: key('grenade') })); + let ok = false; + const h = g => { if (Math.hypot(g.x + 18, g.z + 2) < 5) ok = true; }; + IV.on('explosion', h); + M.when(() => WP.inv.grenades === 0 && WP.throws.length === 0 && !ok, () => { WP.inv.grenades = 2; sarge('Missed. Have another.'); }, { once: false }); + go(() => ok, () => M.done('s11')); + }); + // testing aid: ?bcstep=N starts at station N (0-based) next to it + const startAt = IV.test ? +(IV.params.get('bcstep') || 0) : 0; + if (startAt) { const spots = [[0, 158], [0, 132], [0, 98], [0, 74], [0, 58], [-1, 38], [0, 22], [20, 24], [0, 10], [-8, 4]]; const sp = spots[startAt] || spots[0]; P.spawn(sp[0], sp[1], 0, 'stand'); i = startAt - 1; } + next(); + } + function step(M, dt) { + for (const t of IV.targets || []) if (t.fall != null && t.fall < 1) { t.fall = Math.min(1, t.fall + dt * 4); t.pivot.rotation.x = -t.fall * 1.5; } + } + function frame(M, dt) { + if (M.grass) M.grass.update(W.camera.position.x, W.camera.position.z); + // flags stream with the wind + const w = IV.weapons.wind, ang = Math.atan2(-w.z, w.x); + for (const f of M.flags3d || []) { + f.flag.rotation.y = ang; + const a = f.flag.geometry.attributes.position.array; + for (let i = 0; i < a.length; i += 3) { const x = f.base[i]; a[i + 2] = Math.sin(x * 4 - IV.time * 7) * 0.08 * x; a[i + 1] = f.base[i + 1] - x * 0.08; } + f.flag.geometry.attributes.position.needsUpdate = true; + } + } + function sketch(g, w, h, sk) { + sk.line(g, [[w / 2, h - 20], [w / 2, 60]], { w: 2, dash: [6, 6] }); + const st = [['start', 0.95], ['run', 0.82], ['crouch', 0.74], ['crawl', 0.66], ['vault', 0.6], ['pop-ups', 0.52], ['rifle', 0.44], ['pen', 0.36], ['binoculars', 0.28], ['pit', 0.2]]; + st.forEach((s, i) => { const y = h * s[1]; sk.circle(g, w / 2, y, 7, '#2f4a7a'); sk.text(g, s[0], w / 2 + (i % 2 ? -150 : 20), y + 6, { size: 22 }); }); + sk.text(g, '100 m', w / 2 + 40, h * 0.12, { size: 16 }); sk.text(g, '300 m →', w / 2 + 40, h * 0.07, { size: 16 }); + sk.text(g, 'Camp Hollowmere', 30, 44, { size: 24 }); + } + IV.missions.register({ + id: 'bootcamp', num: 0, title: 'Boot Camp', line: 'A morning on the training range: moving, shooting, sneaking. About five minutes.', + briefing: ['Training range, England, the week before the jump. Sergeant Okafor runs the course.', 'One thing at a time. Each station waits until you have done it, and the prompts show your own keys.'], + preview: [{ text: 'Move, sprint, crouch, crawl, vault and lean' }, { text: 'Pop-up targets down the sights' }, { text: 'The scoped rifle at 100, 200 and 300 m' }, { text: 'Distract a guard and take him down' }, { text: 'Binoculars and grenades' }], + world: { size: 660, day: true, height, surface, groundColor, surfaceKind, skirt: { hills: 60, woods: 1.2, seed: 9, fogK: 0.45, landFogK: 0.6 }, grass: { nearMul: 1.3, carpetMul: 1.25, midMul: 2.2 }, terrainStep: 4, fog: 0.0028, fogColor: 0xb9c4c8, sunDir: [0.45, 0.8, 0.35] }, + build, setup, step, frame, sketch, + medals: [ + { text: 'Finish in under 6:00', ok: s => s.time < 360 }, + { text: 'Three plates in six rifle shots or fewer', ok: (s, M) => M.flags.rifleShots != null && M.flags.rifleShots <= 6 }, + { text: 'Accuracy of 50% or better', ok: s => s.acc >= 50 } + ] + }); +})(); diff --git a/e63334287a3deaa3/ironveil/js/missions/nightdrop.js b/e63334287a3deaa3/ironveil/js/missions/nightdrop.js new file mode 100644 index 00000000..1682060d --- /dev/null +++ b/e63334287a3deaa3/ironveil/js/missions/nightdrop.js @@ -0,0 +1,980 @@ +/* Mission 1: NIGHT DROP. Norman-style hedgerow farmland at night, about 350 x 350 m. + Beats: hanging in the harness under tracer fire -> link up with Cpl. Dunning -> a quiet approach (two patrols, the + crossroads post, crops and shadows; the lane, the stream bed or the wheat) with a bombing run that masks noise -> + cut the field-telephone line (checkpoint 1) -> overwatch on the barn-loft sniper (optional) -> plant the charge on the + flak gun -> SCRIPTED: a guard walks out, the bell rings, the house opens fire -> breach the farmhouse with Dunning + stacked on the door (optional map in the office) -> checkpoint 2 -> hold the yard against a reinforcement truck while + the fuse burns -> the gun blows -> running fight down the sunken lane under flares and mortar fire -> extraction. + Coordinates: x east, z south (north is -z). Place names are our own. */ +(function () { + 'use strict'; + const W = IV.world, K = IV.kit, F = IV.CF, S = IV.S; + const P = IV.player; + + // ---------------------------------------------------------------- layout + const L1 = [[-178, 38], [-140, 34], [-110, 28], [-80, 22], [-55, 19], [-41, 18], [-25, 15], [-8, 11], [0, 10]]; // sunken lane west + const R1 = [[2, 188], [1, 80], [0, 10], [3, -42], [8, -100], [12, -188]]; // north-south road + const R2 = [[3, -42], [40, -48], [70, -52], [86, -57], [96, -64]]; // farm road + const R3 = [[126, -62], [150, -54], [188, -50]]; // east road (the truck) + const L2 = [[116, -54], [126, -32], [134, 0], [144, 40], [156, 74], [170, 98], [188, 112]]; // extraction lane + const ST = [[-56, -188], [-48, -130], [-42, -80], [-41, -35], [-44, -5], [-41, 18], [-36, 60], [-42, 110], [-35, 188]]; // stream + const WHEAT = [[18, -36], [82, -44], [88, -14], [92, 22], [20, 24]]; + const MAIZE = [[13.5, -60], [28, -59.5], [28, -113], [15.5, -112]]; // standing maize beside the approach: the route runs up a trampled path at x 24 + const PAST = [[-170, 60], [-75, 52], [-70, 140], [-165, 150]]; + const MAIZE2 = [[-172, -162, -130, -117, 43]]; // a west maize block (dressing; clear of the copses and the hay field) // the landing pasture (tall grass patches) + const FARM = { x: 108, z: -76 }; + const HOUSE = { x: 98, z: -92, w: 16, d: 9 }; + const BARN = { x: 124, z: -73, w: 10, d: 16 }; + const AA = { x: 102, z: -117 }; + const MG = { x: 89, z: -110 }; + const BELL = { x: 110, z: -63 }; + const OAK = { x: -118, z: 88 }; + const LINK = { x: -92, z: 47 }; + const JPOLE = { x: 37, z: -47.4 }; + const EXTRACT = { x: 166, z: 90 }; + const pd = (x, z, pts) => IV.polyDist(x, z, pts).d; + const HAMLET = (() => { + const H2 = Math.PI / 2, roadX = (z) => z < 80 ? 0 + z / 80 : 1 + (z - 80) / 108; + // neighbours are not alike: each stands at its own distance from the road (sb, metres further back) and a + // little off square to it (ra, radians), with its own width, depth and height + const E_ = (z, sp) => Object.assign({ x: roadX(z) + 2.6 + 3.2 + (sp.sb || 0) + ((sp.kind === 'shoprow' ? 8 : sp.d || 6) / 2), z, rot: -H2 + (sp.ra || 0) }, sp); + const W_ = (z, sp) => Object.assign({ x: roadX(z) - 2.6 - 3.2 - (sp.sb || 0) - ((sp.kind === 'barn' ? sp.w || 10 : sp.d || 6) / 2), z, rot: H2 + (sp.ra || 0) }, sp); + return [ + E_(38, { kind: 'cottage', w: 8.6, d: 6.4, floors: 2, lit: 0.5, roof: 'tile', out: 'plaster', sb: 0.2, ra: 0.03 }), + E_(51, { kind: 'shoprow', units: 2, d: 8, lit: 0.5 }), + E_(63.5, { kind: 'cottage', w: 6.4, d: 5.0, floors: 1, damage: 0.55, out: 'fieldstone', sb: 1.4, ra: -0.06 }), + E_(78, { kind: 'farmhouse', w: 12.5, d: 7.4, out: 'plaster', roof: 'slate', sb: 0.6, ra: 0.04 }), + E_(95, { kind: 'ruin', w: 8, d: 6, damage: 0.9 }), + { kind: 'shed', w: 5, d: 4, x: 21, z: 40, rot: 0.08 }, + W_(34, { kind: 'cottage', w: 7.2, d: 5.6, floors: 2, lit: 0.6, out: 'fieldstone', sb: 0.9, ra: -0.05 }), + W_(45.5, { kind: 'shed', w: 6, d: 5, sb: 1.8, ra: 0.12 }), + W_(57, { kind: 'cottage', w: 9.6, d: 6.6, floors: 1, damage: 0.65, out: 'brick_sooty', ra: 0.06 }), + W_(71, { kind: 'cottage', w: 7.6, d: 5.8, floors: 2, lit: 0.4, roof: 'tile', out: 'plaster', sb: 1.2, ra: -0.04 }), + W_(90, { kind: 'barn', w: 9, d: 13, sb: 0.4, ra: 0.05 }), + W_(105, { kind: 'shed', w: 6, d: 4, sb: 2.2, ra: -0.15 }), + { kind: 'shed', w: 4, d: 3, x: -20, z: 64, rot: H2 }, + { kind: 'church', w: 16, d: 8, x: 37, z: 88, rot: -H2 } + ]; + })(); + // footprint rectangles of the hamlet (for the trodden ring and weeds at wall feet) + const HRECT = HAMLET.map(sp => { const X = sp.kind === 'barn' ? sp.d || 16 : sp.kind === 'shoprow' ? (sp.units || 3) * 5.4 : sp.kind === 'church' ? sp.w + 4.6 : sp.w || 8, Z = sp.kind === 'barn' ? sp.w || 10 : sp.d || 6, sw = Math.abs(Math.sin(sp.rot || 0)) > 0.7; return { x: sp.x, z: sp.z, hx: (sw ? Z : X) / 2, hz: (sw ? X : Z) / 2 }; }); + const bump = (d, a, b) => d <= a ? 1 : d >= b ? 0 : 1 - IV.smooth((d - a) / (b - a)); + + function base(x, z) { return 4.5 * IV.fbm(x / 130 + 3.1, z / 130 + 1.7, 4) + 1.4 * IV.fbm(x / 38, z / 38, 3) - 3.2 - z * 0.012 + x * 0.004; } + const farmH = base(FARM.x, FARM.z) + 0.2; // (a 1.6 m rise changed the MG's sight lines and the loud route failed: kept as before) + // ---- relief: rolling hills, a ridge east of the farm, a deeper stream valley, a quarry, higher ground toward the + // map edge. It is faded to nothing within ~14-40 m of every route the mission, the AI and the bots use (approach, + // loud route, run, patrols, lanes, roads, farm, orchard, crossroads, hamlet, landing), so paths, thresholds, + // cover and sight lines there are as before. The fade mask is a 2 m grid built once. + const KEEP = [ + [[-117, 88], [-92, 47], [-92, 33], [-95, 12], [-62, -12], [-44, -24], [-41, -35], [-30, -45], [-2, -76], [14, -76], [28, -80], [24, -52], [36.8, -48.3], [24, -52], [24, -118], [60, -124], [80, -142], [120, -141], [120, -133], [107, -125]], + [[-92, 47], [-60, 22], [-10, 12], [4, 0], [30, -46], [40, -72], [75, -98], [98, -120], [100.6, -118.6]], + [[116, -66], [126, -32], [134, 0], [144, 40], [156, 74], [170, 98], [188, 112]], + L1, R1, R2, R3, [[46, -70], [74, -71], [76, -100], [46, -99], [44, -84], [46, -70]] + ]; + const KEEP_AREAS = [[FARM.x, FARM.z, 60], [0, 10, 26], [58, -86, 30], [AA.x, AA.z, 25], [MG.x, MG.z, 25], [OAK.x, OAK.z, 22], [LINK.x, LINK.z, 18], [EXTRACT.x, EXTRACT.z, 22], [8, 68, 48], [-41, 18, 16]]; + const CRATERS = [[-40, 62, 3.2], [110, 12, 4.2], [-125, -15, 3.6], [150, -25, 5], [-15, -125, 3.4], [80, 125, 4.5], [-150, 105, 3], [-75, -60, 4], [62, 162, 3.5], [-100, -140, 4.4]]; // shell holes, all off the routes + const PADS = [[-150, -45, 9], [-131, -61, 10], [-162, -62, 5], [150, 152, 9], [168, 136, 10], [-165, 138, 7], [-152, 150, 5], [166, -164, 8], [140, -166, 9]]; + let MASK = null; + function keepMask() { + const N = 191, m = new Float32Array(N * N); + for (let j = 0; j < N; j++) for (let i = 0; i < N; i++) { + const x = -190 + i * 2, z = -190 + j * 2; let d = 1e9; + for (const P of KEEP) d = Math.min(d, pd(x, z, P)); + for (const A of KEEP_AREAS) d = Math.min(d, Math.hypot(x - A[0], z - A[1]) - A[2]); + let dA = 1e9; for (const A of KEEP_AREAS) dA = Math.min(dA, Math.hypot(x - A[0], z - A[1]) - A[2]); + m[j * N + i] = dA < 8 ? -1 : 1 - bump(d, 14, 40); // -1: the combat areas (farm, crossroads, orchard, AA, MG) keep the ground they had + } + return m; + } + function relief(x, z) { + if (!MASK) MASK = keepMask(); + const fx = IV.clamp((x + 190) / 2, 0, 189.999), fz = IV.clamp((z + 190) / 2, 0, 189.999), i = Math.floor(fx), j = Math.floor(fz), tx = fx - i, tz = fz - j, N = 191; + const k = (MASK[j * N + i] * (1 - tx) + MASK[j * N + i + 1] * tx) * (1 - tz) + (MASK[(j + 1) * N + i] * (1 - tx) + MASK[(j + 1) * N + i + 1] * tx) * tz; + if (k < -0.5) return 0; + const kk = Math.max(0, 0.55 + 0.45 * k); // routes keep about half the relief (visible rises and dips, grades under ~7 deg); combat areas none; away from them full + const edge = IV.smooth(IV.clamp((Math.max(Math.abs(x), Math.abs(z)) - 140) / 48, 0, 1)); + let r = 7 * (IV.fbm(x / 80 + 9, z / 80 - 2, 4) - 0.45) + 2.6 * (IV.fbm(x / 26, z / 26 + 5, 3) - 0.5) + edge * 9 * IV.fbm(x / 60 - 3, z / 60 + 8, 3); + r += 12 * Math.exp(-(((x - 172) / 15) ** 2)) * bump(Math.abs(z + 115), 45, 75); // the ridge east of the farm + r -= 2.6 * bump(pd(x, z, ST), 6, 30); // the stream valley + const dq = Math.hypot(x - 95, z - 160); r -= 7 * (1 - IV.smooth(IV.clamp((dq - 15) / 7, 0, 1))); // the old quarry + return r * kk; + } + function height(x, z) { + let h = base(x, z) + relief(x, z); + for (const C of CRATERS) { const dc = Math.hypot(x - C[0], z - C[1]); if (dc < C[2] * 1.8) { const u = dc / C[2]; h += u < 1 ? -1.3 * C[2] / 4 * (1 - u * u) : 0.35 * C[2] / 4 * Math.sin(Math.PI * (u - 1) / 0.8); } } // bowl and thrown-up rim + // the outlying farms stand on levelled pads + for (const P of PADS) { const dp = Math.hypot(x - P[0], z - P[1]); if (dp < P[2] + 8) h = h + (base(P[0], P[1]) + relief(P[0], P[1]) - h) * bump(dp, P[2], P[2] + 8); } + // the farm sits on a levelled rise + const df = Math.hypot((x - FARM.x) / 1.15, z - FARM.z - 4); + h = h + (farmH - h) * bump(df, 34, 52); + // crossroads level + h = h + (base(0, 10) - h) * bump(Math.hypot(x, z - 10), 10, 18); + // the hamlet street climbs north from the crossroads (about 3 m over 90 m, under 2 degrees) and the church stands + // above it on a knoll (level within 12 m of the church, rising ~7 degrees from the street); the street rise fades + // out 24-34 m either side of the road + { const rx = z < 80 ? z / 80 : 1 + (z - 80) / 108; + const street = 3.0 * IV.smooth(IV.clamp((z - 22) / 92, 0, 1)) * bump(Math.abs(x - rx), 24, 34); // (the stream, 37 m west, keeps its level) + h += Math.max(street, 4.0 * bump(Math.hypot(x - 37, z - 88), 12, 24)); } // the knoll stands 1.5 m above the street beside it + // sunken lanes (cancel the cut over the bridge) + const ds = pd(x, z, ST); + const lane = Math.max(bump(pd(x, z, L1), 1.9, 3.6), bump(pd(x, z, L2), 1.9, 3.6) * bump(df, 999, 1000) + bump(pd(x, z, L2), 1.9, 3.6) * (1 - bump(df, 20, 30))); + // the cutting deepens along the lane: 1.25 m at its ends (the farm, crossroads and bridge keep their ground), up to + // 1.85 m in the middle of each run, so the lane dips into the cutting and rises out (floor grade well under 4 deg) + const lc = pd(x, z, L1) < pd(x, z, L2) ? IV.polyDist(x, z, L1) : IV.polyDist(x, z, L2), lt = (lc.i + lc.t) / ((pd(x, z, L1) < pd(x, z, L2) ? L1 : L2).length - 1); + const deep = 0.6 * Math.sin(Math.PI * IV.clamp(lt, 0, 1)) ** 0.7 * (1 - bump(df, 34, 50)) * (1 - bump(Math.hypot(x, z - 10), 26, 40)) * (1 - bump(Math.hypot(x + 41, z - 18), 12, 22)); // none at the farm, the crossroads or the bridge + h -= (1.25 + deep) * lane * (1 - bump(ds, 4, 9)); + // the stream bed + h -= 1.9 * bump(ds, 1.2, 5.5); + // the bridge approach stays at bank height + if (Math.hypot(x + 41, z - 18) < 9) h = Math.max(h, base(-41, 18) - 1.0); + return h; + } + function waterLevel(x, z) { const d = pd(x, z, ST); if (d > 6) return -99; const r = IV.polyDist(x, z, ST), a = ST[r.i], b = ST[r.i + 1]; const cx = a[0] + (b[0] - a[0]) * r.t, cz = a[1] + (b[1] - a[1]) * r.t; return base(cx, cz) - 1.45; } + function surface(x, z) { + if (waterLevel(x, z) > height(x, z) + 0.05) return S.water; + if (pd(x, z, R1) < 2.6 || pd(x, z, R2) < 2.4 || pd(x, z, R3) < 2.6) return S.gravel; + if (pd(x, z, L1) < 2.3 || pd(x, z, L2) < 2.3) return S.mud; + if (x > 88 && x < 132 && z > -86 && z < -55) return S.gravel; + if (IV.inPoly(x, z, WHEAT)) return S.crops; + if (IV.inPoly(x, z, MAIZE) && Math.abs(x - 24) > 0.9) return S.crops; // (the trampled path is open ground) + if (IV.inPoly(x, z, PAST) && IV.fbm(x / 9, z / 9, 2) > 0.55) return S.tallgrass; + if (x > -70 && x < -10 && z > 30 && z < 150 && IV.fbm(x / 7 + 4, z / 7, 2) > 0.6) return S.tallgrass; + return S.grass; + } + // finer ground kinds for the environment art (lanes vs mud, the yard), from the same layout + function surfaceKind(x, z) { + const dl = Math.min(pd(x, z, L1), pd(x, z, L2)); + if (dl < 0.35) return 'lanemid'; // the grassy strip between the ruts + if (dl < 2.3) return 'lane'; + if (dl < 3.2) return 'verge'; + if (x > 88 && x < 132 && z > -86 && z < -55) return 'yard'; + for (const m of MAIZE2) if (x > m[0] - 1.2 && x < m[2] + 1.2 && z > m[1] - 1.2 && z < m[3] + 1.2) return x > m[0] + 1.2 && x < m[2] - 1.2 && z > m[1] + 1.2 && z < m[3] - 1.2 ? 'field' : 'worn'; + if (x > -150 && x < -70 && z > -150 && z < -95 && IV.fbm(x / 30, z / 30, 2) > 0.5) return 'field'; + // damp hollows (darker, trodden, a little standing water) and shorter-grazed patches break up the open fields + if (Math.hypot(x - 95, z - 160) < 21) return 'yard'; // the old quarry: stone and spoil + for (const C of CRATERS) { const dc = Math.hypot(x - C[0], z - C[1]); if (dc < C[2] * 1.15) return 'mud'; if (dc < C[2] * 2.1) return 'scorched'; } // scorched mud, thrown soil, burnt stubble + if (x > -30 && x < 50 && z > 25 && z < 112) for (const r of HRECT) { const dd = Math.max(Math.abs(x - r.x) - r.hx, Math.abs(z - r.z) - r.hz); if (dd < 2.6 && dd > -0.5) return dd < 1.1 ? 'yardedge' : 'verge'; } // trodden ring and weeds at the walls + if (surface(x, z) !== S.grass) return null; // never over the tall grass (stealth cover), crops, mud or water + const f = IV.fbm(x / 34 + 7, z / 34 - 3, 3); + if (f < 0.3) return 'worn'; + if (f > 0.68) return 'pasture'; + return null; + } + function groundColor(x, z, y, n, c) { + const v = IV.fbm(x / 23, z / 23, 3), v2 = IV.noise(x / 4.3, z / 4.3); + // desaturated, muddy greens: this is the darkest game on the site + c.setRGB(0.25 + v * 0.09, 0.285 + v * 0.07, 0.17 + v2 * 0.04); + let mud = 0; + const s = surface(x, z); + if (s === S.gravel) { c.setRGB(0.42, 0.4, 0.36); mud = 2; } + else if (s === S.mud) { c.setRGB(0.36, 0.3, 0.22); mud = 1; } + else if (s === S.crops) { c.setRGB(0.4, 0.36, 0.22); mud = 0.45; } + else if (s === S.water) { c.setRGB(0.2, 0.19, 0.15); mud = 1; } + else if (s === S.tallgrass) c.setRGB(0.32, 0.35, 0.18); + // banks and slopes: more earth + if (n.y < 0.86) { mud = Math.max(mud, 0.7); c.lerp(new THREE.Color(0.33, 0.28, 0.2), 0.5); } + // wheel ruts in lanes + if (s === S.mud) { const r = IV.polyDist(x, z, pd(x, z, L1) < pd(x, z, L2) ? L1 : L2).d; if (Math.abs(r - 0.8) < 0.3) c.multiplyScalar(0.8); } + // the yard: mud round the edges + return mud; + } + + // offset a polyline sideways by d (positive = right of travel) + function offset(pts, d) { + return pts.map((p, i) => { + const a = pts[Math.max(0, i - 1)], b = pts[Math.min(pts.length - 1, i + 1)], dx = b[0] - a[0], dz = b[1] - a[1], l = Math.hypot(dx, dz) || 1; + return [p[0] - dz / l * d, p[1] + dx / l * d]; + }); + } + // gaps given as world points (x,z,width) -> distances along the polyline + function gapsAt(pts, list) { + const out = []; + for (const g of list) { + let acc = 0, best = 1e9, at = 0; + for (let i = 0; i < pts.length - 1; i++) { const r = IV.segDist(g[0], g[1], pts[i][0], pts[i][1], pts[i + 1][0], pts[i + 1][1]), len = Math.hypot(pts[i + 1][0] - pts[i][0], pts[i + 1][1] - pts[i][1]); if (r.d < best) { best = r.d; at = acc + r.t * len; } acc += len; } + out.push([at - g[2] / 2, at + g[2] / 2]); + } + return out; + } + + // ---------------------------------------------------------------- build (static world) + let grass = null; + function build(M) { + const b = K.begin(); + // hedgerows + const hedge = (pts, gaps, o) => IV.art.hedge(b, pts, gapsAt(pts, gaps || []), o); + const L1n = offset(L1, -3.5), L1s = offset(L1, 3.5); + hedge(L1n, [[-120, 31, 5], [-41, 14, 16], [-58, 16, 5], [-14, 9, 5]]); + hedge(L1s, [[-92, 25, 5], [-41, 22, 16], [-22, 18, 5], [-150, 37, 5]]); + const L2w = offset(L2, -3.5), L2e = offset(L2, 3.5); + hedge(L2w.slice(1), [[133, 0, 4], [150, 74, 4]]); + hedge(L2e.slice(1), [[150, 40, 5], [165, 90, 4]]); + hedge([[-125, -30], [-90, -28], [-50, -26]], [[-90, -28, 5]]); + hedge([[-30, -26], [-6, -30]]); + hedge([[30, -58], [30, -112]], [[30, -80, 5]]); + hedge([[30, -114], [90, -116], [96, -132], [150, -134]], [[62, -115, 5], [120, -133, 6]]); + hedge(offset([[3, -46], [8, -100], [12, -170]], 4.2), [[6, -75, 5], [10, -140, 5]]); + hedge(offset([[3, -46], [8, -100], [12, -170]], -4.2), [[6, -75, 5]]); + hedge([[18, 28], [96, 28]], [[30, 28, 5], [70, 28, 5]]); + hedge([[97, 28], [99, -20], [104, -40]], [[99, -5, 5]]); + hedge([[82, -62], [82, -108]], [[82, -82, 4], [82, -100, 4]]); + hedge([[-60, 60], [-60, 150]], [[-60, 100, 6]]); + hedge([[-170, -80], [-110, -84], [-60, -90]], [[-110, -84, 6]]); + hedge([[30, 60], [100, 66], [126, 64]], [[70, 64, 6]]); + hedge([[-30, 70], [-28, 160]], [[-29, 120, 6]]); + hedge([[-175, 160], [-60, 162]], [[-120, 161, 6]]); + hedge([[150, -70], [150, -150]], [[150, -100, 6]]); + hedge([[40, 110], [130, 120], [180, 130]], [[90, 115, 6]]); + hedge([[-170, -150], [-70, -160]], [[-120, -155, 6]]); + // the oak you land in, with the canopy of the parachute + const R = IV.rng(42); + IV.art.tree(b, OAK.x, OAK.z, 'oak', R); + // orchard + for (let x = 42; x <= 76; x += 6.5) for (let z = -104; z <= -66; z += 6.5) if (R() > 0.12) IV.art.tree(b, x + R.range(-0.8, 0.8), z + R.range(-0.8, 0.8), 'apple', R); + // poplars along the road + for (let z = 30; z < 180; z += 14) IV.art.tree(b, -4, z + R.range(-2, 2), 'poplar', R); + for (let z = -110; z > -180; z -= 16) IV.art.tree(b, 16, z, 'poplar', R); + // a treeline all round the edge of the map (two staggered rows, mostly impostors at range) so the world never + // ends in a hard line, and tree clumps on the field corners (visual only beyond the playable area) + const RT = IV.rng(31); // its own stream, so the farm's random placements stay exactly as before + for (let t = -182; t <= 182; t += 11) for (const [x, z] of [[t, -184], [t + 5, 184], [-184, t + 4], [184, t]]) { + const k = RT() < 0.45 ? 'oak' : RT() < 0.7 ? 'ash' : 'poplar'; + IV.art.tree(b, x + RT.range(-2, 2), z + RT.range(-2, 2), k, RT); + if (RT() < 0.6) IV.art.tree(b, x * 0.965 + RT.range(-3, 3), z * 0.965 + RT.range(-3, 3), RT() < 0.6 ? 'oak' : 'ash', RT); + } + [[-150, 175], [-90, 172], [40, 176], [120, 172], [176, -150], [176, 60], [-176, 20], [-176, -100]].forEach(([x, z]) => { for (let i = 0; i < 4; i++) IV.art.tree(b, x + RT.range(-6, 6), z + RT.range(-6, 6), RT() < 0.5 ? 'oak' : 'ash', RT); }); + // fields: hay heaps and bales, troughs, field gates in the hedge gaps, a few lone trees, so the big fields are not + // empty even planes (its own random stream, and nothing on the routes the patrols or the player's approach use) + if (IV.art.envOn() && IVEnv.prop) { + const RF = IV.rng(57), root = W.envRoot && W.envRoot.parent ? W.envRoot : W.statics; + const put = (kind, x, z, rot, o, solid) => { try { const p = IVEnv.prop(kind, (x * 31 + z * 17) | 0 || 3, o), y = W.height(x, z), c = Math.cos(rot), s2 = Math.sin(rot); p.group.position.set(x, y, z); p.group.rotation.y = rot; p.group.traverse(m => { if (m.isMesh) m.userData.detail = 50; }); root.add(p.group); if (solid !== false) for (const k of p.colliders) W.addBox(x + k.x * c + k.z * s2, z - k.x * s2 + k.z * c, k.hx, k.hz, y + k.y0, y + k.y1, rot + k.rot, F.SOLID | F.BULLET | F.NAV, 'wood', k.kind); } catch (e) { console.warn('field dressing', kind, e); } }; + for (const [cx, cz, n] of [[60, 44, 7], [-120, 110, 6], [-110, -125, 6], [165, -110, 4], [-150, 60, 4]]) for (let i = 0; i < n; i++) { const x = cx + RF.range(-16, 16), z = cz + RF.range(-9, 9), lowSkip = IVEnv.Q && IVEnv.Q.name === 'low', kh = RF() < 0.3 ? 'haystack' : 'haybale', rh = RF() * 6.28; if (!lowSkip) put(kh, x, z, rh); } + put('trough', -82, 122, 0.4); put('trough', 48, 50, 1.3); put('trough', 166, -92, 0.1); + for (const [x, z, r] of [[-60, 100, Math.PI / 2], [-29, 120, Math.PI / 2], [-120, 161, 0], [70, 64, 0.09], [150, -100, Math.PI / 2], [-120, -155, -0.1], [90, 115, 0.11]]) put('gate', x, z, r, { width: 3.4, open: 0.9 + RF() * 0.5 }); // same on every quality, posts solid + for (const [x, z] of [[-128, 92], [62, 40], [-96, -128], [160, -128], [-150, 20]]) IV.art.tree(b, x + RF.range(-3, 3), z + RF.range(-3, 3), RF() < 0.6 ? 'oak' : 'ash', RF); + } + // ---- the countryside is lived in: a hamlet strung along the north road above the crossroads (cottages of one and + // two storeys, a cafe-shop row, a smithy, barns and sties, a church in its walled yard, a well and a wayside cross), + // farms on the outlying slopes, and village skylines beyond the map. Some windows lit, most dark, some damaged. + // Every reachable building is one closed collider (no interiors); none sits on a patrol or the approach routes. + { + const H2 = Math.PI / 2, hamlet = HAMLET; + IV.art.settle(b, hamlet.map(sp => sp.kind === 'church' || sp.kind === 'shed' ? sp : Object.assign({ free: ['back'], wingMax: 5.2 }, sp)), { seed: 404, rugged: 1 }); + // the churchyard wall (gap to the road), the well, a wayside cross at the crossroads corner + IV.art.wall(b, [[28, 74], [28, 80.5]], 1.2, [], { coping: 'flat' }); IV.art.wall(b, [[28, 87.5], [28, 104], [47, 104], [47, 72], [28, 72], [28, 74]], 1.2, [], { coping: 'flat' }); + if (IV.art.envOn() && IVEnv.prop) { try { const wl = IVEnv.prop('well', 61); wl.group.position.set(-5.4, W.height(-5.4, 64), 64); (W.envRoot && W.envRoot.parent ? W.envRoot : W.statics).add(wl.group); W.addBox(-5.4, 64, 0.8, 0.8, W.height(-5.4, 64), W.height(-5.4, 64) + 0.9, 0, F.SOLID | F.BULLET | F.NAV, 'stone'); } catch (e) {} } + { const cy = W.height(-4.2, 26); K.box(b, 'wood', -4.2, cy, 26, 0.18, 2.6, 0.18, 0.3, 0x5a4a3a, F.SOLID | F.BULLET, 'wood'); K.box(b, 'wood', -4.2, cy + 1.75, 26, 1.2, 0.16, 0.16, 0.3, 0x5a4a3a); K.box(b, 'stone', -4.2, cy - 0.2, 26, 0.9, 0.35, 0.9, 0.3, 0x8a867c); } + // dressing the street (interiors-props-and-clutter: large, medium, small; clustered at walls and doors, nothing + // aligned, the road and doorways clear): low front-garden walls with gaps at the doors, carts, barrels, firewood, + // a trough, ladders, a wash line, bottles and crates by the shop; puddles and dung on the road; gravestones, a lych + // gate and clipped yews in the churchyard + if (IV.art.envOn() && IVEnv.prop && IVEnv.builder) { + const root = W.envRoot && W.envRoot.parent ? W.envRoot : W.statics, RS = IV.rng(808); + const put = (kind, x, z, rot, o, solid) => { try { const p = IVEnv.prop(kind, (x * 31 + z * 17) | 0 || 5, o), y = W.height(x, z), c = Math.cos(rot), s2 = Math.sin(rot); p.group.position.set(x, y, z); p.group.rotation.y = rot; p.group.traverse(m => { if (m.isMesh) m.userData.detail = 50; }); root.add(p.group); if (solid !== false) for (const k of p.colliders) W.addBox(x + k.x * c + k.z * s2, z - k.x * s2 + k.z * c, k.hx, k.hz, y + k.y0, y + k.y1, rot + k.rot, F.SOLID | F.BULLET | F.NAV, 'wood', k.kind); } catch (e) { console.warn('street', kind, e); } }; + for (const sp of HAMLET) { if (sp.kind === 'church' || sp.kind === 'shed' || Math.abs(Math.abs(sp.rot) - Math.PI / 2) > 0.1) continue; + const side = sp.rot < 0 ? 1 : -1, wx = sp.x - side * ((sp.kind === 'barn' ? sp.w || 10 : sp.kind === 'shoprow' ? 8 : sp.d || 6) / 2 + 1.9), half = (sp.kind === 'barn' ? sp.d || 13 : sp.kind === 'shoprow' ? 10.8 : sp.w || 8) / 2 + 0.8; + if (sp.kind !== 'shoprow' && sp.kind !== 'ruin' && sp.kind !== 'barn') IV.art.wall(b, [[wx, sp.z - half], [wx, sp.z + half]], 0.85, [[half - 0.8, half + 0.8]], { coping: 'flat' }); + const sx = sp.x - side * ((sp.kind === 'barn' ? sp.w || 10 : sp.kind === 'shoprow' ? 8 : sp.d || 6) / 2 + 0.7); + const pick = RS(); if (pick < 0.3) put('barrels', sx, sp.z + half - 1.6, RS() * 6); else if (pick < 0.55) put('logpile', sx + side * 0.2, sp.z - half + 1.6, H2 + RS() * 0.2); else if (pick < 0.75) put('crates', sx, sp.z + half - 1.4, RS()); else put('ladder', sx + side * 0.4, sp.z - half + 2, sp.rot, null, false); } + put('cart', 4.6, 44, 0.3); put('cart', -5.2, 98, 2.6); put('trough', 4.4, 58.5, H2 + 0.05); put('bottles', 14.2, 49, 0); put('crates', 14.6, 55.3, 0.4); put('barrels', -15.8, 47.5, 0.7); + put('washline', -19, 76, 0.2, { length: 5 }, false); + IV.art.prop('sandbags', b, 5.6, 104, 9.5, 108, 3); IV.art.prop('sandbags', b, 9.5, 108, 13, 107, 3); // a sandbagged corner by the burnt house + try { const wc = IVEnv.prop('cart', 515), y = W.height(-6.5, 112); wc.group.position.set(-6.5, y + 0.2, 112); wc.group.rotation.set(0.1, 2.2, 0.45); root.add(wc.group); W.addBox(-6.5, 112, 1.6, 0.8, y, y + 1.2, 2.2, F.SOLID | F.BULLET | F.NAV, 'wood'); } catch (e) {} // a cart on its side put('tarp', 20.5, 33.5, 1.4); put('logpile', -18.5, 51, 0.1); put('haybale', -21, 88, 0.5); put('haybale', -21.5, 91, 1.9); + // rubble from the damaged houses spilling to the road + if (IVEnv.rubble && IVEnv.Q.name !== 'low') { try { const RB = IVEnv.builder(919), RR = IVEnv.rng(919); for (const [x, z, n] of [[5.5, 95, 26], [5.3, 63.5, 10], [-5.8, 57, 12]]) IVEnv.rubble(RB, x, z, 1.8, RR, { brick: 'brick_sooty', stone: 'fieldstone' }, n, W.height(x, z)); const g = RB.finish(); g.traverse(m => { if (m.isMesh) m.userData.detail = 50; }); root.add(g); } catch (e) { console.warn('rubble', e); } } + // road: puddles in the wheel tracks and dung + try { const pud = [], DB = IVEnv.builder(717); for (let z = 26; z < 110; z += 4 + RS() * 7) { const x = (z < 80 ? z / 80 : 1 + (z - 80) / 108) + (RS() < 0.5 ? -1.1 : 1.1); pud.push([x, W.height(x, z), z, 0.5 + RS() * 0.8, 0.25 + RS() * 0.2, Math.PI / 2 + RS() * 0.3]); if (RS() < 0.5) DB.decal('mud', [x + RS() * 1.4 - 0.7, W.height(x, z) + 0.02, z + 1.5], [0, 1, 0], 0.35, 0.3, RS() * 6); } + if (IVEnv.puddleMesh) W.scene.add(IVEnv.puddleMesh(pud)); { const g = DB.finish(); g.traverse(m => { if (m.isMesh) m.userData.detail = 50; }); root.add(g); } } catch (e) { console.warn('road', e); } + // churchyard: gravestones (some leaning), a lych gate over the entrance, clipped yews + try { const GB = IVEnv.builder(71), RG = IV.rng(71); + const stone = (x, z) => { const y = W.height(x, z), hh = 0.6 + RG() * 0.5; GB.box('ashlar', x, y - 0.25, z, 0.5 + RG() * 0.2, hh + 0.25, 0.1, H2 + RG() * 0.12 - 0.06, { rx: RG() < 0.3 ? RG() * 0.2 - 0.1 : 0, rz: RG() < 0.25 ? RG() * 0.16 - 0.08 : 0, tint: E2t(RG) }); GB.decal('moss', [x, y + 0.02, z + 0.6], [0, 1, 0], 0.6, 1.4, 0); }; + const E2t = (R3) => new THREE.Color(0.82 + R3() * 0.15, 0.82 + R3() * 0.12, 0.8 + R3() * 0.1); + for (let z = 75; z < 102; z += 1.9) { stone(30.3 + RG() * 0.4, z + RG() * 0.4); if (z > 97 || z < 79) for (let x = 33; x < 46; x += 1.8) stone(x + RG() * 0.4, z + 0.3); } + for (let z = 75; z < 100; z += 2.2) stone(44.5 + RG() * 0.4, z); + const gy = W.height(28, 84); for (const z of [80.6, 87.4]) { GB.box('timber', 28, gy, z, 0.22, 2.3, 0.22, 0, { grain: 'long' }); W.addBox(28, z, 0.13, 0.13, gy, gy + 2.3, 0, F.SOLID | F.BULLET, 'wood'); } + GB.geo('roof_tile', new THREE.ConeGeometry(1, 1, 4, 1).rotateY(Math.PI / 4), new THREE.Matrix4().compose(new THREE.Vector3(28, gy + 2.3, 84), new THREE.Quaternion(), new THREE.Vector3(1.6, 1.1, 5.2)), { noFoot: true }); + { const g = GB.finish(); g.traverse(m => { if (m.isMesh) m.userData.detail = 60; }); root.add(g); } } catch (e) { console.warn('churchyard', e); } + IV.art.hedge(b, [[30.5, 74], [31.5, 76.5]], [], { h: 2.4, bank: 0 }); IV.art.hedge(b, [[45, 101], [45.6, 103]], [], { h: 2.2, bank: 0 }); // clipped yews + } + // outlying farms on the slopes (inside the map, away from the routes) + IV.art.settle(b, [ + { kind: 'farmhouse', w: 11, d: 7, x: -150, z: -45, rot: 0.3, lit: 0.3 }, { kind: 'barn', w: 9, d: 14, x: -131, z: -61, rot: 0.3 + H2 }, { kind: 'shed', w: 6, d: 4, x: -162, z: -62, rot: 0.3 }, + { kind: 'farmhouse', w: 12, d: 7, x: 150, z: 152, rot: -2.6 }, { kind: 'barn', w: 10, d: 15, x: 168, z: 136, rot: -2.6 + H2 }, + { kind: 'cottage', w: 8, d: 6, floors: 2, x: -165, z: 138, rot: 1.2, lit: 0.5 }, { kind: 'shed', w: 5, d: 4, x: -152, z: 150, rot: 1.2 }, + { kind: 'ruin', w: 10, d: 7, x: 166, z: -164, rot: 2.3, damage: 0.95 }, { kind: 'barn', w: 9, d: 13, x: 140, z: -166, rot: 2.3 + H2, damage: 0.4 } + ], { seed: 515, rugged: 1, shellOnly: IVEnv.Q && IVEnv.Q.name === 'low' }); // (Low: shells, still with colliders) + // village skylines on the far hills: shells only, no colliders + const hFar = IVEnv.skirtHeightAt || ((x, z) => W.height(Math.max(-188, Math.min(188, x)), Math.max(-188, Math.min(188, z)))); + const village = (cx, cz, n, sd, church) => { const RV = IV.rng(sd), list = []; if (church) list.push({ kind: 'church', w: 15, d: 8, x: cx, z: cz, rot: RV() * 6.28, shellOnly: true, solid: false }); + for (let i = 0; i < n; i++) { const a = RV() * 6.28, r = 12 + RV() * 55, x = cx + Math.cos(a) * r, z = cz + Math.sin(a) * r * 0.6, k = RV(); list.push({ kind: k < 0.2 ? 'ruin' : k < 0.55 ? 'cottage' : k < 0.75 ? 'farmhouse' : k < 0.9 ? 'shoprow' : 'barn', damage: k < 0.2 ? 0.95 : k < 0.4 ? 0.6 : 0, w: 7 + RV() * 5, d: 5.5 + RV() * 2, floors: RV() < 0.5 ? 2 : 1, units: 2, x, z, rot: Math.round(RV() * 4) * H2 + RV() * 0.3, lit: RV() < 0.15 ? 0.6 : 0, shellOnly: true, solid: false }); } + return list; }; + if (IV.art.envOn()) IV.art.settle(b, [...village(330, -30, 14, 61, true), ...village(-70, -340, 10, 62, true), ...village(-310, 230, 9, 63, false), ...village(250, 300, 8, 64, false)], { seed: 626, shellOnly: true, heightFn: hFar, lights: false }); + } + // the war going on beyond the hills: searchlights, flak and tracer, aircraft, a burning village and a dump, flares, + // a few far parachutes at first, bombing flashes with a late rumble; smoke from the lit chimneys, bats by the church; + // a dog, the church bell and an owl as sound hooks. None of it is near the routes or reads as an enemy. + IV.art.backdrop({ searchlights: [[330, -120], [-280, -300], [250, 260]], flak: [[330, -120], [260, 230]], planes: true, + chutes: [[-260, 160], [-320, -40]], bombing: [[400, -220], [-400, -160]], fires: [[335, -25, 1.4], [-300, -270, 1]], flares: [[250, -160]], + smoke: IV.art.chimneys.map(c => [c.x, c.y, c.z, false]), bats: [[37, 88], [-150, -45]], + leaves: 'night', sounds: [{ kind: 'dog', every: [20, 50], x: 6, z: 62 }, { kind: 'bell', every: [70, 140], x: 37, z: 80 }, { kind: 'owl', every: [30, 70], x: -60, z: 110 }] }); + // ---- trees to fill the middle distance (their own random stream): tall hedgerow trees every 20-40 m along the + // lanes and field hedges, copses and a shelter belt on the slopes, willow-like ash along the stream, an avenue on + // the road into the hamlet, garden and churchyard trees, lone oaks in fields, scrub at field corners + { const RF2 = IV.rng(2024), clear = (x, z) => { if (pd(x, z, L1) < 4.2 || pd(x, z, L2) < 4.2 || pd(x, z, R1) < 4.5 || pd(x, z, R2) < 4 || pd(x, z, R3) < 4.5 || pd(x, z, ST) < 5) return false; if (Math.hypot(x - FARM.x, z - FARM.z) < 40 || Math.hypot(x - AA.x, z - AA.z) < 18) return false; if (IV.inPoly(x, z, WHEAT) || IV.inPoly(x, z, MAIZE)) return false; for (const r of HRECT) if (Math.abs(x - r.x) < r.hx + 2.5 && Math.abs(z - r.z) < r.hz + 2.5) return false; if (Math.abs(x) > 186 || Math.abs(z) > 186) return false; for (let q = 0; q < 3; q++) if (pd(x, z, KEEP[q]) < 3.5) return false; return true; }; // never on the approach, loud route or run + const tree = (x, z, k) => { if (clear(x, z)) IV.art.tree(b, x, z, k || (RF2() < 0.5 ? 'oak' : RF2() < 0.7 ? 'ash' : 'poplar'), RF2); }; + if (!(IVEnv.Q && IVEnv.Q.name === 'low')) for (const Ln of [offset(L1, -6.5), offset(L1, 6.5), offset(L2, -6.5), offset(L2, 6.5)]) for (let i = 0; i < Ln.length - 1; i++) { const a = Ln[i], c = Ln[i + 1], L = Math.hypot(c[0] - a[0], c[1] - a[1]); for (let t = RF2() * 20; t < L; t += 20 + RF2() * 20) tree(a[0] + (c[0] - a[0]) * t / L, a[1] + (c[1] - a[1]) * t / L, RF2() < 0.7 ? 'oak' : 'ash'); } + if (IVEnv.Q && IVEnv.Q.name === 'low') { /* Low: the hedgerow trees only */ } else { + for (const [cx, cz, n] of [[-60, -130, 12], [-160, -100, 10], [70, 150, 10], [-100, 120, 8], [130, -10, 8], [-170, 0, 9], [175, 20, 8], [-20, -160, 9], [100, -170, 8]]) for (let i = 0; i < n; i++) tree(cx + RF2.range(-16, 16), cz + RF2.range(-14, 14)); + for (let t = 0; t < 1; t += 0.06) { const r = IV.polyDist(0, 0, ST); const i = Math.floor(t * (ST.length - 1)), a = ST[i], c = ST[i + 1], u = t * (ST.length - 1) - i, x = a[0] + (c[0] - a[0]) * u, z = a[1] + (c[1] - a[1]) * u; tree(x + (RF2() < 0.5 ? -7 : 7), z + RF2.range(-3, 3), 'ash'); } + for (let z = 112; z < 180; z += 12) { tree(6.5, z + RF2.range(-1, 1), 'poplar'); } + for (const [x, z] of [[-24, 40], [-25, 77], [22, 58], [24, 30], [-27, 98], [43, 99], [31, 99], [44, 76]]) tree(x, z, RF2() < 0.6 ? 'apple' : 'ash'); + for (const [x, z] of [[-110, 40], [-70, 100], [60, 100], [140, 90], [-120, -60], [90, 0], [-40, 140], [150, -110], [-140, 165], [40, -150]]) tree(x, z, 'oak'); + for (const [x, z] of [[-58, 58], [-62, 152], [-28, 72], [97, 26], [32, -57], [148, -72], [-168, -78], [-72, -88]]) for (let i = 0; i < 3; i++) tree(x + RF2.range(-3, 3), z + RF2.range(-3, 3), 'apple'); } } + // ---- the war has passed through here (destruction-and-bullet-damage, mud-and-splashes): every shell hole has a + // rim of thrown clods, stones and dried crust, scorched soil and brown water in the bottom; burnt dead trees stand + // by the holes and the ruins; a telegraph line on the south road leans, sags and has one wire down; a burnt-out + // lorry lies nose-down in the crater west of the lane; rubble mounds with loose bricks and charred beams by the + // ruins; sandbag walls at the far ruined farm and the lorry. All off the routes (the same rules as the trees). + if (IV.art.envOn() && IVEnv.builder && IVEnv.prop) { try { + const root = W.envRoot && W.envRoot.parent ? W.envRoot : W.statics, RW = IV.rng(3131), pud = []; + const off = (x, z) => pd(x, z, L1) < 4 || pd(x, z, L2) < 4 || pd(x, z, R1) < 4 || pd(x, z, R2) < 4 || pd(x, z, R3) < 4 || Math.hypot(x - FARM.x, z - FARM.z) < 34 || Math.hypot(x - AA.x, z - AA.z) < 16; + const lowQ = IVEnv.Q && IVEnv.Q.name === 'low'; + for (const C of CRATERS) { + const [cx, cz, r] = C, RC = IV.rng((cx * 13 + cz * 7) | 0), by = W.height(cx, cz), WB = IVEnv.builder(cx * 7 + cz | 0); // one mesh per hole: culled and hidden past 70 m + for (let k = 0; k < 18 + r * 3; k++) { const a = RC() * 6.283, d = r * RC.range(0.95, 1.55), x = cx + Math.cos(a) * d, z = cz + Math.sin(a) * d, y = W.height(x, z), s = RC.range(0.08, 0.32) * (RC() < 0.15 ? 2 : 1); + if (lowQ) continue; WB.geo(RC() < 0.7 ? 'mud' : 'earth', IVEnv.rockGeo((RC() * 40) | 0, 0), new THREE.Matrix4().compose(new THREE.Vector3(x, y - s * 0.35, z), new THREE.Quaternion().setFromEuler(new THREE.Euler(RC() * 3, RC() * 3, RC() * 3)), new THREE.Vector3(s, s, s)), {}); } + for (let k = 0; k < (lowQ ? 0 : 8 + r * 2); k++) { const a = RC() * 6.283, d = r * RC.range(0.3, 1.4), x = cx + Math.cos(a) * d, z = cz + Math.sin(a) * d; const s = RC.range(0.06, 0.18); WB.geo('fieldstone', IVEnv.rockGeo((RC() * 40) | 0, 0), new THREE.Matrix4().compose(new THREE.Vector3(x, W.height(x, z) - 0.04, z), new THREE.Quaternion().setFromEuler(new THREE.Euler(RC() * 3, RC() * 3, RC() * 3)), new THREE.Vector3(s, s, s)), {}); } + for (let k = 0; k < 6; k++) { const a = RC() * 6.283, d = r * RC.range(1.0, 1.5), x = cx + Math.cos(a) * d, z = cz + Math.sin(a) * d; WB.box('earth', x, W.height(x, z) - 0.03, z, RC.range(0.3, 0.7), 0.06, RC.range(0.2, 0.5), RC() * 3, { rx: RC.range(-0.2, 0.2), rz: RC.range(-0.2, 0.2), tint: new THREE.Color(0.85, 0.8, 0.72) }); } // dried crust plates + WB.decal('scorch', [cx, by + 0.05, cz], [0, 1, 0], r * 3.2, r * 3.2, RC() * 3); + for (let k = 0; k < 3; k++) { const a = RC() * 6.283; WB.decal('scorch', [cx + Math.cos(a) * r * 1.3, W.height(cx + Math.cos(a) * r * 1.3, cz + Math.sin(a) * r * 1.3) + 0.05, cz + Math.sin(a) * r * 1.3], [0, 1, 0], r * 1.4, r * 0.9, a); } + pud.push([cx + RC.range(-0.3, 0.3), W.height(cx, cz) + 0.12, cz + RC.range(-0.3, 0.3), r * RC.range(0.38, 0.55), r * RC.range(0.3, 0.45), RC() * 3]); + // a burnt, dead tree on the rim of most holes + { const g = WB.finish({ castShadow: false }); g.traverse(m => { if (m.isMesh && !m.userData.detail && IVEnv.registerDetail) IVEnv.registerDetail(m, 70); }); root.add(g); } + if (RW() < 0.7) { const a = RW() * 6.283, x = cx + Math.cos(a) * (r * 1.9 + 1.5), z = cz + Math.sin(a) * (r * 1.9 + 1.5); if (!off(x, z)) IV.art.tree(b, x, z, RW() < 0.6 ? 'burnt' : 'dead', RW); } + } + for (const [x, z] of [[8, 112], [17, 98], [168, -158], [160, -170], [-129, -8], [-80, -66], [-20, -131], [148, -32]]) if (!off(x, z)) IV.art.tree(b, x, z, RW() < 0.7 ? 'burnt' : 'dead', RW); + if (IVEnv.puddleMesh) W.scene.add(IVEnv.puddleMesh(pud, { brown: true })); + // tyre ruts across the open ground from the lorry's last run: two wet tracks (ground marks) with puddles + if (IVEnv.marks) { let x = -150, z = -32; const dir = 0.32; for (let t = 0; t < 30; t += 0.9) { const px = x + Math.cos(dir) * t, pz = z + Math.sin(dir) * t; for (const sdd of [-0.85, 0.85]) IVEnv.marks.stamp(px - Math.sin(dir) * sdd, pz + Math.cos(dir) * sdd, 'rut', dir, 0.9); } } + let WB = IVEnv.builder(3131); + // the burnt-out lorry in the crater west of the lane, nose down, and a sandbag wall beside it + try { const tr = IVEnv.prop('wreck', 77), tx = -124, tz = -16, ty = W.height(tx, tz); tr.group.position.set(tx, ty - 0.3, tz); tr.group.rotation.set(-0.16, 2.4, 0.09); + root.add(tr.group); W.addBox(tx, tz, 1.3, 3.2, ty - 0.5, ty + 2.2, 2.4, F.SOLID | F.BULLET | F.NAV | F.SIGHT, 'metal'); + WB.decal('soot', [tx, ty + 0.08, tz], [0, 1, 0], 7, 5, 0.6); for (let k = 0; k < 4; k++) WB.decal('scorch', [tx + RW.range(-3, 3), W.height(tx, tz) + 0.06, tz + RW.range(-3, 3)], [0, 1, 0], 2.5, 2.5, RW() * 3); } catch (e) { console.warn('wreck', e); } + IV.art.prop('sandbags', b, -118, -24, -113, -21, 3); + // the far ruined farm: a sandbagged post in its yard, rubble mounds with beams + IV.art.prop('sandbags', b, 158, -156, 162, -152, 3); IV.art.prop('sandbags', b, 162, -152, 166, -151, 3); + { const g = WB.finish(); g.traverse(m => { if (m.isMesh && IVEnv.registerDetail && !m.userData.detail) IVEnv.registerDetail(m, 80); }); root.add(g); WB = IVEnv.builder(4243); } + const RB = IVEnv.rng(4242); + for (const [x, z, rr, n] of [[163, -160, 2.6, 34], [170, -170, 2.0, 22], [11, 92, 2.2, 26], [15.8, 99.5, 1.4, 12]]) { + const y = W.height(x, z); IVEnv.rubble(WB, x, z, rr, RB, { brick: 'brick_sooty', stone: 'fieldstone' }, n, y); + for (let k = 0; k < 3; k++) WB.box('timber', x + RB.range(-rr, rr) * 0.6, y + RB.range(0.1, 0.5), z + RB.range(-rr, rr) * 0.6, 0.16, 0.18, RB.range(1.6, 3.2), RB() * 3, { rx: RB.range(-0.35, 0.35), rz: RB.range(-0.2, 0.2), grain: 'long', tint: new THREE.Color(0.28, 0.25, 0.22) }); + WB.decal('soot', [x, y + 0.05, z], [0, 1, 0], rr * 2.6, rr * 2.2, RB() * 3); + { const g = WB.finish(); g.traverse(m => { if (m.isMesh && IVEnv.registerDetail && !m.userData.detail) IVEnv.registerDetail(m, 70); }); root.add(g); WB = IVEnv.builder(x * 3 | 0); } + } + // leaning telegraph poles down the south road, wires sagging between them; the third span is down + { const wires = [], tops = []; let prev = null; + for (let i = 0; i < 6; i++) { const t = i / 5, z = -50 - t * 125, x = 3 + (8 - 3) * ((-z - 42) / 58 > 1 ? 1 : (-z - 42) / 58) + (z < -100 ? (12 - 8) * (-z - 100) / 88 : 0) - 5.5; + const p = IVEnv.prop('telegraph', 900 + i), y = W.height(x, z), lean = [0.02, -0.06, 0.16, 0.09, -0.04, 0.22][i]; p.group.position.set(x, y, z); p.group.rotation.set(0, 1.5, lean); root.add(p.group); p.group.updateMatrixWorld(true); + const tw = (p.group.userData.wireTop || []).map(v => new THREE.Vector3(v[0], v[1], v[2]).applyMatrix4(p.group.matrixWorld)); + if (prev) for (let k = 0; k < Math.min(prev.length, tw.length); k++) { if (i === 3 && k < 2) { const a = prev[k]; wires.push([a.x, a.y, a.z, a.x + RW.range(-0.5, 0.5), W.height(a.x, a.z - 5) + 0.05, a.z - 5 - k]); continue; } wires.push([prev[k].x, prev[k].y, prev[k].z, tw[k].x, tw[k].y, tw[k].z]); } + prev = tw; } + if (IVEnv.wireMesh) root.add(IVEnv.wireMesh(wires, 0.012, 0.9)); } + { const g = WB.finish(); g.traverse(m => { if (m.isMesh) m.userData.detail = m.userData.detail || 70; }); root.add(g); } + } catch (e) { console.warn('war dressing', e); } } + // scattered field trees + [[-150, 120], [-100, 140], [-20, 100], [60, 90], [140, 150], [-140, -40], [-90, -120], [40, -150], [110, 30], [-160, -120]].forEach(p => IV.art.tree(b, p[0], p[1], 'oak', R)); + // stone walls round the yard (low, vaultable) + IV.art.wall(b, [[88, -58], [88, -86]], 1.05, [[3, 7]]); + IV.art.wall(b, [[88, -58], [116, -54]], 1.05, [[0.5, 7.5]]); + IV.art.wall(b, [[130, -58], [131, -86]], 1.05, [[5, 9]]); + IV.art.wall(b, [[-58, 48], [-58, 20]], 0.95); + IV.art.wall(b, [[20, -30], [20, 20]], 0.9, [[20, 26]]); + // the stream: water ribbon, stone bridge on the lane, footbridge to the north + IV.art.water(ST, waterLevel, 7.2, water); bridge(b); footbridge(b); + // farmhouse: two storeys of wall but one floor inside, slate roof + const hy = farmH + 0.05; + const H = IV.art.building(b, { x: HOUSE.x, z: HOUSE.z, w: HOUSE.w, d: HOUSE.d, y: hy, h: 3.1, floor: 0.35, mat: 'stone', color: 0xb9b1a0, chimney: [-5, 0], + sides: { s: [{ t: 'door', at: 0, w: 1.15 }, { t: 'win', at: -5.3, w: 1.1, lit: true, shut: true }, { t: 'win', at: 5.2, w: 1.1, lit: true, shut: true }], + n: [{ t: 'door', at: 0, w: 1.1 }, { t: 'win', at: -5.3, w: 1.0, shut: true }, { t: 'win', at: 5.2, w: 1.0 }], + w: [{ t: 'win', at: -2, w: 1.0, lit: true }], e: [{ t: 'win', at: 2, w: 1.0 }, { t: 'win', at: -2.2, w: 1.0 }] }, + inner: [{ a: [-2.5, -4], b: [-2.5, 4], doors: [{ at: 1.9, w: 0.95 }, { at: 6.1, w: 0.95 }] }, { a: [2.5, -4], b: [2.5, 4], doors: [{ at: 1.9, w: 0.95 }, { at: 6.1, w: 0.95 }] }, + { a: [-7.5, 0], b: [-2.5, 0], doors: [{ at: 2.5, w: 0.95 }] }, { a: [2.5, 0], b: [7.5, 0] }], + roof: { pitch: 0.85, over: 0.45 } }); + const fy = H.fy, L = H.L2W; + // lit windows glow softly into the fog + // warm spill from the lit windows onto the yard and the walls outside (visual only: the AI's light test skips these) + for (const w of H.wins) if (w.lit) { const dx = w.x - HOUSE.x, dz = w.z - HOUSE.z, ax = Math.abs(dx) / (HOUSE.w / 2), az = Math.abs(dz) / (HOUSE.d / 2), ox = ax > az ? Math.sign(dx) : 0, oz = ax > az ? 0 : Math.sign(dz); W.addLamp({ x: w.x + ox * 1.1, y: w.y - 0.2, z: w.z + oz * 1.1, r: 6, i: 0, power: 1.5, color: 0xff9a48, flicker: true, los: false, visual: true }); } + for (const w of H.wins) if (w.lit) { const s = new THREE.Sprite(new THREE.SpriteMaterial({ map: W.tex.glow(), color: 0xff9a40, transparent: true, opacity: 0.35, blending: THREE.AdditiveBlending, depthWrite: false, toneMapped: false })); s.position.set(w.x, w.y, w.z); s.scale.set(3.2, 2.4, 1); W.statics.add(s); } + const prop = (fn, lx, lz, rot, ...a) => { const p = L(lx, lz); IV.art.prop(fn, b, p[0], fy, p[1], rot || 0, ...a); }; + prop('table', -5, 2.2, 0, 1.6, 0.9); prop('chair', -5.9, 2.2, Math.PI / 2); prop('chair', -4.1, 2.2, -Math.PI / 2); prop('stove', -7, 3.4, 0); prop('shelf', -3.3, 3.7, Math.PI, 1.0); // kitchen + prop('table', -5, -2.2, 0, 1.2, 0.8); prop('chair', -5, -3.2, 0); prop('shelf', -7.2, -2, Math.PI / 2, 1.4); prop('crate', -3.4, -3.4, 0.3, 0.6); // parlour + prop('table', 5.4, 2.0, 0, 1.5, 0.8); prop('chair', 5.4, 2.9, Math.PI); prop('shelf', 7.2, 2.2, -Math.PI / 2, 1.4); prop('crate', 3.3, 3.5, 0, 0.6); // office + prop('bed', 5.5, -2.2, Math.PI / 2); prop('shelf', 3.2, -3.6, 0, 1.0); // bedroom + prop('crate', -1.6, -3.4, 0, 0.7); prop('barrel', 1.6, 3.4); // hall + // the map on the office desk + { const p = L(5.4, 1.85); K.box(b, 'cloth', p[0], fy + 0.75, p[1], 0.6, 0.01, 0.45, 0.2, 0xd8ccaa); M.mapPos = { x: p[0], y: fy + 0.8, z: p[1] }; } + // interior lights (kitchen, office) and the doors' positions for the script + [[-5, 2.2], [5.4, 2.0], [-5, -2.2]].forEach((q, i) => { const p = L(q[0], q[1]); W.addLamp({ x: p[0], y: fy + 2.4, z: p[1], r: 6.5, i: 0.8, power: 1.2, color: 0xffa850, flicker: true }); }); + M.houseDoorN = { x: L(0, -5.3)[0], z: L(0, -5.3)[1] }; M.houseDoorS = { x: L(0, 5.3)[0], z: L(0, 5.3)[1] }; M.houseFy = fy; + M.rooms = { kitchen: L(-5, 2.6), parlour: L(-5, -2.4), office: L(5, 2.2), bedroom: L(5, -2.2), hall: L(0, 0) }; + // barn: tall wooden walls on a stone base, loft over the north half, hay door high on the west wall + const BB = IV.art.building(b, { x: BARN.x, z: BARN.z, w: BARN.w, d: BARN.d, y: farmH - 0.1, h: 6.2, floor: 0.12, mat: 'wood', color: 0x8a7458, floorMat: 'stone', floorCol: 0x6a6258, beams: false, + sides: { w: [{ t: 'door', at: 2.5, w: 3.2, h: 3.2 }, { t: 'win', at: -5, w: 1.6, sill: 4.0, oh: 1.3, open: true }], e: [{ t: 'door', at: 4, w: 1.2 }], s: [{ t: 'win', at: 0, w: 1.4, sill: 4.0, oh: 1.0, open: true }] }, + roof: { pitch: 0.95, over: 0.5, ridge: 'z' } }); + const by = BB.fy, BL = BB.L2W, loftY = by + 3.4; + { const p = BL(0, -4.4); K.box(b, 'wood', p[0], loftY - 0.15, p[1], 9.0, 0.15, 6.6, 0, 0x7a6448, F.SOLID | F.BULLET | F.SIGHT, 'wood'); } + // stairs up to the loft along the east wall (local x 3.9), rising toward the north + for (let i = 0; i < 12; i++) { const p = BL(3.9, 3.8 - i * 0.48); K.box(b, 'wood', p[0], by, p[1], 1.0, (i + 1) * (3.4 / 12), 0.5, 0, 0x6e5a40, F.SOLID, 'wood'); } + { const p = BL(0.5, -1.15); K.box(b, 'wood', p[0], loftY, p[1], 6.8, 1.0, 0.08, 0, 0x6e5a40, F.SOLID | F.BULLET, 'wood'); } // loft rail + for (const q of [[-3, 3], [-1.8, 4.5], [-3.2, 5.6], [2, 6.2]]) { const p = BL(q[0], q[1]); IV.art.prop('hay', b, p[0], by, p[1], R() * 0.4); IV.art.prop('hay', b, p[0], by + 0.55, p[1] + 0.2, R() * 0.4); } + for (const q of [[-3, -6], [-1, -6.5], [2, -6.6]]) { const p = BL(q[0], q[1]); IV.art.prop('hay', b, p[0], loftY, p[1], 0.2); } + { const p = BL(-1.5, 1.5); IV.art.prop('cart', b, p[0], p[1], 0.4); } + M.loft = { x: BL(-3.8, -5)[0], z: BL(-3.8, -5)[1], y: loftY }; + // crossroads guard hut, sandbags and lamp + IV.art.building(b, { x: 13, z: 19, w: 3.2, d: 3.2, h: 2.5, floor: 0.15, mat: 'wood', color: 0x7a6650, sides: { w: [{ t: 'door', at: 0, w: 0.9 }], n: [{ t: 'win', at: 0, w: 0.8, lit: true }] }, roof: { pitch: 0.5, ridge: 'x' }, beams: false }); + IV.art.prop('sandbags', b, 6.5, 2, 6.5, 9, 4); IV.art.prop('sandbags', b, 6.5, 2, 10.5, 1.5, 4); + IV.art.prop('lamp', b, 4.5, 14, 3.4); + IV.art.prop('lamp', b, -84, 25.5, 3.4); IV.art.prop('lamp', b, -45, 22.5, 3.4); // lane: a pool of light ahead from the landing pasture, and at the bridge + IV.art.prop('cart', b, -12, 6, 1.2); + // the farm: yard lamp, gate lamp, bell post, woodpile, cart, barrels + IV.art.prop('lamp', b, 106, -64, 3.4); IV.art.prop('lamp', b, 92, -60, 3.2); + { const gy = W.height(BELL.x, BELL.z); K.add(b, 'wood', K.GEO.box, BELL.x, gy + 1.6, BELL.z, 0.18, 3.2, 0.18, 0, 0, 0, 0x5a4a38); K.add(b, 'wood', K.GEO.box, BELL.x, gy + 3.2, BELL.z + 0.3, 0.12, 0.12, 0.8, 0, 0, 0, 0x5a4a38); W.addBox(BELL.x, BELL.z, 0.12, 0.12, gy, gy + 3.2, 0, F.SOLID | F.BULLET | F.NAV, 'wood'); } + IV.art.prop('woodpile', b, 92, -80, 0); IV.art.prop('cart', b, 116, -60, 2.2); IV.art.prop('barrel', b, 117, -82, W.height(117, -82)); IV.art.prop('barrel', b, 118, -83, W.height(118, -83)); + for (const q of [[112, -84], [96, -70]]) IV.art.prop('crate', b, q[0], W.height(q[0], q[1]), q[1], 0.4, 0.9); + // cover for the hold-out (level-design pass: cover within 4-6 m anywhere in the yard, low and high, staggered) + for (const q of [[100, -75, 0.3], [113.5, -72, 1.1], [104, -62.5, 0.7], [121, -80, 0.2], [93.5, -63, 1.4]]) { IV.art.prop('crate', b, q[0], W.height(q[0], q[1]), q[1], q[2], 1.0); IV.art.prop('crate', b, q[0] + 0.5, W.height(q[0], q[1]) + 1.0, q[1] + 0.2, q[2] + 0.4, 0.7); } + IV.art.prop('sandbags', b, 96, -67, 99.5, -67.5, 4); IV.art.prop('sandbags', b, 124, -63, 127, -61, 4); + IV.art.prop('woodpile', b, 108, -80, 1.4); + // cover down the extraction lane: a fallen trunk to vault, a broken cart, stacked crates + { const gy = W.height(126.4, -26); K.box(b, 'bark', 126.4, gy, -26, 2.2, 0.75, 0.75, 0.4, 0x7a6a58, F.SOLID | F.BULLET | F.NAV | F.LOW | F.VAULT, 'wood', 0.3); } + IV.art.prop('cart', b, 138.5, 18, 0.25); + IV.art.prop('crate', b, 147.5, W.height(147.5, 50), 50, 0.3, 1.0); IV.art.prop('crate', b, 146.6, W.height(146.6, 51.2), 51.2, 1.0, 0.9); + // the flak pit: a ring of sandbags, ammunition crates; MG nest to the west of it + // gaps in the ring: the yard side, and the north (the quiet way in) + const ring = 8; for (let i = 0; i < ring; i++) { if (i === 2 || i === 6) continue; const a0 = i / ring * 6.283, a1 = (i + 1) / ring * 6.283; IV.art.prop('sandbags', b, AA.x + Math.cos(a0) * 4, AA.z + Math.sin(a0) * 4, AA.x + Math.cos(a1) * 4, AA.z + Math.sin(a1) * 4, 4); } + IV.art.prop('crate', b, AA.x + 2.6, W.height(AA.x + 2.6, AA.z - 1), AA.z - 1, 0.2, 0.7); IV.art.prop('crate', b, AA.x + 2.4, W.height(AA.x + 2.4, AA.z + 0.2), AA.z + 0.2, 0.5, 0.7); + IV.art.prop('sandbags', b, MG.x - 1.6, MG.z - 1.5, MG.x - 1.6, MG.z + 1.6, 4); IV.art.prop('sandbags', b, MG.x - 1.6, MG.z + 1.6, MG.x + 1.2, MG.z + 2.6, 4); + // telephone poles along the farm road and the main road, the junction box on one of them + const polesPts = [[94, -60.5], [70, -55.5], [JPOLE.x, JPOLE.z], [6, -45], [5, -10], [6, 30], [6, 70], [5, 110], [5, 150]]; + M.poles = polesPts.map(p => IV.art.pole(b, p[0], p[1], 6.2)); + { const p = M.poles[2]; K.box(b, 'metal', p.x + 0.2, p.y - 4.6, p.z, 0.25, 0.4, 0.2, 0, 0x3a4034); M.jbox = { x: p.x + 0.4, y: p.y - 4.4, z: p.z }; } + // searchlight stand + { const gy = W.height(AA.x + 11, AA.z + 3); K.add(b, 'metal', K.GEO.box, AA.x + 11, gy + 0.6, AA.z + 3, 0.9, 1.2, 0.9, 0, 0, 0, 0x2e3330); M.spotPos = { x: AA.x + 11, y: gy + 1.6, z: AA.z + 3 }; W.addBox(AA.x + 11, AA.z + 3, 0.5, 0.5, gy, gy + 1.2, 0, F.SOLID | F.BULLET | F.NAV, 'metal'); } + // a burnt-out glider in the far field, and a dead cow-free pasture (no animals harmed) + K.box(b, 'wood', -150, W.height(-150, 125) - 0.2, 125, 2.4, 1.6, 9, 0.6, 0x4a4a40, F.SOLID | F.BULLET | F.NAV | F.SIGHT, 'wood', 0.3); + K.box(b, 'wood', -152, W.height(-152, 125) + 0.6, 125, 16, 0.12, 1.8, 0.62, 0x3a3a32, 0); + K.finish(b); + // standing water in the ruts of both sunken lanes + if (IV.art.envOn() && IVEnv.puddleMesh) { try { + const pud = [], RR = IV.rng(77); + for (const Ln of [L1, L2]) for (let i = 0; i < Ln.length - 1; i++) { const a = Ln[i], c = Ln[i + 1], len = Math.hypot(c[0] - a[0], c[1] - a[1]), dx = (c[0] - a[0]) / len, dz = (c[1] - a[1]) / len; + for (let t = RR.range(2, 8); t < len; t += RR.range(5, 14)) { const sd = RR() < 0.5 ? -0.85 : 0.85, x = a[0] + dx * t - dz * sd, z = a[1] + dz * t + dx * sd; pud.push([x, W.height(x, z), z, RR.range(0.6, 1.8), 0.3, Math.atan2(-dz, dx)]); } } + W.scene.add(IVEnv.puddleMesh(pud)); + } catch (e) { console.warn('puddles', e); } } + // crops (wheat) and tall grass in the pasture + IV.art.crops(WHEAT, 0.95 * W.P.crops, 1.15, 0xb7a56e); + if (IV.art.envOn() && IVEnv.scatter) { try { const mz = IVEnv.scatter('maize', (x, z) => { if (!IV.inPoly(x, z, MAIZE) || Math.abs(x - 24) < 0.9) return 0; let e = 1e9; for (let i = 0; i < 4; i++) { const a = MAIZE[i], c = MAIZE[(i + 1) % 4]; e = Math.min(e, IV.segDist(x, z, a[0], a[1], c[0], c[1]).d); } return e < 1.4 ? 0 : 1; }, { heightFn: W.height, density: 1, bounds: [13, -114, 29, -59], seed: 41 }); W.scene.add(mz.group); } catch (e) { console.warn('maize', e); } } + // more maize in the west fields (dressing only: the world's own surface stays grass, so stealth and AI rules there + // are as before): two blocks with a headland strip of stubble round each, rows following the block + if (IV.art.envOn() && IVEnv.scatter) for (const [x0, z0, x1, z1, sd] of MAIZE2) { try { const mz = IVEnv.scatter('maize', (x, z) => { const e = Math.min(x - x0, x1 - x, z - z0, z1 - z); return e < 1.6 ? 0 : 1; }, { heightFn: W.height, density: 1, bounds: [x0, z0, x1, z1], seed: sd }); W.scene.add(mz.group); } catch (e) { console.warn('maize2', e); } } + // grass round the camera + grass = IV.art.grass(W.P.grass, W.P.grassR, (x, z) => { const s = W.surfAt(x, z); if (s === S.tallgrass) return 1.5; if (s !== S.grass) return 0; return 0.55 + IV.noise(x / 6, z / 6) * 0.6; }, (x, z, c) => c.setRGB(0.42 + IV.noise(x / 9, z / 9) * 0.15, 0.46, 0.25)); + // tall grass also counts as concealment: second pass of taller cards on tallgrass only + // searchlight light (driven by the script) + W.addSpot(); + } + function water() { + // a ribbon along the stream at the water level + const pts = [], idx = []; + const seg = []; + for (let i = 0; i < ST.length - 1; i++) { const a = ST[i], c = ST[i + 1], n = Math.ceil(Math.hypot(c[0] - a[0], c[1] - a[1]) / 4); for (let k = 0; k < n; k++) seg.push([a[0] + (c[0] - a[0]) * k / n, a[1] + (c[1] - a[1]) * k / n]); } + seg.push(ST[ST.length - 1]); + for (let i = 0; i < seg.length; i++) { + const a = seg[Math.max(0, i - 1)], c = seg[Math.min(seg.length - 1, i + 1)], dx = c[0] - a[0], dz = c[1] - a[1], l = Math.hypot(dx, dz) || 1, nx = -dz / l, nz = dx / l; + const y = base(seg[i][0], seg[i][1]) - 1.45; + pts.push(seg[i][0] + nx * 3.6, y, seg[i][1] + nz * 3.6, seg[i][0] - nx * 3.6, y, seg[i][1] - nz * 3.6); + if (i) { const k = i * 2; idx.push(k - 2, k - 1, k, k - 1, k + 1, k); } + } + const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.Float32BufferAttribute(pts, 3)); g.setIndex(idx); g.computeVertexNormals(); + const m = new THREE.MeshStandardMaterial({ color: 0x0e161c, roughness: 0.06, metalness: 0.1, transparent: true, opacity: 0.88 }); + m.onBeforeCompile = sh => { sh.uniforms.uT = W.windU; sh.fragmentShader = 'uniform float uT;\n' + sh.fragmentShader.replace('#include ', '#include \n normal = normalize(normal + vec3(sin(vViewPosition.x*3.1+uT*1.7)*0.05, 0.0, cos(vViewPosition.y*2.3+uT*1.3)*0.05));'); }; + const mesh = new THREE.Mesh(g, m); mesh.receiveShadow = true; W.statics.add(mesh); + } + function bridge(b) { + const x = -41, z = 18, y = base(-41, 18) - 1.0, rot = Math.atan2(-(15 - 19), -25 + 55); + K.box(b, 'stone', x, y - 0.5, z, 13, 0.55, 5.6, rot, 0xa09a8c, F.SOLID | F.BULLET, 'stone'); + K.box(b, 'stone', x, y - 2.6, z, 5, 2.1, 5.2, rot, 0x8c867a, F.SOLID | F.BULLET | F.SIGHT | F.NAV, 'stone'); + for (const s of [-1, 1]) { const ox = -Math.sin(rot) * 2.65 * s, oz = -Math.cos(rot) * 2.65 * s; K.box(b, 'stone', x + ox, y + 0.05, z + oz, 13, 0.75, 0.4, rot, 0x9a948a, F.SOLID | F.BULLET | F.NAV | F.VAULT | F.LOW, 'stone'); } + } + function footbridge(b) { + const x = -41, z = -35, y = base(-41, -35) - 0.6; + K.box(b, 'wood', x, y, z, 9, 0.12, 1.6, 0, 0x6e5a42, F.SOLID, 'wood'); + for (const s of [-1, 1]) { K.box(b, 'wood', x, y + 0.9, z + s * 0.75, 9, 0.08, 0.08, 0, 0x5a4a38); for (let k = -4; k <= 4; k += 2) K.box(b, 'wood', x + k, y, z + s * 0.75, 0.1, 1.0, 0.1, 0, 0x5a4a38); } + W.addBox(x, z - 0.8, 4.5, 0.05, y, y + 1, 0, F.SOLID, 'wood'); W.addBox(x, z + 0.8, 4.5, 0.05, y, y + 1, 0, F.SOLID, 'wood'); + } + + // ---------------------------------------------------------------- dynamic props (rebuilt each start/checkpoint) + function aaGun(M) { + const g = new THREE.Group(), gy = W.height(AA.x, AA.z); + const mat = new THREE.MeshStandardMaterial({ color: 0x4c5446, roughness: 0.6, metalness: 0.5 }); + const dark = new THREE.MeshStandardMaterial({ color: 0x23272a, roughness: 0.5, metalness: 0.7 }); + const add = (geo, m, x, y, z, rx, ry, rz) => { const o = new THREE.Mesh(geo, m); o.position.set(x, y, z); o.rotation.set(rx || 0, ry || 0, rz || 0); o.castShadow = true; g.add(o); return o; }; + add(new THREE.BoxGeometry(3.6, 0.2, 0.4), mat, 0, 0.3, 0); add(new THREE.BoxGeometry(0.4, 0.2, 3.6), mat, 0, 0.3, 0); + add(new THREE.CylinderGeometry(0.55, 0.7, 0.5, 14), mat, 0, 0.6, 0); + const mount = new THREE.Group(); mount.position.y = 1.0; g.add(mount); + const m2 = (geo, m, x, y, z, rx) => { const o = new THREE.Mesh(geo, m); o.position.set(x, y, z); o.rotation.x = rx || 0; o.castShadow = true; mount.add(o); return o; }; + m2(new THREE.BoxGeometry(1.4, 0.7, 1.2), mat, 0, 0.2, 0); + m2(new THREE.BoxGeometry(1.8, 1.0, 0.08), mat, 0, 0.5, 0.75, -0.15); // shield + for (const s of [-0.22, 0.22]) { const bar = m2(new THREE.CylinderGeometry(0.05, 0.06, 2.6, 8), dark, s, 1.0, 0.9, -0.95); } + m2(new THREE.BoxGeometry(0.3, 0.35, 0.6), dark, 0.6, 0.4, -0.2); + g.position.set(AA.x, gy, AA.z); g.rotation.y = 2.5; + M.group.add(g); + M.aa = { g, mount }; + W.addBox(AA.x, AA.z, 1.0, 1.0, gy, gy + 1.8, 0, F.SOLID | F.BULLET | F.NAV, 'metal', 'aa'); + // the searchlight head + const sh = new THREE.Group(); sh.position.set(M.spotPos.x, M.spotPos.y, M.spotPos.z); + const can = new THREE.Mesh(new THREE.CylinderGeometry(0.42, 0.42, 0.7, 16).rotateX(Math.PI / 2), mat); can.castShadow = true; sh.add(can); + const lens = new THREE.Mesh(new THREE.CircleGeometry(0.4, 16), new THREE.MeshBasicMaterial({ color: 0xf4f6ff, toneMapped: false })); lens.position.z = 0.36; sh.add(lens); + M.group.add(sh); M.spotHead = sh; M.spotLens = lens; + // the beam: a faint additive cone from the lamp toward where it points + const beamGeo = new THREE.CylinderGeometry(0.35, 6.5, 1, 20, 1, true); beamGeo.translate(0, -0.5, 0); beamGeo.rotateX(-Math.PI / 2); + const beam = new THREE.Mesh(beamGeo, new THREE.MeshBasicMaterial({ color: 0xc8d4ff, transparent: true, opacity: IV.art.envOn() ? 0.018 : 0.05, blending: THREE.AdditiveBlending, depthWrite: false, side: THREE.DoubleSide, toneMapped: false })); + beam.position.copy(sh.position); M.group.add(beam); M.spotBeam = beam; + // with the environment kit's lighting and mist the flat cone reads as a pale solid shape, so it is left out there (the spot light still sweeps) + if (IV.art.envOn()) beam.visible = false; + } + function truckModel() { + const g = new THREE.Group(); + const body = new THREE.MeshStandardMaterial({ color: 0x4a4e44, roughness: 0.8, metalness: 0.2 }), canvas = new THREE.MeshStandardMaterial({ color: 0x5a5a48, roughness: 1 }), tyre = new THREE.MeshStandardMaterial({ color: 0x151515, roughness: 0.9 }); + const add = (geo, m, x, y, z) => { const o = new THREE.Mesh(geo, m); o.position.set(x, y, z); o.castShadow = true; g.add(o); return o; }; + add(new THREE.BoxGeometry(2.2, 1.2, 2.0), body, 0, 1.3, 2.4); add(new THREE.BoxGeometry(2.0, 0.6, 1.4), body, 0, 0.95, 3.8); + add(new THREE.BoxGeometry(2.3, 0.3, 4.6), body, 0, 0.85, -1.0); + const cover = add(new THREE.CylinderGeometry(1.2, 1.2, 4.4, 14, 1, true, 0, Math.PI), canvas, 0, 1.4, -1.0); cover.rotation.set(Math.PI / 2, 0, Math.PI / 2); cover.scale.set(1, 1, 0.85); + for (const z of [3.1, -0.4, -2.4]) for (const s of [-1, 1]) { const w = add(new THREE.CylinderGeometry(0.48, 0.48, 0.3, 14), tyre, s * 1.05, 0.48, z); w.rotation.z = Math.PI / 2; } + const hl = new THREE.Sprite(new THREE.SpriteMaterial({ map: W.tex.glow(), color: 0xffe0a0, blending: THREE.AdditiveBlending, depthWrite: false, toneMapped: false })); hl.position.set(0.7, 1.1, 4.55); hl.scale.set(1.2, 1.2, 1); g.add(hl); + const hl2 = hl.clone(); hl2.position.x = -0.7; g.add(hl2); + return g; + } + function wireLines(M) { + // the telephone wire, sagging from pole to pole; once cut the run nearest the junction box hangs down + const pts = M.poles.map(p => ({ x: p.x + 0.45, y: p.y, z: p.z })); + if (M.wireMesh) M.group.remove(M.wireMesh); + const lines = []; + for (let i = 0; i < pts.length - 1; i++) { if (M.flags.wire && (i === 1 || i === 2)) continue; lines.push(pts[i], pts[i + 1]); } + const p = []; + for (let i = 0; i < lines.length; i += 2) { const a = lines[i], c = lines[i + 1]; for (let k = 0; k < 10; k++) { const t0 = k / 10, t1 = (k + 1) / 10; p.push(a.x + (c.x - a.x) * t0, a.y + (c.y - a.y) * t0 - Math.sin(Math.PI * t0) * 0.7, a.z + (c.z - a.z) * t0, a.x + (c.x - a.x) * t1, a.y + (c.y - a.y) * t1 - Math.sin(Math.PI * t1) * 0.7, a.z + (c.z - a.z) * t1); } } + if (M.flags.wire) { const j = pts[2]; for (const o of [pts[1], pts[3]]) { p.push(j.x, j.y, j.z, j.x + (o.x - j.x) * 0.05, j.y - 4.2, j.z + (o.z - j.z) * 0.05); } } + const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.Float32BufferAttribute(p, 3)); + M.wireMesh = new THREE.LineSegments(g, new THREE.LineBasicMaterial({ color: 0x0d0e10 })); M.group.add(M.wireMesh); + } + function chute(M) { // the parachute caught in the oak, and its lines to you while you hang + const gy = W.height(OAK.x, OAK.z); + const c = new THREE.Mesh(new THREE.SphereGeometry(3.4, 18, 8, 0, Math.PI * 2, 0, Math.PI * 0.42), new THREE.MeshStandardMaterial({ color: 0xc8c4b0, roughness: 0.95, side: THREE.DoubleSide })); + c.scale.set(1, 0.45, 1); c.position.set(OAK.x + 1.0, gy + 7.4, OAK.z - 0.6); c.rotation.set(0.35, 0, 0.25); c.castShadow = false; c.receiveShadow = true; // thin silk: its hard, black moon shadow read as a hole in the ground under the start view + M.group.add(c); M.chute = c; + const lg = new THREE.BufferGeometry(); lg.setAttribute('position', new THREE.Float32BufferAttribute(new Array(8 * 6).fill(0), 3)); + M.chuteLines = new THREE.LineSegments(lg, new THREE.LineBasicMaterial({ color: 0x9a9888, transparent: true, opacity: 0.8 })); M.group.add(M.chuteLines); + } + + // ---------------------------------------------------------------- enemies + const HALF_PI = Math.PI / 2; + function enemies(M, dead) { + const AI = IV.ai, fy = M.houseFy, R = M.rooms; + const sp = (name, o) => { if (dead.includes(name)) return null; o.name = name; const e = AI.spawn(o); M.E[name] = e; return e; }; + M.E = {}; + // the lane patrol (a pair walking the sunken lane between the bridge and the crossroads) + sp('p1a', { x: -34, z: 16.5, route: [[-34, 16.5, 5, -HALF_PI], [-9, 11.5, 6, HALF_PI]], loop: false }); + sp('p1b', { x: -30, z: 15.5, route: [[-30, 15.5, 7, -HALF_PI], [-12, 12, 4, HALF_PI]], loop: false, smg: true }); + // the crossroads post + sp('x1', { x: 8.3, z: 6, yaw: HALF_PI, scan: [0.5, -0.4, 0.9] }); + sp('x2', { x: 4.5, z: 17, yaw: HALF_PI + 0.6, scan: [0, 0.8, -0.7] }); + // the orchard patrol + sp('p2', { x: 46, z: -70, route: [[46, -70, 3], [74, -71, 2, 0], [76, -100, 5, HALF_PI], [46, -99, 2], [44, -84, 4, HALF_PI]] }); + // farm gate sentry + sp('g1', { x: 92, z: -57.5, yaw: HALF_PI - 0.2, scan: [0, 0.7, -0.5] }); + // the sniper in the barn loft (looks west over the orchard) + sp('sn', { kind: 'sniper', x: M.loft.x, z: M.loft.z, y: M.loft.y, yaw: HALF_PI + 0.15, scan: [0, 0.35, -0.3], fixed: true }); + // flak crew: the machine-gunner at his nest and a loader at the gun + sp('mg', { kind: 'gunner', x: MG.x, z: MG.z, yaw: HALF_PI + 0.35, scan: [0, 0.5, -0.4], fixed: true, stance: 'crouch' }); + sp('ld', { x: AA.x + 1.8, z: AA.z + 1.2, yaw: 2.6, scan: [0, 1.2, -1.0] }); + // in the house: the officer at his desk, two soldiers resting + sp('of', { kind: 'officer', x: R.office[0] - 0.4, z: R.office[1] - 0.6, y: fy, yaw: Math.PI, scan: [0, 0.6] }); + sp('h1', { x: R.kitchen[0], z: R.kitchen[1] - 0.5, y: fy, yaw: 0.3, scan: [0], anim: 'sitIdle' }); + sp('h2', { x: R.parlour[0], z: R.parlour[1], y: fy, yaw: -2.6, scan: [0.4, -0.4] }); + AI.alarm = { x: BELL.x - 0.9, z: BELL.z + 0.4, bx: BELL.x, bz: BELL.z }; + } + + // ---------------------------------------------------------------- script + function setup(M, cp, data) { + const AI = IV.ai, AL = IV.ally, WP = IV.weapons; + M.flags.dead = M.flags.dead || []; + aaGun(M); wireLines(M); chute(M); + // player + loadout + if (cp === 0) P.spawn(OAK.x + 0.4, OAK.z + 0.3, -0.6, 'stand'); + else if (cp === 1) P.spawn(JPOLE.x - 2, JPOLE.z + 2.5, -1.9, 'crouch'); + else if (cp === 2) P.spawn(HOUSE.x + 1, HOUSE.z + 7, Math.PI * 0.4, 'crouch'); + else P.spawn(118, -54, Math.PI * 0.95, 'stand'); + WP.reset({ start: 'smg', rifleRes: 25, smgRes: 120, grenades: 2 }); + // squadmate + if (cp === 0) { AL.spawn(LINK.x, LINK.z, 2.4); AL.goTo(LINK.x, LINK.z, { stance: 'crouch', run: false }); AL.met = false; } + else if (cp === 1) { AL.spawn(JPOLE.x - 3.5, JPOLE.z + 4, -1.9); } + else if (cp === 2) { AL.spawn(HOUSE.x - 2, HOUSE.z + 7.5, Math.PI * 0.4); } + else { AL.spawn(116.5, -55.5, Math.PI * 0.95); } + enemies(M, M.flags.dead); + // the searchlight: sweeping until the gun goes + M.spot = { on: !M.flags.blown, a: 0 }; + if (M.flags.blown) { M.aa.g.visible = false; } + // ---- beats + M.phase = cp === 0 ? 'harness' : cp === 1 ? 'approach' : cp === 2 ? 'hold' : 'run'; + if (cp === 0) beatHarness(M); + else if (cp === 1) { beatApproach(M, true); } + else if (cp === 2) beatHold(M, true); + else { M.flags.blown = 1; M.aa.g.rotation.z = 0.5; M.aa.mount.rotation.x = 0.7; M.spot.on = false; IV.fx.fire(AA.x, W.height(AA.x, AA.z) + 0.5, AA.z, 400, 22); IV.audio.alarm(true); M.say(IV.t('Down the lane! Go!')); beatRun(M); } + // things that can happen any time + M.when(() => IV.ai.alarmRung && !M.flags.alarmTold, () => { M.flags.alarmTold = true; if (M.phase === 'approach' || M.phase === 'overwatch') M.say(IV.t('That\'s the bell. Every soldier on the farm is awake now.')); }); + } + // track kills so a checkpoint restore leaves them dead + IV.on('enemyDied', e => { const M = IV.mission; if (M.def && M.def.id === 'nightdrop' && e.name && M.flags.dead && !M.flags.dead.includes(e.name)) M.flags.dead.push(e.name); }); + IV.on('spotted', () => { const M = IV.mission; if (M.def && M.def.id === 'nightdrop' && (M.phase === 'approach' || M.phase === 'overwatch' || M.phase === 'link')) M.flags.spottedEarly = (M.flags.spottedEarly || 0) + 1; }); + + function beatHarness(M) { + const t = IV.t; + M.noWeapons = true; + const gy = W.height(OAK.x, OAK.z); + P.pos.set(OAK.x + 0.4, gy + 2.7, OAK.z + 0.3); P.prev.copy(P.pos); + let sway = 0; + P.cine = dt => { sway += dt; P.pos.x = OAK.x + 0.4 + Math.sin(sway * 0.9) * 0.08; P.pos.z = OAK.z + 0.3 + Math.cos(sway * 0.7) * 0.06; P.actor.play('idle', { fade: 0.2 }); }; + P.cineClip = false; + M.obj('cut', 'Cut yourself free of the harness', { quiet: true }); + M.after(1.2, () => M.hq(t('Pathfinder Two, Rook. You came down short. The stick is scattered east of the river.'))); + M.after(1.4, () => M.hq(t('The flak gun at the farm is still yours. Find your corporal and get it done.'))); + IV.audio.aircraft(true, 24, 0.5); + M.interact({ id: 'harness', x: P.pos.x, z: P.pos.z, y: gy + 2.7, r: 3, cine: true, text: 'Cut the harness', hold: 1.1, done() { + M.done('cut'); IV.audio.play('wire'); + let vy = 0; const top = P.pos.y; + P.cine = dt => { vy -= 18 * dt; P.pos.y += vy * dt; const g = W.groundAt(P.pos.x, P.pos.z, top); if (P.pos.y <= g) { P.pos.y = g; P.cine = null; P.setStance('crouch'); P.stanceT = 0; IV.audio.play('land', { surf: 'grass' }); IV.camera.shake(0.3); M.noWeapons = false; beatLink(M); } }; + } }); + } + function beatLink(M) { + const t = IV.t; + M.phase = 'link'; + M.obj('link', 'Find Cpl. Dunning', { marker: { x: LINK.x, z: LINK.z, y: W.height(LINK.x, LINK.z) + 1.6 } }); + M.after(2.5, () => { M.say(t('(low whistle from the hedge to the north-east)'), 2.5); IV.hud.hint = { text: t('Crouch to move quietly'), key: IV.touch ? '' : IV.input.label('crouch') }; }); + M.after(9, () => { if (IV.hud.hint) IV.hud.hint = null; }); + M.when(() => Math.hypot(P.pos.x - IV.ally.ent.pos.x, P.pos.z - IV.ally.ent.pos.z) < 5, () => { + M.done('link'); IV.hud.hint = null; IV.ally.met = true; + M.say(t('Easy, it\'s me. Dunning. Thought you were hung up for the night.')); + M.say(t('Rest of the stick landed past the river. So it\'s you and me for the gun.')); + M.say(t('Farm\'s north-east. There\'s a lane patrol and a post at the crossroads. We go quiet.')); + IV.ally.release(); + beatApproach(M, false); + }); + } + function beatApproach(M, fromCp) { + const t = IV.t; + M.phase = 'approach'; + if (!M.flags.wire) M.obj('wire', 'Cut the field-telephone line', { marker: { x: M.jbox.x, z: M.jbox.z, y: M.jbox.y } }); + M.obj('farm', 'Get to the orchard west of the farm', { marker: { x: 40, z: -72, y: W.height(40, -72) + 1.6 } }); + // stealth lessons from Dunning, each once and only when it fits + const once = (k, cond, line) => M.when(() => !M.flags[k] && cond(), () => { M.flags[k] = 1; M.say(t(line)); }); + once('tipLane', () => M.E.p1a && M.E.p1a.alive && Math.hypot(P.pos.x - M.E.p1a.pos.x, P.pos.z - M.E.p1a.pos.z) < 45 && M.E.p1a.state === 'unaware', 'Patrol in the lane. Keep low and stay in the dark under the bank.'); + once('tipSus', () => IV.ai.list.some(e => e.alive && e.state === 'suspicious'), 'Freeze. He heard something. Let him settle.'); + once('tipCrop', () => P.crops && P.stance !== 'stand', 'Good. Down in the wheat they\'ll walk right past us.'); + once('tipRock', () => IV.ai.list.some(e => e.alive && e.state === 'unaware' && Math.hypot(P.pos.x - e.pos.x, P.pos.z - e.pos.z) < 14), 'Throw a stone past him. He\'ll go and look, and we slip by.'); + once('tipStream', () => P.inWater, 'Stream bed\'s low, but the water is noisy. Slow and steady.'); + once('tipCross', () => Math.hypot(P.pos.x, P.pos.z - 10) < 40 && M.E.x1 && M.E.x1.alive, 'Crossroads post, two of them. Wheat field\'s east of the road, it takes us right past.'); + // the bombing run: twenty seconds where nobody hears much + M.when(() => !M.flags.bombs && (P.pos.x > -58 || M.time > 200), () => { + M.flags.bombs = 1; + M.hq(t('Rook to all units: bombers on the rail junction east of you in thirty seconds.')); + M.after(4, () => M.say(t('When they hit, move. Nobody will hear us over that.'))); + M.after(10, () => { IV.audio.aircraft(true, 34, 0.65); }); + M.after(16, () => { IV.ai.maskUntil = IV.time + 20; M.flags.bombing = IV.time + 20; IV.hud.toast(t('Bombing run: your noise is masked')); }); + }); + // the wire + if (!M.flags.wire) M.interact({ id: 'wire', x: M.jbox.x, z: M.jbox.z, y: M.jbox.y, r: 2.4, text: 'Cut the telephone line', hold: 2.0, done() { + M.flags.wire = 1; wireLines(M); IV.audio.play('wire'); M.done('wire'); + M.say(t('Line\'s dead. Now all they\'ve got is the bell.')); + M.after(2.5, () => M.checkpoint(1)); + } }); + // orchard edge: overwatch on the sniper, then the charge + // the farm beat starts at the orchard, or anywhere near the gun if you came another way (never a soft-lock) + M.when(() => (P.pos.x > 33 && P.pos.z < -58) || Math.hypot(P.pos.x - AA.x, P.pos.z - AA.z) < 35, () => beatOverwatch(M)); + // a nudge if nothing has happened for a while + M.when(() => M.phase === 'approach' && M.time - (M.flags.lastBeat || 0) > 200, () => { M.flags.lastBeat = M.time; M.say(t('Farm\'s north-east, past the orchard. Keep moving.')); }, { once: false }); + if (fromCp) M.say(t('Line\'s cut. Orchard next, then the farm.')); + } + function beatOverwatch(M) { + const t = IV.t; + M.done('farm'); M.phase = 'overwatch'; + const sn = M.E.sn; + if (sn && sn.alive) { + M.say(t('Hold. Barn loft, the hay door. There\'s a sniper up there.')); + M.say(t('Rifle\'s yours. Mind the drop and the wind. Or we go round below his window.')); + M.obj('sniper', 'Take out the sniper in the barn loft', { optional: true, marker: { x: sn.pos.x, z: sn.pos.z, y: sn.pos.y + 1.7 } }); + M.when(() => !sn.alive, () => { M.done('sniper'); M.say(t('Good shot. Loft\'s clear.')); }); + IV.hud.hint = { text: t('Hold aim with the rifle to use the scope'), key: IV.touch ? '' : IV.input.label('rifle') }; + M.after(10, () => { IV.hud.hint = null; }); + } + M.obj('charge', 'Plant the charge on the flak gun', { marker: { x: AA.x, z: AA.z, y: W.height(AA.x, AA.z) + 2.4 } }); + M.interact({ id: 'charge', x: AA.x, z: AA.z, r: 2.6, text: 'Plant the charge', hold: 3.0, done() { IV.audio.play('charge'); beatLoud(M); } }); + } + // SCRIPTED: the farm goes loud as soon as the charge is set + function beatLoud(M) { + const t = IV.t, AI = IV.ai; + M.phase = 'loud'; M.done('charge'); + M.flags.charge = 1; M.fuseEnd = 0; + M.obj('fuse', 'Charge set on the flak gun', { quiet: true }); + M.say(t('Charge is set. Pencil fuse, a few minutes. Now let\'s get clear of—'), 2.6); + // a soldier steps out of the back door with a lamp and sees us + M.after(1.6, () => { + const d = M.houseDoorN; + const e = AI.spawn({ name: 'walker', x: d.x, z: d.z - 1.2, yaw: 0 }); + M.E.walker = e; + e.alerted = true; e.aw = 1; e.lkp = { x: P.pos.x, z: P.pos.z, t: IV.time }; e.setState('combat'); + IV.ai.bark(e, 'spotted'); + }); + M.after(3.2, () => { + AI.ringAlarm(null); + M.say(t('That\'s torn it! They\'re in the house, shooting from the windows!')); + for (const e of AI.list) if (e.alive) { e.alerted = true; e.aw = 1; e.lkp = { x: P.pos.x, z: P.pos.z, t: IV.time }; e.setState('combat'); } + // the house soldiers hold the windows + for (const k of ['h1', 'h2', 'of']) { const e = M.E[k]; if (e && e.alive) { e.fixed = true; e.noRoam = true; } } + beatBreach(M); + }); + } + function beatBreach(M) { + const t = IV.t, AL = IV.ally; + M.phase = 'breach'; + M.obj('house', 'Clear the farmhouse', { marker: { x: HOUSE.x, z: HOUSE.z - 5.4, y: M.houseFy + 2.5 } }); + const map = M.mapPos; + M.obj('map', 'Take the map from the office desk', { optional: true, marker: { x: map.x, z: map.z, y: map.y + 0.6 } }); + M.interact({ id: 'map', x: map.x, z: map.z, y: map.y, r: 1.6, text: 'Take the map', hold: 1.2, done() { M.done('map'); IV.audio.play('cloth'); M.say(t('Their gun plan for the whole sector. Rook will want that.')); } }); + // Dunning stacks on the back door + const d = M.houseDoorN; + M.after(3.5, () => { AL.goTo(d.x - 1.0, d.z - 1.1, { stance: 'crouch', run: true, yaw: Math.PI, aim: true }); M.say(t('On the back door. Get on the other side, I\'ll go in first.')); }); + M.interact({ id: 'breach', x: d.x + 0.9, z: d.z - 1.0, r: 2.2, text: 'Breach the door', hold: 0.5, on: () => !M.flags.breached, done() { + M.flags.breached = 1; IV.audio.play('door'); IV.fx.dust(d.x, M.houseFy + 1, d.z, 14, 0.5); IV.camera.shake(0.2); + M.say(t('Going in!'), 1.4); + const R = M.rooms; + AL.goTo(R.hall[0], R.hall[1] - 1.5, { run: true, aim: true, done() { AL.goTo(R.hall[0], R.hall[1] + 1, { run: true, aim: true, done() { AL.release(); } }); } }); + } }); + M.after(150, () => { if (M.phase === 'breach') M.say(t('The house! Clear it, or we\'ll never hold this yard.')); }); + // cleared when everyone inside is down + M.when(() => ['h1', 'h2', 'of'].every(k => !M.E[k] || !M.E[k].alive) && !IV.ai.list.some(e => e.alive && Math.abs(e.pos.x - HOUSE.x) < 8 && Math.abs(e.pos.z - HOUSE.z) < 4.5), () => { + M.done('house'); AL.release(); + M.say(t('House clear!')); + M.after(1.5, () => { M.fuseEnd = M.time + 60; beatHold(M, false); M.checkpoint(2); }); + }); + } + function beatHold(M, fromCp) { + const t = IV.t, AI = IV.ai; + M.phase = 'hold'; + if (fromCp) { M.fuseEnd = M.time + 60; M.flags.charge = 1; AI.alarmRung = true; IV.audio.alarm(true); M.say(t('Charge is still burning. Hold the yard!')); } + M.obj('hold', 'Hold the yard until the charge blows: {s}'); + M.fuseObj = true; M.drop('fuse'); + M.say(t('Truck on the east road! Get to the wall and hold them off!')); + IV.fx.flare(130, W.height(130, -60) + 70, -60); + // the truck drives in along the east road and four soldiers jump down + const tr = truckModel(); M.group.add(tr); M.truck = { g: tr, s: 0, path: [[188, -50], [150, -54], [138, -57]], stopped: false }; + IV.audio.play('truck', { x: 188, z: -50 }); + } + function truckStep(M, dt) { + const T2 = M.truck; if (!T2 || T2.stopped) return; + const pts = T2.path; T2.s += dt * 9; + let acc = 0; for (let i = 0; i < pts.length - 1; i++) { + const a = pts[i], b = pts[i + 1], l = Math.hypot(b[0] - a[0], b[1] - a[1]); + if (T2.s <= acc + l || i === pts.length - 2) { + const k = Math.min(1, (T2.s - acc) / l), x = a[0] + (b[0] - a[0]) * k, z = a[1] + (b[1] - a[1]) * k; + T2.g.position.set(x, W.height(x, z), z); T2.g.rotation.y = Math.atan2(b[0] - a[0], b[1] - a[1]); + if (k >= 1 && i === pts.length - 2) { + T2.stopped = true; IV.audio.play('truck', { x, z }); + W.addBox(x, z, 1.3, 3.4, W.height(x, z), W.height(x, z) + 2.4, T2.g.rotation.y, F.SOLID | F.BULLET | F.SIGHT, 'metal', 'truck'); + // dismount + const offs = [[-2, -2], [2, -2], [-2, -4], [2, -4]]; + offs.forEach((o, n) => { const e = IV.ai.spawn({ name: 'tr' + n, x: x + o[0], z: z + o[1], yaw: Math.PI / 2, smg: n % 2 === 0 }); e.alerted = true; e.aw = 1; e.lkp = { x: P.pos.x, z: P.pos.z, t: IV.time }; e.setState('combat'); if (n === 1) e.role = 'flank'; }); + IV.mission.say(IV.t('They\'re off the truck! Four of them!')); + } + break; + } + acc += l; + } + } + function blowGun(M) { + const t = IV.t, AI = IV.ai; + M.flags.blown = 1; M.phase = 'run'; + const gy = W.height(AA.x, AA.z); + IV.fx.explosion(AA.x, gy + 1, AA.z, true); + IV.audio.play('explosion', { x: AA.x, z: AA.z, big: true }); + IV.camera.shake(IV.clamp(1.2 - Math.hypot(P.pos.x - AA.x, P.pos.z - AA.z) / 80, 0.2, 1)); + $flash(0.6); + IV.fx.fire(AA.x, gy + 0.5, AA.z, 400, 22); + M.aa.g.rotation.z = 0.5; M.aa.mount.rotation.x = 0.7; M.aa.g.position.y -= 0.3; + M.aa.g.traverse(o => { if (o.material) o.material = new THREE.MeshStandardMaterial({ color: 0x1a1a1a, roughness: 1 }); }); + M.spot.on = false; if (W.spot) W.spot.intensity = 0; + IV.weapons.explodeAt(AA.x, gy + 1, AA.z, null); + for (const e of AI.list) if (e.alive && Math.hypot(e.pos.x - AA.x, e.pos.z - AA.z) < 12) e.die({ x: (e.pos.x - AA.x) / 10, z: (e.pos.z - AA.z) / 10 }, true); + for (const e of AI.list) if (e.alive) { e.suppr = 1; e.stagger = 1.2; e.actor.setUpper('hit'); } + if (P.alive && Math.hypot(P.pos.x - AA.x, P.pos.z - AA.z) < 10) P.hurt(80, { x: AA.x, z: AA.z }); + M.done('hold'); M.fuseObj = false; + // if the gun went while you were still in the house, those objectives are over + M.drop('fuse'); if (!M.isDone('house')) M.drop('house'); if (!M.isDone('map')) M.drop('map'); if (!M.isDone('sniper')) M.drop('sniper'); + M.after(1.2, () => M.say(t('Gun\'s gone! Out the gap by the barn and down the lane! Go, go!'))); + M.after(2, () => { beatRun(M); M.checkpoint(3); }); + } + function $flash(k) { const f = IV.$('flash'); f.style.transition = 'none'; f.style.opacity = String(k * 0.5); requestAnimationFrame(() => { f.style.transition = 'opacity .8s'; f.style.opacity = '0'; }); } + function beatRun(M) { + const t = IV.t, AI = IV.ai; + M.obj('run', 'Reach the extraction lane', { marker: { x: EXTRACT.x, z: EXTRACT.z, y: W.height(EXTRACT.x, EXTRACT.z) + 1.8 } }); + // an ambush in the lane: soldiers at the hedge gaps ahead + [[140, 16], [148, 45], [152, 30]].forEach((p, n) => { const e = AI.spawn({ name: 'am' + n, x: p[0] + 5, z: p[1], yaw: Math.PI * 0.8 }); e.alerted = true; e.aw = 0.9; e.lkp = { x: 128, z: -30, t: IV.time }; e.interest = { x: 128, z: -30 }; e.setState('searching'); }); + // flares and mortar rounds over the lane while you run + M.flags.mortar = 1; M.nextFlare = M.time + 3; M.nextMortar = M.time + 4; + M.when(() => Math.hypot(P.pos.x - 140, P.pos.z - 15) < 30, () => M.say(t('Contact in the lane! Down the side, use the bank!'))); + M.when(() => Math.hypot(P.pos.x - EXTRACT.x, P.pos.z - EXTRACT.z) < 9, () => { + M.flags.mortar = 0; + M.hq(t('Pathfinder Two, Rook. We see you. Come on in.')); + M.done('run'); M.after(2.2, () => M.complete()); + }); + } + + // ---------------------------------------------------------------- per step / per frame + function step(M, dt) { + const AI = IV.ai; + // sky tracers and flak while the planes are about (the intro, and the bombing run) + const sky = M.phase === 'harness' || M.phase === 'link' || (M.flags.bombing && IV.time < M.flags.bombing); + if (sky && Math.random() < dt * (M.phase === 'harness' ? 7 : 3)) skyFire(M); + if (M.flags.bombing && IV.time < M.flags.bombing && Math.random() < dt * 0.9) { IV.audio.distantBoom(0.6); const a = Math.random(); W.flashAt(260 + a * 80, 30, -100 + a * 200, 60, 0.4, 0.4, 0xffa060); } + // searchlight sweep (it lights you up if it finds you) + if (W.spot && M.spot) { + const s = M.spot; W.spotOn = s.on; + if (s.on) { + s.a += dt * 0.22; + const yaw = 2.2 + Math.sin(s.a) * 1.0, dist = 45 + Math.sin(s.a * 0.7) * 15; + const sp = M.spotPos, tx = sp.x - Math.sin(yaw) * dist, tz = sp.z - Math.cos(yaw) * dist; + W.spot.position.set(sp.x, sp.y + 0.2, sp.z); W.spot.target.position.set(tx, W.height(tx, tz), tz); W.spot.intensity = 2.6; + M.spotHead.lookAt(tx, W.height(tx, tz), tz); + } else W.spot.intensity = 0; + } + // fuse countdown in the objective text + if (M.fuseObj && M.fuseEnd) { + const left = Math.max(0, M.fuseEnd - M.time), s = IV.fmtTime(left); + for (const o of M.objs) if (o.id === 'hold' && o.state === 'active') { const txt = IV.t('Hold the yard until the charge blows: {s}', { s }); if (o.shown !== txt) { o.shown = txt; o.text = txt; IV.emit('objectives'); } } + if (left <= 0 && !M.flags.blown) blowGun(M); + } + truckStep(M, dt); + // the running fight: flares and mortar rounds that land near, never on, the lane runner + if (M.flags.mortar) { + if (M.time > M.nextFlare) { M.nextFlare = M.time + 11 + Math.random() * 4; IV.fx.flare(P.pos.x + 20 + Math.random() * 30, W.height(P.pos.x, P.pos.z) + 75, P.pos.z + 20 + Math.random() * 30); IV.audio.play('pin'); } + if (M.time > M.nextMortar) { + M.nextMortar = M.time + 4.5 + Math.random() * 3; + const a = Math.random() * 6.283, r = 15 + Math.random() * 14, x = P.pos.x + Math.cos(a) * r, z = P.pos.z + Math.sin(a) * r; + IV.audio.play('whiz'); M.after(0.7, () => { IV.fx.explosion(x, W.height(x, z), z, false); IV.audio.play('explosion', { x, z }); IV.camera.shake(0.25); IV.fx.dust(x, W.height(x, z), z, 20, 1); }); + } + } + } + const skyPts = []; + function skyFire(M) { + const a = Math.random() * 6.283, r = 160 + Math.random() * 120, x = P.pos.x + Math.cos(a) * r, z = P.pos.z + Math.sin(a) * r, y = W.height(x, z) + 1; + if (Math.random() < 0.7) { // a stream of tracer going up + const vx = (Math.random() - 0.5) * 120, vz = (Math.random() - 0.5) * 120; + for (let i = 0; i < 4; i++) setTimeout(() => IV.weapons.spawnBullet({ x, y, z, vx, vy: 520, vz, drag: 0, dmg: 0, owner: null, team: 'sky', tracer: true, enemy: true, life: 1.6 }), i * 90); + } else { // a flak burst high up + const bx = x * 0.6 + P.pos.x * 0.4, bz = z * 0.6 + P.pos.z * 0.4, by = 140 + Math.random() * 80; + W.flashAt(bx, by, bz, 120, 0.25, 0.15, 0xffc080); + for (let i = 0; i < 6; i++) IV.fx.smoke(bx, by, bz, 1, 3, true); + setTimeout(() => IV.audio.distantBoom(0.25), 600 + Math.random() * 400); + } + } + const tmpV = new THREE.Vector3(); + function frame(M, dt) { + if (grass) grass.update(W.camera.position.x, W.camera.position.z); + // parachute lines while hanging + if (M.chuteLines) { + const a = M.chuteLines.geometry.attributes.position.array, hanging = M.phase === 'harness'; + M.chuteLines.visible = hanging; + if (hanging) { const c = M.chute.position, p = P.render; for (let i = 0; i < 8; i++) { const ang = i / 8 * 6.283; a[i * 6] = c.x + Math.cos(ang) * 2.4; a[i * 6 + 1] = c.y - 0.6; a[i * 6 + 2] = c.z + Math.sin(ang) * 2.4; a[i * 6 + 3] = p.x + (i % 2 ? 0.18 : -0.18); a[i * 6 + 4] = p.y + 1.5; a[i * 6 + 5] = p.z; } M.chuteLines.geometry.attributes.position.needsUpdate = true; } + } + if (M.spotLens) M.spotLens.material.color.setHex(M.spot && M.spot.on ? 0xf4f6ff : 0x222222); + if (M.spotBeam && W.spot) { const on = M.spot && M.spot.on; M.spotBeam.visible = on && !IV.art.envOn(); if (on) { const tg = W.spot.target.position, sp = M.spotBeam.position, d = sp.distanceTo(tg); M.spotBeam.lookAt(tg); M.spotBeam.scale.set(1, 1, d); } } + } + + // ---------------------------------------------------------------- title backdrop: Dunning and you by a hedge at night + function backdrop(M) { + IV.ai.reset(); IV.ally.remove(); IV.fx.clear(); + if (M.group) W.scene.remove(M.group); M.group = new THREE.Group(); W.scene.add(M.group); + aaGun(M); M.flags = {}; wireLines(M); + const x = 40, z = -77; + P.spawn(x, z, -Math.PI / 2 + 0.2, 'crouch'); P.actor.play('crouchIdle', { fade: 0 }); + IV.weapons.reset({ start: 'rifle' }); + IV.ally.spawn(x - 1.4, z + 1.9, -Math.PI / 2 + 0.35); IV.ally.ent.stance = 'crouch'; IV.ally.ent.actor.play('crouchIdle', { fade: 0 }); + // guards by the farm, lamplit + IV.ai.spawn({ x: 92, z: -60.5, yaw: Math.PI / 2 - 0.2 }); IV.ai.spawn({ x: 104, z: -113, yaw: 2.4 }); IV.ai.spawn({ x: 86, z: -84, yaw: 1.2, smg: true }); + M.spot = { on: true, a: 0 }; M.phase = 'title'; + let t = 0; + IV.camera.override = (cam, dt) => { + t += dt; + const cx = x - 3.6 + Math.sin(t * 0.05) * 0.4, cz = z + 2.4 + Math.cos(t * 0.04) * 0.3; + cam.position.set(cx, W.height(cx, cz) + 1.35, cz); + tmpV.set(x + 30, W.height(x + 30, z - 6) + 3.2, z - 6); cam.lookAt(tmpV); + if (cam.fov !== 52) { cam.fov = 52; cam.updateProjectionMatrix(); } + }; + M.def.backdropFrame = (M2, dt) => { step(M2, dt * 0); stepSpot(M2, dt); frame(M2, dt); IV.player.actor.update(dt); }; + } + function stepSpot(M, dt) { + if (!W.spot || !M.spot) return; + const s = M.spot; s.a += dt * 0.22; W.spotOn = true; + const yaw = 2.2 + Math.sin(s.a) * 1.0, dist = 45 + Math.sin(s.a * 0.7) * 15, sp = M.spotPos, tx = sp.x - Math.sin(yaw) * dist, tz = sp.z - Math.cos(yaw) * dist; + W.spot.position.set(sp.x, sp.y + 0.2, sp.z); W.spot.target.position.set(tx, W.height(tx, tz), tz); W.spot.intensity = 2.6; M.spotHead.lookAt(tx, W.height(tx, tz), tz); + } + + // ---------------------------------------------------------------- the briefing sketch + function sketch(g, w, h, sk) { + const s = w / 380, X = x => (x + 190) * s, Z = z => (z + 190) * s; + const P2 = pts => pts.map(p => [X(p[0]), Z(p[1])]); + sk.hatch(g, P2(WHEAT), { c: 'rgba(150,120,40,.35)', s: 7, slope: 200, edge: 'rgba(120,100,40,.6)' }); + for (let x = 44; x <= 76; x += 8) for (let z = -102; z <= -68; z += 8) sk.circle(g, X(x), Z(z), 4, 'rgba(50,70,30,.7)'); + sk.line(g, P2(ST), { c: 'rgba(40,70,120,.8)', w: 3.4 }); + for (const pts of [L1, L2]) { sk.line(g, P2(offset(pts, -3.5)), { w: 1.4, c: 'rgba(40,60,20,.8)' }); sk.line(g, P2(offset(pts, 3.5)), { w: 1.4, c: 'rgba(40,60,20,.8)' }); } + for (const pts of [R1, R2, R3]) { sk.line(g, P2(offset(pts, -1.6)), { w: 1.2 }); sk.line(g, P2(offset(pts, 1.6)), { w: 1.2 }); } + const rect = (cx, cz, ww, dd) => sk.hatch(g, [[X(cx - ww / 2), Z(cz - dd / 2)], [X(cx + ww / 2), Z(cz - dd / 2)], [X(cx + ww / 2), Z(cz + dd / 2)], [X(cx - ww / 2), Z(cz + dd / 2)]], { s: 5 }); + rect(HOUSE.x, HOUSE.z, HOUSE.w, HOUSE.d); rect(BARN.x, BARN.z, BARN.w, BARN.d); rect(13, 19, 4, 4); + sk.x(g, X(AA.x), Z(AA.z), 9); sk.text(g, 'FLAK', X(AA.x) + 14, Z(AA.z) + 4, { size: 20, c: '#8a2a1c' }); + sk.circle(g, X(MG.x), Z(MG.z), 6); sk.text(g, 'MG', X(MG.x) - 34, Z(MG.z) + 4, { size: 16, c: '#8a2a1c' }); + sk.circle(g, X(0), Z(10), 8); sk.text(g, 'post', X(8), Z(24), { size: 16, c: '#8a2a1c' }); + sk.text(g, 'sniper?', X(BARN.x) + 10, Z(BARN.z) - 14, { size: 15, c: '#8a2a1c' }); + sk.text(g, 'Mauvenant Farm', X(HOUSE.x) - 50, Z(HOUSE.z) + 34, { size: 19 }); + sk.text(g, 'orchard', X(46), Z(-112), { size: 16 }); + sk.text(g, 'wheat', X(40), Z(5), { size: 16 }); + sk.text(g, 'the Lirette', X(-80), Z(-120), { size: 16, rot: -1.4 }); + sk.text(g, 'telephone line', X(14), Z(-58), { size: 13 }); + sk.line(g, M2pts(), { c: 'rgba(30,30,30,.6)', w: 1, dash: [3, 4] }); + function M2pts() { return [[94, -60.5], [70, -55.5], [JPOLE.x, JPOLE.z], [6, -45], [5, -10], [6, 30]].map(p => [X(p[0]), Z(p[1])]); } + sk.x(g, X(OAK.x), Z(OAK.z), 6, '#2f4a7a'); sk.text(g, 'you are here (roughly)', X(OAK.x) - 60, Z(OAK.z) + 24, { size: 15, c: '#2f4a7a' }); + sk.arrow(g, P2([[-110, 70], [-60, 30], [-20, 12], [30, -20], [40, -60], [95, -105]])); + sk.arrow(g, P2([[95, -70], [128, -35], [140, 20], [160, 82]]), '#2f6a3a'); + sk.text(g, 'out', X(165), Z(100), { size: 18, c: '#2f6a3a' }); + sk.text(g, 'N ↑', w - 70, 50, { size: 26 }); + sk.text(g, '100 m', 30, h - 24, { size: 14 }); sk.line(g, [[30, h - 40], [30 + 100 * s, h - 40]], { w: 2 }); + } + + IV.missions.register({ + id: 'nightdrop', num: 1, title: 'Night Drop', line: 'Behind the lines at night. Find your corporal, then the flak gun at Mauvenant Farm.', + needAlly: true, optionalTotal: 2, + briefing: [ + 'June 1944. Your stick of pathfinders jumps ahead of the main drop. A flak gun at Mauvenant Farm covers the drop zone, and it has to be gone before the transports come over.', + 'You will land wide. Find Cpl. Dunning, keep off the lanes the patrols walk, and cut the farm\'s field-telephone line on the way.', + 'Set the charge on the gun. When it goes up the whole farm will be on you: get clear and down the sunken lane to the east, where Rook\'s men are waiting.' + ], + preview: [{ text: 'Find Cpl. Dunning' }, { text: 'Cut the field-telephone line' }, { text: 'Destroy the flak gun' }, { text: 'Reach the extraction lane' }, { text: 'Take the map from the farm office', opt: true }, { text: 'Take out the sniper in the barn loft', opt: true }], + world: { size: 380, day: false, height, surface, groundColor, waterLevel, surfaceKind, skirt: { hills: 34, fogK: 0.8, woods: 0.55 }, grass: { nearMul: 1.3, carpetMul: 1.25, midMul: 1.6 }, fog: 0.0125, fogColor: 0x0a0f15 }, + build, setup, step, frame, backdrop, sketch, + medals: [ + { text: 'Finish in under 15:00', ok: s => s.time < 900 }, + { text: 'Spotted no more than once before the farm', ok: (s, M) => (M.flags.spottedEarly || 0) <= 1 }, + { text: 'Take the map from the farm office', ok: (s, M) => M.isDone('map') } + ] + }); +})(); diff --git a/e63334287a3deaa3/ironveil/js/nav.js b/e63334287a3deaa3/ironveil/js/nav.js new file mode 100644 index 00000000..180dd185 --- /dev/null +++ b/e63334287a3deaa3/ironveil/js/nav.js @@ -0,0 +1,142 @@ +/* Ironveil navigation: a 0.5 m walk grid rasterised from the colliders (hedgerow banks, walls, buildings; gaps, gates + and doorways stay open), steep banks blocked, water costly. A* with a binary heap, then string-pulled so soldiers + walk straight lines. Also builds cover points along anything that stops bullets. */ +(function () { + 'use strict'; + const W = IV.world, F = IV.CF; + const N = IV.nav = { cell: 0.5, n: 0, grid: null, cover: [] }; + const BLOCK = 1, WATER = 2; + + N.build = function () { + const cs = N.cell, n = N.n = Math.floor(W.size / cs), half = W.half, g = N.grid = new Uint8Array(n * n); + N.g = new Float32Array(n * n); N.came = new Int32Array(n * n); N.mark = new Uint32Array(n * n); N.closed = new Uint32Array(n * n); N.stampV = 0; + // terrain: too steep, or deep water + for (let j = 0; j < n; j++) for (let i = 0; i < n; i++) { + const x = i * cs - half + cs / 2, z = j * cs - half + cs / 2, h = W.height(x, z); + const s = Math.max(Math.abs(W.height(x + 0.5, z) - W.height(x - 0.5, z)), Math.abs(W.height(x, z + 0.5) - W.height(x, z - 0.5))); + if (s > 0.85) g[j * n + i] = BLOCK; + else if (h < W.waterLevel(x, z) - 0.25) g[j * n + i] = WATER; + if (i < 4 || j < 4 || i > n - 5 || j > n - 5) g[j * n + i] = BLOCK; + } + // colliders: anything solid that reaches body height, padded by a body radius + const pad = 0.3; + for (const c of W.colliders) { + if (!(c.f & F.NAV) || !c.on) continue; + // body height above the lowest ground under the box (on a slope the centre alone would let a wall's + // downhill end pass under the body band) + const gy = Math.min(W.height(c.x, c.z), W.height(c.x + c.ex, c.z + c.ez), W.height(c.x - c.ex, c.z - c.ez), W.height(c.x + c.ex, c.z - c.ez), W.height(c.x - c.ex, c.z + c.ez)); + if (c.y1 < gy + 0.4 || c.y0 > gy + 1.7 + (Math.max(W.height(c.x + c.ex, c.z + c.ez), W.height(c.x - c.ex, c.z - c.ez)) - gy)) continue; + const ex = c.ex + pad, ez = c.ez + pad; + const i0 = Math.max(0, Math.floor((c.x - ex + half) / cs)), i1 = Math.min(n - 1, Math.floor((c.x + ex + half) / cs)); + const j0 = Math.max(0, Math.floor((c.z - ez + half) / cs)), j1 = Math.min(n - 1, Math.floor((c.z + ez + half) / cs)); + for (let j = j0; j <= j1; j++) for (let i = i0; i <= i1; i++) { + const x = i * cs - half + cs / 2, z = j * cs - half + cs / 2, dx = x - c.x, dz = z - c.z; + const lx = dx * c.c - dz * c.s, lz = dx * c.s + dz * c.c; + if (Math.abs(lx) <= c.hx + pad && Math.abs(lz) <= c.hz + pad) g[j * n + i] = BLOCK; + } + } + buildCover(); + }; + N.idx = (x, z) => { const i = Math.floor((x + W.half) / N.cell), j = Math.floor((z + W.half) / N.cell); return (i < 0 || j < 0 || i >= N.n || j >= N.n) ? -1 : j * N.n + i; }; + N.walkable = (x, z) => { const k = N.idx(x, z); return k >= 0 && N.grid[k] !== BLOCK; }; + N.center = k => ({ x: (k % N.n) * N.cell - W.half + N.cell / 2, z: Math.floor(k / N.n) * N.cell - W.half + N.cell / 2 }); + N.nearest = function (x, z, maxR) { + if (N.walkable(x, z)) return { x, z }; + for (let r = 0.5; r <= (maxR || 6); r += 0.5) for (let a = 0; a < 16; a++) { const xx = x + Math.cos(a / 16 * 6.283) * r, zz = z + Math.sin(a / 16 * 6.283) * r; if (N.walkable(xx, zz)) return { x: xx, z: zz }; } + return null; + }; + // straight walk between two points on the grid (for string pulling and "can I just walk there") + N.lineClear = function (ax, az, bx, bz) { + const d = Math.hypot(bx - ax, bz - az), steps = Math.ceil(d / (N.cell * 0.5)); + for (let s = 1; s <= steps; s++) { const t = s / steps, k = N.idx(ax + (bx - ax) * t, az + (bz - az) * t); if (k < 0 || N.grid[k] === BLOCK) return false; } + return true; + }; + + // binary heap on f + let heap = new Int32Array(1 << 16), hf = new Float32Array(1 << 16), hn = 0; + function push(k, f) { if (hn >= heap.length) { const a = new Int32Array(heap.length * 2), b = new Float32Array(heap.length * 2); a.set(heap); b.set(hf); heap = a; hf = b; } let i = hn++; while (i > 0) { const p = (i - 1) >> 1; if (hf[p] <= f) break; heap[i] = heap[p]; hf[i] = hf[p]; i = p; } heap[i] = k; hf[i] = f; } + function pop() { const top = heap[0], lk = heap[--hn], lf = hf[hn]; let i = 0; for (;;) { let c = i * 2 + 1; if (c >= hn) break; if (c + 1 < hn && hf[c + 1] < hf[c]) c++; if (hf[c] >= lf) break; heap[i] = heap[c]; hf[i] = hf[c]; i = c; } heap[i] = lk; hf[i] = lf; return top; } + const DIRS = [[1, 0, 1], [-1, 0, 1], [0, 1, 1], [0, -1, 1], [1, 1, 1.414], [1, -1, 1.414], [-1, 1, 1.414], [-1, -1, 1.414]]; + N.expanded = 0; + // A* from (sx,sz) to (tx,tz). Returns [{x,z},...] (excluding the start) or null. + N.path = function (sx, sz, tx, tz, maxNodes) { + const s = N.nearest(sx, sz, 3), t = N.nearest(tx, tz, 6); + if (!s || !t) return null; + if (N.lineClear(s.x, s.z, t.x, t.z)) return [{ x: t.x, z: t.z }]; + const n = N.n, g = N.grid, G = N.g, came = N.came, mark = N.mark, closed = N.closed; + const st = ++N.stampV; + const sk = N.idx(s.x, s.z), tk = N.idx(t.x, t.z), ti = tk % n, tj = (tk / n) | 0; + hn = 0; G[sk] = 0; mark[sk] = st; came[sk] = -1; push(sk, 0); + let found = false, count = 0; maxNodes = maxNodes || 60000; + while (hn > 0 && count < maxNodes) { + const k = pop(); if (closed[k] === st) continue; closed[k] = st; count++; + if (k === tk) { found = true; break; } + const i = k % n, j = (k / n) | 0; + for (const d of DIRS) { + const ni = i + d[0], nj = j + d[1]; if (ni < 0 || nj < 0 || ni >= n || nj >= n) continue; + const nk = nj * n + ni, gv = g[nk]; if (gv === BLOCK || closed[nk] === st) continue; + if (d[0] && d[1] && (g[j * n + ni] === BLOCK || g[nj * n + i] === BLOCK)) continue; // no corner cutting + const cost = G[k] + d[2] * (gv === WATER ? 3 : 1); + if (mark[nk] !== st || cost < G[nk]) { + mark[nk] = st; G[nk] = cost; came[nk] = k; + const di = Math.abs(ni - ti), dj = Math.abs(nj - tj), h = (di + dj) + (1.414 - 2) * Math.min(di, dj); + push(nk, cost + h * 1.15); + } + } + } + N.expanded = count; + if (!found) return null; + const raw = []; for (let k = tk; k !== -1 && k !== sk; k = came[k]) raw.push(N.center(k)); + raw.reverse(); raw[raw.length - 1] = { x: t.x, z: t.z }; + // string pull + const out = []; let ax = s.x, az = s.z, i = 0; + while (i < raw.length) { + let j = raw.length - 1; + while (j > i && !N.lineClear(ax, az, raw[j].x, raw[j].z)) j--; + out.push(raw[j]); ax = raw[j].x; az = raw[j].z; i = j + 1; + } + return out; + }; + + // Regenerate the walk grid and the cover points after the terrain or the colliders change (new buildings, relief): + // IV.nav.rebuild() -> { cells, blocked, cover, ms } (also exposed to tests as __IV__.navRebuild()) + // Soldiers and the squadmate drop their current paths and find new ones on their next decision. + N.rebuild = function () { + const t0 = performance.now(); N.build(); + for (const e of (IV.ai && IV.ai.list) || []) { e.path = null; e.pathI = 0; e.repath = 0; } + if (IV.ally && IV.ally.ent) { IV.ally.ent.path = null; IV.ally.ent.repath = 0; } + let blocked = 0; for (let i = 0; i < N.grid.length; i++) if (N.grid[i] === BLOCK) blocked++; + return N.lastBuild = { cells: N.grid.length, blocked, cover: N.cover.length, ms: Math.round(performance.now() - t0) }; + }; + // ---------------------------------------------------------------- cover points + function buildCover() { + const out = N.cover = []; + for (const c of W.colliders) { + if (!(c.f & F.BULLET) || !(c.f & F.SOLID) || !c.on) continue; + if (!/wall|hedge|sandbags|tree|plinth|^$|fence|cart|woodpile/.test(c.kind)) continue; + if (c.kind === 'fence') continue; + const gy = W.height(c.x, c.z), hgt = c.y1 - gy; + if (hgt < 0.85) continue; + const low = hgt < 1.45; + // sample along the two long faces + const long = c.hx >= c.hz, L = long ? c.hx : c.hz, Sd = long ? c.hz : c.hx; + const steps = Math.max(1, Math.floor((L * 2) / 2.5)); + for (let s = 0; s <= steps; s++) for (const side of [-1, 1]) { + const u = -L + (2 * L) * (s / steps), off = Sd + 0.55; + const lx = long ? u : side * off, lz = long ? side * off : u; + const x = c.x + lx * c.c + lz * c.s, z = c.z - lx * c.s + lz * c.c; + if (!N.walkable(x, z)) continue; + const nlx = long ? 0 : side, nlz = long ? side : 0; + out.push({ x, z, nx: nlx * c.c + nlz * c.s, nz: -nlx * c.s + nlz * c.c, low, used: null }); + } + } + // spatial buckets (16 m) + N.coverHash = new Map(); + for (const p of out) { const k = Math.floor(p.x / 16) * 1000 + Math.floor(p.z / 16); let a = N.coverHash.get(k); if (!a) N.coverHash.set(k, a = []); a.push(p); } + } + N.coverNear = function (x, z, r) { + const res = []; const i0 = Math.floor((x - r) / 16), i1 = Math.floor((x + r) / 16), j0 = Math.floor((z - r) / 16), j1 = Math.floor((z + r) / 16); + for (let i = i0; i <= i1; i++) for (let j = j0; j <= j1; j++) { const a = N.coverHash.get(i * 1000 + j); if (a) for (const p of a) if (Math.hypot(p.x - x, p.z - z) < r) res.push(p); } + return res; + }; +})(); diff --git a/e63334287a3deaa3/ironveil/js/player.js b/e63334287a3deaa3/ironveil/js/player.js new file mode 100644 index 00000000..e0267a41 --- /dev/null +++ b/e63334287a3deaa3/ironveil/js/player.js @@ -0,0 +1,286 @@ +/* Ironveil player: a kinematic capsule on the heightfield and boxes (MOVEMENT.md sections 1-2). + - Velocity always eases toward a target (exponential), never set from the keys. Speeds and times in TUNING.move. + - Strafing and backpedalling are slower than forward; diagonals are not faster. + - A full reversal at jog or sprint plants for a moment before the new direction takes over; sprint turns slowly. + - Not aiming: the body turns toward the movement at a capped rate. Aiming: the body faces the aim and the legs strafe. + Standing still while the camera swings past about 60 degrees: the body turns in place (with steps). + - Step-up (0.35 m), ground snap (no hopping downhill), slopes over about 40 degrees push you back down. + - Stance with timed transitions, vault over low walls and fences, wading, footstep noise for the AI (by distance + walked, in the fixed step), health with a regen delay. + - Animation: one call per rendered frame, actor.drive(state); footstep sound, dust and rustle hang off actor.onFoot. */ +(function () { + 'use strict'; + const T = IV.TUNING, MV = T.move, W = IV.world, F = IV.CF; + const P = IV.player = { + pos: new THREE.Vector3(), prev: new THREE.Vector3(), vel: new THREE.Vector3(), render: new THREE.Vector3(), + yaw: 0, pitch: 0, bodyYaw: 0, bodyPrev: 0, stance: 'stand', stanceT: 0, grounded: true, hp: 100, alive: true, + sprinting: false, speed: 0, gait: 'still', vault: null, inWater: false, lastHurt: -99, stride: 0, actor: null, + noise: 0, crops: false, god: false, frozen: false, cine: null, hurtDir: 0, plantT: 0, turning: false, yawRate: 0, fallSpeed: 0 + }; + const HEIGHT = { stand: 1.78, crouch: 1.2, prone: 0.55 }; + P.height = () => HEIGHT[P.stance]; + P.eyeY = () => P.pos.y + (P.stance === 'stand' ? 1.62 : P.stance === 'crouch' ? 1.08 : 0.42); + + P.spawn = function (x, z, yaw, stance) { + P.pos.set(x, W.height(x, z), z); P.prev.copy(P.pos); P.render.copy(P.pos); P.vel.set(0, 0, 0); + P.yaw = yaw || 0; P.bodyYaw = P.bodyPrev = P.yaw; P.pitch = -0.05; P.stance = stance || 'stand'; P.stanceT = 0; + P.hp = T.health.max; P.alive = true; P.vault = null; P.frozen = false; P.cine = null; P.cineClip = false; P.lastHurt = -99; P.plantT = 0; P.turning = false; + if (!P.actor) { + P.actor = IVChars.spawn('hero'); + P.actor.root.traverse(o => { o.userData.player = true; }); + // chars.js foot IK; none during a scripted moment (hanging in the harness the ground is metres below, and the + // pelvis drop would pull the body down to it) + P.actor.groundAt = (x, z) => P.cine ? null : W.groundAt(x, z, P.render.y + 0.4); + // footsteps come from the animation's foot contacts + P.actor.onFoot = (side, strength) => footFx(P.render, P.stance === 'stand' ? (P.sprinting ? 'sprint' : P.speed > 2.6 ? 'run' : 'walk') : P.stance === 'crouch' ? 'crouch' : 'prone', strength, true); + } + W.dynamic.add(P.actor.root); + P.actor._gOff = null; P.actor._pelDrop = 0; // a respawn starts the foot IK fresh, not eased from where the body was + P.actor.play(P.stance === 'prone' ? 'proneIdle' : P.stance === 'crouch' ? 'crouchIdle' : 'idle', { fade: 0 }); + }; + // the ground kind under a point, as the audio and effects know it + const AUDIO_SURF = { grass: 'grass', pasture: 'grass', meadow: 'tallgrass', tussock: 'tallgrass', verge: 'grass', lanemid: 'grass', worn: 'mud', leaves: 'grass', yardedge: 'gravel', lane: 'mud', mud: 'mud', yard: 'gravel', road: 'gravel', gravel: 'gravel', cobbles: 'stone', field: 'crops', water: 'water', floor: 'wood', none: 'grass' }; + function footFx(p, gait, strength, isPlayer, vol) { + const kind = W.surfaceAt(p.x, p.z), wet = W.height(p.x, p.z) < W.waterLevel(p.x, p.z) - 0.25; + let surf = wet ? 'water' : AUDIO_SURF[kind] || 'grass'; + if (kind === 'indoors') { const c = W.near(p.x, p.z, 0.3).find(c => Math.abs(c.y1 - p.y) < 0.06); surf = c ? (c.surf === 'stone' ? 'stone' : 'wood') : 'stone'; } + // the environment kit's ground (war-look): standing water, mud, leaf litter. Mud presses a boot print and kicks clods; + // boots carry mud onto hard ground as tracked prints that fade; puddles splash; leaves rustle + const E = window.IVEnv, near = isPlayer || (W.camera && Math.hypot(p.x - W.camera.position.x, p.z - W.camera.position.z) < 35); + if (E && E.groundInfo && kind !== 'indoors' && kind !== 'floor' && near) { + let es = null, gi = null; try { es = E.surfaceAt ? E.surfaceAt(p.x, p.z) : null; gi = E.groundInfo(p.x, p.z); } catch (e) {} + const yaw = isPlayer ? P.bodyYaw : Math.random() * 6.28, f = IV.fwd(yaw), M = E.marks; + if (es === 'puddle' && !wet) { surf = 'water'; IV.fx.splash && IV.fx.splash(p.x, p.y, p.z, gait === 'sprint' || gait === 'run' ? 1.2 : 0.6); } + else if (es === 'leaves' && surf === 'grass') surf = 'tallgrass'; + const muddy = gi && (gi.mud > 0.5 || es === 'mud' || es === 'lane'); + if (muddy && !wet && gait !== 'prone') { + surf = 'mud'; + M && M.stamp && M.stamp(p.x - f.z * 0.1 * (IV.R && IV.R() < 0.5 ? 1 : -1), p.z + f.x * 0.1, 'boot', yaw, 0.8 + 0.2 * (gi.wet || 0)); + if (gait !== 'crouch' && IV.fx.clods) IV.fx.clods(p.x, p.y, p.z, gait === 'sprint' ? 6 : 3, f.x, f.z); + if (isPlayer) P.mudBoots = 1; + if (Math.random() < 0.35) IV.audio && IV.audio.play('squelch'); + } else if (isPlayer && P.mudBoots > 0.08 && (surf === 'gravel' || surf === 'stone' || surf === 'wood')) { + M && M.stamp && M.stamp(p.x, p.z, 'track', yaw, P.mudBoots); P.mudBoots *= 0.78; + } else if (isPlayer && P.mudBoots > 0) P.mudBoots *= 0.9; + } + IV.audio && IV.audio.step(surf, gait, (vol || 1) * (0.6 + 0.4 * (strength || 1)), isPlayer ? null : p); + if (surf === 'gravel' && gait !== 'crouch' && gait !== 'prone' && Math.random() < 0.6) IV.fx.dust(p.x, p.y + 0.05, p.z, 2, 0.12); + if (surf === 'water' && wet && Math.random() < 0.8) IV.fx.impact(p.x, p.y + 0.1, p.z, 0, 1, 0, 'water'); + if (isPlayer) IV.camera && IV.camera.footBob(strength || 1); + } + IV.footFx = footFx; + + // ---------------------------------------------------------------- stance + P.setStance = function (s) { + if (s === P.stance || P.vault) return; + if ((s === 'stand' || (s === 'crouch' && P.stance === 'prone'))) { + const cl = W.ceilingAt(P.pos.x, P.pos.z, P.pos.y); + if (cl < P.pos.y + HEIGHT[s] + 0.05) return; // no room to get up + } + // stance changes take longer the further you go (stand-crouch 0.25 s, to or from prone 0.6-0.9 s) + P.stanceT = (P.stance === 'prone' || s === 'prone') ? (P.stance === 'stand' || s === 'stand' ? 0.9 : 0.6) : 0.25; P.stance = s; + IV.audio && IV.audio.play('cloth', { vol: 0.6 }); + IV.emit('stance', s); + }; + + // ---------------------------------------------------------------- vault + const probe = { x: 0, z: 0 }; + function tryVault() { + const mv = Math.hypot(P.vel.x, P.vel.z); + const dir = mv > 0.5 ? { x: P.vel.x / mv, z: P.vel.z / mv } : IV.fwd(P.yaw); + const a = W.near(P.pos.x + dir.x, P.pos.z + dir.z, 1.6); + let best = null, bd = 9; + for (let i = 0; i < a.length; i++) { + const c = a[i]; if (!(c.f & F.VAULT)) continue; + const top = c.y1 - P.pos.y; if (top < MV.vaultMin || top > MV.vaultMax) continue; + const hit = W.raycast(P.pos.x, P.pos.y + top - 0.12, P.pos.z, dir.x, 0, dir.z, 1.8, F.VAULT, true); + if (!hit || hit.col !== c) continue; + if (hit.t < bd) { bd = hit.t; best = { c, t: hit.t, top }; } + } + if (!best) return false; + const c = best.c; let d = best.t + 0.3; + for (; d < best.t + 2.4; d += 0.1) { + probe.x = P.pos.x + dir.x * d; probe.z = P.pos.z + dir.z * d; + const L = W.toLocal(c, probe.x, probe.z, {}); + if (Math.abs(L.x) > c.hx + MV.radius + 0.05 || Math.abs(L.z) > c.hz + MV.radius + 0.05) break; + } + const ex = P.pos.x + dir.x * d, ez = P.pos.z + dir.z * d, ey = W.groundAt(ex, ez, c.y1 + 0.2, 0.2); + if (ey > c.y1 + 0.1) return false; + const o = { x: ex, z: ez, r: MV.radius }; + W.collide(o, MV.radius, ey + 0.4, ey + 1.6); + if (Math.hypot(o.x - ex, o.z - ez) > 0.2) return false; + P.vault = { t: 0, sx: P.pos.x, sy: P.pos.y, sz: P.pos.z, ex, ey, ez, top: c.y1 }; + if (P.stance !== 'stand') P.stance = 'stand'; + P.bodyYaw = IV.yawTo(dir.x, dir.z); + P.actor.play('vault', { fade: 0.08, once: true, restart: true }); + IV.ai && IV.ai.noise(P.pos.x, P.pos.z, T.noise.vault, 'step', P); + IV.audio && IV.audio.play('vault'); + IV.emit('vault'); + return true; + } + + // turn an angle toward a target at a capped rate (rad/s) + function turnToward(a, b, rate, dt) { const d = IV.wrapA(b - a), m = rate * dt; return a + (Math.abs(d) <= m ? d : Math.sign(d) * m); } + IV.turnToward = turnToward; + + // ---------------------------------------------------------------- simulate one fixed step + const o = { x: 0, z: 0 }, nrm = new THREE.Vector3(); + P.step = function (dt) { + P.prev.copy(P.pos); P.bodyPrev = P.bodyYaw; + if (!P.alive) { P.yawRate = 0; return; } + const I = IV.input; + if (P.stanceT > 0) P.stanceT -= dt; + if (P.cine) { P.cine(dt); P.speed = 0; return; } // a scripted moment moves the player + if (P.frozen) { P.vel.set(0, 0, 0); P.speed = 0; return; } + if (P.vault) { + const v = P.vault; v.t += dt / (IVChars.standin ? MV.vaultTime : MV.vaultTimeClip); const k = Math.min(1, v.t), e = IV.smooth(k); + P.pos.x = v.sx + (v.ex - v.sx) * e; P.pos.z = v.sz + (v.ez - v.sz) * e; + P.pos.y = v.sy + (v.ey - v.sy) * e + Math.sin(k * Math.PI) * Math.max(0.25, v.top - Math.min(v.sy, v.ey) + 0.15) * 0.85 + (v.top - v.sy) * 0.15 * Math.sin(k * Math.PI); + if (k >= 1) { P.vault = null; P.vel.set((v.ex - v.sx) * 1.2, 0, (v.ez - v.sz) * 1.2); IV.audio && IV.audio.play('land', { surf: IV.SURF[W.surfAt(P.pos.x, P.pos.z)] }); IV.camera && IV.camera.landDip(0.6); } + return; + } + // stance input + if (I.pressed('crouch')) P.setStance(P.stance === 'crouch' ? 'stand' : 'crouch'); + if (I.pressed('prone')) P.setStance(P.stance === 'prone' ? 'crouch' : 'prone'); + if (I.pressed('vault')) { if (P.stance !== 'stand' && !nearVault()) P.setStance('stand'); else if (!tryVault() && P.stance !== 'stand') P.setStance('stand'); } + const W8 = IV.weapons, aiming = W8 && (W8.aiming || W8.scoped), binoc = W8 && W8.binoc; + // sprint: standing, moving mostly forward, not aiming. Shift while crouched is a quieter crouch-run. + const sprint = I.held('sprint') && I.moveY > 0.3 && !aiming && !binoc && !(W8 && W8.busyThrow) && P.stance === 'stand'; + if (P.sprinting && !sprint) P.sprintOutT = MV.sprintOut; // the weapon needs a moment to come up after a sprint + P.sprintOutT = Math.max(0, (P.sprintOutT || 0) - dt); + P.sprinting = sprint; + P.crouchRun = I.held('sprint') && P.stance === 'crouch'; + // target velocity, camera relative; strafe and backpedal slower than forward + const f = IV.fwd(P.yaw), rx = -f.z, rz = f.x; + const mx = I.moveX, my = I.moveY, ml = Math.min(1, Math.hypot(mx, my)); + let tx = f.x * my + rx * mx, tz = f.z * my + rz * mx; + const tl = Math.hypot(tx, tz); if (tl > 1e-4) { tx /= tl; tz /= tl; } + const fw = Math.max(0, my), bk = Math.max(0, -my), sd = Math.abs(mx), dirMul = (fw + bk * MV.backMul + sd * MV.strafeMul) / Math.max(1e-4, fw + bk + sd); + let sp; + if (P.stance === 'prone') sp = MV.prone; + else if (P.stance === 'crouch') sp = P.crouchRun ? MV.crouchRun : MV.crouch; + else sp = sprint ? MV.sprint : aiming ? MV.walk : MV.run; + if (aiming && P.stance !== 'stand') sp = Math.min(sp, MV.crouch * 0.85); + if (binoc) sp *= 0.5; + if (P.stanceT > 0) sp *= 0.5; + // slopes: slower going up (about 15% at 15 degrees, 30% at 25), a little slower steeply down; across is free + if (tl > 1e-4 && P.grounded) { + const ahead = W.height(P.pos.x + tx * 0.6, P.pos.z + tz * 0.6) - W.height(P.pos.x - tx * 0.6, P.pos.z - tz * 0.6), grade = ahead / 1.2; + sp *= grade > 0 ? Math.max(0.6, 1 - grade * 1.1) : Math.max(0.85, 1 + grade * 0.3); + } + if (P.landT > 0) { P.landT -= dt; sp *= 0.5; } + P.inWater = W.height(P.pos.x, P.pos.z) < W.waterLevel(P.pos.x, P.pos.z) - 0.25; + if (P.inWater) sp *= MV.waterMul; + // mud drags at the boots (the environment kit's ground: about 10-20 % slower in deep wet mud, nothing on hard ground) + if (!P.inWater && P.grounded && window.IVEnv && IVEnv.groundInfo && !W.underRoof(P.pos.x, P.pos.z)) { try { const gi = IVEnv.groundInfo(P.pos.x, P.pos.z); if (gi.mud > 0.4) sp *= 1 - 0.16 * gi.mud * (0.7 + 0.3 * gi.wet); P.mud = gi.mud; } catch (e) {} } + sp *= ml * (sprint ? 1 : dirMul); + // reversal plant: a hard change of direction at speed holds the acceleration back for a moment + const cur = Math.hypot(P.vel.x, P.vel.z); + if (cur > MV.plantSpeed && ml > 0.3 && (P.vel.x * tx + P.vel.z * tz) / cur < -0.3 && P.plantT <= 0 && !P.planted) { P.plantT = MV.plantTime; P.planted = true; } + if ((P.vel.x * tx + P.vel.z * tz) >= 0) P.planted = false; + let k; + const fast = cur > MV.run + 0.5; // coming down from a sprint: brake over about 0.4 s so the feet can plant + if (P.plantT > 0) { P.plantT -= dt; tx = 0; tz = 0; sp = 0; k = fast ? MV.sprintDecel : MV.decel * 1.4; } + else if (!P.grounded) k = MV.airAccel; + else if (sp < 0.05) k = fast ? MV.sprintDecel : MV.decel; + else k = sprint && cur > MV.run - 0.3 ? MV.sprintAccel : MV.accel; + // sprinting can't turn on the spot: the velocity's direction swings at a capped rate + if (sprint && cur > 2.5 && sp > 0) { + const va = IV.yawTo(P.vel.x, P.vel.z), ta = IV.yawTo(tx, tz), na = turnToward(va, ta, MV.sprintTurnRate, dt), nf = IV.fwd(na); + tx = nf.x; tz = nf.z; + } + P.vel.x = IV.damp(P.vel.x, tx * sp, k, dt); P.vel.z = IV.damp(P.vel.z, tz * sp, k, dt); + // move + collide (boxes lower than a step are stood on, not pushed against) + o.x = P.pos.x + P.vel.x * dt; o.z = P.pos.z + P.vel.z * dt; + const hit = W.collide(o, MV.radius, P.pos.y + MV.step, P.pos.y + P.height()); + const gNew = W.groundAt(o.x, o.z, P.pos.y); + if (gNew - P.pos.y > MV.step + 0.02) { o.x = P.pos.x; o.z = P.pos.z; } + if (hit) { const vn = P.vel.x * o.nx + P.vel.z * o.nz; if (vn < 0) { P.vel.x -= o.nx * vn; P.vel.z -= o.nz * vn; } } + // slope limit: on terrain steeper than about 40 degrees you can't climb, and you slide back down + W.normal(o.x, o.z, nrm); + if (nrm.y < MV.slopeCos && gNew <= W.height(o.x, o.z) + 0.02) { + const hx = nrm.x, hz = nrm.z, hl = Math.hypot(hx, hz) || 1, up = -((o.x - P.pos.x) * hx + (o.z - P.pos.z) * hz) / hl; + if (up > 0) { o.x += hx / hl * up; o.z += hz / hl * up; } + P.vel.x += hx / hl * MV.slideAccel * dt; P.vel.z += hz / hl * MV.slideAccel * dt; + } + P.pos.x = IV.clamp(o.x, -W.half + 2, W.half - 2); P.pos.z = IV.clamp(o.z, -W.half + 2, W.half - 2); + // vertical: snap to ground within reach, otherwise fall + const g = W.groundAt(P.pos.x, P.pos.z, P.pos.y); + if (P.pos.y - g < MV.snap && P.vel.y <= 0.01) { + if (!P.grounded && P.vel.y < -6) P.landT = 0.25; // a heavy landing slows you for a moment + if (!P.grounded && P.vel.y < -6) { IV.audio && IV.audio.play('land', { surf: IV.SURF[W.surfAt(P.pos.x, P.pos.z)] }); IV.ai && IV.ai.noise(P.pos.x, P.pos.z, T.noise.land, 'step', P); IV.camera && IV.camera.landDip(Math.min(1, -P.vel.y / 10)); } + P.pos.y = g; P.vel.y = 0; P.grounded = true; + } else { P.vel.y -= MV.gravity * dt; P.pos.y += P.vel.y * dt; P.grounded = false; if (P.pos.y < g) { P.pos.y = g; P.vel.y = 0; P.grounded = true; } } + P.fallSpeed = P.grounded ? 0 : -P.vel.y; + // body facing + P.speed = Math.hypot(P.vel.x, P.vel.z); + const faceAim = aiming || binoc || (W8 && (W8.firingRecently || W8.busyThrow)); + if (faceAim) { P.bodyYaw = turnToward(P.bodyYaw, P.yaw, MV.aimTurnRate, dt); P.turning = false; } + else if (P.speed > 0.4 && sp > 0) { P.bodyYaw = turnToward(P.bodyYaw, IV.yawTo(P.vel.x, P.vel.z), MV.turnRate * (P.stance === 'prone' ? 0.35 : 1), dt); P.turning = false; } + else if (P.speed < 0.4 && P.stance !== 'prone') { + const d = Math.abs(IV.wrapA(P.yaw - P.bodyYaw)); + if (d > MV.turnInPlace) P.turning = true; + if (P.turning) { P.bodyYaw = turnToward(P.bodyYaw, P.yaw, MV.turnInPlaceRate, dt); if (Math.abs(IV.wrapA(P.yaw - P.bodyYaw)) < 0.12) P.turning = false; } + } + P.yawRate = IV.wrapA(P.bodyYaw - P.bodyPrev) / dt; + // footstep noise the guards can hear: by distance walked, in the fixed step (the sound itself comes from onFoot) + P.gait = P.speed < 0.3 ? 'still' : P.stance === 'prone' ? 'prone' : P.stance === 'crouch' ? (P.crouchRun ? 'crouchRun' : 'crouch') : sprint ? 'sprint' : P.speed > 2.6 ? 'run' : 'walk'; + const kind = W.surfaceAt(P.pos.x, P.pos.z); + P.surface = P.inWater ? 'water' : AUDIO_SURF[kind] || 'grass'; + const onBox = g > W.height(P.pos.x, P.pos.z) + 0.05; + if (onBox) { const c = W.near(P.pos.x, P.pos.z, 0.3).find(c => Math.abs(c.y1 - g) < 0.03); if (c) P.surface = c.surf === 'foliage' ? 'grass' : c.surf; } + P.crops = !onBox && (kind === 'field' || kind === 'meadow'); + if (P.gait !== 'still' && P.grounded) { + const strideLen = P.gait === 'sprint' ? 1.9 : P.gait === 'run' ? 1.5 : P.gait === 'prone' ? 0.8 : 0.9; + P.stride += P.speed * dt; + if (P.stride > strideLen) { + P.stride = 0; + const r = (T.noise[P.gait] || 5) * (T.noise.surface[P.surface] || 1); + P.noise = r; + IV.ai && IV.ai.noise(P.pos.x, P.pos.z, r, 'step', P); + } + } else P.noise = Math.max(0, P.noise - dt * 8); + if (P.hp < T.health.max && IV.time - P.lastHurt > T.health.regenDelay) P.hp = Math.min(T.health.max, P.hp + T.health.regenRate * dt); + }; + function nearVault() { + const f = IV.fwd(P.bodyYaw), a = W.near(P.pos.x + f.x, P.pos.z + f.z, 1.2); + for (const c of a) if (c.f & F.VAULT) { const r = W.raycast(P.pos.x, P.pos.y + 0.3, P.pos.z, f.x, 0, f.z, 1.2, F.VAULT, true); if (r) return true; } + return false; + } + + // ---------------------------------------------------------------- damage + P.hurt = function (dmg, from) { + if (!P.alive || P.god) return; + const d = IV.mission && IV.mission.diffMul ? dmg * IV.mission.diffMul.taken : dmg; + P.hp -= d; P.lastHurt = IV.time; + if (from) P.hurtDir = IV.wrapA(IV.yawTo(from.x - P.pos.x, from.z - P.pos.z) - P.yaw); + IV.emit('hurt', { dmg: d, from }); + IV.camera && IV.camera.shake(0.25); + if (P.hp <= 0) { P.hp = 0; P.alive = false; P.actor.setUpper(null); P.actor.play(Math.random() < 0.5 ? 'deathFront' : 'deathBack', { fade: 0.1, once: true }); IV.emit('playerDied'); } + }; + + // ---------------------------------------------------------------- render: interpolate, then one drive() call + const st = { vx: 0, vz: 0, speed: 0, yawRate: 0, stance: 'stand', aiming: false, aimPitch: 0, aimYawOffset: 0, sprinting: false, grounded: true, fallSpeed: 0, slopeY: 1, weapon: '', dt: 0 }; + IV.driveState = function (out, vel, bodyYaw, o) { // fill a drive() state (vx, vz in the character's own frame: +x LEFT, +z forward, as IVChars wants) + const f = IV.fwd(bodyYaw), rx = -f.z, rz = f.x; + out.vx = -(vel.x * rx + vel.z * rz); out.vz = vel.x * f.x + vel.z * f.z; out.speed = Math.hypot(vel.x, vel.z); + return Object.assign(out, o); + }; + P.frame = function (alpha, dt) { + P.render.lerpVectors(P.prev, P.pos, alpha); + const A = P.actor; if (!A) return; + A.root.position.copy(P.render); + const by = P.bodyPrev + IV.wrapA(P.bodyYaw - P.bodyPrev) * alpha; + A.root.rotation.y = by + Math.PI; + const W8 = IV.weapons; + if (P.alive && !P.vault && !P.cineClip) { + W.normal(P.render.x, P.render.z, nrm); + IV.driveState(st, P.vel, P.bodyYaw, { yawRate: P.yawRate, stance: P.stance, aiming: !!(W8 && (W8.aiming || W8.scoped || W8.binoc)), aimPitch: P.pitch, + aimYawOffset: IV.clamp(IV.wrapA(P.yaw - P.bodyYaw), -1.2, 1.2), sprinting: P.sprinting, grounded: P.grounded, fallSpeed: P.fallSpeed, slopeY: nrm.y, weapon: W8 ? W8.cur : '', dt }); + if (!P.cine) IV.releaseLoopPose(A); + A.drive(st); + } else A.setAim(P.pitch, IV.clamp(IV.wrapA(P.yaw - P.bodyYaw), -1.2, 1.2)); + A.update(dt); + IV.fp && IV.fp.afterBodyUpdate(); + }; +})(); diff --git a/e63334287a3deaa3/ironveil/js/touch.js b/e63334287a3deaa3/ironveil/js/touch.js new file mode 100644 index 00000000..50e0b10b --- /dev/null +++ b/e63334287a3deaa3/ironveil/js/touch.js @@ -0,0 +1,76 @@ +/* Ironveil touch controls (only on touch screens): a move stick on the left, drag anywhere on the right half to look, + and buttons for fire, aim (tap to toggle), crouch, prone, reload, use / takedown, sprint, vault, binoculars, + grenade, rock and hold-breath. Fire also looks while you drag it. Optional auto-fire when the reticle is on a + soldier. Played sideways; upright phones get a "turn your phone" card while in a mission. */ +(function () { + 'use strict'; + const I = IV.input, $ = IV.$; + const TC = IV.touchUI = { on: false }; + const toggles = { aim: false, sprint: false, binoc: false }; + TC.enable = function (on) { TC.on = on; document.body.classList.toggle('touch', on); IV.touch = on; }; + if (IV.touch) TC.enable(true); + addEventListener('pointerdown', e => { if (e.pointerType === 'touch' && !TC.on) TC.enable(true); }, true); + + // move stick + const st = $('tStick'), knob = st.querySelector('i'); + let sid = null, sx = 0, sy = 0; + I.stick = { x: 0, y: 0 }; + st.addEventListener('pointerdown', e => { e.preventDefault(); sid = e.pointerId; const r = st.getBoundingClientRect(); sx = r.left + r.width / 2; sy = r.top + r.height / 2; st.setPointerCapture(sid); moveStick(e); }); + st.addEventListener('pointermove', e => { if (e.pointerId === sid) moveStick(e); }); + const endStick = e => { if (e.pointerId !== sid) return; sid = null; I.stick.x = I.stick.y = 0; knob.style.transform = ''; if (toggles.sprint) setToggle('sprint', false); }; + st.addEventListener('pointerup', endStick); st.addEventListener('pointercancel', endStick); + function moveStick(e) { + let dx = e.clientX - sx, dy = e.clientY - sy; const R = 52, l = Math.hypot(dx, dy); + if (l > R) { dx *= R / l; dy *= R / l; } + knob.style.transform = `translate(${dx}px,${dy}px)`; + let x = dx / R, y = -dy / R; const m = Math.hypot(x, y); + if (m < 0.15) { x = y = 0; } else { const k = (m - 0.15) / 0.85 / m; x *= k; y *= k; } + I.stick.x = x; I.stick.y = y; + } + // drag to look (the right side of the screen, and the fire button) + function dragLook(el) { + const pts = new Map(); + el.addEventListener('pointerdown', e => { pts.set(e.pointerId, [e.clientX, e.clientY]); try { el.setPointerCapture(e.pointerId); } catch (_) {} }); + el.addEventListener('pointermove', e => { + const p = pts.get(e.pointerId); if (!p || !IV.playing()) return; + IV.camera.look(e.clientX - p[0], e.clientY - p[1], true); p[0] = e.clientX; p[1] = e.clientY; + }); + const end = e => pts.delete(e.pointerId); el.addEventListener('pointerup', end); el.addEventListener('pointercancel', end); + } + dragLook($('tLook')); + // buttons + function setToggle(id, v) { toggles[id] = v; I.sim(id, v); const b = document.querySelector(`[data-t="${id}"]`); b && b.classList.toggle('on', v); } + document.querySelectorAll('#touch [data-t]').forEach(b => { + const id = b.dataset.t; + b.addEventListener('contextmenu', e => e.preventDefault()); + b.addEventListener('pointerdown', e => { + e.preventDefault(); e.stopPropagation(); + if (id === 'pause') { IV.emit('escape'); return; } + if (id === 'order') { I.sim('order', true); setTimeout(() => I.sim('order', false), 60); return; } + if (id === 'swap') { I.sim('swap', true); setTimeout(() => I.sim('swap', false), 60); return; } + if (id in toggles) { setToggle(id, !toggles[id]); return; } + if (id === 'use') { I.sim('knife', true); } + I.sim(id, true); b.classList.add('on'); + }); + const up = e => { if (id in toggles || id === 'pause' || id === 'order' || id === 'swap') return; I.sim(id, false); if (id === 'use') I.sim('knife', false); b.classList.remove('on'); }; + b.addEventListener('pointerup', up); b.addEventListener('pointercancel', up); b.addEventListener('pointerleave', up); + }); + dragLook(document.querySelector('[data-t="fire"]')); + // per frame: auto-fire, hold-breath button only while scoped, aim off when the weapon can't aim + TC.frame = function () { + if (!TC.on) return; + const WP = IV.weapons; + const br = document.querySelector('[data-t="breath"]'); br.hidden = !WP.scoped; + if (IV.settings.auto && IV.playing() && (WP.aiming || WP.scoped)) { + const t = IV.camera.findTarget(WP.scoped ? 0.006 : 0.03, 120); + const want = !!t; + if (want !== !!TC.autoOn) { TC.autoOn = want; I.sim('fire', want); } + } else if (TC.autoOn) { TC.autoOn = false; I.sim('fire', false); } + // portrait: the game is played sideways + const portrait = innerHeight > innerWidth; + $('portrait').hidden = !(portrait && IV.playing() && !TC.upright); + }; + // "Play upright anyway": the controls have an upright layout too (index.html, orientation: portrait) + $('portraitGo').addEventListener('click', () => { TC.upright = true; $('portrait').hidden = true; }); + TC.reset = function () { for (const k in toggles) setToggle(k, false); I.stick.x = I.stick.y = 0; knob.style.transform = ''; }; +})(); diff --git a/e63334287a3deaa3/ironveil/js/weapons.js b/e63334287a3deaa3/ironveil/js/weapons.js new file mode 100644 index 00000000..a95da06a --- /dev/null +++ b/e63334287a3deaa3/ironveil/js/weapons.js @@ -0,0 +1,553 @@ +/* Ironveil weapons: the player's rifle (scoped, bolt action, real projectile with drag, gravity, wind and travel time), + SMG (recoil pattern, spread bloom), pistol, knife takedown, grenades (cookable fuse, arc preview), thrown rocks + (distraction), binoculars (tag + range). Every bullet in the game, the enemies' too, is a projectile stepped here and + tested against the world and against stance-based hit spheres (head, torso, limbs). */ +(function () { + 'use strict'; + const T = IV.TUNING, WT = T.weapons, BL = T.ballistics, W = IV.world, F = IV.CF; + const P = IV.player; + const WP = IV.weapons = { + cur: 'rifle', aiming: false, scoped: false, binoc: false, busyThrow: null, firingRecently: false, + hideSlungWhenAiming: true, inv: null, reloadT: 0, boltT: 0, cool: 0, bloom: 0, burst: 0, lastFire: -9, bullets: [], throws: [], wind: { x: 1.6, z: 0.4 }, + stats: { shots: 0, hits: 0, kills: 0, heads: 0, takedowns: 0 }, models: {}, tagged: new Set(), takedownTarget: null + }; + const NAMES = { rifle: 'Scoped rifle', smg: 'Submachine gun', pistol: 'Pistol' }; + WP.name = k => IV.t(NAMES[k] || k); + + // ---------------------------------------------------------------- ballistics + // Step a round with quadratic drag relative to the air (so wind drifts it) and gravity. + function ballStep(b, dt, wind) { + const rx = b.vx - wind.x, ry = b.vy, rz = b.vz - wind.z, sp = Math.sqrt(rx * rx + ry * ry + rz * rz), k = b.drag * sp; + b.vx -= k * rx * dt; b.vy -= (k * ry + BL.g) * dt; b.vz -= k * rz * dt; + } + WP.ballStep = ballStep; + // Fly a round from the scope's line of sight and find where it is relative to that line at each range: + // the zero angle makes it cross the sight line at BL.zero; the drop marks are the angles below centre for 200, 300 m. + function simulateDrop(angle, ranges) { + const b = { x: 0, y: -BL.sightHeight, z: 0, vx: BL.v0 * Math.cos(angle), vy: BL.v0 * Math.sin(angle), vz: 0, drag: BL.drag }; + const out = {}, dt = 1 / 2000, still = { x: 0, z: 0 }; + let ri = 0; + for (let t = 0; t < 2 && ri < ranges.length; t += dt) { + const px = b.x, py = b.y; + b.x += b.vx * dt; b.y += b.vy * dt; ballStep(b, dt, still); + while (ri < ranges.length && b.x >= ranges[ri]) { const k = (ranges[ri] - px) / (b.x - px); out[ranges[ri]] = { y: py + (b.y - py) * k, t }; ri++; } + } + return out; + } + WP.simulateDrop = simulateDrop; + WP.computeZero = function () { + let lo = 0, hi = 0.01; + for (let i = 0; i < 40; i++) { const m = (lo + hi) / 2; if (simulateDrop(m, [BL.zero])[BL.zero].y < 0) lo = m; else hi = m; } + WP.zeroAngle = (lo + hi) / 2; + const r = simulateDrop(WP.zeroAngle, [100, 200, 300, 400]); + WP.marks = [100, 200, 300].map(d => ({ d, drop: -r[d].y, ang: Math.atan2(-r[d].y, d), t: r[d].t })); // angle below centre + WP.tof = r; + }; + WP.computeZero(); + + // ---------------------------------------------------------------- loadout + WP.reset = function (loadout) { + loadout = loadout || {}; + WP.inv = { + rifle: { mag: WT.rifle.mag, res: loadout.rifleRes != null ? loadout.rifleRes : WT.rifle.reserve }, + smg: { mag: WT.smg.mag, res: loadout.smgRes != null ? loadout.smgRes : WT.smg.reserve }, + pistol: { mag: WT.pistol.mag, res: WT.pistol.reserve }, + grenades: loadout.grenades != null ? loadout.grenades : WT.grenade.count, rocks: 99 + }; + WP.has = loadout.has || { rifle: true, smg: true, pistol: true }; + WP.cur = loadout.start || 'smg'; WP.aiming = WP.scoped = WP.binoc = false; WP.busyThrow = null; + WP.reloadT = WP.boltT = WP.cool = WP.bloom = 0; WP.bullets.length = 0; WP.throws.length = 0; + WP.stats = { shots: 0, hits: 0, kills: 0, heads: 0, takedowns: 0 }; WP.tagged = new Set(); + // models on the hero + const A = P.actor; + for (const k in WP.models) A.detach(WP.models[k]); + WP.models = { rifle: IVChars.weapon('rifleScoped'), smg: IVChars.weapon('smg'), pistol: IVChars.weapon('pistol'), binoc: IVChars.weapon('binoculars'), grenade: IVChars.weapon('grenade') }; + equipModels(); + }; + function equipModels() { + const A = P.actor, M = WP.models; + IV.fp && IV.fp.beforeAttach && IV.fp.beforeAttach(); + for (const k in M) A.detach(M[k]); + if (WP.binoc) A.attach(M.binoc, 'handR'); + else if (WP.busyThrow) A.attach(M.grenade, 'handR'); + else A.attach(M[WP.cur], 'handR'); + const longOther = WP.cur === 'rifle' ? 'smg' : 'rifle'; + if (WP.has[longOther]) A.attach(M[longOther], 'sling'); // the characters' muzzle-down back carry + if (WP.cur !== 'pistol' && WP.has.pistol) A.attach(M.pistol, 'hip'); + } + WP.equip = function (k) { + if (!WP.has[k] || k === WP.cur || WP.busyThrow) return; + WP.cur = k; WP.reloadT = 0; WP.boltT = 0; WP.cool = 0.35; WP.bloom = 0; + equipModels(); P.actor.setUpper(null); + IV.audio && IV.audio.play('equip'); + IV.emit('weapon', k); + }; + + // ---------------------------------------------------------------- hit spheres (stance templates, local: x lateral, y up, z forward) + const TPL = { + stand: [[0, 1.66, 0.02, 0.12, 'head'], [0, 1.33, 0, 0.21, 'torso'], [0, 1.07, 0, 0.19, 'torso'], [0.11, 0.72, 0, 0.11, 'limb'], [-0.11, 0.72, 0, 0.11, 'limb'], [0.11, 0.32, 0, 0.1, 'limb'], [-0.11, 0.32, 0, 0.1, 'limb'], [0.25, 1.18, 0.08, 0.08, 'limb'], [-0.25, 1.18, 0.08, 0.08, 'limb']], + crouch: [[0, 1.2, 0.14, 0.12, 'head'], [0, 0.92, 0.08, 0.21, 'torso'], [0, 0.66, 0, 0.18, 'torso'], [0.12, 0.42, 0.25, 0.12, 'limb'], [-0.1, 0.2, -0.15, 0.12, 'limb']], + prone: [[0, 0.32, 0.78, 0.12, 'head'], [0, 0.22, 0.4, 0.2, 'torso'], [0, 0.2, 0.05, 0.19, 'torso'], [0.1, 0.14, -0.45, 0.12, 'limb'], [-0.1, 0.14, -0.45, 0.12, 'limb'], [0.1, 0.12, -0.85, 0.1, 'limb'], [-0.1, 0.12, -0.85, 0.1, 'limb']] + }; + WP.spheres = function (e, out) { + out.length = 0; if (!e.alive) return out; + const tpl = TPL[e.stanceKey()] || TPL.stand, y = e.bodyYaw, fx = -Math.sin(y), fz = -Math.cos(y), rx = Math.cos(y), rz = -Math.sin(y); + for (const s of tpl) out.push([e.pos.x + rx * -s[0] + fx * s[2], e.pos.y + s[1], e.pos.z + rz * -s[0] + fz * s[2], s[3], s[4]]); + return out; + }; + const sph = []; + // segment (a -> a + d*len) against a sphere: returns t or -1 + function segSphere(ax, ay, az, dx, dy, dz, len, cx, cy, cz, r) { + const ox = ax - cx, oy = ay - cy, oz = az - cz, b = ox * dx + oy * dy + oz * dz, c = ox * ox + oy * oy + oz * oz - r * r; + const disc = b * b - c; if (disc < 0) return -1; + const t = -b - Math.sqrt(disc); return t >= 0 && t <= len ? t : (c < 0 ? 0 : -1); + } + // every combatant: the player, the squadmate and the enemies + WP.combatants = function () { const l = IV.ai ? IV.ai.list.slice() : []; if (IV.ally && IV.ally.ent) l.push(IV.ally.ent); l.push(WP.playerEnt); return l; }; + WP.playerEnt = { + team: 'us', isPlayer: true, get alive() { return P.alive; }, get pos() { return P.pos; }, get bodyYaw() { return P.bodyYaw; }, + stanceKey: () => P.stance, chestH: () => P.stance === 'prone' ? 0.25 : P.stance === 'crouch' ? 0.9 : 1.3, + hit(zone, dmg, dir, from) { P.hurt(dmg, from); } + }; + + // ---------------------------------------------------------------- bullets + // b: {x,y,z,vx,vy,vz,drag,dmg,owner,team,life,tracer,enemy} + WP.spawnBullet = function (b) { + b.alive = true; b.travelled = 0; b.life = b.life || 2.5; b.drag = b.drag != null ? b.drag : BL.drag; + WP.bullets.push(b); + if (b.tracer) IV.fx.tracer(b); + return b; + }; + const near = []; + function stepBullet(b, dt) { + const x0 = b.x, y0 = b.y, z0 = b.z; + b.x += b.vx * dt; b.y += b.vy * dt; b.z += b.vz * dt; ballStep(b, dt, WP.wind); + const dx = b.x - x0, dy = b.y - y0, dz = b.z - z0, len = Math.sqrt(dx * dx + dy * dy + dz * dz); + b.travelled += len; b.life -= dt; + const ux = dx / len, uy = dy / len, uz = dz / len; + let best = len, hitEnt = null, hitZone = null; + const wh = W.raycast(x0, y0, z0, ux, uy, uz, len, F.BULLET); + if (wh) best = wh.t; + const whit = wh ? { x: wh.x, y: wh.y, z: wh.z, nx: wh.nx, ny: wh.ny, nz: wh.nz, surf: wh.surf, col: wh.col } : null; + // actors + const list = WP.combatants(); + for (const e of list) { + if (!e.alive || e === b.owner || e.team === b.team) continue; + const ex = e.pos.x - x0, ez = e.pos.z - z0, along = ex * ux + ez * uz; + if (along < -2 || along > len + 2) continue; + const lat = Math.abs(ex * uz - ez * ux); if (lat > 2.2) continue; + WP.spheres(e, sph); + for (const s of sph) { const t = segSphere(x0, y0, z0, ux, uy, uz, best, s[0], s[1], s[2], s[3]); if (t >= 0 && t < best) { best = t; hitEnt = e; hitZone = s[4]; } } + // near miss: suppression and the crack of a passing round + if (!hitEnt || hitEnt !== e) { + const cx = e.pos.x, cy = e.pos.y + e.chestH(), cz = e.pos.z; + const t = IV.clamp((cx - x0) * ux + (cy - y0) * uy + (cz - z0) * uz, 0, len); + const d = Math.hypot(x0 + ux * t - cx, y0 + uy * t - cy, z0 + uz * t - cz); + if (d < 2.2 && !b.nearSet) { b.nearSet = true; if (e.isPlayer) { IV.audio && IV.audio.play('whiz'); IV.emit('suppressed', 1 - d / 2.2); } else if (e.suppress) e.suppress(1 - d / 2.2, b.owner); } + } + } + if (hitEnt) { + const hx = x0 + ux * best, hy = y0 + uy * best, hz = z0 + uz * best; + const mul = b.flat ? (hitZone === 'head' ? 1.4 : 1) : hitZone === 'head' ? WT.headMul : hitZone === 'limb' ? WT.limbMul : 1; + const wasAlive = hitEnt.alive; + const fo = b.fall ? IV.clamp(1 - (b.travelled - b.fall[0]) / (b.fall[1] - b.fall[0]), 0, 1) * (1 - b.fall[2]) + b.fall[2] : 1; + hitEnt.hit(hitZone, b.dmg * mul * fo, { x: ux, y: uy, z: uz }, b.owner ? b.owner.pos : null, b); + IV.fx.blood(hx, hy, hz, ux, uy, uz, hitZone === 'head' || b.dmg > 100); + if (b.owner === WP.playerEnt) { + WP.stats.hits++; + const killed = wasAlive && !hitEnt.alive; + if (killed) { WP.stats.kills++; if (hitZone === 'head') WP.stats.heads++; } + IV.emit('hitmarker', { kill: killed, head: hitZone === 'head' }); + IV.audio && IV.audio.play(killed ? 'killThud' : 'hitThud'); + } + b.alive = false; return; + } + if (wh) { + IV.art.impact(whit.surf, whit, { x: whit.nx, y: whit.ny, z: whit.nz }, { x: ux, y: uy, z: uz }); + IV.audio && IV.audio.play('impact', { surf: whit.surf, x: whit.x, z: whit.z }); + if (b.owner === WP.playerEnt && IV.ai) IV.ai.noise(whit.x, whit.z, 9, 'impact', P); + if (whit.col && whit.col.onHit) whit.col.onHit(b); + b.alive = false; return; + } + if (b.life <= 0 || b.y < -50) b.alive = false; + } + + // ---------------------------------------------------------------- the player's actions (fixed step) + const aimPt = new THREE.Vector3(); + function camRayPoint() { // the world point under the reticle + const c = W.camera, d = IV.camera.lookDir; + const h = W.raycast(c.position.x, c.position.y, c.position.z, d.x, d.y, d.z, 600, F.BULLET); + let t = h ? h.t : 600, hs = null; + // actors too + for (const e of WP.combatants()) { + if (!e.alive || e.isPlayer) continue; + WP.spheres(e, sph); + for (const s of sph) { const tt = segSphere(c.position.x, c.position.y, c.position.z, d.x, d.y, d.z, t, s[0], s[1], s[2], s[3]); if (tt >= 0 && tt < t) { t = tt; hs = s.slice(); } } + } + // aim at the middle of the part under the reticle, so the shot from the muzzle (a little off the camera's line) still lands + if (hs) aimPt.set(hs[0], hs[1], hs[2]); else aimPt.set(c.position.x + d.x * t, c.position.y + d.y * t, c.position.z + d.z * t); + return t; + } + WP.camRayPoint = () => { camRayPoint(); return aimPt; }; + const mz = new THREE.Vector3(); + function fire() { + const k = WP.cur, w = WT[k], inv = WP.inv[k], c = W.camera, d = IV.camera.lookDir; + if (inv.mag <= 0) { + IV.audio && IV.audio.play('dry'); WP.cool = 0.3; + if (inv.res > 0) startReload(); + else { const alt = ['pistol', 'smg', 'rifle'].find(x => x !== k && WP.has[x] && WP.inv[x] && WP.inv[x].mag + WP.inv[x].res > 0); if (alt) WP.equip(alt); } // out of rounds: draw the next gun that has any + return; + } + inv.mag--; WP.stats.shots++; WP.lastFire = IV.time; WP.firingRecently = true; + let ox, oy, oz, dx, dy, dz; + const model = WP.models[k], muzzle = model.userData.muzzle; + muzzle.getWorldPosition(mz); + if (IV.fp && IV.fp.on() && !WP.scoped) IV.fp.muzzle(mz); // first person: the flash and tracer start at the visible muzzle + if (WP.scoped) { + // from the scope: start one sight-height below the eye, angled up by the zero angle + const up = new THREE.Vector3(0, 1, 0).applyQuaternion(c.quaternion); + ox = c.position.x - up.x * BL.sightHeight; oy = c.position.y - up.y * BL.sightHeight; oz = c.position.z - up.z * BL.sightHeight; + const right = new THREE.Vector3(1, 0, 0).applyQuaternion(c.quaternion); + const v = d.clone().applyAxisAngle(right, WP.zeroAngle); + dx = v.x; dy = v.y; dz = v.z; + } else { + const dist = camRayPoint(); + // the shot travels along the reticle's line (gunplay skill): it starts where that line passes the player's + // shoulder, so nothing between the camera and you is hit and the bullet goes exactly where the sight points + const cp = c.position, t0 = Math.max(0, (P.pos.x - cp.x) * d.x + (P.eyeY() - 0.2 - cp.y) * d.y + (P.pos.z - cp.z) * d.z); + ox = cp.x + d.x * t0; oy = cp.y + d.y * t0; oz = cp.z + d.z * t0; + if (!W.clear(mz.x, mz.y, mz.z, ox, oy, oz, F.BULLET)) { ox = mz.x; oy = mz.y; oz = mz.z; } // muzzle round a corner: from the muzzle + // from the muzzle toward the point under the reticle (if the muzzle is inside a wall, fire from the camera line) + if (!W.clear(c.position.x, c.position.y, c.position.z, ox, oy, oz, F.BULLET)) { ox = c.position.x + d.x * 0.5; oy = c.position.y + d.y * 0.5; oz = c.position.z + d.z * 0.5; } + // point blank (the muzzle is already past the target): fire from the eye instead + if (Math.hypot(aimPt.x - ox, aimPt.y - oy, aimPt.z - oz) < 1.6 || Math.hypot(aimPt.x - P.pos.x, aimPt.z - P.pos.z) < 2.2) { const f = IV.fwd(P.yaw); ox = P.pos.x - f.z * 0.15; oy = P.eyeY() - 0.1; oz = P.pos.z + f.x * 0.15; } + dx = aimPt.x - ox; dy = aimPt.y - oy; dz = aimPt.z - oz; const l = Math.hypot(dx, dy, dz) || 1; dx /= l; dy /= l; dz /= l; + } + // spread: tight aimed, loose from the hip, bloom for the SMG, worse while moving + let sp = WP.currentSpread(); + if ((WP.aiming || WP.scoped) && P.speed < 0.3 && (k !== 'smg' || WP.burst === 0)) sp = 0; // first aimed shot, standing still: dead on + const a = Math.random() * 6.283, r = Math.sqrt(Math.random()) * sp; + const ux = new THREE.Vector3(dx, dy, dz), ortho1 = new THREE.Vector3().crossVectors(ux, Math.abs(dy) < 0.9 ? new THREE.Vector3(0, 1, 0) : new THREE.Vector3(1, 0, 0)).normalize(), ortho2 = new THREE.Vector3().crossVectors(ux, ortho1); + ux.addScaledVector(ortho1, Math.cos(a) * r).addScaledVector(ortho2, Math.sin(a) * r).normalize(); + const v0 = k === 'rifle' ? BL.v0 : k === 'smg' ? BL.smgV0 : BL.pistolV0; + WP.spawnBullet({ x: ox, y: oy, z: oz, vx: ux.x * v0, vy: ux.y * v0, vz: ux.z * v0, drag: k === 'rifle' ? BL.drag : 0.0012, dmg: w.dmg, fall: w.fall, owner: WP.playerEnt, team: 'us', tracer: k === 'smg' && (WP.stats.shots % 3 === 0), life: k === 'rifle' ? 2.5 : 1.2 }); // tracer rounds every third in the SMG magazine + // effects + IV.fx.muzzle(mz.x, mz.y, mz.z, ux.x, ux.y, ux.z, k === 'rifle'); + const fpArms = IV.fp && IV.fp.realActive && IV.fp.realActive(); // first person on the arms rig: its clip events throw the cases + if (fpArms) { if (model) model.userData.kickT = 1; } + else if (part(model, (PART_KIND[k] || k) + '_ejection')) WP.gunShot(model, PART_KIND[k] || k); // bolt kick and a case from the ejection port + else if (k !== 'rifle') { const rt = new THREE.Vector3(-1, 0, 0).applyQuaternion(model.getWorldQuaternion(new THREE.Quaternion())); IV.fx.casing(mz.x - ux.x * 0.5, mz.y, mz.z - ux.z * 0.5, rt.x * 2.2 + Math.random(), 2 + Math.random(), rt.z * 2.2 + Math.random()); } + IV.audio && IV.audio.play(k, { x: mz.x, z: mz.z }); + IV.ai && IV.ai.noise(P.pos.x, P.pos.z, w.noise, 'shot', P); + // recoil: rifle a big kick, SMG a climbing pattern with a little sideways wander, pistol a snap + const motion = IV.settings.motion ? 0.6 : 1; + if (k === 'smg') { WP.burst++; const pat = Math.sin(WP.burst * 0.9) * 0.5 + (WP.burst > 6 ? 0.4 : 0); IV.camera.kick(w.recoil * (WP.aiming ? 0.7 : 1), -w.recoil * 0.45 * pat); WP.bloom = Math.min(w.bloomMax, WP.bloom + w.bloom); } + else IV.camera.kick(w.recoil * (P.stance === 'prone' ? 0.6 : 1), (Math.random() - 0.5) * w.recoil * 0.3); + IV.camera.shake((k === 'rifle' ? 0.12 : 0.05) * motion); + IV.fp && IV.fp.recoil(k === 'rifle' ? 1 : k === 'smg' ? 0.35 : 0.6); + // the bolt: as long as the arms' fire and bolt clips take in first person, else the tuning value + if (k === 'rifle') { const fl = IV.fp && IV.fp.clipLen ? IV.fp.clipLen(WP.aiming || WP.scoped ? 'fireAds' : 'fire', 'rifle') + IV.fp.clipLen('boltCycle', 'rifle') : 0; WP.boltT = fl > 0.3 && IV.fp.on() ? fl : WT.rifle.bolt; if (!fpArms) setTimeout(() => IV.audio && IV.audio.play('bolt'), 330); } + WP.cool = w.rpm ? 60 / w.rpm : 0.18; + IV.setUpper(P.actor, k === 'rifle' ? 'boltCycle' : 'fire'); + IV.emit('shot', k); + } + // the current spread cone (rad): the HUD crosshair draws exactly this + WP.currentSpread = function () { + const k = WP.cur, w = WT[k]; let sp = (WP.aiming || WP.scoped) ? w.spread : w.hipSpread; + if (k === 'smg') sp += WP.bloom; + if (P.speed > 1) sp *= 1.6; + if (P.stance === 'crouch') sp *= 0.8; else if (P.stance === 'prone') sp *= 0.6; + return sp; + }; + function startReload() { + const k = WP.cur, inv = WP.inv[k]; + if (WP.reloadT > 0 || inv.res <= 0 || inv.mag >= WT[k].mag) return; + WP.reloadT = WT[k].reload; WP.scoped = false; + // first person on the arms rig: rounds go in at the clip's 'magIn' and the reload ends at its 'done' (js/fp.js); + // the timer is only a safety net a little past the clip's end + const rl = IV.fp && IV.fp.onReload ? IV.fp.onReload(inv.mag === 0) : 0; + WP.fpReload = rl > 0.5 ? { magged: false } : null; + if (WP.fpReload) WP.reloadT = rl + 0.4; + P.actor.setUpper('reload'); + if (!WP.fpReload) IV.audio && IV.audio.play('reload', { kind: k }); + } + function finishReload() { + if (!(WP.fpReload && WP.fpReload.magged)) { const k = WP.cur, inv = WP.inv[k], need = WT[k].mag - inv.mag, take = Math.min(need, inv.res); inv.mag += take; inv.res -= take; } + WP.fpReload = null; P.actor.setUpper(WP.aiming ? 'aimIdle' : null); + } + WP.magIn = function () { if (WP.reloadT > 0 && WP.fpReload && !WP.fpReload.magged) { const k = WP.cur, inv = WP.inv[k], take = Math.min(WT[k].mag - inv.mag, inv.res); inv.mag += take; inv.res -= take; WP.fpReload.magged = true; } }; + WP.reloadDone = function () { if (WP.reloadT > 0 && WP.fpReload) { WP.reloadT = 0; finishReload(); } }; + + // grenade / rock throw: hold to aim (arc preview), let go to throw. Grenade fuse runs from the press (cooking). + function throwVel(kind) { + const d = IV.camera.lookDir, v = kind === 'grenade' ? WT.grenade.throwV : WT.rock.throwV; + const up = 0.32 + Math.max(0, d.y) * 0.3; + return { x: d.x * v, y: d.y * v + v * up, z: d.z * v }; + } + function throwOrigin() { const f = IV.fwd(P.yaw), r = { x: -f.z, z: f.x }; return { x: P.pos.x + r.x * 0.25 + f.x * 0.3, y: P.eyeY() + 0.15, z: P.pos.z + r.z * 0.25 + f.z * 0.3 }; } + WP.arc = function () { // predicted path for the preview line + if (!WP.busyThrow) return null; + const o = throwOrigin(), v = throwVel(WP.busyThrow.kind), pts = []; + let x = o.x, y = o.y, z = o.z, vx = v.x, vy = v.y, vz = v.z; + for (let i = 0; i < 60; i++) { + pts.push(x, y, z); + const nx = x + vx * 0.04, ny = y + vy * 0.04, nz = z + vz * 0.04; + const dl = Math.hypot(nx - x, ny - y, nz - z), h = W.raycast(x, y, z, (nx - x) / dl, (ny - y) / dl, (nz - z) / dl, dl, F.SOLID | F.BULLET); + if (h) { pts.push(h.x, h.y, h.z); break; } + x = nx; y = ny; z = nz; vy -= 9.8 * 0.04; + } + return pts; + }; + function release() { + const bt = WP.busyThrow; if (!bt) return; + const o = throwOrigin(), v = throwVel(bt.kind); + WP.throws.push({ kind: bt.kind, x: o.x, y: o.y, z: o.z, vx: v.x, vy: v.y, vz: v.z, fuse: bt.kind === 'grenade' ? WT.grenade.fuse - (IV.time - bt.t0) : 99, rest: false, bounced: 0 }); + if (bt.kind === 'grenade') WP.inv.grenades--; + P.actor.setUpper('throw'); IV.audio && IV.audio.play('throw'); + WP.busyThrow = null; WP.throwCool = 0.5; equipModels(); + IV.emit('threw', bt.kind); + } + function explode(g) { + const R = WT.grenade.radius; + IV.fx.explosion(g.x, g.y, g.z, false); + IV.audio && IV.audio.play('explosion', { x: g.x, z: g.z, big: false }); + IV.camera.shake(IV.clamp(1 - Math.hypot(P.pos.x - g.x, P.pos.z - g.z) / 30, 0, 0.8)); + IV.ai && IV.ai.noise(g.x, g.z, 220, 'explosion', g.owner || P); + for (const e of WP.combatants()) { + if (!e.alive) continue; + const d = Math.hypot(e.pos.x - g.x, e.pos.y + 0.8 - g.y, e.pos.z - g.z); + if (d > R) continue; + if (!W.clear(g.x, g.y + 0.3, g.z, e.pos.x, e.pos.y + e.chestH(), e.pos.z, F.BULLET)) continue; + const dmg = WT.grenade.dmg * Math.pow(1 - d / R, 1.3) * (e.isPlayer ? 0.7 : 1); + const wasAlive = e.alive; + e.hit('torso', dmg, { x: (e.pos.x - g.x) / (d + 0.01), y: 0.4, z: (e.pos.z - g.z) / (d + 0.01) }, { x: g.x, y: g.y, z: g.z }, { explosive: true }); + if (g.player && wasAlive && !e.alive && !e.isPlayer) { WP.stats.kills++; IV.emit('hitmarker', { kill: true }); } + } + IV.emit('explosion', g); + } + WP.explodeAt = (x, y, z, owner) => explode({ x, y, z, owner }); + WP.enemyGrenade = function (from, tx, tz) { + // lob from 'from' (an enemy) to land near (tx,tz) + const ox = from.pos.x, oy = from.pos.y + 1.6, oz = from.pos.z, dx = tx - ox, dz = tz - oz, d = Math.hypot(dx, dz), tf = IV.clamp(d / 12, 0.6, 1.8); + WP.throws.push({ kind: 'grenade', x: ox, y: oy, z: oz, vx: dx / tf, vy: (W.height(tx, tz) - oy + 0.5 * 9.8 * tf * tf) / tf, vz: dz / tf, fuse: 3.6, rest: false, bounced: 0, owner: from, enemy: true }); + IV.audio && IV.audio.play('throw', { x: ox, z: oz }); + }; + function stepThrows(dt) { + for (let i = WP.throws.length - 1; i >= 0; i--) { + const g = WP.throws[i]; + g.fuse -= dt; + if (!g.rest) { + const x0 = g.x, y0 = g.y, z0 = g.z; + g.vy -= 9.8 * dt; g.x += g.vx * dt; g.y += g.vy * dt; g.z += g.vz * dt; + const dx = g.x - x0, dy = g.y - y0, dz = g.z - z0, l = Math.hypot(dx, dy, dz); + const h = l > 0 ? W.raycast(x0, y0, z0, dx / l, dy / l, dz / l, l + 0.06, F.SOLID | F.BULLET) : null; + if (h) { + // bounce off the surface + const vn = g.vx * h.nx + g.vy * h.ny + g.vz * h.nz; + g.vx = (g.vx - 2 * vn * h.nx) * 0.35; g.vy = (g.vy - 2 * vn * h.ny) * 0.3; g.vz = (g.vz - 2 * vn * h.nz) * 0.35; + g.x = h.x + h.nx * 0.06; g.y = h.y + h.ny * 0.06; g.z = h.z + h.nz * 0.06; + g.bounced++; + if (g.kind === 'rock' && g.bounced === 1) { + IV.audio && IV.audio.play('rock', { surf: h.surf, x: g.x, z: g.z }); + IV.ai && IV.ai.noise(g.x, g.z, T.noise.rockHit, 'rock', P); + IV.emit('rockLanded', g); + } else if (g.kind === 'grenade' && g.bounced < 3) IV.audio && IV.audio.play('clink', { x: g.x, z: g.z }); + if (Math.hypot(g.vx, g.vy, g.vz) < 1.2 && h.ny > 0.5) g.rest = true; + } + } + if (g.kind === 'grenade' && g.fuse <= 0) { explode({ x: g.x, y: g.y, z: g.z, player: !g.enemy, owner: g.owner }); WP.throws.splice(i, 1); continue; } + if (g.kind === 'rock' && (g.rest || g.fuse < 90)) { if (g.rest) WP.throws.splice(i, 1); } + } + } + + // knife takedown: from behind, close, the soldier not already fighting you + WP.findTakedown = function () { + if (!IV.ai) return null; + let best = null, bd = WT.takedownRange; + for (const e of IV.ai.list) { + if (!e.alive || e.state === 'combat' || e.busy) continue; + const dx = P.pos.x - e.pos.x, dz = P.pos.z - e.pos.z, d = Math.hypot(dx, dz); + if (d > bd || Math.abs(P.pos.y - e.pos.y) > 0.8) continue; + // angle between where he faces and where you are + const rel = Math.abs(IV.wrapA(IV.yawTo(dx, dz) - e.bodyYaw)); + if (rel < WT.takedownAngle && e.state !== 'suspicious') continue; + if (rel < 1.2) continue; // never from the front + best = e; bd = d; + } + return best; + }; + function takedown(e) { + WP.stats.takedowns++; WP.stats.kills++; + P.frozen = true; WP.aiming = WP.scoped = false; + const f = IV.fwd(e.bodyYaw); + const gap = IVChars.takedownGap || (IVChars.standin ? 0.75 : 0.42); // chars.js clips want 0.42 m + const tx = e.pos.x - f.x * gap, tz = e.pos.z - f.z * gap; + const sx = P.pos.x, sz = P.pos.z; let t = 0; + P.bodyYaw = e.bodyYaw; P.yaw = e.bodyYaw; + P.actor.play('takedown', { fade: 0.1, once: true, restart: true }); P.cineClip = true; + WP.takedownT = IV.time; // first person: the knife viewmodel plays its stab from this time (js/fp.js) + e.takedown(); + IV.audio && IV.audio.play('takedown'); + IV.ai.noise(P.pos.x, P.pos.z, T.noise.takedown, 'step', P); + P.cine = function (dt) { + t += dt; const k = Math.min(1, t / 0.25); + P.pos.x = sx + (tx - sx) * k; P.pos.z = sz + (tz - sz) * k; P.pos.y = W.groundAt(P.pos.x, P.pos.z, P.pos.y); + if (t > (IVChars.standin ? 1.3 : 2.6)) { P.cine = null; P.frozen = false; P.cineClip = false; P.actor.play(P.stance === 'crouch' ? 'crouchIdle' : 'idle', { fade: 0.25 }); } + }; + IV.emit('takedown', e); + } + + WP.step = function (dt) { + const I = IV.input; + WP.cool = Math.max(0, WP.cool - dt); WP.throwCool = Math.max(0, (WP.throwCool || 0) - dt); + if (WP.boltT > 0) { WP.boltT -= dt; if (WP.boltT <= 0) P.actor.setUpper(WP.aiming ? 'aimIdle' : null); } + if (WP.reloadT > 0 && P.sprinting) { WP.reloadT = 0; WP.fpReload = null; P.actor.setUpper(null); IV.fp && IV.fp.cancelAction && IV.fp.cancelAction(); } // sprinting cancels a reload (no rounds added) + if (WP.reloadT > 0) { WP.reloadT -= dt; if (WP.reloadT <= 0) finishReload(); } + WP.bloom = Math.max(0, WP.bloom - dt * (I.held('fire') ? 0.01 : 0.12)); + if (!I.held('fire')) WP.burst = 0; + WP.firingRecently = IV.time - WP.lastFire < 0.6; + // bullets and thrown things always move (also while the player is dead or in a cutscene) + for (let i = WP.bullets.length - 1; i >= 0; i--) { const b = WP.bullets[i]; if (b.alive) stepBullet(b, dt); if (!b.alive) WP.bullets.splice(i, 1); } + stepThrows(dt); + if (!P.alive || P.frozen || P.cine || P.vault || IV.mission.noWeapons) { WP.aiming = WP.scoped = false; WP.binoc = false; return; } + // weapon select + if (I.pressed('rifle')) WP.equip('rifle'); if (I.pressed('smg')) WP.equip('smg'); if (I.pressed('pistol')) WP.equip('pistol'); + if (I.pressed('swap') || I.wheel) { const order = ['rifle', 'smg', 'pistol'].filter(k => WP.has[k]); const i = order.indexOf(WP.cur); WP.equip(order[(i + (I.wheel < 0 ? -1 : 1) + order.length) % order.length]); I.wheel = 0; } + // binoculars (hold) + const wantBinoc = I.held('binoc') && !WP.busyThrow && WP.reloadT <= 0 && WP.has.binoc !== false; + if (wantBinoc !== WP.binoc) { WP.binoc = wantBinoc; equipModels(); IV.setUpper(P.actor, wantBinoc ? 'binoc' : null); if (wantBinoc) IV.audio && IV.audio.play('cloth'); } + if (WP.binoc) { + if (I.pressed('fire')) { const t = IV.camera.findTarget(0.07, 400); if (t && !WP.tagged.has(t.e)) { WP.tagged.add(t.e); t.e.tagged = true; IV.audio && IV.audio.play('tag'); IV.emit('tagged', t.e); } } + WP.aiming = WP.scoped = false; return; + } + // throws + if (!WP.busyThrow && WP.throwCool <= 0 && WP.reloadT <= 0) { + if (I.pressed('grenade') && WP.inv.grenades > 0) { WP.busyThrow = { kind: 'grenade', t0: IV.time }; equipModels(); IV.audio && IV.audio.play('pin'); } + else if (I.pressed('rock')) { WP.busyThrow = { kind: 'rock', t0: IV.time }; equipModels(); } + } + if (WP.busyThrow) { + WP.aiming = WP.scoped = false; + const bt = WP.busyThrow, held = I.held(bt.kind); + const cookedOut = bt.kind === 'grenade' && IV.time - bt.t0 > WT.grenade.fuse - 0.35; + // first person: the throw leaves the hand when the arms' clip reaches its release (js/fp.js holds the cocked pose while the key is held) + if (!held || cookedOut) { if (!(bt.kind === 'grenade' && IV.fp && IV.fp.throwSync && IV.fp.throwSync(bt, cookedOut))) release(); } + return; + } + // takedown (F), shown as a prompt by the HUD when available + WP.takedownTarget = WP.findTakedown(); + if (I.pressed('knife') && WP.takedownTarget) { takedown(WP.takedownTarget); return; } + // aim + const wantAim = I.held('aim') && WP.reloadT <= 0 && !P.sprinting; + if (wantAim && !WP.aiming) IV.camera.onAimStart(WP.cur === 'rifle'); + WP.aiming = wantAim && WP.cur !== 'rifle'; + const scopedNow = wantAim && WP.cur === 'rifle'; + if (scopedNow !== WP.scoped) { WP.scoped = scopedNow; IV.audio && IV.audio.play('cloth', { vol: 0.4 }); } + if (wantAim && WP.boltT <= 0 && WP.reloadT <= 0) P.actor.setUpper('aimIdle'); + else if (!wantAim && IV.upperOf(P.actor) === 'aimIdle') P.actor.setUpper(null); + // reload + if (I.pressed('reload')) startReload(); + // fire + const auto = WT[WP.cur].rpm >= 400; + const trig = auto ? I.held('fire') : I.pressed('fire'); + if (trig && WP.cool <= 0 && WP.reloadT <= 0 && WP.boltT <= 0 && !P.sprinting && !(P.sprintOutT > 0)) fire(); + else if (trig && P.sprinting) P.sprinting = false; + }; + + // grenade arc line (render) + let arcLine = null; + // ---------------------------------------------------------------- moving parts (named empties in weapons.glb) + // Each part moves relative to its rest transform: bolts and charging handles kick back on a shot, triggers pull while + // the trigger is held, the magazine drops out and comes back during a reload, the MG bipod folds down when the gunner + // is set up. chars.js already moves the rifle bolt (boltCycle) and the pistol slide (firePistol). + const PART_KIND = { rifle: 'rifleScoped', smg: 'smg', pistol: 'pistol', binoc: 'binoculars', grenade: 'grenade' }; + function part(model, name) { + if (!model) return null; + const c = model.userData._parts || (model.userData._parts = {}); + if (!(name in c)) { const o = model.getObjectByName(name) || null; if (o) { o.userData.p0 = o.position.clone(); o.userData.r0 = o.rotation.clone(); } c[name] = o; } + return c[name]; + } + WP.part = part; + const kickBack = (o, k, dist) => { if (o) o.position.copy(o.userData.p0).z -= dist * k; }; // barrel is +Z: back is -Z + const pullTrig = (o, k) => { if (o) { o.rotation.copy(o.userData.r0); o.rotation.x -= 0.35 * k; } }; + // a brass case thrown from the ejection port: +Z of the _ejection empty is the way cases fly + const ev = new THREE.Vector3(), eq = new THREE.Quaternion(), ed = new THREE.Vector3(); + WP.ejectCase = function (model, kind) { + const e = part(model, kind + '_ejection'); + if (!e) return false; + e.getWorldPosition(ev); e.getWorldQuaternion(eq); ed.set(0, 0, 1).applyQuaternion(eq); + const s = 2.2 + Math.random() * 0.8; + IV.fx.casing(ev.x, ev.y, ev.z, ed.x * s + (Math.random() - 0.5) * 0.4, ed.y * s + 1.4 + Math.random() * 0.6, ed.z * s + (Math.random() - 0.5) * 0.4); + return true; + }; + // a soldier's (or the player's) gun after a shot: called by the AI too + WP.gunShot = function (model, kind) { + if (!model) return; + model.userData.kickT = 1; + if (kind !== 'rifleScoped' && kind !== 'enemyRifle') WP.ejectCase(model, kind); // bolt-actions eject when the bolt is worked + else model.userData.caseT = 0.45; + }; + // per rendered frame: animate the parts of one gun + WP.animateGun = function (model, kind, dt, o) { + if (!model) return; + const u = model.userData; + if (u.kickT > 0) u.kickT = Math.max(0, u.kickT - dt / 0.06); + if (u.caseT > 0) { u.caseT -= dt; if (u.caseT <= 0) WP.ejectCase(model, kind); } + const kt = u.kickT || 0, k = kt > 0.5 ? (1 - kt) * 2 : kt * 2; // back and home again inside 60 ms + if (kind === 'smg' || kind === 'enemySmg') { kickBack(part(model, kind + '_bolt'), k, 0.07); kickBack(part(model, kind + '_charging'), k, 0.07); } + if (kind === 'mg') { + kickBack(part(model, 'mg_charging'), k, 0.05); + const belt = part(model, 'mg_belt'); if (belt) { belt.rotation.copy(belt.userData.r0); belt.rotation.z += Math.sin(IV.time * 40) * 0.06 * (u.kickT > 0 ? 1 : 0); } + const bip = part(model, 'mg_bipod'); if (bip) { u.bipodK = IV.damp(u.bipodK || 0, o && o.deployed ? 1 : 0, 6, dt); bip.rotation.copy(bip.userData.r0); bip.rotation.x += (u.bipodSign || 1) * u.bipodK * Math.PI / 2; } + } + pullTrig(part(model, kind + '_trigger'), o && o.trigger ? 1 : 0); + // magazine: out at 20-35% of the reload, gone until 60%, back in by 75% + const mag = part(model, kind + '_mag'); + if (mag) { + let d = 0, vis = true; const f = o && o.reload != null ? o.reload : -1; + if (f >= 0.2 && f < 0.35) d = (f - 0.2) / 0.15; else if (f >= 0.35 && f < 0.6) { d = 1; vis = false; } else if (f >= 0.6 && f < 0.75) d = 1 - (f - 0.6) / 0.15; + mag.position.copy(mag.userData.p0); mag.position.y -= d * 0.22; mag.visible = vis; + } + }; + // the MG bipod: pick the fold direction that puts the legs below the gun (the empty's axis sign is not documented) + WP.prepMG = function (model) { + const bip = part(model, 'mg_bipod'); if (!bip || model.userData.bipodSign) return; + const box = new THREE.Box3(), test = s => { bip.rotation.copy(bip.userData.r0); bip.rotation.x += s * Math.PI / 2; model.updateMatrixWorld(true); box.setFromObject(bip); const y = box.min.y; bip.rotation.copy(bip.userData.r0); return y; }; + model.userData.bipodSign = test(1) < test(-1) ? 1 : -1; model.updateMatrixWorld(true); + }; + function playerParts(dt) { + const k = WP.cur, m = WP.models && WP.models[k]; if (!m) return; + const back = WP.models[k === 'rifle' ? 'smg' : 'rifle']; if (back && back.parent && back !== m) back.visible = !(WP.hideSlungWhenAiming && (WP.aiming || WP.scoped)); // the slung gun would cross the head in the aim view + const kind = PART_KIND[k] || k, I = IV.input; + WP.animateGun(m, kind, dt, { trigger: I.held('fire') && !WP.busyThrow, reload: WP.reloadT > 0 ? 1 - WP.reloadT / WT[k].reload : -1 }); + } + + WP.frame = function () { + playerParts(1 / 60); + const pts = WP.busyThrow ? WP.arc() : null; + if (!arcLine || arcLine.parent !== W.scene) { + arcLine = new THREE.Line(new THREE.BufferGeometry(), new THREE.LineDashedMaterial({ color: 0xf0e6c8, dashSize: 0.3, gapSize: 0.2, transparent: true, opacity: 0.8, depthTest: false })); + arcLine.geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(64 * 3), 3)); + arcLine.frustumCulled = false; arcLine.renderOrder = 9; W.scene.add(arcLine); + } + if (pts) { const a = arcLine.geometry.attributes.position.array; a.set(pts.slice(0, 192)); arcLine.geometry.setDrawRange(0, Math.min(64, pts.length / 3)); arcLine.geometry.attributes.position.needsUpdate = true; arcLine.computeLineDistances(); arcLine.visible = true; } + else arcLine.visible = false; + // grenade/rock meshes in flight + // grenades are the real models (the enemy's is the stick grenade), rocks a small stone; each tumbles in flight + WP.throwMeshes = WP.throwMeshes || {}; + const used = {}; + for (const g of WP.throws) { + const key = g.kind === 'rock' ? 'rock' : g.enemy ? 'stickGrenade' : 'grenade'; + const pool = WP.throwMeshes[key] || (WP.throwMeshes[key] = []), n = used[key] = (used[key] || 0) + 1; + while (pool.length < n) { + let m = key !== 'rock' && window.IVChars && IVChars.weapon ? IVChars.weapon(key) : null; + if (!m) m = new THREE.Mesh(new THREE.SphereGeometry(0.05, 8, 6), new THREE.MeshStandardMaterial({ color: key === 'rock' ? 0x77736a : 0x4a5030, roughness: 0.8 })); + pool.push(m); + } + const m = pool[n - 1]; if (m.parent !== W.scene) W.scene.add(m); + m.visible = true; m.position.set(g.x, g.y, g.z); + if (!g.rest) { g.spin = (g.spin || 0) + Math.hypot(g.vx, g.vz) * 0.016 * 2.5; m.rotation.set(g.spin, Math.atan2(g.vx, g.vz), 0); } + else m.rotation.x = Math.PI / 2; // lying on the ground + } + for (const key in WP.throwMeshes) WP.throwMeshes[key].forEach((m, i) => { if (i >= (used[key] || 0)) m.visible = false; }); + }; +})(); diff --git a/e63334287a3deaa3/ironveil/js/world.js b/e63334287a3deaa3/ironveil/js/world.js new file mode 100644 index 00000000..bfdcd664 --- /dev/null +++ b/e63334287a3deaa3/ironveil/js/world.js @@ -0,0 +1,639 @@ +/* Ironveil world: renderer, quality presets, sky and light, the terrain heightfield, static colliders in a spatial hash, + ray casts (bullets, sight), ground height, surfaces and concealment, and how lit a point is (for stealth). + Colliders are boxes turned about Y: {x,z,hx,hz,c,s,y0,y1,f,surf,kind}. Flags in f: */ +(function () { + 'use strict'; + const T = IV.TUNING; + const F = IV.CF = { SOLID: 1, SIGHT: 2, BULLET: 4, VAULT: 8, NAV: 16, LOW: 32 }; + const SURF = IV.SURF = ['grass', 'mud', 'gravel', 'stone', 'wood', 'water', 'crops', 'tallgrass']; + const S = {}; SURF.forEach((n, i) => S[n] = i); IV.S = S; + + const W = IV.world = { + renderer: null, scene: null, camera: null, quality: 1, + size: 0, half: 0, N: 0, heights: null, surf: null, + colliders: [], hash: new Map(), stamp: 1, + lamps: [], flashes: [], roofs: [], waterY: -99, day: false, moonDir: new THREE.Vector3(-0.45, 0.8, 0.38).normalize(), + dynamic: null, statics: null + }; + + // ---------------------------------------------------------------- quality presets + W.PRESETS = [ + { name: 'Low', pr: 0.85, aa: false, shadow: 0, grass: 1600, grassR: 22, points: 3, fogMul: 1.25, crops: 0.55, hedgeDetail: 0 }, + { name: 'Medium', pr: 1, aa: true, shadow: 1024, grass: 4200, grassR: 32, points: 5, fogMul: 1, crops: 0.8, hedgeDetail: 1 }, + { name: 'High', pr: 1.5, aa: true, shadow: 2048, grass: 7000, grassR: 42, points: 6, fogMul: 1, crops: 1, hedgeDetail: 1 } + ]; + + W.init = function (canvas) { + const q = W.quality = IV.clamp(+IV.settings.quality | 0, 0, 2), P = W.P = W.PRESETS[q]; + const r = W.renderer = new THREE.WebGLRenderer({ canvas, antialias: P.aa, powerPreference: 'high-performance', preserveDrawingBuffer: IV.test }); + r.setPixelRatio(Math.min(devicePixelRatio || 1, P.pr)); + r.outputEncoding = THREE.sRGBEncoding; + r.toneMapping = THREE.ACESFilmicToneMapping; + r.toneMappingExposure = 0.92; + r.shadowMap.enabled = P.shadow > 0; + r.shadowMap.type = THREE.PCFSoftShadowMap; + r.shadowMap.autoUpdate = true; + W.scene = new THREE.Scene(); + W.camera = new THREE.PerspectiveCamera(68, 1, 0.08, 900); + W.maxAniso = r.capabilities.getMaxAnisotropy(); + W.resize(); + addEventListener('resize', W.resize); + }; + // one place that draws a frame: IVEnv's post stack when there is one (not on Low), else the plain renderer + W.draw = function (dt) { if (W.post) W.post.render(dt); else W.renderer.render(W.scene, W.camera); }; + W.resize = function () { + const w = innerWidth, h = innerHeight; + W.renderer.setSize(w, h, false); + W.camera.aspect = w / h; W.camera.updateProjectionMatrix(); + if (W.post && W.post.setSize) W.post.setSize(w, h); + const hc = IV.$('hudc'), d = Math.min(devicePixelRatio || 1, 2); + hc.width = Math.round(w * d); hc.height = Math.round(h * d); + IV.emit('resize'); + }; + + // ---------------------------------------------------------------- textures (drawn once on canvases) + const texCache = {}; + function canvasTex(key, size, draw, srgb) { + if (texCache[key]) return texCache[key]; + const c = document.createElement('canvas'); c.width = c.height = size; + const g = c.getContext('2d'); draw(g, size, IV.rng(key.length * 7919 + size)); + const t = new THREE.CanvasTexture(c); + t.wrapS = t.wrapT = THREE.RepeatWrapping; t.anisotropy = Math.min(8, W.maxAniso || 1); + if (srgb !== false) t.encoding = THREE.sRGBEncoding; + texCache[key] = t; return t; + } + function speckle(g, n, R, s, cols, a0, a1, r0, r1) { + for (let i = 0; i < n; i++) { g.globalAlpha = R.range(a0, a1); g.fillStyle = R.pick(cols); const r = R.range(r0, r1); g.fillRect(R() * s, R() * s, r, r); } + g.globalAlpha = 1; + } + function noiseFill(g, s, base, amp, scale, R) { + const img = g.createImageData(s, s), d = img.data, ox = R() * 100; + for (let y = 0; y < s; y++) for (let x = 0; x < s; x++) { + // tileable: sample noise on a torus-ish by wrapping coordinates with periodic blend + const u = x / s, v = y / s; + const n = periodicFbm(u, v, scale, ox); + const k = (y * s + x) * 4, val = (n - 0.5) * amp; + d[k] = IV.clamp(base[0] + val, 0, 255); d[k + 1] = IV.clamp(base[1] + val, 0, 255); d[k + 2] = IV.clamp(base[2] + val, 0, 255); d[k + 3] = 255; + } + g.putImageData(img, 0, 0); + } + function periodicFbm(u, v, scale, o) { // tileable fbm by blending four offset samples + const a = IV.fbm(u * scale + o, v * scale, 4), b = IV.fbm((u - 1) * scale + o, v * scale, 4); + const c = IV.fbm(u * scale + o, (v - 1) * scale, 4), d = IV.fbm((u - 1) * scale + o, (v - 1) * scale, 4); + const ab = a * (1 - u) + b * u, cd = c * (1 - u) + d * u; + return ab * (1 - v) + cd * v; + } + W.tex = { + // grey detail textures (mean ~ 0.5): the hue comes from vertex colours + grass: () => canvasTex('grass', 256, (g, s, R) => { + noiseFill(g, s, [128, 128, 128], 70, 6, R); + for (let i = 0; i < 2600; i++) { const x = R() * s, y = R() * s, l = R.range(3, 9); g.strokeStyle = R() < 0.5 ? 'rgba(200,200,200,.35)' : 'rgba(40,40,40,.35)'; g.lineWidth = 1; g.beginPath(); g.moveTo(x, y); g.lineTo(x + R.range(-2, 2), y - l); g.stroke(); } + }, false), + mud: () => canvasTex('mud', 256, (g, s, R) => { + noiseFill(g, s, [128, 128, 128], 90, 8, R); + speckle(g, 900, R, s, ['#5a5a5a', '#a0a0a0', '#303030'], 0.3, 0.7, 1, 3); + for (let i = 0; i < 26; i++) { g.strokeStyle = 'rgba(40,40,40,.35)'; g.lineWidth = R.range(2, 5); g.beginPath(); const y = R() * s; g.moveTo(0, y); g.bezierCurveTo(s * 0.3, y + R.range(-20, 20), s * 0.6, y + R.range(-20, 20), s, y); g.stroke(); } + }, false), + stone: () => canvasTex('stone', 512, (g, s, R) => { // rubble stone wall, drawn as rough courses + g.fillStyle = '#6d6a62'; g.fillRect(0, 0, s, s); + let y = 0; + while (y < s) { + const h = R.range(26, 46); let x = -R.range(0, 40); + while (x < s) { + const w = R.range(36, 80), sh = 150 + R.range(-30, 30) | 0; + g.fillStyle = `rgb(${sh},${sh - 4},${sh - 14})`; + g.beginPath(); g.moveTo(x + 3, y + 3); g.lineTo(x + w - 3, y + 2 + R() * 3); g.lineTo(x + w - 2, y + h - 3); g.lineTo(x + 2 + R() * 3, y + h - 2); g.closePath(); g.fill(); + g.fillStyle = 'rgba(255,255,255,.08)'; g.fillRect(x + 4, y + 3, w - 8, 3); + x += w; + } + y += h; + } + speckle(g, 3000, R, s, ['#000', '#fff'], 0.03, 0.1, 1, 3); + }), + plaster: () => canvasTex('plaster', 256, (g, s, R) => { noiseFill(g, s, [196, 188, 170], 34, 5, R); speckle(g, 500, R, s, ['#8a8270', '#fff'], 0.1, 0.25, 1, 4); }), + wood: () => canvasTex('wood', 256, (g, s, R) => { + g.fillStyle = '#7a5a3a'; g.fillRect(0, 0, s, s); + const n = 8; + for (let i = 0; i < n; i++) { + const x = i * s / n, sh = R.range(-18, 18); + g.fillStyle = `rgb(${120 + sh},${90 + sh},${58 + sh})`; g.fillRect(x + 1, 0, s / n - 2, s); + for (let k = 0; k < 14; k++) { g.strokeStyle = 'rgba(40,25,10,.25)'; g.lineWidth = 1; g.beginPath(); const xx = x + R() * s / n; g.moveTo(xx, 0); g.bezierCurveTo(xx + R.range(-3, 3), s * 0.3, xx + R.range(-3, 3), s * 0.7, xx, s); g.stroke(); } + g.fillStyle = 'rgba(20,12,4,.6)'; g.fillRect(x, 0, 1.5, s); + } + }), + roof: () => canvasTex('roof', 256, (g, s, R) => { // slate/tile rows + g.fillStyle = '#3d3a3a'; g.fillRect(0, 0, s, s); + const rows = 10, h = s / rows; + for (let r = 0; r < rows; r++) for (let x = -(r % 2) * 14; x < s; x += 28) { + const sh = R.range(-14, 14) | 0; g.fillStyle = `rgb(${86 + sh},${76 + sh},${72 + sh})`; + g.fillRect(x + 1, r * h + 1, 26, h - 2); g.fillStyle = 'rgba(0,0,0,.35)'; g.fillRect(x + 1, r * h + h - 4, 26, 3); + } + }), + foliage: () => canvasTex('foliage', 256, (g, s, R) => { + g.fillStyle = '#7e7e7e'; g.fillRect(0, 0, s, s); + for (let i = 0; i < 2600; i++) { + const x = R() * s, y = R() * s, r = R.range(3, 7), sh = R.range(60, 200) | 0; + g.fillStyle = `rgb(${sh},${sh},${sh})`; g.beginPath(); g.ellipse(x, y, r, r * 0.55, R() * 3.14, 0, 6.29); g.fill(); + } + }, false), + bark: () => canvasTex('bark', 128, (g, s, R) => { g.fillStyle = '#5a4c3e'; g.fillRect(0, 0, s, s); for (let i = 0; i < 90; i++) { g.strokeStyle = R() < 0.5 ? 'rgba(20,15,10,.5)' : 'rgba(140,125,105,.25)'; g.lineWidth = R.range(1, 3); const x = R() * s; g.beginPath(); g.moveTo(x, 0); g.lineTo(x + R.range(-6, 6), s); g.stroke(); } }), + cloth: () => canvasTex('cloth', 128, (g, s, R) => { noiseFill(g, s, [150, 140, 112], 40, 10, R); for (let i = 0; i < s; i += 4) { g.fillStyle = 'rgba(0,0,0,.06)'; g.fillRect(0, i, s, 1); g.fillRect(i, 0, 1, s); } }), + metal: () => canvasTex('metal', 128, (g, s, R) => { noiseFill(g, s, [90, 96, 84], 26, 12, R); speckle(g, 300, R, s, ['#3b2a1a', '#b0a890'], 0.1, 0.3, 1, 3); }), + gravel: () => canvasTex('gravel', 256, (g, s, R) => { noiseFill(g, s, [128, 128, 128], 50, 12, R); speckle(g, 5000, R, s, ['#e0e0e0', '#404040', '#909090'], 0.25, 0.6, 1, 3); }, false), + wheat: () => canvasTex('wheat', 128, (g, s, R) => { // alpha card for crops + g.clearRect(0, 0, s, s); + for (let i = 0; i < 46; i++) { + const x = R.range(4, s - 4), top = R.range(4, 40), sh = R.range(150, 220) | 0; + g.strokeStyle = `rgb(${sh},${sh - 20},${sh - 90})`; g.lineWidth = R.range(1, 2.2); g.beginPath(); g.moveTo(x + R.range(-6, 6), s); g.quadraticCurveTo(x, (s + top) / 2, x + R.range(-4, 4), top); g.stroke(); + g.fillStyle = `rgb(${sh + 20},${sh},${sh - 80})`; g.beginPath(); g.ellipse(x, top + 5, 2.2, 7, 0, 0, 6.29); g.fill(); + } + }), + grassCard: () => canvasTex('grassCard', 128, (g, s, R) => { + g.clearRect(0, 0, s, s); + for (let i = 0; i < 70; i++) { + const x = R.range(6, s - 6), top = R.range(10, 70), sh = R.range(120, 230) | 0; + g.strokeStyle = `rgb(${sh},${sh},${sh})`; g.lineWidth = R.range(1.2, 2.6); g.beginPath(); g.moveTo(x, s); g.quadraticCurveTo(x + R.range(-6, 6), (s + top) / 2, x + R.range(-14, 14), top); g.stroke(); + } + }), + leafCard: () => canvasTex('leafCard', 128, (g, s, R) => { + g.clearRect(0, 0, s, s); + for (let i = 0; i < 260; i++) { + const a = R() * 6.28, rr = Math.sqrt(R()) * s * 0.46, x = s / 2 + Math.cos(a) * rr, y = s / 2 + Math.sin(a) * rr, sh = R.range(110, 235) | 0; + g.fillStyle = `rgb(${sh},${sh},${sh})`; g.beginPath(); g.ellipse(x, y, R.range(3, 6), R.range(1.6, 3), R() * 3.14, 0, 6.29); g.fill(); + } + }), + glow: () => canvasTex('glow', 64, (g, s) => { const gr = g.createRadialGradient(s / 2, s / 2, 0, s / 2, s / 2, s / 2); gr.addColorStop(0, 'rgba(255,255,255,1)'); gr.addColorStop(0.25, 'rgba(255,255,255,.5)'); gr.addColorStop(1, 'rgba(255,255,255,0)'); g.fillStyle = gr; g.fillRect(0, 0, s, s); }), + smoke: () => canvasTex('smoke', 64, (g, s, R) => { for (let i = 0; i < 18; i++) { const x = s / 2 + R.range(-12, 12), y = s / 2 + R.range(-12, 12), r = R.range(8, 20); const gr = g.createRadialGradient(x, y, 0, x, y, r); gr.addColorStop(0, 'rgba(255,255,255,.35)'); gr.addColorStop(1, 'rgba(255,255,255,0)'); g.fillStyle = gr; g.fillRect(0, 0, s, s); } }) + }; + + // ---------------------------------------------------------------- materials + W.mats = {}; + function std(o) { return new THREE.MeshStandardMaterial(Object.assign({ roughness: 0.92, metalness: 0 }, o)); } + // r128 has no colour management: hex colours are linear unless converted. Everything here is authored in sRGB. + const linDone = new WeakSet(); + W.linearize = function (root) { + root.traverse(o => { const ms = o.material ? (Array.isArray(o.material) ? o.material : [o.material]) : []; for (const m of ms) { if (linDone.has(m)) continue; linDone.add(m); if (m.userData.linear) continue; if (m.color) m.color.convertSRGBToLinear(); if (m.emissive) m.emissive.convertSRGBToLinear(); } }); // IVEnv materials are already linear (colour and emissive): skipped + }; + W.makeMats = function () { + const t = W.tex, M = W.mats; + if (M.stone) return M; + M.stone = std({ map: t.stone(), bumpMap: t.stone(), bumpScale: 0.03, color: 0xb8b2a4, vertexColors: true }); + M.plaster = std({ map: t.plaster(), color: 0xd8d0bc, vertexColors: true }); + M.wood = std({ map: t.wood(), bumpMap: t.wood(), bumpScale: 0.01, color: 0xa08868, vertexColors: true }); + M.roof = std({ map: t.roof(), bumpMap: t.roof(), bumpScale: 0.02, color: 0x9a9090, vertexColors: true }); + M.metal = std({ map: t.metal(), color: 0x8a8f80, metalness: 0.55, roughness: 0.55, vertexColors: true }); + M.cloth = std({ map: t.cloth(), color: 0xb0a480, vertexColors: true }); + M.earth = std({ map: t.mud(), color: 0x6a5a44, vertexColors: true }); + M.bark = std({ map: t.bark(), color: 0x9a8a78, vertexColors: true }); + M.plain = std({ vertexColors: true, roughness: 0.8 }); + M.lit = new THREE.MeshBasicMaterial({ color: 0xffc070, toneMapped: false }); // lit windows + M.litDim = new THREE.MeshBasicMaterial({ color: 0x8a5a26, toneMapped: false }); + M.dark = new THREE.MeshBasicMaterial({ color: 0x0b0c0e }); // unlit window glass + M.foliage = std({ map: t.foliage(), vertexColors: true, roughness: 1 }); + M.foliage.onBeforeCompile = windPatch(0.07, 1.6); + // leaf cards a little darker than the clumps, so a light raking across them doesn't blow out to white speckle + M.leafCard = std({ map: t.leafCard(), alphaTest: 0.5, side: THREE.DoubleSide, vertexColors: true, roughness: 1, color: 0x8a8a8a }); + M.leafCard.onBeforeCompile = windPatch(0.1, 1.9); + return M; + }; + // Wind sway for instanced vegetation: vertices bend by height above the instance origin. + W.windU = { value: 0 }; + W.grassClear = { value: new THREE.Vector4(0, 0, 0, 0) }; + // r128 keys a compiled program on onBeforeCompile.toString(): every call of this patch has the same source but bakes + // its own amp/freq into the shader, so each patch gets its own toString (and so its own program) + function windPatch(amp, freq) { + const f = function (sh) { + // cards: both faces light like the front (no dark backs) + sh.fragmentShader = sh.fragmentShader.replace('#include ', THREE.ShaderChunk.normal_fragment_begin.replace(/normal\s*=\s*normal\s*\*\s*faceDirection;/g, '').replace(/normal\s*\*=\s*faceDirection;/g, '')); + sh.uniforms.uTime = W.windU; + sh.vertexShader = 'uniform float uTime;\n' + sh.vertexShader.replace('#include ', `#include + #ifdef USE_INSTANCING + vec3 ip = vec3(instanceMatrix[3][0], instanceMatrix[3][1], instanceMatrix[3][2]); + #else + vec3 ip = vec3(0.0); + #endif + float hgt = max(position.y, 0.0); + float ph = ip.x * 0.37 + ip.z * 0.29; + transformed.x += sin(uTime * ${freq.toFixed(2)} + ph) * ${amp.toFixed(3)} * hgt; + transformed.z += cos(uTime * ${(freq * 0.83).toFixed(2)} + ph * 1.3) * ${(amp * 0.6).toFixed(3)} * hgt;`); + }; + f.toString = () => 'ivwind:' + amp + ':' + freq; + return f; + } + W.windPatch = windPatch; + + // ---------------------------------------------------------------- level lifecycle + W.clearLevel = function () { + const sc = W.scene; + for (let i = sc.children.length - 1; i >= 0; i--) { + const o = sc.children[i]; + sc.remove(o); + o.traverse(n => { if (n.geometry && !n.userData.keepGeo) n.geometry.dispose(); }); + } + W.colliders = []; W.hash = new Map(); W.lamps = []; W.flashes = []; W.roofs = []; W.waterPolys = []; W.cullList = []; + IV.art && IV.art.reset(); + W.statics = new THREE.Group(); W.dynamic = new THREE.Group(); sc.add(W.statics); sc.add(W.dynamic); + }; + + // cfg: {size, height(x,z), surface(x,z)->index, day, fog, waterY} + W.setupLevel = function (cfg) { + W.clearLevel(); + W.makeMats(); + const P = W.P; + W.day = !!cfg.day; + W.size = cfg.size; W.half = cfg.size / 2; W.N = cfg.size + 1; W.waterY = cfg.waterY != null ? cfg.waterY : -99; + W.waterLevel = cfg.waterLevel || (() => W.waterY); + W.cfg = cfg; + const N = W.N, h = W.heights = new Float32Array(N * N), sf = W.surf = new Uint8Array(N * N); + for (let j = 0; j < N; j++) for (let i = 0; i < N; i++) { + const x = i - W.half, z = j - W.half; + h[j * N + i] = cfg.height(x, z); + sf[j * N + i] = cfg.surface ? cfg.surface(x, z) : 0; + } + lights(cfg); + if (!W.atm) sky(cfg); + // IVEnv's post stack (sharpening, grading, bloom...) on Medium and High + W.post = IV.art.envOn() && window.IVEnv.post ? window.IVEnv.post(W.renderer, W.scene, W.camera, ['low', 'medium', 'high'][W.quality]) : null; + terrain(cfg); + }; + + function lights(cfg) { + const sc = W.scene, P = W.P, day = W.day; + // IVEnv atmosphere presets replace the moon, sky fill and fog here (see art.js) + const atm = W.atm = IV.art && IV.art.atmosphere(cfg); + if (atm) { W.sun = atm.sun; W.hemi = atm.hemi; if (!sc.fog) sc.fog = new THREE.FogExp2(0x0c131c, 0.012); } + else { + sc.fog = new THREE.FogExp2(cfg.fogColor || (day ? 0xb9c4c8 : 0x0d1520), (cfg.fog || (day ? 0.0036 : 0.0175)) * P.fogMul); + sc.background = new THREE.Color(cfg.fogColor || (day ? 0xb9c4c8 : 0x0d1520)); + sc.fog.color.convertSRGBToLinear(); // fog is added in linear space, then encoded like the materials + const hemi = W.hemi = new THREE.HemisphereLight(day ? 0xb0bccc : 0x5b6f9c, day ? 0x403a2e : 0x1e1e1a, day ? 0.5 : 0.34); + sc.add(hemi); + const sun = W.sun = new THREE.DirectionalLight(day ? 0xf4e8d4 : 0x96b0e6, day ? 1.5 : 0.66); + W.moonDir.set(...(cfg.sunDir || (day ? [0.5, 0.75, 0.3] : [-0.45, 0.8, 0.38]))).normalize(); + sun.position.copy(W.moonDir).multiplyScalar(80); + sc.add(sun); sc.add(sun.target); + if (P.shadow) { + sun.castShadow = true; + sun.shadow.mapSize.set(P.shadow, P.shadow); + const s = W.shadowR = P.shadow > 1024 ? 42 : 34; + Object.assign(sun.shadow.camera, { left: -s, right: s, top: s, bottom: -s, near: 1, far: 220 }); + sun.shadow.bias = -0.0006; sun.shadow.normalBias = 0.04; + sun.shadow.radius = 2.5; + } + // A fixed pool of point lights: the nearest lamps get them each frame (changing the light count recompiles shaders). + } + W.pointPool = []; + for (let i = 0; i < P.points; i++) { const l = new THREE.PointLight(0xffb060, 0, 14, 2); sc.add(l); W.pointPool.push(l); } + W.flashLight = new THREE.PointLight(0xffc880, 0, 12, 2); sc.add(W.flashLight); + W.spot = null; + } + W.addSpot = function () { // the searchlight + const s = W.spot = new THREE.SpotLight(0xe8eeff, 0, 140, 0.11, 0.35, 1.2); + W.scene.add(s); W.scene.add(s.target); return s; + }; + + function sky(cfg) { + const day = W.day, fogC = new THREE.Color(cfg.fogColor || (day ? 0xb9c4c8 : 0x0d1520)); + const top = new THREE.Color(day ? 0x5d86b8 : 0x05070c); + const mat = new THREE.ShaderMaterial({ + side: THREE.BackSide, depthWrite: false, fog: false, + uniforms: { top: { value: top }, hor: { value: fogC }, glowDir: { value: W.moonDir }, glowC: { value: new THREE.Color(day ? 0xfff2d0 : 0x6e86b0) } }, + vertexShader: 'varying vec3 vD; void main(){ vD = normalize(position); gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0); gl_Position.z = gl_Position.w; }', + fragmentShader: 'uniform vec3 top; uniform vec3 hor; uniform vec3 glowDir; uniform vec3 glowC; varying vec3 vD;\n' + + 'void main(){ float h = clamp(vD.y, 0.0, 1.0); vec3 c = mix(hor, top, pow(h, 0.45)); float g = max(dot(vD, glowDir), 0.0);\n' + + ' c += glowC * (pow(g, 24.0) * 0.35 + pow(g, 600.0) * 1.5); if (vD.y < 0.0) c = hor; gl_FragColor = vec4(c, 1.0); }' + }); + const dome = new THREE.Mesh(new THREE.SphereGeometry(600, 24, 12), mat); + dome.renderOrder = -10; dome.frustumCulled = false; + W.skyDome = dome; W.scene.add(dome); + if (!day) { // stars and the moon disc + const n = 900, p = new Float32Array(n * 3), R = IV.rng(77); + for (let i = 0; i < n; i++) { const a = R() * 6.283, y = R.range(0.12, 1), r = Math.sqrt(1 - y * y); p[i * 3] = Math.cos(a) * r * 560; p[i * 3 + 1] = y * 560; p[i * 3 + 2] = Math.sin(a) * r * 560; } + const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.BufferAttribute(p, 3)); + const st = new THREE.Points(g, new THREE.PointsMaterial({ color: 0xcfd8ff, size: 1.6, sizeAttenuation: false, fog: false, transparent: true, opacity: 0.75, depthWrite: false })); + st.renderOrder = -9; st.frustumCulled = false; dome.add(st); + const moon = new THREE.Sprite(new THREE.SpriteMaterial({ map: W.tex.glow(), color: 0xe8eeff, fog: false, depthWrite: false, toneMapped: false })); + moon.position.copy(W.moonDir).multiplyScalar(540); moon.scale.set(34, 34, 1); dome.add(moon); + const disc = new THREE.Mesh(new THREE.CircleGeometry(7, 24), new THREE.MeshBasicMaterial({ color: 0xf4f2e6, fog: false, toneMapped: false })); + disc.position.copy(W.moonDir).multiplyScalar(545); disc.lookAt(0, 0, 0); dome.add(disc); + } + } + + // ---------------------------------------------------------------- terrain + W.height = function (x, z) { + const N = W.N, fx = IV.clamp(x + W.half, 0, N - 1.001), fz = IV.clamp(z + W.half, 0, N - 1.001); + const i = fx | 0, j = fz | 0, u = fx - i, v = fz - j, h = W.heights, k = j * N + i; + return (h[k] * (1 - u) + h[k + 1] * u) * (1 - v) + (h[k + N] * (1 - u) + h[k + N + 1] * u) * v; + }; + W.normal = function (x, z, out) { + const e = 0.75, nx = W.height(x - e, z) - W.height(x + e, z), nz = W.height(x, z - e) - W.height(x, z + e); + return (out || new THREE.Vector3()).set(nx, 2 * e, nz).normalize(); + }; + W.surfAt = function (x, z) { + const i = Math.round(x + W.half), j = Math.round(z + W.half); + if (i < 0 || j < 0 || i >= W.N || j >= W.N) return 0; + return W.surf[j * W.N + i]; + }; + // ---- hooks for the environment art (IVEnv): one terrain height, one ground-kind map, the characters that bend grass + W.heightAt = (x, z) => W.height(x, z); // the same height physics, placement and rendering use + // IVEnv's vocabulary. Grass grows on grass, pasture, meadow, tussock, verge, lanemid, worn, leaves, yardedge; bare: lane, + // mud, yard, road, gravel, cobbles, field (crops), water, floor, none. Meadow (long grass) and field (crops) are also the + // stealth cover (the player and ai.js read this same function), so what looks like cover is cover. + const KIND = { grass: 'grass', tallgrass: 'meadow', mud: 'mud', gravel: 'road', crops: 'field', water: 'water', stone: 'yard', wood: 'floor' }; + W.surfaceAt = function (x, z) { + if (W.underRoof(x, z)) return 'floor'; + if (W.cfg && W.cfg.surfaceKind) { const k = W.cfg.surfaceKind(x, z); if (k) return k; } + return KIND[SURF[W.surfAt(x, z)]] || 'grass'; + }; + // up to 8 characters near the camera: {x, z, r, crouch, prone} + W.pushers = []; + W.updatePushers = function () { + const out = W.pushers; out.length = 0; const P = IV.player, c = W.camera.position; + if (P.actor) out.push({ x: P.render.x, z: P.render.z, r: P.stance === 'prone' ? 0.9 : 0.5, crouch: P.stance === 'crouch', prone: P.stance === 'prone' }); + const al = IV.ally && IV.ally.ent; if (al) out.push({ x: al.pos.x, z: al.pos.z, r: al.stance === 'prone' ? 0.9 : 0.5, crouch: al.stance === 'crouch', prone: al.stance === 'prone' }); + const es = (IV.ai ? IV.ai.list : []).filter(e => e.alive || e.landed).map(e => ({ e, d: (e.pos.x - c.x) ** 2 + (e.pos.z - c.z) ** 2 })).sort((a, b) => a.d - b.d); + for (const { e } of es) { if (out.length >= 8) break; out.push({ x: e.pos.x, z: e.pos.z, r: e.alive ? 0.5 : 1.0, crouch: e.stance === 'crouch', prone: !e.alive || e.stance === 'prone' }); } + return out; + }; + W.setSurf = function (x, z, v) { const i = Math.round(x + W.half), j = Math.round(z + W.half); if (i >= 0 && j >= 0 && i < W.N && j < W.N) W.surf[j * W.N + i] = v; }; + + function terrain(cfg) { + // IVEnv draws the ground from the same height function when it is loaded + const eg = IV.art.ground(cfg); + if (eg) { W.terrainMesh = eg.group || eg; W.statics.add(W.terrainMesh); return; } + const step = cfg.terrainStep || (W.quality === 0 ? 4 : 2), n = Math.floor(W.size / step) + 1, half = W.half; + const pos = new Float32Array(n * n * 3), nor = new Float32Array(n * n * 3), col = new Float32Array(n * n * 3), mud = new Float32Array(n * n); + const v3 = new THREE.Vector3(), c = new THREE.Color(); + for (let j = 0; j < n; j++) for (let i = 0; i < n; i++) { + const k = j * n + i, x = i * step - half, z = j * step - half, y = W.height(x, z); + pos[k * 3] = x; pos[k * 3 + 1] = y; pos[k * 3 + 2] = z; + W.normal(x, z, v3); nor[k * 3] = v3.x; nor[k * 3 + 1] = v3.y; nor[k * 3 + 2] = v3.z; + const r = cfg.groundColor(x, z, y, v3, c); c.convertSRGBToLinear(); col[k * 3] = c.r; col[k * 3 + 1] = c.g; col[k * 3 + 2] = c.b; mud[k] = r || 0; + } + const idx = new Uint32Array((n - 1) * (n - 1) * 6); let q = 0; + for (let j = 0; j < n - 1; j++) for (let i = 0; i < n - 1; i++) { + const a = j * n + i, b = a + 1, cc = a + n, d = cc + 1; + // split along the shorter diagonal-ish by alternating, avoids long slivers on banks + if ((i + j) & 1) { idx[q++] = a; idx[q++] = cc; idx[q++] = b; idx[q++] = b; idx[q++] = cc; idx[q++] = d; } + else { idx[q++] = a; idx[q++] = cc; idx[q++] = d; idx[q++] = a; idx[q++] = d; idx[q++] = b; } + } + const g = new THREE.BufferGeometry(); + g.setAttribute('position', new THREE.BufferAttribute(pos, 3)); + g.setAttribute('normal', new THREE.BufferAttribute(nor, 3)); + g.setAttribute('color', new THREE.BufferAttribute(col, 3)); + g.setAttribute('aMud', new THREE.BufferAttribute(mud, 1)); + g.setIndex(new THREE.BufferAttribute(idx, 1)); + g.computeBoundingSphere(); + const m = new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.95, metalness: 0 }); + const tg = W.tex.grass(), tm = W.tex.mud(), tgr = W.tex.gravel(); m.customProgramCacheKey = () => 'ivkitterrain'; + m.onBeforeCompile = function (sh) { + sh.uniforms.tGrass = { value: tg }; sh.uniforms.tMud = { value: tm }; sh.uniforms.tGrav = { value: tgr }; + sh.vertexShader = 'attribute float aMud; varying float vMud; varying vec3 vWP;\n' + sh.vertexShader.replace('#include ', '#include \n vMud = aMud; vWP = (modelMatrix * vec4(position,1.0)).xyz;'); + sh.fragmentShader = 'uniform sampler2D tGrass; uniform sampler2D tMud; uniform sampler2D tGrav; varying float vMud; varying vec3 vWP;\n' + + sh.fragmentShader.replace('#include ', ` + vec2 tuv = vWP.xz * 0.21; + float macro = texture2D(tGrass, vWP.xz * 0.011).r; + vec3 gA = texture2D(tGrass, tuv).rgb, gB = texture2D(tGrass, tuv * 0.31 + vec2(0.37, 0.71)).rgb; + vec3 gr = mix(gA, gB, smoothstep(0.35, 0.65, macro)); + vec3 md = texture2D(tMud, tuv * 0.8).rgb; + vec3 gv = texture2D(tGrav, tuv * 1.3).rgb; + float mw = clamp(vMud, 0.0, 1.0); + float gw = clamp(vMud - 1.0, 0.0, 1.0); + float hb = smoothstep(0.0, 1.0, clamp((mw * 1.4 - (gr.g - 0.3)), 0.0, 1.0)); + vec3 det = mix(gr, md, hb); + det = mix(det, gv, gw); + diffuseColor.rgb *= det * 2.0 * (0.85 + macro * 0.3); + `); + }; + const mesh = new THREE.Mesh(g, m); + mesh.receiveShadow = true; + W.terrainMesh = mesh; + W.statics.add(mesh); + } + + // ---------------------------------------------------------------- colliders + const CELL = 8; + function hk(ix, iz) { return (ix + 512) * 2048 + (iz + 512); } + // Add a box. cx,cz centre; hx,hz half sizes; y0,y1 bottom and top; rot about Y; f flags; surf for footsteps/impacts. + W.addBox = function (cx, cz, hx, hz, y0, y1, rot, f, surf, kind) { + const c = Math.cos(rot || 0), s = Math.sin(rot || 0); + const ex = Math.abs(hx * c) + Math.abs(hz * s), ez = Math.abs(hx * s) + Math.abs(hz * c); + const col = { x: cx, z: cz, hx, hz, c, s, y0, y1, f: f == null ? 31 : f, surf: surf || 'stone', kind: kind || '', ex, ez, id: W.colliders.length, on: true, st: 0 }; + W.colliders.push(col); + const i0 = Math.floor((cx - ex) / CELL), i1 = Math.floor((cx + ex) / CELL), j0 = Math.floor((cz - ez) / CELL), j1 = Math.floor((cz + ez) / CELL); + for (let i = i0; i <= i1; i++) for (let j = j0; j <= j1; j++) { const k = hk(i, j); let a = W.hash.get(k); if (!a) W.hash.set(k, a = []); a.push(col); } + return col; + }; + // colliders near a point (radius r); fills and returns a shared array + const near = []; + W.near = function (x, z, r) { + near.length = 0; const st = ++W.stamp; + const i0 = Math.floor((x - r) / CELL), i1 = Math.floor((x + r) / CELL), j0 = Math.floor((z - r) / CELL), j1 = Math.floor((z + r) / CELL); + for (let i = i0; i <= i1; i++) for (let j = j0; j <= j1; j++) { + const a = W.hash.get(hk(i, j)); if (!a) continue; + for (let k = 0; k < a.length; k++) { const c = a[k]; if (c.st !== st && c.on) { c.st = st; near.push(c); } } + } + return near; + }; + // local coordinates of a point in a collider + function toLocal(c, x, z, o) { const dx = x - c.x, dz = z - c.z; o.x = dx * c.c - dz * c.s; o.z = dx * c.s + dz * c.c; return o; } + W.toLocal = toLocal; + const L = { x: 0, z: 0 }; + // Height of whatever you would stand on at (x,z) when your feet are at y (terrain or a box top within a step). + W.groundAt = function (x, z, y, stepH) { + let g = W.height(x, z); const top = y + (stepH == null ? T.move.step : stepH); + const a = W.near(x, z, 0.5); + for (let i = 0; i < a.length; i++) { + const c = a[i]; if (!(c.f & F.SOLID) || c.y1 > top || c.y1 <= g) continue; + toLocal(c, x, z, L); + if (Math.abs(L.x) <= c.hx + 0.12 && Math.abs(L.z) <= c.hz + 0.12) g = c.y1; + } + return g; + }; + W.ceilingAt = function (x, z, y) { // lowest box bottom above y (for crouch/stand checks) + let cl = 1e9; const a = W.near(x, z, 0.5); + for (let i = 0; i < a.length; i++) { + const c = a[i]; if (!(c.f & F.SOLID) || c.y0 < y + 0.2 || c.y0 > cl) continue; + toLocal(c, x, z, L); + if (Math.abs(L.x) <= c.hx + 0.25 && Math.abs(L.z) <= c.hz + 0.25) cl = c.y0; + } + return cl; + }; + // Push a vertical cylinder (x,z,r) spanning y0..y1 out of solid boxes. Returns the corrected position in o, and the + // last collider hit (for vault checks). + W.collide = function (o, r, y0, y1, mask) { + mask = mask || F.SOLID; let hit = null; + for (let it = 0; it < 3; it++) { + const a = W.near(o.x, o.z, r + 0.5); let moved = false; + for (let i = 0; i < a.length; i++) { + const c = a[i]; if (!(c.f & mask) || c.y1 <= y0 || c.y0 >= y1) continue; + toLocal(c, o.x, o.z, L); + const px = IV.clamp(L.x, -c.hx, c.hx), pz = IV.clamp(L.z, -c.hz, c.hz); + let dx = L.x - px, dz = L.z - pz, d2 = dx * dx + dz * dz; + if (d2 >= r * r) continue; + let nx, nz, pen; + if (d2 > 1e-8) { const d = Math.sqrt(d2); nx = dx / d; nz = dz / d; pen = r - d; } + else { // centre inside the box: push out along the shallowest axis + const ox = c.hx - Math.abs(L.x), oz = c.hz - Math.abs(L.z); + if (ox < oz) { nx = Math.sign(L.x) || 1; nz = 0; pen = ox + r; } else { nx = 0; nz = Math.sign(L.z) || 1; pen = oz + r; } + } + // back to world + const wx = nx * c.c + nz * c.s, wz = -nx * c.s + nz * c.c; + o.x += wx * pen; o.z += wz * pen; moved = true; hit = c; o.nx = wx; o.nz = wz; + } + if (!moved) break; + } + return hit; + }; + + // ---------------------------------------------------------------- ray casts + // Ray from (ox,oy,oz) along unit (dx,dy,dz) up to max metres. mask: collider flags that count. Returns W.hit or null. + const HIT = W.hit = { t: 0, x: 0, y: 0, z: 0, nx: 0, ny: 1, nz: 0, surf: 'grass', col: null, terrain: false }; + W.raycast = function (ox, oy, oz, dx, dy, dz, max, mask, noTerrain) { + let best = max, bc = null, bn = 0; + const st = ++W.stamp; + // walk the 8 m cells along the ray (2D DDA) + let ix = Math.floor(ox / CELL), iz = Math.floor(oz / CELL); + const sx = dx > 0 ? 1 : -1, sz = dz > 0 ? 1 : -1; + const tdx = Math.abs(dx) > 1e-9 ? CELL / Math.abs(dx) : 1e9, tdz = Math.abs(dz) > 1e-9 ? CELL / Math.abs(dz) : 1e9; + let tx = Math.abs(dx) > 1e-9 ? ((sx > 0 ? (ix + 1) * CELL - ox : ox - ix * CELL) / Math.abs(dx)) : 1e9; + let tz = Math.abs(dz) > 1e-9 ? ((sz > 0 ? (iz + 1) * CELL - oz : oz - iz * CELL) / Math.abs(dz)) : 1e9; + let tcell = 0; + for (let guard = 0; guard < 400 && tcell <= best; guard++) { + const a = W.hash.get(hk(ix, iz)); + if (a) for (let k = 0; k < a.length; k++) { + const c = a[k]; if (c.st === st || !c.on || !(c.f & mask)) continue; c.st = st; + // slab test in the box's frame + const rx = ox - c.x, rz = oz - c.z; + const lox = rx * c.c - rz * c.s, loz = rx * c.s + rz * c.c, ldx = dx * c.c - dz * c.s, ldz = dx * c.s + dz * c.c; + let t0 = 0, t1 = best, axis = -1, sgn = 0; + // x + if (Math.abs(ldx) < 1e-9) { if (lox < -c.hx || lox > c.hx) continue; } + else { let a0 = (-c.hx - lox) / ldx, a1 = (c.hx - lox) / ldx, s0 = -1; if (a0 > a1) { const tt = a0; a0 = a1; a1 = tt; s0 = 1; } if (a0 > t0) { t0 = a0; axis = 0; sgn = s0; } if (a1 < t1) t1 = a1; if (t0 > t1) continue; } + if (Math.abs(dy) < 1e-9) { if (oy < c.y0 || oy > c.y1) continue; } + else { let a0 = (c.y0 - oy) / dy, a1 = (c.y1 - oy) / dy, s0 = -1; if (a0 > a1) { const tt = a0; a0 = a1; a1 = tt; s0 = 1; } if (a0 > t0) { t0 = a0; axis = 1; sgn = s0; } if (a1 < t1) t1 = a1; if (t0 > t1) continue; } + if (Math.abs(ldz) < 1e-9) { if (loz < -c.hz || loz > c.hz) continue; } + else { let a0 = (-c.hz - loz) / ldz, a1 = (c.hz - loz) / ldz, s0 = -1; if (a0 > a1) { const tt = a0; a0 = a1; a1 = tt; s0 = 1; } if (a0 > t0) { t0 = a0; axis = 2; sgn = s0; } if (a1 < t1) t1 = a1; if (t0 > t1) continue; } + if (t0 < best && axis >= 0) { best = t0; bc = c; bn = axis * 2 + (sgn > 0 ? 1 : 0); } + } + if (tx < tz) { tcell = tx; tx += tdx; ix += sx; } else { tcell = tz; tz += tdz; iz += sz; } + } + let terr = false; + if (!noTerrain) { const tt = W.terrainRay(ox, oy, oz, dx, dy, dz, best); if (tt < best) { best = tt; terr = true; bc = null; } } + if (best >= max) return null; + HIT.t = best; HIT.x = ox + dx * best; HIT.y = oy + dy * best; HIT.z = oz + dz * best; HIT.col = bc; HIT.terrain = terr; + if (terr) { const n = W.normal(HIT.x, HIT.z, tmpN); HIT.nx = n.x; HIT.ny = n.y; HIT.nz = n.z; const s = W.surfAt(HIT.x, HIT.z); HIT.surf = SURF[s]; } + else { + const axis = bn >> 1, pos = bn & 1; let lx = 0, ly = 0, lz = 0; + if (axis === 0) lx = pos ? 1 : -1; else if (axis === 1) ly = pos ? 1 : -1; else lz = pos ? 1 : -1; + // the entering face's normal points against the ray: sign as computed (s0 = +1 when ray goes -) + HIT.nx = lx * bc.c + lz * bc.s; HIT.ny = ly; HIT.nz = -lx * bc.s + lz * bc.c; HIT.surf = bc.surf; + } + return HIT; + }; + const tmpN = new THREE.Vector3(); + W.terrainRay = function (ox, oy, oz, dx, dy, dz, max) { + const st = max > 60 ? 1.5 : 0.7; + let pt = 0, pd = oy - W.height(ox, oz); + if (pd < 0) return 0; + for (let t = st; t <= max + st; t += st) { + const tt = Math.min(t, max), y = oy + dy * tt, d = y - W.height(ox + dx * tt, oz + dz * tt); + if (d < 0) { // refine + let a = pt, b = tt; + for (let k = 0; k < 7; k++) { const m = (a + b) / 2; if (oy + dy * m - W.height(ox + dx * m, oz + dz * m) < 0) b = m; else a = m; } + return a; + } + pt = tt; pd = d; + if (tt >= max) break; + } + return 1e9; + }; + // Is the line between two points clear of sight-blocking things (hedges, walls, buildings, terrain)? + W.clear = function (ax, ay, az, bx, by, bz, mask) { + const dx = bx - ax, dy = by - ay, dz = bz - az, d = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (d < 0.01) return true; + return !W.raycast(ax, ay, az, dx / d, dy / d, dz / d, d - 0.05, mask || F.SIGHT); + }; + + // ---------------------------------------------------------------- light (for stealth) + // lamps: {x,y,z,r,i, los:true, on:true}. flashes: {x,y,z,r,i,until}. roofs: [x0,z0,x1,z1,y] rectangles that shade. + W.addLamp = function (l) { l.on = l.on !== false; l.los = l.los !== false; W.lamps.push(l); return l; }; + W.flashAt = function (x, y, z, r, i, dur, color) { + if (W.flashes.length > 40) W.flashes.splice(0, W.flashes.length - 40); + W.flashes.push({ x, y, z, r, i, until: IV.time + dur, dur, color: color || 0xffc880 }); + }; + W.underRoof = function (x, z, y) { + for (let i = 0; i < W.roofs.length; i++) { const r = W.roofs[i]; if (x > r[0] && x < r[2] && z > r[1] && z < r[3] && (y == null || y < r[4])) return true; } + return false; + }; + // 0 (black) .. 1 (fully lit). ai.js turns it into how far away you can be seen. + W.lightAt = function (x, y, z) { + if (W.day) return W.underRoof(x, z, y) ? 0.6 : 1; + const md = W.moonDir; + let base = T.ai.lightNight; + if (W.underRoof(x, z, y) || !W.clear(x, y + 0.1, z, x + md.x * 22, y + md.y * 22, z + md.z * 22, F.SIGHT)) base = T.ai.lightShadow; + let add = 0; + for (let i = 0; i < W.lamps.length; i++) { + const l = W.lamps[i]; if (!l.on || l.visual) continue; // visual-only lamps (window spill) do not light you for the AI + const dx = x - l.x, dy = y - l.y, dz = z - l.z, d = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (d >= l.r) continue; + const k = 1 - d / l.r, v = l.i * k * k * 1.6; + if (v < 0.04) continue; + if (l.los && !W.clear(l.x, l.y, l.z, x, y, z, F.SIGHT)) continue; + add += v; + } + if (W.spot && W.spot.intensity > 0 && W.spotOn) { + const sp = W.spot.position, tg = W.spot.target.position; + const ax = tg.x - sp.x, ay = tg.y - sp.y, az = tg.z - sp.z, al = Math.hypot(ax, ay, az); + const bx = x - sp.x, by = y - sp.y, bz = z - sp.z, bl = Math.hypot(bx, by, bz); + const cos = (ax * bx + ay * by + az * bz) / (al * bl + 1e-6); + if (cos > Math.cos(W.spot.angle * 1.25) && bl < 140 && W.clear(sp.x, sp.y, sp.z, x, y, z, F.SIGHT)) add += 1.2; + } + for (let i = 0; i < W.flashes.length; i++) { + const f = W.flashes[i]; if (f.until < IV.time) continue; // (expired ones are removed at render time) + const d = Math.hypot(x - f.x, y - f.y, z - f.z); + if (d < f.r) add += f.i * (1 - (IV.time - (f.until - f.dur)) / f.dur) * (1 - d / f.r); + } + return IV.clamp(base + add, 0, 1.4); + }; + + // Each frame: give the pooled point lights to the lamps nearest the camera, drive the flash light, follow the shadow. + const lampSort = [], cullM = new THREE.Matrix4(), cullF = new THREE.Frustum(); + W.frame = function (dt, focus) { + W.windU.value += dt; + const cam = W.camera.position; + // expire flashes + for (let i = W.flashes.length - 1; i >= 0; i--) if (W.flashes[i].until < IV.time) W.flashes.splice(i, 1); + lampSort.length = 0; + for (let i = 0; i < W.lamps.length; i++) { const l = W.lamps[i]; if (!l.on || l.vis === false) continue; l._d = (l.x - cam.x) ** 2 + (l.z - cam.z) ** 2; lampSort.push(l); } + lampSort.sort((a, b) => a._d - b._d); + for (let i = 0; i < W.pointPool.length; i++) { + const pl = W.pointPool[i], l = lampSort[i]; + if (l && l._d < 110 * 110) { + // a long, soft falloff (distance well past the lamp's gameplay radius) so pools fade out instead of ending in a ring + pl.position.set(l.x, l.y, l.z); pl.color.setHex(l.color || 0xffb060); pl.distance = l.r * 1.8; + const flick = l.flicker ? 0.86 + 0.14 * IV.noise(IV.time * 7 + i * 10, 0.5) : 1; + pl.intensity = (l.power || 1.6) * 0.85 * flick * IV.clamp(1.6 - Math.sqrt(l._d) / 90, 0, 1); + } else pl.intensity = 0; + } + // brightest live flash gets the flash light + let fb = null, fv = 0; + for (let i = 0; i < W.flashes.length; i++) { const f = W.flashes[i], k = (f.until - IV.time) / f.dur; if (k * f.i > fv) { fv = k * f.i; fb = f; } } + const fl = W.flashLight; + if (fb) { fl.position.set(fb.x, fb.y, fb.z); fl.distance = Math.min(60, fb.r * 1.6); fl.intensity = Math.min(5, fv * 3); fl.color.setHex(fb.color); } else fl.intensity = 0; + // shadow camera follows the focus point, snapped to texels so shadows do not swim + if (W.sun.castShadow && focus && !W.atm) { + const s = W.shadowR || 40, texel = (2 * s) / (W.sun.shadow.mapSize.x || 1024); + const fx = Math.round(focus.x / texel) * texel, fz = Math.round(focus.z / texel) * texel; + W.sun.target.position.set(fx, focus.y, fz); + W.sun.position.set(fx + W.moonDir.x * 90, focus.y + W.moonDir.y * 90, fz + W.moonDir.z * 90); + } + if (W.skyDome) W.skyDome.position.copy(cam); + // chunked vegetation: off screen or past the fog, don't draw it + if (W.cullList && W.cullList.length) { + const c = W.camera; c.updateMatrixWorld(); cullM.multiplyMatrices(c.projectionMatrix, c.matrixWorldInverse); cullF.setFromProjectionMatrix(cullM); + const far = W.day ? 400 : 190; + for (const m of W.cullList) { const s = m.userData.cull; m.visible = s.center.distanceTo(cam) - s.radius < far && cullF.intersectsSphere(s); } + } + }; +})(); diff --git a/e63334287a3deaa3/ironveil/preview.jpg b/e63334287a3deaa3/ironveil/preview.jpg new file mode 100644 index 00000000..cbb9ade8 Binary files /dev/null and b/e63334287a3deaa3/ironveil/preview.jpg differ diff --git a/e63334287a3deaa3/ironveil/tools/chars/README.md b/e63334287a3deaa3/ironveil/tools/chars/README.md new file mode 100644 index 00000000..91c4219c --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/README.md @@ -0,0 +1,87 @@ +# Character build scripts + +These scripts rebuild everything in `../../assets/` except the three.js loader copies in `assets/lib/`: the hero, ally +and enemy models (`hero.glb`, `ally.glb`, `enemy.glb`), every animation clip (`anims.glb` plus `anims.json`) and the +weapons (`weapons.glb`, now maintained on the weapons branch). The game never runs them; they are kept so the files +can be rebuilt or changed later. Nothing downloaded is committed: `fetch.sh` gets the sources, and `../../CREDITS.md` +lists each one with its licence. + +## What you need + +- Python 3.13 with the `bpy` (Blender as a module), `numpy` and `pillow` packages. `fetch.sh` makes a venv for them. +- Node with `@gltf-transform/cli` for compression (`pack.sh`), and `playwright` plus Chrome or Chromium for the + screenshots and videos (`capture.js`, `shot.js`). `ffmpeg` for the videos. +- About 3 GB of free space in the working folder. + +## Folders + +All paths come from `env.sh` and can be overridden: + +- `CHARS_WORK`: the working folder for downloads, intermediate `.blend` files and `out/` (default `../work` + next to this folder; keep it outside the repo). +- `CHARS_ASSETS`: where `pack.sh` writes the compressed files (default `../../assets`). +- `CHARS_OUT`: where videos, sheets and measurements go (default `../evidence`). +- `PORT`: the local web server port for the test page (default 8981). + +## Rebuilding + +``` +CHARS_WORK=~/ironveil-work ./fetch.sh # sources (the Quaternius pack is a manual download, see the script) +CHARS_WORK=~/ironveil-work ./rebuild_all.sh # models and clips, then packs them into assets/ +``` + +To rebuild only the clips: `bvenv/bin/python anims_build.py out/anims.glb` from the working folder, then +`./pack.sh anims`. `ONLY=walkF,jogF` limits the build to some clips, and the log ends with a check of every +motion-capture loop (planted-foot speed, leg reach error and the largest per-frame bone rotation). + +## What each script does + +| Script | Job | +|---|---| +| `mhlib.py`, `geo.py` | Build a MakeHuman body from the CC0 data, re-pose it to the UAL skeleton, fit clothes and proxies, weights | +| `outfits.py`, `wear.py`, `mats.py`, `pipe.py` | Uniforms and gear as geometry, worn node materials, high-to-low bakes, decimation and UVs | +| `build_hero.py` (`KIND=ally` for the squadmate), `build_enemy.py`, `assemble.py` | Build, bake and export each character | +| `weapons.py`, `build_weapons.py`, `export_weapons.py` | The weapons and their grip frames | +| `anim_lib.py` | World-space posing helpers on the skeleton (aims, two-bone IK, finger curls, actions) | +| `anims_build.py` | Every clip of the IVChars API: authored poses, the UAL clips, and the motion-capture loops | +| `amc.py`, `mocap.py`, `mocap_list.py` | CMU ASF/AMC reader, the retarget (cycle cut, phase, foot pinning, IK) and the list of takes | +| `cmu_scan.py` | Prints speed and travel direction over time for CMU trials, to choose loop segments | +| `pack.sh` | meshopt compression (and resampling for clips) into `assets/` | +| `capture.js`, `videos.sh`, `shot.js`, `sheet.sh` | Drive-mode videos with measurements, and screenshot sheets from `chars-test.html` | + +## First-person arms (`fp.glb`, `fp.json`) + +Built in four steps from `$CHARS_WORK/fp` (`FP_WORK`), one Blender process at a time: + +``` +bvenv/bin/python fp_arms.py # fp_geo.blend: forearms and hands cut from the hero body, sleeves, watch, skeleton +bvenv/bin/python fp_tex.py # fp_tex.blend + tex/*.png: UV atlas and the 2048 set (albedo, normal, ORM) +node fp_unpack.mjs ../../assets/weapons.glb $CHARS_WORK/fp/weapons_plain.glb # the weapons, readable by Blender +bvenv/bin/python fp_clips.py preview # optional: Cycles stills of chosen frames (KINDS, SHOTS=idle@0,reload@0.7) +bvenv/bin/python fp_clips.py export # fp.glb + fp.json (clip lengths, events, props, hand-penetration report) +node fp_pack.mjs $CHARS_WORK/fp/fp.glb ../../assets/fp.glb; cp $CHARS_WORK/fp/fp.json ../../assets/ +``` + +- `fp_arms.py`: the hero's MakeHuman body (same `humans.HERO` build) cut at mid upper arm, the forearms subdivided + once, rolled sleeves and the cuff roll as ring lofts round the arm, a lathed watch case with lugs and crown on a + leather strap. The skeleton is the hero's arm chain plus `lowerarm_twist_*` (part of each forearm's weight, so the + wrist does not candy-wrap), `fp_root` at the eye and the weapon bones `w_root`, `w_bolt`, `w_boltHandle`, `w_mag`, + `w_trigger`, `w_hammer`, `w_charging`, `w_prop` whose rest frames equal the glTF identity, so `chars.js` can hang the + normal weapon model and its moving parts on them with identity transforms. +- `fp_tex.py`: Cycles bakes only the rest-pose position, normal, region and occlusion of each texel; everything else + (skin, hair, veins, tendons, wrinkles, creases, nails, scar, grime, camouflage, weave, seam, strap, dial) is computed + per texel in numpy from the 3D position, and the heights become a tangent-space normal map from each texel's own + position derivatives. +- `fp_clips.py` / `fp_lib.py`: hand frames are defined on each weapon's measured shape (`GRIPSPEC`), then fitted: a + search over the palm offset and a small turn scored by hand vertices inside the weapon (BVH of the real mesh) and + palm contact, alternating with closing every finger joint on the surface. Arms are two-bone IK with the elbow pole + chosen per frame to keep the arm out of the weapon; skinning is the same linear blend three.js runs, so the + penetration numbers in `fp.json` are what the game shows. Clip programs are small keyframe functions per weapon. + +## Notes for later edits + +- Bone names, clip names and the `anims.json` fields (`duration`, `stride`, `speed`, `theta`) are part of the API that + `chars.js` and the game read; keep them. +- Every locomotion loop has the left foot landing at phase 0 and the right at 0.5. `stride` is metres per cycle. +- Subjects 139, 141 and 143 of the CMU database were captured at 60 Hz, the rest at 120 Hz (`mocap.RATE60`). +- No hate symbols, real people or insignia anywhere, including textures. Enemies wear only the invented white chevron. diff --git a/e63334287a3deaa3/ironveil/tools/chars/aimsheet.sh b/e63334287a3deaa3/ironveil/tools/chars/aimsheet.sh new file mode 100755 index 00000000..c03471e2 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/aimsheet.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# aimsheet.sh out.png : player-camera stills (1.7 m back, 0.85 m right) of the aim with SMG and rifle, standing and +# crouched, still and strafing, with a rifle slung on the back; grey floor +. "$(dirname "$0")/env.sh" +out=$1; T=$(mktemp -d); i=0 +for w in smg rifleScoped; do + for pose in "anim=idle&upper=aimIdle" "anim=walkR&upper=aimIdle" "anim=crouchIdle&upper=crouchAim" "anim=jogF&upper=holdRifle"; do + i=$((i+1)); timeout 200 node "$HERE/shot.js" $T/p$i.png "/e63334287a3deaa3/ironveil/chars-test.html?shot=1&kind=hero&$pose&t=0.5&weapon=$w&sling=rifleScoped&grey=1&cam=ots2" 400 300 >/dev/null + done +done +python3 -I -c " +import sys +from PIL import Image +n=int(sys.argv[3]); ims=[Image.open(sys.argv[2]+'/p%d.png'%i) for i in range(1,n+1)] +c=Image.new('RGB',(1600,300*((n+3)//4))); [c.paste(im,((i%4)*400,(i//4)*300)) for i,im in enumerate(ims)]; c.save(sys.argv[1])" $out $T $i diff --git a/e63334287a3deaa3/ironveil/tools/chars/amc.py b/e63334287a3deaa3/ironveil/tools/chars/amc.py new file mode 100644 index 00000000..ba37700b --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/amc.py @@ -0,0 +1,91 @@ +# Minimal CMU ASF/AMC reader + forward kinematics (numpy). Positions in metres, Z-up, as world joint positions per frame. +import numpy as np, math + +UNIT = 2.54 / 100 / 0.45 # ASF length unit 0.45 -> inches -> metres + +def rot(axis, deg): + a = math.radians(deg); c, s = math.cos(a), math.sin(a) + if axis == 'x': return np.array([[1, 0, 0], [0, c, -s], [0, s, c]]) + if axis == 'y': return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]]) + return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]]) + +def euler(vals, order): + """order e.g. 'XYZ': rotate about X first, then Y, then Z (static frame) -> R = Rz Ry Rx""" + R = np.eye(3) + for ax, v in zip(order.lower(), vals): + R = rot(ax, v) @ R + return R + +class Skel: + def __init__(self, path): + self.bones = {}; self.parent = {}; self.children = {} + txt = open(path).read() + bd = txt.split(':bonedata')[1].split(':hierarchy')[0] + for blk in bd.split('begin')[1:]: + lines = [l.split() for l in blk.split('end')[0].strip().splitlines() if l.strip()] + b = {'dof': []} + for l in lines: + if l[0] == 'name': b['name'] = l[1] + elif l[0] == 'direction': b['dir'] = np.array([float(x) for x in l[1:4]]) + elif l[0] == 'length': b['len'] = float(l[1]) * UNIT + elif l[0] == 'axis': b['axis'] = ([float(x) for x in l[1:4]], l[4]) + elif l[0] == 'dof': b['dof'] = l[1:] + C = euler(b['axis'][0], b['axis'][1]) + b['C'] = C; b['Cinv'] = C.T + self.bones[b['name']] = b + hi = txt.split(':hierarchy')[1].split('end')[0].strip().splitlines() + for l in hi: + p = l.split() + if not p or p[0] == 'begin': continue + for c in p[1:]: + self.parent[c] = p[0]; self.children.setdefault(p[0], []).append(c) + ro = txt.split(':root')[1].split(':bonedata')[0] + self.root_order = [l.split()[1:] for l in ro.splitlines() if l.strip().startswith('order')][0] + ax = [l.split()[1] for l in ro.splitlines() if l.strip().startswith('axis')][0] + self.root_axis = ax + +def read_amc(path): + frames = []; cur = None + for l in open(path): + l = l.strip() + if not l or l[0] in '#:': continue + p = l.split() + if p[0].isdigit(): + cur = {}; frames.append(cur) + else: + cur[p[0]] = [float(x) for x in p[1:]] + return frames + +def fk(sk, fr): + """Returns dict bone -> (start position, end position) in metres (ASF Y-up converted to Z-up, -Y forward unknown).""" + rv = fr['root'] + vals = dict(zip([o.lower() for o in sk.root_order], rv)) + T = np.array([vals['tx'], vals['ty'], vals['tz']]) * UNIT + R0 = euler([vals['rx'], vals['ry'], vals['rz']], 'XYZ') + out = {'root': (T, T)} + mats = {'root': R0} + def walk(name, pstart): + for c in sk.children.get(name, []): + b = sk.bones[c] + Pm = mats[name] + if b['dof']: + v = fr.get(c, [0] * len(b['dof'])) + ang = [0.0, 0.0, 0.0] + for d, x in zip(b['dof'], v): + ang['xyz'.index(d[-1])] = x + M = euler(ang, 'XYZ') + else: + M = np.eye(3) + W = Pm @ b['C'] @ M @ b['Cinv'] + mats[c] = W + end = pstart + W @ (b['dir'] * b['len']) + out[c] = (pstart, end) + walk(c, end) + walk('root', T) + # Y-up -> Z-up + conv = lambda p: np.array([p[0], -p[2], p[1]]) + return {k: (conv(a), conv(b)) for k, (a, b) in out.items()} + +def load(asf, amcf, step=4): + sk = Skel(asf); frs = read_amc(amcf) + return [fk(sk, f) for f in frs[::step]], 120.0 / step diff --git a/e63334287a3deaa3/ironveil/tools/chars/anim_lib.py b/e63334287a3deaa3/ironveil/tools/chars/anim_lib.py new file mode 100644 index 00000000..8a629d24 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/anim_lib.py @@ -0,0 +1,260 @@ +# Pose authoring on the shared UAL-named skeleton, in world space (Blender: -Y forward, +X = character left, +Z up). +import bpy, math +from mathutils import Vector, Matrix, Quaternion + +FWD = Vector((0, -1, 0)); LEFT = Vector((1, 0, 0)); UP = Vector((0, 0, 1)) + +def fcurves_of(action): + st = action.layers[0].strips[0] + return st.channelbags[0].fcurves + +class Rig: + def __init__(self, arm): + self.arm = arm + self.bones = [b.name for b in arm.data.bones] + self.parent = {b.name: (b.parent.name if b.parent else None) for b in arm.data.bones} + self.Mr = {b.name: b.matrix_local.copy() for b in arm.data.bones} + self.Lr = {} + for b in self.bones: + p = self.parent[b] + self.Lr[b] = (self.Mr[p].inverted() @ self.Mr[b]) if p else self.Mr[b].copy() + # hierarchical order + order = [] + def walk(n): + order.append(n) + for c in arm.data.bones[n].children: walk(c.name) + for b in arm.data.bones: + if b.parent is None: walk(b.name) + self.order = order + self.Rr = {b: self.Mr[b].to_3x3() for b in self.bones} + self.dir = {b: (self.Mr[b].to_3x3() @ Vector((0, 1, 0))).normalized() for b in self.bones} + self.len = {b: arm.data.bones[b].length for b in self.bones} + self.pel_scale = 1.0 + + # ---------- pose containers + def rest(self): + return {b: self.Lr[b].copy() for b in self.bones} + + def from_action(self, action, t, fps_src=24.0, mirror=False): + """Pose (local matrices) of a source action at time t (seconds).""" + L = self.rest() + f = t * fps_src + ch = {} + for fc in fcurves_of(action): + dp = fc.data_path + if not dp.startswith('pose.bones'): continue + bn = dp.split('"')[1]; prop = dp.rsplit('.', 1)[1] + ch.setdefault(bn, {}).setdefault(prop, {})[fc.array_index] = fc.evaluate(f) + for bn, props in ch.items(): + if bn not in L: continue + q = props.get('rotation_quaternion') + Q = Quaternion((q.get(0, 1), q.get(1, 0), q.get(2, 0), q.get(3, 0))) if q else Quaternion() + Q.normalize() + loc = props.get('location') + T = Vector((loc.get(0, 0), loc.get(1, 0), loc.get(2, 0))) if loc else Vector() + if bn != 'pelvis': T = Vector() + else: T = T * self.pel_scale + basis = Matrix.Translation(T) @ Q.to_matrix().to_4x4() + L[bn] = self.Lr[bn] @ basis + return L + + def W(self, L): + W = {} + for b in self.order: + p = self.parent[b] + W[b] = (W[p] @ L[b]) if p else L[b].copy() + return W + + def set_world(self, L, W, b, M): + p = self.parent[b] + L[b] = (W[p].inverted() @ M) if p else M.copy() + # refresh subtree worlds + self._refresh(L, W, b) + + def _refresh(self, L, W, b): + p = self.parent[b] + W[b] = (W[p] @ L[b]) if p else L[b].copy() + for c in self.arm.data.bones[b].children: + self._refresh(L, W, c.name) + + def rot_world(self, L, W, b, q, pivot=None): + M = W[b] + pv = M.translation.copy() if pivot is None else pivot + R = Matrix.Translation(pv) @ q.to_matrix().to_4x4() @ Matrix.Translation(-pv) + self.set_world(L, W, b, R @ M) + + def set_world_rot(self, L, W, b, R3): + """Set the bone's world rotation (3x3), keeping its head where the parent puts it.""" + h = W[b].translation.copy() + M = R3.to_4x4(); M.translation = h + self.set_world(L, W, b, M) + + def delta(self, W, b): + """World rotation of the bone relative to its rest orientation (3x3).""" + return W[b].to_3x3() @ self.Rr[b].inverted() + + def move_pelvis(self, L, W, pos=None, rot=None): + M = W['pelvis'] + if rot is not None: + R = rot.to_matrix().to_4x4() + M = Matrix.Translation(M.translation) @ R @ Matrix.Translation(-M.translation) @ M + if pos is not None: + M = M.copy(); M.translation = pos + self.set_world(L, W, 'pelvis', M) + + # ---------- helpers + @staticmethod + def frame_rot(a0, b0, a1, b1): + """Rotation taking (a0,b0) to (a1,b1) (a exact, b orthogonalised).""" + def basis(a, b): + a = a.normalized(); b = (b - a * b.dot(a)).normalized(); c = a.cross(b) + return Matrix((a, b, c)).transposed() + return basis(a1, b1) @ basis(a0, b0).inverted() + + def aim_bone(self, L, W, b, want_dir, want_ref=None, rest_ref=None): + """Point bone along want_dir; optionally align rest_ref (world vector in rest) to want_ref.""" + if want_ref is None: + cur = (W[b].to_3x3() @ Vector((0, 1, 0))).normalized() + q = cur.rotation_difference(want_dir.normalized()) + self.rot_world(L, W, b, q) + else: + D = self.frame_rot(self.dir[b], rest_ref, want_dir, want_ref) + self.set_world_rot(L, W, b, D @ self.Rr[b]) + + def two_bone(self, L, W, upper, lower, end, target, pole, hinge_rest, twist_share=0.0, end_rot=None): + """Analytic two-bone IK. hinge_rest: world hinge axis of the joint in rest pose (e.g. Z for elbows, X for knees).""" + A = W[upper].translation.copy(); B = W[lower].translation.copy(); C = W[end].translation.copy() + l1 = (B - A).length; l2 = (C - B).length + T = Vector(target) + d = T - A; dist = max(1e-4, min(d.length, (l1 + l2) * 0.9995)) + dn = d.normalized() + cosA = max(-1, min(1, (l1 * l1 + dist * dist - l2 * l2) / (2 * l1 * dist))) + sinA = math.sqrt(max(0.0, 1 - cosA * cosA)) + pv = Vector(pole) - dn * Vector(pole).dot(dn) + if pv.length < 1e-6: pv = UP - dn * UP.dot(dn) + pv.normalize() + Bn = A + (dn * cosA + pv * sinA) * l1 + updir = (Bn - A).normalized() + lodir = (A + dn * dist - Bn).normalized() + # hinge axis perpendicular to the limb plane; sign chosen to match the rest hinge sense + # = updir x lodir up to a positive factor (dist * sinA), but stays defined when the limb is straight + hn = pv.cross(dn).normalized() + rest_up = self.dir[upper]; rest_lo = self.dir[lower] + rh = Vector(hinge_rest).normalized() # = rest_up x (naturally bent lower dir) + self.set_world_rot(L, W, upper, self.frame_rot(rest_up, rh, updir, hn) @ self.Rr[upper]) + self.set_world_rot(L, W, lower, self.frame_rot(rest_lo, rh, lodir, hn) @ self.Rr[lower]) + if end_rot is not None: + self.set_world_rot(L, W, end, end_rot) + if twist_share > 0: + # share the forearm twist so the wrist does not candy-wrap + Dl = W[lower].to_3x3(); De = W[end].to_3x3() @ self.Rr[end].inverted() @ self.Rr[lower] + rel = (Dl.inverted() @ De).to_quaternion() + ax = Vector((0, 1, 0)) + # swing-twist decomposition about bone Y + tw = Quaternion((rel.w, 0, rel.y, 0)); tw.normalize() + ang = 2 * math.atan2(tw.y, tw.w) + qtw = Quaternion(lodir, ang * twist_share) + endM = W[end].copy() + self.rot_world(L, W, lower, qtw) + self.set_world(L, W, end, endM) + + def hand_rot(self, side, want_dir, want_palm): + """World rotation for hand_ so its bone axis follows want_dir and its palm faces want_palm.""" + b = 'hand_' + side + rest_palm = Vector((0, 0, -1)) # T-pose palms down + D = self.frame_rot(self.dir[b], rest_palm, want_dir, want_palm) + return D @ self.Rr[b] + + def curl(self, L, W, side, amounts, thumb=0.5, spread=0.0): + """amounts: dict finger -> 0..1 curl. Applied after the hand is placed.""" + hb = 'hand_' + side + Dh = self.delta(W, hb) + palm = Dh @ Vector((0, 0, -1)) + for f in ('index', 'middle', 'ring', 'pinky'): + a = amounts.get(f, 0.0) + for i, k in ((1, 0.9), (2, 1.1), (3, 0.8)): + b = '%s_0%d_%s' % (f, i, side) + if b not in W: continue + d = (W[b].to_3x3() @ Vector((0, 1, 0))).normalized() + ax = d.cross(palm).normalized() + self.rot_world(L, W, b, Quaternion(ax, a * k * 1.45)) + for i, k in ((1, 0.5), (2, 0.8), (3, 0.9)): + b = 'thumb_0%d_%s' % (i, side) + if b not in W: continue + d = (W[b].to_3x3() @ Vector((0, 1, 0))).normalized() + ax = d.cross(palm).normalized() + self.rot_world(L, W, b, Quaternion(ax, thumb * k * 1.1)) + + def spine(self, L, W, pitch=0.0, yaw=0.0, roll=0.0, frac=(0.25, 0.35, 0.4), rel=True): + """Bend the spine: pitch>0 forward, yaw>0 turn left, roll>0 lean left. Rotations about character axes.""" + for b, f in zip(('spine_01', 'spine_02', 'spine_03'), frac): + q = Quaternion(UP, yaw * f) @ Quaternion(LEFT, pitch * f) @ Quaternion(FWD, -roll * f) + if rel: + # character axes follow the pelvis yaw only + pass + self.rot_world(L, W, b, q) + + def look(self, L, W, yaw=0.0, pitch=0.0, roll=0.0, neck=0.4): + for b, f in (('neck_01', neck), ('Head', 1 - neck)): + q = Quaternion(UP, yaw * f) @ Quaternion(LEFT, pitch * f) @ Quaternion(FWD, -roll * f) + self.rot_world(L, W, b, q) + + # ---------- output + def basis(self, L): + out = {} + for b in self.bones: + B = self.Lr[b].inverted() @ L[b] + out[b] = (B.to_translation(), B.to_quaternion()) + return out + +def make_action(rig_obj, name, frames, bones, fps=30, loc_bones=('pelvis',)): + """frames: list of basis dicts (from Rig.basis). Writes a new action with fcurves.""" + act = bpy.data.actions.get(name) + if act: bpy.data.actions.remove(act) + act = bpy.data.actions.new(name) + slot = act.slots.new('OBJECT', rig_obj.name) + layer = act.layers.new('Layer') + strip = layer.strips.new(type='KEYFRAME') + cb = strip.channelbag(slot, ensure=True) + n = len(frames) + for b in bones: + qs = [f[b][1] for f in frames] + # keep quaternion signs continuous + for i in range(1, n): + if qs[i].dot(qs[i - 1]) < 0: qs[i] = -qs[i] + for k in range(4): + fc = cb.fcurves.new('pose.bones["%s"].rotation_quaternion' % b, index=k, group_name=b) + fc.keyframe_points.add(n) + co = [] + for i in range(n): co += [i * (24.0 / fps) if False else float(i), qs[i][k]] + fc.keyframe_points.foreach_set('co', co) + fc.keyframe_points.foreach_set('interpolation', [1] * n) # LINEAR + fc.update() + if b in loc_bones: + for k in range(3): + fc = cb.fcurves.new('pose.bones["%s"].location' % b, index=k, group_name=b) + fc.keyframe_points.add(n) + co = [] + for i in range(n): co += [float(i), frames[i][b][0][k]] + fc.keyframe_points.foreach_set('co', co) + fc.keyframe_points.foreach_set('interpolation', [1] * n) + fc.update() + act.use_fake_user = True + act['ivslot'] = slot.identifier + return act + +def smooth(t): + t = max(0.0, min(1.0, t)); return t * t * (3 - 2 * t) + +def lerp(a, b, t): + return a + (b - a) * t + +def keys(track, t): + """track: list of (time, value) with numbers or Vectors; smoothstep between keys.""" + if t <= track[0][0]: return track[0][1] + for (t0, v0), (t1, v1) in zip(track, track[1:]): + if t <= t1: + u = smooth((t - t0) / max(1e-6, t1 - t0)) + if isinstance(v0, Quaternion): return v0.slerp(v1, u) + return v0 + (v1 - v0) * u + return track[-1][1] diff --git a/e63334287a3deaa3/ironveil/tools/chars/anims_build.py b/e63334287a3deaa3/ironveil/tools/chars/anims_build.py new file mode 100644 index 00000000..9d604cef --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/anims_build.py @@ -0,0 +1,1078 @@ +# Builds every clip of the IVChars API on the shared skeleton and exports anims.glb + grips.json. +import bpy, sys, os, math, json +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import mhlib as L_, anim_lib as A +from mathutils import Vector, Matrix, Quaternion, Euler +from anim_lib import FWD, LEFT, UP, keys, smooth, lerp + +OUT = sys.argv[-1] +ONLY = os.environ.get('ONLY', '').split(',') if os.environ.get('ONLY') else None +FPS = 30 +bpy.ops.wm.open_mainfile(filepath=L_.WORK + '/hero_baked.blend') +arm = bpy.data.objects['Armature'] +if 'weapon_r' not in arm.data.bones: + L_.set_active(arm); bpy.ops.object.mode_set(mode='EDIT') + eb = arm.data.edit_bones; hr = eb['hand_r']; w = eb.new('weapon_r') + w.head = hr.head.copy(); w.tail = hr.tail.copy(); w.roll = hr.roll; w.parent = hr + bpy.ops.object.mode_set(mode='OBJECT') +# UAL2 clips +before = set(bpy.data.actions) +bpy.ops.import_scene.gltf(filepath=L_.UAL2) +for o in list(bpy.data.objects): + if o.name not in ('Armature',) and (o.type in ('MESH', 'ARMATURE')) and o.name.startswith(('Armature.', 'Mannequin', 'Icosphere')): + bpy.data.objects.remove(o) +R = A.Rig(arm) +R.pel_scale = R.Mr['pelvis'].translation.z / 0.917 +SRC = {a.name: a for a in bpy.data.actions} +def src(n): return SRC[n] +def dur(n): return (src(n).frame_range[1] - src(n).frame_range[0]) / 24.0 + +EYE_R = Vector((-0.031, -0.235, 1.712)) +REST = R.rest(); WREST = R.W(REST) + +# ---------------- weapon classes (weapon local: -Y barrel, +Z up, +X weapon-left; origin = right grip point) +GUNS = { + 'rifle': dict(sight=0.072, eye=0.23, butt=0.34, + gripR=Vector((0, 0.035, -0.012)), dirR=Vector((0.15, -0.55, -0.82)), palmR=Vector((1, 0, -0.1)), + gripL=Vector((0, -0.29, -0.004)), dirL=Vector((-0.42, -0.82, 0.38)), palmL=Vector((-0.35, 0.0, 0.94))), + 'pistol': dict(sight=0.04, eye=0.55, butt=0.0, + gripR=Vector((0, 0.02, -0.05)), dirR=Vector((0.1, -0.35, -0.93)), palmR=Vector((1, 0, -0.05)), + gripL=Vector((0.012, 0.03, -0.06)), dirL=Vector((-0.5, -0.4, -0.75)), palmL=Vector((-0.9, 0.0, 0.3))), +} +CURL_R = {'index': 0.35, 'middle': 0.85, 'ring': 0.92, 'pinky': 0.95} +CURL_L = {'index': 0.6, 'middle': 0.65, 'ring': 0.7, 'pinky': 0.72} + +def weapon_matrix(origin, fwd, up=UP): + f = fwd.normalized(); x = up.cross(-f).normalized() if False else (-f).cross(up).normalized() + # local axes: +X = weapon left, +Y = backward (-fwd), +Z = up + y = -f; z = x.cross(y).normalized(); x = y.cross(z).normalized() + M = Matrix((x, y, z)).transposed().to_4x4(); M.translation = origin + return M + +def chest_delta(W): + return W['spine_03'] @ R.Mr['spine_03'].inverted() + +LAST = {} +def place_hands(L, W, Wm, gun, right=True, left=True, curl=True, lw=1.0, left_override=None): + g = GUNS[gun] + R3 = Wm.to_3x3() + if right: + grip = Wm @ g['gripR']; d = (R3 @ g['dirR']).normalized(); pm = (R3 @ g['palmR']).normalized() + wrist = grip - d * 0.065 - pm * 0.028 + rot = R.hand_rot('r', d, pm) + LAST['r'] = rot.to_4x4(); LAST['r'].translation = wrist + # firing elbow down and out (30-45 degrees below horizontal), not up beside the helmet + pole = chest_delta(W).to_3x3() @ Vector((-0.55, 0.12, -1.0)) + R.two_bone(L, W, 'upperarm_r', 'lowerarm_r', 'hand_r', wrist, pole, Vector((0, 0, 1)), end_rot=rot) + if curl: R.curl(L, W, 'r', CURL_R, thumb=0.55) + if left: + if left_override is not None: + wrist, rot = left_override + else: + grip = Wm @ g['gripL']; d = (R3 @ g['dirL']).normalized(); pm = (R3 @ g['palmL']).normalized() + wrist = grip - d * 0.06 - pm * 0.03 + rot = R.hand_rot('l', d, pm) + LAST['l'] = rot.to_4x4(); LAST['l'].translation = wrist + pole = chest_delta(W).to_3x3() @ Vector((0.35, 0.1, -1.0)) + R.two_bone(L, W, 'upperarm_l', 'lowerarm_l', 'hand_l', wrist, pole, Vector((0, 0, -1)), end_rot=rot) + if curl: R.curl(L, W, 'l', CURL_L, thumb=0.35) + +def set_weapon_bone(L, W, Wm, gun_grip): + """Make weapon_r carry the weapon at Wm whatever the hand does (gun_grip = hand frame in weapon space).""" + R.set_world(L, W, 'weapon_r', Wm @ gun_grip) + +# ---------- aim solution for the long gun (computed once from the idle base) +def aim_weapon(L, W, pitch=0.0, recoil=0.0, gun='rifle'): + Dh = R.delta(W, 'Head') + eye = W['Head'].translation + Dh @ (EYE_R - R.Mr['Head'].translation) + aim = (Quaternion(LEFT, -pitch + recoil * 0.25) @ FWD).normalized() + g = GUNS[gun] + up = (Quaternion(LEFT, -pitch) @ UP) + origin = eye + aim * g['eye'] - up * g['sight'] - aim * recoil * 0.045 + return weapon_matrix(origin, aim, up) + +def eye_pos(W): + Dh = R.delta(W, 'Head') + return W['Head'].translation + Dh @ (EYE_R - R.Mr['Head'].translation) + +def head_to(L, W, target, iters=10, chain=('neck_01', 'Head', 'spine_03'), limits=(0.5, 0.36, 0.14)): + """CCD: bring the right eye onto the sight line (cheek weld).""" + for it in range(iters): + for b, lim in zip(chain, limits): + e = eye_pos(W); pv = W[b].translation + a = (e - pv); c = (target - pv) + if a.length < 1e-4 or c.length < 1e-4: continue + q = a.rotation_difference(c) + ang = q.angle + if ang < 1e-5: continue + ax = q.axis + # damp roll about the aim axis so the head tilts but does not lie on its side + fw = ax.dot(FWD) + ax = (ax - FWD * fw * 0.65).normalized() + q = Quaternion(ax, min(ang, lim / iters * 2)) + R.rot_world(L, W, b, q) + return (eye_pos(W) - target).length + +def stance_aim(L, W, t, pitch=0.0, recoil=0.0, breathe=True, gun='rifle', lean=0.08, blade=-0.22): + br = math.sin(t * 2 * math.pi / 3.2) * 0.008 if breathe else 0.0 + R.spine(L, W, pitch=lean + br - recoil * 0.10, yaw=blade, roll=0.02) + R.look(L, W, yaw=-blade * 0.8, pitch=0.0) + # right shoulder up and forward into the stock, left one forward toward the fore-end + R.rot_world(L, W, 'clavicle_r', Quaternion(UP, -0.10) @ Quaternion(FWD, 0.10)) + R.rot_world(L, W, 'clavicle_l', Quaternion(UP, 0.12)) + C3 = chest_delta(W).to_3x3() + g = GUNS[gun] + # stock high in the shoulder pocket, so the head only has to come forward and down a little onto the comb + pocket = W['upperarm_r'].translation + C3 @ Vector((0.08, -0.05, 0.012)) + aim = (Quaternion(LEFT, -pitch + recoil * 0.22) @ FWD).normalized() + up = (Quaternion(LEFT, -pitch + recoil * 0.22) @ UP) + Wm = weapon_matrix(Vector(), aim, up) + butt = Vector((0, g['butt'], -0.02)) + origin = pocket - Wm.to_3x3() @ butt - aim * recoil * 0.04 + Wm.translation = origin + target = Wm @ Vector((0, g['eye'], g['sight'] + 0.012)) + err = head_to(L, W, target) + if err > 0.015: + # cannot get the cheek down far enough: raise the gun the rest of the way + e = eye_pos(W) + Wm.translation += Vector((0, 0, max(0.0, e.z - target.z))) + place_hands(L, W, Wm, gun) + return Wm + +def hold_low(L, W, t, gun='rifle', bob=0.0): + """Low ready: muzzle down-forward, stock under the right armpit.""" + R.spine(L, W, pitch=0.04, yaw=-0.12, roll=0.0) + R.look(L, W, yaw=0.10, pitch=0.02) + C = chest_delta(W) + aim = (Quaternion(UP, 0.22) @ Quaternion(LEFT, 0.2) @ FWD).normalized() + up = (Quaternion(UP, 0.22) @ Quaternion(LEFT, 0.2) @ Quaternion(FWD, 0.2) @ UP) + o = Vector((-0.12, -0.26, 1.2 + bob)) + Wm = C @ weapon_matrix(o, aim, up) + place_hands(L, W, Wm, gun) + return Wm + +def port_arms(L, W, t): + """Rifle diagonal across the chest for sprinting.""" + C = chest_delta(W) + aim = Vector((0.55, -0.35, 0.75)).normalized() + up = Vector((0.0, -0.9, 0.3)).normalized() + o = Vector((-0.10, -0.24, 1.20)) + Wm = C @ weapon_matrix(o, aim, up) + place_hands(L, W, Wm, 'rifle') + return Wm + +# ---------------- clip builders +CLIPS = {} +def clip(name, length, loop=True): + def deco(fn): + CLIPS[name] = (fn, length, loop) + return fn + return deco + +def base(name, t, speed=1.0): + d = dur(name) + L = R.from_action(src(name), (t * speed) % d if d > 0 else 0) + if name in ('Idle_Loop', 'Walk_Loop'): + # the source idle/walk slouch and look at the floor; a soldier stands taller and looks ahead + W = R.W(L) + R.spine(L, W, pitch=-0.07) + R.look(L, W, pitch=-0.22 if name == 'Idle_Loop' else -0.12) + return L + +def loc_strip(L): + pass + +def finalize(L, W, Wm=None, gun='rifle'): + """weapon_r: identity on the hand unless a weapon matrix is given.""" + if Wm is not None and GRIP.get(gun) is not None: + set_weapon_bone(L, W, Wm, GRIP[gun]) + else: + L['weapon_r'] = R.Lr['weapon_r'].copy() + return L + +GRIP = {} + +def solve_grips(): + L = base('Idle_Loop', 0.0); W = R.W(L) + # grips = the intended hand frames in weapon space (independent of whether the IK reached them) + Wm = stance_aim(L, W, 0.0, breathe=False) + GRIP['rifle'] = Wm.inverted() @ LAST['r'] + GRIP['rifleL'] = Wm.inverted() @ LAST['l'] + L = base('Idle_Loop', 0.0); W = R.W(L) + Wm = pistol_aim(L, W, 0.0) + GRIP['pistol'] = Wm.inverted() @ LAST['r'] + GRIP['pistolL'] = Wm.inverted() @ LAST['l'] + for k in ('rifle', 'pistol'): + print('grip', k, GRIP[k].translation, 'reach error r', (W['hand_r'].translation - LAST['r'].translation).length) + return GRIP + +def pistol_aim(L, W, t, recoil=0.0): + R.spine(L, W, pitch=0.05 - recoil * 0.1, yaw=-0.12, roll=0.0) + R.look(L, W, yaw=0.1, pitch=0.08) + Dh = R.delta(W, 'Head') + eye = W['Head'].translation + Dh @ (EYE_R + Vector((0.031, 0, 0)) - R.Mr['Head'].translation) + aim = (Quaternion(LEFT, recoil * 0.4) @ FWD).normalized() + up = Quaternion(LEFT, recoil * 0.4) @ UP + origin = eye + aim * 0.42 - up * 0.05 - aim * recoil * 0.04 + Wm = weapon_matrix(origin, aim, up) + place_hands(L, W, Wm, 'pistol') + return Wm + +# --- locomotion (full body, unarmed upper; the game layers a weapon pose on top) +for nm, srcn in [('idle', 'Idle_Loop'), ('walk', 'Walk_Loop'), ('run', 'Jog_Fwd_Loop'), ('sprint', 'Sprint_Loop'), + ('crouchWalk', 'Crouch_Fwd_Loop'), ('sitIdle', 'Sitting_Idle_Loop')]: + def mk(srcn=srcn): + def f(t): + L = base(srcn, t); W = R.W(L); return finalize(L, W) + return f + CLIPS[nm] = (mk(), dur(srcn), True) + +def _crouch_idle(t): + L = R.rest(); W = R.W(L); q = combat_crouch(L, W, t) + relaxed_arms(L, W, swing=0.0, bend=0.6, curl=0.4) + return finalize(L, W) +CLIPS['crouchIdle'] = (_crouch_idle, 3.2, True) + +if os.environ.get('UALTEST'): + for srcn in ['Death01', 'Hit_Knockback', 'Hit_Chest', 'Hit_Head', 'OverhandThrow', 'Melee_Hook', 'ClimbUp_1m', 'LayToIdle', 'Idle_Rail_Call', 'Punch_Cross', 'Roll', 'Interact', 'PickUp_Table']: + def mk(srcn=srcn): + def f(t): + L = base(srcn, min(t, dur(srcn) - 0.001)); W = R.W(L); return finalize(L, W) + return f + CLIPS['ual_' + srcn] = (mk(), dur(srcn), False) + +@clip('aimIdle', 3.2) +def c_aimIdle(t): + L = base('Idle_Loop', t); W = R.W(L) + Wm = stance_aim(L, W, t); return finalize(L, W) + +@clip('aimWalk', dur('Walk_Loop')) +def c_aimWalk(t): + L = base('Walk_Loop', t); W = R.W(L) + # steady the chest against the walk sway + Wm = stance_aim(L, W, t, breathe=False); return finalize(L, W) + +@clip('crouchAim', 3.2) +def c_crouchAim(t): + L = R.rest(); W = R.W(L); combat_crouch(L, W, t) + Wm = stance_aim(L, W, t, pitch=0.0, lean=0.06); return finalize(L, W) + +@clip('holdRifle', 2.5) +def c_hold(t): + L = base('Idle_Loop', t); W = R.W(L) + hold_low(L, W, t); return finalize(L, W) + +@clip('aimPistol', 3.2) +def c_aimPistol(t): + L = base('Idle_Loop', t); W = R.W(L) + pistol_aim(L, W, t); return finalize(L, W) + +@clip('sprintRifle', dur('Sprint_Loop')) +def c_sprintRifle(t): + L = base('Sprint_Loop', t); W = R.W(L) + port_arms(L, W, t); return finalize(L, W) + +@clip('fire', 0.3, loop=False) +def c_fire(t): + L = base('Idle_Loop', 0.4); W = R.W(L) + k = math.exp(-t * 18) * (1 - math.exp(-t * 90)) * 1.6 + stance_aim(L, W, 0.4, recoil=k, breathe=False); return finalize(L, W) + +@clip('firePistol', 0.3, loop=False) +def c_firePistol(t): + L = base('Idle_Loop', 0.4); W = R.W(L) + k = math.exp(-t * 16) * (1 - math.exp(-t * 90)) * 1.6 + pistol_aim(L, W, 0.4, recoil=k); return finalize(L, W) + +# ======================= authored full-body and upper clips ======================= +def ease(track, t): + """track: list of (time, value[, 'in'|'out'|'lin'|'smooth']).""" + if t <= track[0][0]: return track[0][1] + for k0, k1 in zip(track, track[1:]): + t0, v0 = k0[0], k0[1]; t1, v1 = k1[0], k1[1] + if t <= t1: + u = max(0.0, min(1.0, (t - t0) / max(1e-6, t1 - t0))) + mode = k1[2] if len(k1) > 2 else 'smooth' + if mode == 'in': u = u * u + elif mode == 'out': u = 1 - (1 - u) * (1 - u) + elif mode == 'smooth': u = u * u * (3 - 2 * u) + elif mode == 'bounce': u = 1 - abs(math.cos(u * math.pi * 1.5)) * (1 - u) if u < 1 else 1 + if isinstance(v0, Quaternion): return v0.slerp(v1, u) + if isinstance(v0, tuple): return tuple(a + (b - a) * u for a, b in zip(v0, v1)) + return v0 + (v1 - v0) * u + return track[-1][1] + +V = lambda x, y, z: Vector((x, y, z)) +PEL0 = R.Mr['pelvis'].translation.copy() +SH = {s: R.Mr['upperarm_' + s].translation.copy() for s in 'lr'} +HIPS = {s: R.Mr['thigh_' + s].translation.copy() for s in 'lr'} +ANK = {s: R.Mr['foot_' + s].translation.copy() for s in 'lr'} + +def pelvis_set(L, W, pos, pitch=0.0, yaw=0.0, roll=0.0): + q = Quaternion(UP, yaw) @ Quaternion(LEFT, pitch) @ Quaternion(FWD, -roll) + M = Matrix.Translation(pos) @ q.to_matrix().to_4x4() @ Matrix.Translation(-PEL0) @ R.Mr['pelvis'] + R.set_world(L, W, 'pelvis', M) + return q + +def spine_rel(L, W, q_body, pitch=0.0, yaw=0.0, roll=0.0, frac=(0.25, 0.35, 0.4)): + """Spine bend about the body's own axes (q_body = pelvis orientation).""" + up, left, fwd = q_body @ UP, q_body @ LEFT, q_body @ FWD + for b, f in zip(('spine_01', 'spine_02', 'spine_03'), frac): + R.rot_world(L, W, b, Quaternion(up, yaw * f) @ Quaternion(left, pitch * f) @ Quaternion(fwd, -roll * f)) + +def look_rel(L, W, q_body, yaw=0.0, pitch=0.0, roll=0.0, neck=0.45): + up, left, fwd = q_body @ UP, q_body @ LEFT, q_body @ FWD + for b, f in (('neck_01', neck), ('Head', 1 - neck)): + R.rot_world(L, W, b, Quaternion(up, yaw * f) @ Quaternion(left, pitch * f) @ Quaternion(fwd, -roll * f)) + +def leg(L, W, s, ankle, pole=FWD, foot_dir=None, foot_up=None): + R.two_bone(L, W, 'thigh_' + s, 'calf_' + s, 'foot_' + s, ankle, pole, Vector((1, 0, 0))) + if foot_dir is not None: + if foot_up is None: + R.aim_bone(L, W, 'foot_' + s, foot_dir) + else: + rest_up = Vector((0, 0, 1)) + R.aim_bone(L, W, 'foot_' + s, foot_dir, foot_up, rest_up) + +def arm_ik(L, W, s, wrist, pole, hdir=None, palm=None, curl=None): + hinge = Vector((0, 0, -1)) if s == 'l' else Vector((0, 0, 1)) + rot = R.hand_rot(s, hdir, palm) if hdir is not None else None + R.two_bone(L, W, 'upperarm_' + s, 'lowerarm_' + s, 'hand_' + s, wrist, pole, hinge, end_rot=rot) + if curl is not None: + R.curl(L, W, s, {'index': curl, 'middle': curl, 'ring': curl, 'pinky': curl}, thumb=curl * 0.6) + +def chest_pt(W, v): + """Point given in rest-chest coordinates, moved with the chest.""" + return chest_delta(W) @ v + +def relaxed_arms(L, W, swing=0.0, bend=0.35, curl=0.35, spread=0.12): + for s, sg in (('l', 1), ('r', -1)): + sh = W['upperarm_' + s].translation + C3 = chest_delta(W).to_3x3() + wrist = sh + C3 @ Vector((sg * spread, -0.12 - swing * sg, -0.5 + bend * 0.12)) + arm_ik(L, W, s, wrist, C3 @ Vector((sg * 0.6, 1.0, -0.2)), C3 @ Vector((sg * 0.15, -0.3, -1)), C3 @ Vector((-sg, 0.2, 0)), curl) + +# ---- prone +PRONE_Z = 0.13 +def prone_base(L, W, t, crawl=None): + q = pelvis_set(L, W, V(0, 0.15, PRONE_Z + 0.03), pitch=math.radians(84)) + spine_rel(L, W, q, pitch=-0.42, yaw=0.0) # chest up on the elbows + for s, sg in (('l', 1), ('r', -1)): + k = crawl.get(s, 0.0) if crawl else 0.0 + hip = W['thigh_' + s].translation + # leg straight back, feet slightly apart, toes in the ground; crawl draws the knee up to the side + ank = V(sg * (0.2 + 0.18 * k), hip.y + 0.86 - 0.42 * k, 0.09 + 0.04 * k) + leg(L, W, s, ank, pole=V(sg * (0.2 + k), 0.2 - k * 0.5, -1).normalized(), foot_dir=V(0, 0.35, -1).normalized()) + return q + +def prone_rifle(L, W, t, aim=False, crawl=None): + q = prone_base(L, W, t, crawl) + if aim: + look_rel(L, W, q, pitch=-0.65) + sh = W['upperarm_r'].translation + aimd = FWD.copy(); up = UP.copy() + Wm = weapon_matrix(Vector(), aimd, up) + pocket = sh + V(0.07, -0.05, 0.02) + Wm.translation = pocket - Wm.to_3x3() @ Vector((0, GUNS['rifle']['butt'], -0.02)) + target = Wm @ Vector((0, GUNS['rifle']['eye'], GUNS['rifle']['sight'] + 0.012)) + head_to(L, W, target, chain=('Head', 'neck_01'), limits=(0.6, 0.5)) + else: + look_rel(L, W, q, pitch=-0.75) + C = chest_delta(W) + Wm = weapon_matrix(V(-0.1, -0.45, 0.2), Quaternion(UP, 0.25) @ FWD, UP) + place_hands(L, W, Wm, 'rifle') + return Wm + +@clip('proneIdle', 3.0) +def c_proneIdle(t): + L = R.rest(); W = R.W(L) + prone_rifle(L, W, t); return finalize(L, W) + +@clip('proneAim', 3.0) +def c_proneAim(t): + L = R.rest(); W = R.W(L) + prone_rifle(L, W, t, aim=True); return finalize(L, W) + +@clip('proneCrawl', 1.6) +def c_proneCrawl(t): + ph = t / 1.6 * 2 * math.pi + kl = max(0.0, math.sin(ph)); kr = max(0.0, -math.sin(ph)) + L = R.rest(); W = R.W(L) + q = prone_base(L, W, t, crawl={'l': kl, 'r': kr}) + R.rot_world(L, W, 'pelvis', Quaternion(q @ UP, math.sin(ph) * 0.12)) + look_rel(L, W, q, pitch=-0.7, yaw=-math.sin(ph) * 0.1) + # elbows reach forward alternately; the rifle rides in the right hand across the forearms + C3 = chest_delta(W).to_3x3() + sh = W['upperarm_l'].translation + wrist = V(sh.x - 0.1, sh.y - 0.28 - 0.18 * kr, 0.11 + 0.05 * kr) + arm_ik(L, W, 'l', wrist, V(0.8, 0.1, -0.6), V(-0.4, -1, 0), V(0, 0, -1), 0.5) + sh = W['upperarm_r'].translation + Wm = weapon_matrix(V(sh.x + 0.1, sh.y - 0.42 - 0.18 * kl, 0.16 + 0.04 * kl), Quaternion(UP, 0.12) @ FWD, Quaternion(FWD, 0.5) @ UP) + place_hands(L, W, Wm, 'rifle', left=False) + return finalize(L, W) + +# ---- weapon handling (upper clips layered over legs) +def reload_pose(L, W, t, T=2.4): + """Rifle tilted, held by the left hand; right hand fetches a clip from the belt and loads from the top.""" + R.spine(L, W, pitch=0.12, yaw=-0.15) + R.look(L, W, yaw=0.15, pitch=0.35) + C = chest_delta(W) + tilt = ease([(0, 0.0), (0.25, 0.45), (T - 0.35, 0.45), (T, 0.0)], t) + aim = (Quaternion(UP, 0.35) @ Quaternion(LEFT, 0.35) @ FWD).normalized() + up = Quaternion(aim, -tilt) @ (Quaternion(UP, 0.35) @ Quaternion(LEFT, 0.35) @ UP) + Wm = C @ weapon_matrix(V(-0.06, -0.3, 1.26), aim, up) + place_hands(L, W, Wm, 'rifle', right=False) + # right hand path: grip -> belt pouch -> above the receiver (push) -> grip + g = GUNS['rifle'] + grip = Wm @ g['gripR']; top = Wm @ V(0.0, -0.04, 0.09); press = Wm @ V(0.0, -0.04, 0.045) + pouch = C @ V(-0.12, -0.22, 1.04) + pts = [(0.0, grip), (0.35, grip), (0.75, pouch), (0.95, pouch), (1.35, top), (1.6, press), (1.75, top), (2.0, grip), (T, grip)] + w = ease(pts, t) + on_grip = t < 0.4 or t > 1.95 + if on_grip: + place_hands(L, W, Wm, 'rifle', left=False) + else: + arm_ik(L, W, 'r', w - V(0, 0, 0.03), C.to_3x3() @ V(-1, 0.3, -0.5), C.to_3x3() @ V(0.2, -0.4, -1), C.to_3x3() @ V(1, 0, 0), 0.75) + return Wm + +@clip('reload', 2.4, loop=False) +def c_reload(t): + L = base('Idle_Loop', t); W = R.W(L) + Wm = reload_pose(L, W, t); return finalize(L, W, Wm) + +def bolt_pose(L, W, t, T=1.0): + Wm = stance_aim(L, W, 0.0, breathe=False, recoil=ease([(0, 0.4), (0.2, 0.0), (T, 0.0)], t)) + g = GUNS['rifle'] + knob = V(-0.062, 0.025, 0.012) + k_up = knob + V(0.0, 0.0, 0.035); k_back = k_up + V(0, 0.085, 0) + path = [(0.0, g['gripR'] + V(0, 0, 0)), (0.18, knob), (0.3, k_up), (0.48, k_back), (0.62, k_up), (0.72, knob), (0.92, g['gripR']), (T, g['gripR'])] + p = ease(path, t) + if t < 0.06 or t > 0.9: + return Wm + wp = Wm @ p + C3 = Wm.to_3x3() + arm_ik(L, W, 'r', wp - C3 @ V(-0.02, 0.06, 0.02), V(-1, 0.2, -0.6), C3 @ V(0.4, -0.2, -0.9), C3 @ V(0.8, 0, 0.3), 0.7) + return Wm + +@clip('boltCycle', 1.0, loop=False) +def c_bolt(t): + L = base('Idle_Loop', 0.4); W = R.W(L) + Wm = bolt_pose(L, W, t); return finalize(L, W, Wm) + +@clip('throw', 1.4, loop=False) +def c_throw(t): + """Overhand grenade throw: wind-up with the right arm back, step and release at ~0.75 s.""" + L = base('Idle_Loop', 0.3); W = R.W(L) + lean = ease([(0, 0.0), (0.45, -0.25), (0.75, 0.35, 'in'), (1.0, 0.25), (1.4, 0.0)], t) + twist = ease([(0, 0.0), (0.45, -0.6), (0.75, 0.45, 'in'), (1.4, 0.0)], t) + pel = PEL0 + V(0, ease([(0, 0.0), (0.45, 0.08), (0.8, -0.12), (1.4, 0.0)], t), ease([(0, -0.03), (0.45, -0.05), (0.8, -0.08), (1.4, -0.03)], t)) + q = pelvis_set(L, W, pel, yaw=twist * 0.4) + for s, sg in (('l', 1), ('r', -1)): + a0 = ANK[s].copy(); a0.z = 0.085 + fwd = ease([(0, 0.0), (0.45, 0.0), (0.75, -0.25), (1.4, -0.12)], t) if s == 'l' else ease([(0, 0.0), (0.45, 0.12), (1.4, 0.05)], t) + leg(L, W, s, a0 + V(0, fwd, 0), pole=FWD, foot_dir=V(0, -0.85, -0.5).normalized()) + spine_rel(L, W, q, pitch=lean, yaw=twist * 0.6) + look_rel(L, W, q, yaw=-twist * 0.6, pitch=-0.1) + C3 = chest_delta(W).to_3x3() + sh = W['upperarm_r'].translation + wr = ease([(0.0, V(-0.1, -0.25, -0.25)), (0.45, V(-0.12, 0.3, 0.25)), (0.72, V(-0.05, -0.25, 0.3), 'in'), (0.95, V(0.05, -0.45, -0.25)), (1.4, V(-0.1, -0.2, -0.45))], t) + arm_ik(L, W, 'r', sh + C3 @ wr, C3 @ V(-1, 0.3, -0.4), C3 @ wr.normalized(), C3 @ V(1, 0, 0), 0.8 if t < 0.75 else 0.2) + shl = W['upperarm_l'].translation + wl = ease([(0.0, V(0.15, -0.2, -0.45)), (0.45, V(0.15, -0.45, 0.05)), (0.8, V(0.2, 0.1, -0.4)), (1.4, V(0.15, -0.15, -0.48))], t) + arm_ik(L, W, 'l', shl + C3 @ wl, C3 @ V(1, 0.3, -0.5), C3 @ V(0.1, -1, 0.2), C3 @ V(-1, 0, 0), 0.4) + return finalize(L, W) + +@clip('melee', 0.9, loop=False) +def c_melee(t): + """Rifle-butt stroke: from low ready, the butt drives forward and up.""" + L = base('Idle_Loop', 0.3); W = R.W(L) + k = ease([(0, 0.0), (0.25, -0.35), (0.45, 1.0, 'in'), (0.6, 1.0), (0.9, 0.0)], t) + R.spine(L, W, pitch=0.05 + 0.15 * max(0, k), yaw=-0.1 + 0.45 * k) + R.look(L, W, yaw=-0.3 * k) + C = chest_delta(W) + aim = (Quaternion(UP, 0.4 + 0.8 * max(0, k)) @ Quaternion(LEFT, 0.5 - 1.3 * max(0, k)) @ FWD).normalized() + up = Quaternion(UP, 0.4) @ UP + Wm = C @ weapon_matrix(V(-0.12, -0.24 - 0.12 * max(0, k), 1.22 + 0.1 * max(0, k)), aim, up) + place_hands(L, W, Wm, 'rifle') + return finalize(L, W) + +@clip('hit', dur('Hit_Chest'), loop=False) +def c_hit(t): + L = base('Hit_Chest', min(t, dur('Hit_Chest') - 0.01)); W = R.W(L); return finalize(L, W) + +@clip('deathBack', dur('Death01'), loop=False) +def c_deathBack(t): + L = base('Death01', min(t, dur('Death01') - 0.01)); W = R.W(L); return finalize(L, W) + +def fall_front(L, W, t, run=False, twist=0.0): + """Weighty forward death: knees go first, torso folds, hits the ground, small settle.""" + T0 = 0.0 + if run: + z = ease([(0, PEL0.z - 0.05), (0.25, PEL0.z - 0.02), (0.55, 0.62, 'in'), (0.8, 0.18, 'in'), (0.92, 0.22, 'out'), (1.1, 0.16), (2.0, 0.15)], t) + y = ease([(0, 0.0), (0.8, -0.85, 'lin'), (1.2, -1.15, 'out'), (2.0, -1.15)], t) + pit = ease([(0, 0.25), (0.55, 0.8, 'in'), (0.85, 1.48, 'in'), (0.95, 1.42), (1.2, 1.5), (2.0, 1.5)], t) + else: + z = ease([(0, PEL0.z - 0.02), (0.18, PEL0.z - 0.06), (0.55, 0.55, 'in'), (0.85, 0.2, 'in'), (0.95, 0.24, 'out'), (1.15, 0.16), (2.4, 0.15)], t) + y = ease([(0, 0.0), (0.55, -0.25), (0.95, -0.55, 'in'), (2.4, -0.6)], t) + pit = ease([(0, 0.0), (0.2, -0.08), (0.55, 0.45, 'in'), (0.9, 1.45, 'in'), (1.0, 1.38), (1.25, 1.5), (2.4, 1.5)], t) + q = pelvis_set(L, W, V(0, y, z), pitch=pit, yaw=0.15 + twist * ease([(0, 0.0), (0.5, 0.6), (1.0, 1.0), (2.4, 1.0)], t), roll=ease([(0, 0.0), (1.0, 0.18), (2.4, 0.22)], t) + twist * 0.35 * ease([(0, 0.0), (1.0, 1.0)], t)) + curl = ease([(0, 0.0), (0.35, 0.35), (0.85, 0.15), (1.0, -0.15), (1.3, -0.05)], t) + spine_rel(L, W, q, pitch=curl, roll=0.1) + look_rel(L, W, q, yaw=ease([(0, 0.0), (1.0, 0.7), (2.4, 0.9)], t), pitch=ease([(0, 0.2), (0.9, -0.2), (1.2, 0.1)], t)) + # knees buckle then legs trail + for s, sg in (('l', 1), ('r', -1)): + hip = W['thigh_' + s].translation + kd = ease([(0, 0.0), (0.45, 0.42), (0.9, 0.25), (1.3, 0.15)], t) + ank_g = V(sg * 0.14 + (0.04 if s == 'l' else -0.02), y + 0.15 + (0.0 if s == 'l' else 0.1), 0.09) + ank_l = V(sg * 0.18, hip.y + 0.7 + (0.12 if s == 'r' else 0.0), 0.12 + (0.12 if s == 'l' else 0.0)) + u = smooth((t - 0.35) / 0.6) + ank = ank_g.lerp(ank_l, u) + leg(L, W, s, ank, pole=(q @ FWD).normalized().lerp(V(0, 0, -1), u) + V(sg * 0.2, 0, 0), foot_dir=V(0, 0.3, -1).normalized() if u > 0.5 else V(0, -0.8, -0.6).normalized()) + # arms reach out to break the fall, then go limp + C3 = chest_delta(W).to_3x3() + for s, sg in (('l', 1), ('r', -1)): + sh = W['upperarm_' + s].translation + a = ease([(0, V(sg * 0.12, -0.15, -0.5)), (0.6, V(sg * 0.2, -0.45, -0.2)), (0.95, V(sg * 0.35, -0.3, -0.05)), (1.3, V(sg * 0.42, -0.05, 0.1)), (2.4, V(sg * 0.42, 0.0, 0.12))], t) + w = sh + C3 @ a + w.z = max(w.z, 0.06) + arm_ik(L, W, s, w, C3 @ V(sg, 0.4, -0.3), C3 @ a.normalized(), V(0, 0, -1), ease([(0, 0.4), (1.0, 0.2), (1.5, 0.45)], t)) + +@clip('deathFront', 2.4, loop=False) +def c_deathFront(t): + L = R.rest(); W = R.W(L) + fall_front(L, W, t); return finalize(L, W) + +@clip('deathLeft', 2.4, loop=False) +def c_deathLeft(t): + # hit from the left: spins away to the right as the knees go + L = R.rest(); W = R.W(L) + fall_front(L, W, t, twist=-1.1); return finalize(L, W) + +@clip('deathRight', 2.4, loop=False) +def c_deathRight(t): + L = R.rest(); W = R.W(L) + fall_front(L, W, t, twist=1.1); return finalize(L, W) + +@clip('deathCover', 2.2, loop=False) +def c_deathCover(t): + # from a crouch behind cover: slumps down onto the side and rolls back against the wall + L = R.rest(); W = R.W(L) + k = ease([(0, 0.0), (0.4, 0.3), (1.0, 1.0, 'in'), (1.15, 0.95), (2.2, 1.0)], t) + z = lerp(PEL0.z - 0.3, 0.2, k) + q = pelvis_set(L, W, V(0.0, 0.15 * k, z), pitch=lerp(0.12, -0.5, k), roll=lerp(0.0, 0.9, k), yaw=0.2 * k) + for s, sg in (('l', 1), ('r', -1)): + a = V(sg * 0.2, lerp(-0.1, -0.55, k) + (0.1 if s == 'r' else 0), 0.09) + leg(L, W, s, a, pole=V(sg * 0.4, -1, 0.3 * k).normalized(), foot_dir=V(0, -0.85, -0.5).normalized()) + spine_rel(L, W, q, pitch=lerp(0.1, -0.2, k), roll=0.2 * k) + look_rel(L, W, q, pitch=lerp(0.0, 0.6, k), roll=0.5 * k) + C3 = chest_delta(W).to_3x3() + for s, sg in (('l', 1), ('r', -1)): + sh = W['upperarm_' + s].translation + arm_ik(L, W, s, sh + C3 @ V(sg * 0.15, -0.15 + 0.1 * k, -0.48), C3 @ V(sg, 0.3, -0.3), C3 @ V(0, -0.2, -1), C3 @ V(-sg, 0, 0), 0.4) + return finalize(L, W) + +@clip('deathRun', 2.0, loop=False) +def c_deathRun(t): + L = R.rest(); W = R.W(L) + fall_front(L, W, t, run=True); return finalize(L, W) + +@clip('stagger', 1.3, loop=False) +def c_stagger(t): + """Wounded hit: torso snaps back, a step back, hunched with a hand to the side, then recovers.""" + L = base('Idle_Loop', 0.5); W = R.W(L) + k = ease([(0, 0.0), (0.12, 1.0, 'out'), (0.5, 0.6), (1.3, 0.0)], t) + hunch = ease([(0, 0.0), (0.25, -0.1), (0.6, 0.45), (1.0, 0.3), (1.3, 0.0)], t) + pel = PEL0 + V(0, ease([(0, 0.0), (0.3, 0.14), (0.7, 0.18), (1.3, 0.0)], t), -0.06 * k - 0.04 * max(0, hunch)) + q = pelvis_set(L, W, pel, pitch=-0.15 * k + 0.15 * max(0, hunch), yaw=0.2 * k) + for s, sg in (('l', 1), ('r', -1)): + a0 = ANK[s].copy(); a0.z = 0.085 + back = ease([(0, 0.0), (0.25, 0.0), (0.45, 0.3), (1.3, 0.0)], t) if s == 'r' else ease([(0, 0.0), (0.55, 0.0), (0.75, 0.18), (1.3, 0.0)], t) + lift = 0.08 * math.sin(max(0, min(1, (t - (0.25 if s == 'r' else 0.55)) / 0.2)) * math.pi) + leg(L, W, s, a0 + V(0, back, lift), pole=FWD, foot_dir=V(0, -0.85, -0.5).normalized()) + spine_rel(L, W, q, pitch=-0.25 * k + hunch, yaw=0.3 * k) + look_rel(L, W, q, pitch=-0.2 * k + 0.2 * hunch) + C3 = chest_delta(W).to_3x3() + shl = W['upperarm_l'].translation + arm_ik(L, W, 'l', W['spine_02'].translation + C3 @ V(0.13, -0.08, -0.05), C3 @ V(1, 0.3, -0.5), C3 @ V(-0.3, -0.2, -1), C3 @ V(-1, 0.3, 0), 0.5) + shr = W['upperarm_r'].translation + arm_ik(L, W, 'r', shr + C3 @ V(-0.2, -0.15 + 0.2 * k, -0.45), C3 @ V(-1, 0.4, -0.3), C3 @ V(0, -0.2, -1), C3 @ V(1, 0, 0), 0.5) + return finalize(L, W) + +@clip('alert', 4.0) +def c_alert(t): + L = base('Idle_Loop', t * 0.6); W = R.W(L) + sc = ease([(0, 0.0), (0.8, 0.7), (1.6, 0.7), (2.4, -0.6), (3.3, -0.6), (4.0, 0.0)], t) + R.spine(L, W, pitch=0.03, yaw=sc * 0.35) + R.look(L, W, yaw=sc * 0.6, pitch=0.05) + hold_low(L, W, t) + return finalize(L, W) + +@clip('salute', 2.0, loop=False) +def c_salute(t): + L = base('Idle_Loop', 0.6); W = R.W(L) + k = ease([(0, 0.0), (0.35, 1.0), (1.5, 1.0), (2.0, 0.0)], t) + for s in 'lr': + a0 = ANK[s].copy(); a0.z = 0.085; a0.x *= 0.7 + leg(L, W, s, a0, pole=FWD, foot_dir=V(0, -0.85, -0.5).normalized()) + R.look(L, W, pitch=-0.05) + C3 = chest_delta(W).to_3x3() + eye = eye_pos(W) + tgt = eye + V(-0.07, -0.02, 0.0) + sh = W['upperarm_r'].translation + rest = sh + C3 @ V(-0.05, -0.05, -0.53) + arm_ik(L, W, 'r', rest.lerp(tgt, k), V(-1, 0.1, 0.0), V(0.5, -0.2, 0.55).normalized().lerp(V(0, -0.15, -1), 1 - k).normalized(), V(0, -0.6, 0.6).normalized().lerp(V(1, 0, 0), 1 - k), 0.05) + shl = W['upperarm_l'].translation + arm_ik(L, W, 'l', shl + C3 @ V(0.04, -0.03, -0.53), C3 @ V(1, 0.3, 0), C3 @ V(0, -0.1, -1), C3 @ V(-1, 0, 0), 0.3) + return finalize(L, W) + +def crouch_legs(L, W, depth=0.38, lean=0.25, wide=0.22, stagger=0.25): + q = pelvis_set(L, W, V(0, 0.05, PEL0.z - depth), pitch=lean) + for s, sg in (('l', 1), ('r', -1)): + a = V(sg * wide, (-stagger if s == 'l' else 0.12), 0.085) + leg(L, W, s, a, pole=V(sg * 0.3, -1, 0.1).normalized(), foot_dir=V(0, -0.85, -0.5).normalized()) + return q + +@clip('stackUp', 2.4) +def c_stackUp(t): + L = R.rest(); W = R.W(L) + q = crouch_legs(L, W, depth=0.22 + 0.01 * math.sin(t * 2.6), lean=0.3, wide=0.17, stagger=0.2) + spine_rel(L, W, q, pitch=0.05, yaw=-0.1) + look_rel(L, W, q, pitch=-0.25, yaw=0.1) + hold_low(L, W, t) + return finalize(L, W) + +@clip('wallLean', 3.0) +def c_wallLean(t): + """Shoulder against a wall on the character's left, rifle at low ready, catching breath.""" + L = base('Idle_Loop', t); W = R.W(L) + q = pelvis_set(L, W, PEL0 + V(0.05, 0.02, -0.05), roll=0.08) + for s, sg in (('l', 1), ('r', -1)): + a = V(sg * 0.17 - 0.06, -0.02 + (0.1 if s == 'r' else 0), 0.085) + leg(L, W, s, a, pole=FWD, foot_dir=V(0, -0.85, -0.5).normalized()) + spine_rel(L, W, q, roll=0.12 + 0.01 * math.sin(t * 2.1), pitch=0.04 + 0.015 * math.sin(t * 2.1)) + look_rel(L, W, q, yaw=0.25, pitch=0.05) + hold_low(L, W, t) + return finalize(L, W) + +@clip('breachKick', 1.2, loop=False) +def c_breach(t): + """Front kick at a door (contact ~0.45 s), rifle held at low ready.""" + L = base('Idle_Loop', 0.4); W = R.W(L) + chamber = ease([(0, 0.0), (0.25, 1.0), (0.42, 0.2, 'in'), (0.6, 0.7), (0.9, 0.0), (1.2, 0.0)], t) + ext = ease([(0, 0.0), (0.25, 0.0), (0.42, 1.0, 'in'), (0.55, 0.6), (0.9, 0.0)], t) + q = pelvis_set(L, W, PEL0 + V(0.03, 0.06 * ext, -0.03 - 0.03 * chamber), pitch=-0.25 * ext + 0.08 * chamber) + a0 = ANK['l'].copy(); a0.z = 0.085 + leg(L, W, 'l', a0 + V(0, 0.05, 0), pole=FWD, foot_dir=V(0, -0.85, -0.5).normalized()) + hip = W['thigh_r'].translation + k_pos = V(-0.12, -0.25 * chamber, 0.09 + 0.45 * chamber) + e_pos = V(-0.12, -0.75, 0.55) + ank = k_pos.lerp(e_pos, ext) + ank.z += 0.0 + leg(L, W, 'r', ank, pole=V(0, -1, 0.6).normalized(), foot_dir=V(0, -1, 0.5).normalized().lerp(V(0, -0.85, -0.5), 1 - ext).normalized()) + spine_rel(L, W, q, pitch=0.12 * ext - 0.05, yaw=-0.1) + look_rel(L, W, q, pitch=0.2) + hold_low(L, W, t) + return finalize(L, W) + +@clip('signalMoveUp', 1.3, loop=False) +def c_signal(t): + """Left hand raised beside the head, then chopped forward: 'move up'. Rifle stays in the right hand.""" + L = base('Idle_Loop', 0.5); W = R.W(L) + R.spine(L, W, pitch=0.04, yaw=0.12) + R.look(L, W, yaw=0.5, pitch=0.0) + C = chest_delta(W) + aim = (Quaternion(UP, 0.2) @ Quaternion(LEFT, 0.7) @ FWD).normalized() + Wm = C @ weapon_matrix(V(-0.16, -0.18, 1.12), aim, Quaternion(UP, 0.2) @ UP) + place_hands(L, W, Wm, 'rifle', left=False) + C3 = C.to_3x3() + shl = W['upperarm_l'].translation + w = ease([(0, V(0.12, -0.2, -0.45)), (0.3, V(0.12, -0.05, 0.22)), (0.55, V(0.1, -0.5, 0.05), 'in'), (0.75, V(0.08, -0.55, -0.02)), (1.3, V(0.12, -0.2, -0.45))], t) + hd = ease([(0, V(0, -0.2, -1)), (0.3, V(0, 0, 1)), (0.55, V(-0.1, -1, 0.1)), (1.3, V(0, -0.2, -1))], t) + arm_ik(L, W, 'l', shl + C3 @ w, C3 @ V(1, 0.3, -0.5), C3 @ hd.normalized(), C3 @ V(-1, 0, 0), 0.0) + return finalize(L, W) + +@clip('fireCrouch', 0.3, loop=False) +def c_fireCrouch(t): + L = R.rest(); W = R.W(L); combat_crouch(L, W, 0.4, breathe=False) + k = math.exp(-t * 18) * (1 - math.exp(-t * 90)) * 1.6 + stance_aim(L, W, 0.4, recoil=k, breathe=False, lean=0.06); return finalize(L, W) + +def combat_crouch(L, W, t=0.0, breathe=True): + """Combat crouch: half squat with the left foot forward, back fairly straight, head up.""" + b = math.sin(t * 2 * math.pi / 3.2) * 0.006 if breathe else 0.0 + q = crouch_legs(L, W, depth=0.33 + b, lean=0.08, wide=0.19, stagger=0.3) + spine_rel(L, W, q, pitch=0.06) + look_rel(L, W, q, pitch=-0.04) + return q + +def cover_pose(L, W, t, recoil=0.0): + q = crouch_legs(L, W, depth=0.3, lean=0.12, wide=0.2, stagger=0.28) + return stance_aim(L, W, t, recoil=recoil, breathe=recoil == 0, lean=0.12) + +@clip('aimCover', 3.2) +def c_aimCover(t): + L = R.rest(); W = R.W(L) + cover_pose(L, W, t); return finalize(L, W) + +@clip('fireCover', 0.3, loop=False) +def c_fireCover(t): + L = R.rest(); W = R.W(L) + k = math.exp(-t * 18) * (1 - math.exp(-t * 90)) * 1.6 + cover_pose(L, W, 0.4, recoil=k); return finalize(L, W) + +@clip('limp', dur('Walk_Loop') * 1.25) +def c_limp(t): + """Wounded walk: the right leg stays stiff, the body dips onto the left, rifle low.""" + d = dur('Walk_Loop') * 1.25 + ts = t / 1.25 + L = base('Walk_Loop', ts); W = R.W(L) + ph = ts / dur('Walk_Loop') * 2 * math.pi + # stiffen the right knee by re-solving its leg with the ankle pulled toward a straight leg + hip = W['thigh_r'].translation; ank = W['foot_r'].translation.copy() + straight = hip + (ank - hip).normalized() * (R.len['thigh_r'] + R.len['calf_r']) * 0.985 + leg(L, W, 'r', ank.lerp(straight, 0.55), pole=FWD) + dip = 0.035 * max(0.0, math.sin(ph)) + pelvis_set(L, W, W['pelvis'].translation - V(0, 0, dip), roll=0.05 * math.sin(ph), pitch=0.08) + R.spine(L, W, roll=-0.1 - 0.06 * math.sin(ph), pitch=0.12) + hold_low(L, W, t) + return finalize(L, W) + +@clip('holdPistol', 2.5) +def c_holdPistol(t): + L = base('Idle_Loop', t); W = R.W(L) + R.spine(L, W, pitch=0.03) + C = chest_delta(W) + aim = (Quaternion(LEFT, 0.8) @ FWD).normalized() + Wm = C @ weapon_matrix(V(-0.14, -0.3, 1.05), aim, Quaternion(LEFT, 0.8) @ UP) + place_hands(L, W, Wm, 'pistol') + return finalize(L, W) + +def vault_pose(L, W, t, T=0.9): + """Hand-plant vault over a ~1 m wall that starts 0.5 m ahead. In place: the game moves the root ~1.3 m forward.""" + u = t / T + # pelvis rises over the wall and drops on the far side (root is moved by the game, so y stays ~0) + z = ease([(0, PEL0.z - 0.05), (0.2, PEL0.z - 0.12), (0.45, 1.32, 'out'), (0.7, 1.2), (0.9, PEL0.z - 0.12, 'in'), (1.1, PEL0.z - 0.03)], t) + side = ease([(0, 0.0), (0.45, 0.1), (0.9, 0.0)], t) + q = pelvis_set(L, W, V(side, 0.0, z), pitch=ease([(0, 0.1), (0.4, 0.35), (0.75, 0.1), (1.1, 0.0)], t), roll=ease([(0, 0.0), (0.45, -0.35), (0.9, 0.0)], t)) + spine_rel(L, W, q, pitch=ease([(0, 0.1), (0.4, 0.3), (0.8, 0.1), (1.1, 0.0)], t)) + look_rel(L, W, q, pitch=-0.15) + tuck = ease([(0, 0.0), (0.25, 0.2), (0.45, 1.0), (0.7, 0.7), (0.9, 0.0)], t) + for s, sg in (('l', 1), ('r', -1)): + hip = W['thigh_' + s].translation + ground = V(sg * 0.12, 0.0, 0.085 + max(0.0, z - PEL0.z) * 0.0) + tucked = hip + V(-0.25, -0.1 + (0.08 if s == 'l' else -0.05), -0.42) + a = ground.lerp(tucked, tuck) + a.z = max(a.z, 0.085) + leg(L, W, s, a, pole=V(-0.5, -1, 0.2).normalized(), foot_dir=V(0, -0.85, -0.5).normalized()) + # left hand planted on the wall top, right hand keeps the rifle + plant = ease([(0, 0.0), (0.15, 1.0), (0.55, 1.0), (0.7, 0.0), (1.1, 0.0)], t) + C3 = chest_delta(W).to_3x3() + shl = W['upperarm_l'].translation + wall = V(0.15, -0.25, 1.02) + free = shl + C3 @ V(0.15, -0.2, -0.45) + arm_ik(L, W, 'l', free.lerp(wall, plant), V(1, 0.5, 0), V(0.1, -1, -0.2).normalized().lerp(V(0, -0.2, -1), 1 - plant), V(0, 0, -1).lerp(V(-1, 0, 0), 1 - plant), 0.3) + hold_low(L, W, t) + place_hands(L, W, chest_delta(W) @ weapon_matrix(V(-0.13, -0.24, 1.22), (Quaternion(UP, 0.25) @ Quaternion(LEFT, 0.55) @ FWD).normalized(), UP), 'rifle', left=False) + +@clip('vault', 1.1, loop=False) +def c_vault(t): + L = R.rest(); W = R.W(L) + vault_pose(L, W, t); return finalize(L, W) + +# ---- paired takedown: attacker grabs from behind (left arm round the neck), strikes, lowers the victim. +# Victim root = attacker root + 0.42 m forward, same facing. 2.6 s. No blood or wounds are shown. +TD = 2.6 +def victim_path(t): + return {'pel': ease([(0, PEL0 + V(0, 0, -0.02)), (0.35, PEL0 + V(0, 0.12, -0.04)), (1.2, PEL0 + V(0, 0.18, -0.08)), (1.7, V(0, 0.25, 0.62), 'in'), + (2.1, V(0, 0.15, 0.2), 'in'), (2.6, V(0, 0.1, 0.16))], t), + 'pit': ease([(0, 0.0), (0.35, -0.3), (1.2, -0.25), (1.7, 0.2), (2.1, 1.2, 'in'), (2.6, 1.45)], t)} + +@clip('takedown', TD, loop=False) +def c_takedown(t): + L = base('Idle_Loop', 0.3); W = R.W(L) + vp = victim_path(t) + fwd = ease([(0, 0.0), (0.3, -0.12), (1.4, -0.12), (2.1, -0.15), (2.6, -0.05)], t) + down = ease([(0, 0.0), (0.3, 0.06), (1.3, 0.08), (2.0, 0.42), (2.6, 0.12)], t) + q = pelvis_set(L, W, PEL0 + V(0, fwd, -down), pitch=ease([(0, 0.0), (0.3, 0.1), (1.3, 0.05), (2.0, 0.5), (2.6, 0.1)], t)) + for s, sg in (('l', 1), ('r', -1)): + a = V(sg * 0.18, (-0.18 if s == 'l' else 0.1) + fwd * 0.5, 0.085) + leg(L, W, s, a, pole=V(sg * 0.2, -1, 0).normalized(), foot_dir=V(0, -0.85, -0.5).normalized()) + spine_rel(L, W, q, pitch=ease([(0, 0.0), (0.3, 0.05), (1.3, 0.0), (2.0, 0.4), (2.6, 0.1)], t)) + look_rel(L, W, q, pitch=0.15) + C3 = chest_delta(W).to_3x3() + # victim neck in attacker space + vneck = V(0, -0.42, 0) + vp['pel'] + V(0, -0.1 * math.sin(vp['pit']), 0.55 * math.cos(vp['pit'])) + grab = ease([(0, 0.0), (0.3, 1.0), (2.2, 1.0), (2.6, 0.0)], t) + shl = W['upperarm_l'].translation + w = (shl + C3 @ V(0.15, -0.2, -0.45)).lerp(vneck + V(-0.06, -0.03, -0.02), grab) + arm_ik(L, W, 'l', w, V(1, 0.2, 0), V(-1, -0.2, 0), V(0, 1, 0), 0.7) + # right hand: knife strike to the victim's side at ~0.9 s and 1.25 s + shr = W['upperarm_r'].translation + strike = ease([(0, 0.0), (0.6, -0.4), (0.85, 1.0, 'in'), (1.0, 0.6), (1.15, 1.0, 'in'), (1.4, 0.0), (2.6, -0.2)], t) + wr = shr + C3 @ V(-0.08, -0.15 - 0.25 * max(0, strike), -0.32 + 0.1 * strike) + arm_ik(L, W, 'r', wr, V(-1, 0.3, -0.3), C3 @ V(0.2, -0.6, -0.6), C3 @ V(1, 0, 0), 0.9) + return finalize(L, W) + +@clip('takedownVictim', TD, loop=False) +def c_takedownVictim(t): + L = base('Idle_Loop', 0.3); W = R.W(L) + vp = victim_path(t) + q = pelvis_set(L, W, vp['pel'], pitch=vp['pit'], yaw=ease([(0, 0.0), (2.6, 0.25)], t)) + knees = ease([(0, 0.0), (1.2, 0.2), (1.7, 1.0), (2.1, 0.4), (2.6, 0.1)], t) + for s, sg in (('l', 1), ('r', -1)): + a0 = V(sg * 0.13, 0.05, 0.085) + lying = V(sg * 0.2, vp['pel'].y + 0.85, 0.1) + kneel = V(sg * 0.15, 0.45, 0.1) + u = smooth((t - 1.2) / 0.5); v2 = smooth((t - 1.8) / 0.6) + a = a0.lerp(kneel, u).lerp(lying, v2) + leg(L, W, s, a, pole=V(sg * 0.1, -1, -0.2 * v2).normalized(), foot_dir=V(0, -0.85, -0.5).normalized().lerp(V(0, 0.3, -1), v2).normalized()) + spine_rel(L, W, q, pitch=ease([(0, 0.0), (0.35, -0.25), (1.2, -0.15), (1.7, 0.2), (2.6, -0.1)], t)) + look_rel(L, W, q, pitch=ease([(0, 0.0), (0.35, -0.4), (1.4, 0.2), (2.6, 0.0)], t), yaw=ease([(0, 0.0), (2.6, 0.8)], t)) + C3 = chest_delta(W).to_3x3() + neck = W['neck_01'].translation + claw = ease([(0, 0.0), (0.35, 1.0), (1.3, 1.0), (1.7, 0.0)], t) + for s, sg in (('l', 1), ('r', -1)): + sh = W['upperarm_' + s].translation + limp = sh + C3 @ V(sg * 0.25, -0.1, -0.4) + grab = neck + C3 @ V(sg * 0.05, -0.08, -0.02) + arm_ik(L, W, s, limp.lerp(grab, claw), C3 @ V(sg, 0.2, -0.5), C3 @ V(0, 0.2, 1).lerp(V(sg * 0.2, -0.1, -1), 1 - claw).normalized(), C3 @ V(0, 1, 0), 0.6 * claw + 0.3) + return finalize(L, W) + +# ======================= locomotion set for actor.drive() ======================= +# Every loop: left foot contact at phase 0, right at 0.5. META records duration and stride (m per cycle). +META = {} + +def foot_samples(fn, T, n=120): + out = [] + for i in range(n): + t = T * i / n + L = fn(t); W = R.W(L) + out.append((t, W['foot_l'].translation.copy(), W['foot_r'].translation.copy(), W['ball_l'].translation.copy())) + return out + +def analyse(fn, T): + """Left heel strike time (foot furthest forward while low) and ground speed of the planted foot.""" + S = foot_samples(fn, T) + zs = [s[1].z for s in S]; zmin = min(zs) + # heel strike: left foot most forward (min y) among low samples + low = [s for s in S if s[1].z < zmin + 0.04] + t0 = min(low, key=lambda s: s[1].y)[0] if low else 0.0 + # planted-foot speed (relative to body): median backward speed while low + sp = [] + bmin = min(s[3].z for s in S) + for a, b in zip(S, S[1:] + S[:1]): + if a[3].z < bmin + 0.012 and b[3].z < bmin + 0.012: + dt = (b[0] - a[0]) % T or T / len(S) + sp.append((b[3].y - a[3].y) / dt) + sp.sort() + v = sp[len(sp) // 2] if sp else 0.0 + return t0, v + +def from_source(name, srcn, speed=1.0): + T = dur(srcn) / speed + def raw(t): + L = base(srcn, (t * speed) % dur(srcn)); W = R.W(L); return finalize(L, W) + t0, v = analyse(raw, T) + def f(t): + return raw((t + t0) % T) + CLIPS[name] = (f, T, True) + META[name] = {'duration': T, 'stride': abs(v) * T, 'speed': abs(v)} + +def gait(name, theta_deg, v, T, beta, crouch=0.0, lift=0.09, bob=0.025, width=0.1, lean=0.05, arm=0.25, heel=0.45): + """Procedural step cycle on the shared skeleton. theta: travel direction (0 forward, +90 left, 180 back).""" + th = math.radians(theta_deg) + S = v * T + # hips turn toward sideways travel (legs walk a diagonal), chest counter-turns to keep facing the aim + if abs(theta_deg) <= 140: + psi = max(-1.0, min(1.0, th * 0.68)) + else: + b = th - math.copysign(math.pi, th) + psi = max(-0.55, min(0.55, b * 0.55)) + d = Vector((math.sin(th), -math.cos(th), 0)) # travel direction in root space + hipf = Quaternion(UP, psi) + def f(t): + ph = (t / T) % 1.0 + L = R.rest(); W = R.W(L) + jog = beta < 0.5 + # pelvis: bob (low at contact for walk, at mid-stance for jog), sway over the stance foot, counter yaw + if jog: + zb = -bob * math.cos(4 * math.pi * (ph - beta * 0.5)) + else: + zb = -bob * math.cos(4 * math.pi * ph) + sway = (0.02 if not jog else 0.01) * math.sin(2 * math.pi * (ph + 0.25)) + pos = Vector((0, 0.0, PEL0.z - crouch + zb - (0.005 if jog else 0.0))) + (hipf @ Vector((sway, 0, 0))) + oy = 0.07 * math.sin(2 * math.pi * ph) * (1.0 if not jog else 0.8) + q = pelvis_set(L, W, pos, pitch=lean + crouch * 0.9, yaw=psi + oy, roll=0.035 * math.sin(2 * math.pi * ph + math.pi / 2)) + # feet + for s, off, sg in (('l', 0.0, 1), ('r', 0.5, -1)): + u = (ph - off) % 1.0 + base_p = hipf @ Vector((sg * width, 0.01, 0.0)) + if u < beta: + k = u / beta + disp = S * beta * (0.5 - k); h = 0.0 + rollp = -heel * max(0.0, (k - 0.7) / 0.3) ** 2 * 0.6 # heel peels up before toe-off + else: + k = (u - beta) / (1 - beta) + e = k * k * (3 - 2 * k) + disp = S * beta * (-0.5 + e) + h = lift * math.sin(math.pi * k) ** (0.8 if jog else 1.2) + (0.02 if k > 0.8 else 0) + rollp = -heel * (1 - k) ** 2 * 0.9 + 0.18 * max(0.0, (k - 0.7) / 0.3) # toe up before heel strike + ank = base_p + d * disp + ank.z = 0.086 + h + max(0.0, -rollp) * 0.07 + fdir = (hipf @ Quaternion(UP, 0.0) @ Vector((0, -0.85, -0.5))).normalized() + fdir = (Quaternion(hipf @ LEFT, -rollp) @ fdir).normalized() + leg(L, W, s, ank, pole=(hipf @ FWD + Vector((sg * 0.15, 0, 0))).normalized(), foot_dir=fdir) + # torso: counter the hip turn, lean with speed, counter-swing + spine_rel(L, W, q, pitch=-0.02 - crouch * 0.6, yaw=-(psi + oy) * 0.95) + look_rel(L, W, q, yaw=0.0, pitch=0.05 + crouch * 0.4) + # arms swing opposite to the legs (left arm back when the left foot lands) + back = -1.0 if abs(theta_deg) > 100 else 1.0 + relaxed_arms(L, W, swing=-arm * math.cos(2 * math.pi * ph) * back, bend=0.35 + (0.6 if jog else 0.0) + crouch) + return finalize(L, W) + CLIPS[name] = (f, T, True) + META[name] = {'duration': T, 'stride': S, 'speed': v, 'theta': theta_deg} + +DIRS = [('F', 0), ('FL', 45), ('L', 90), ('BL', 135), ('B', 180), ('BR', -135), ('R', -90), ('FR', -45)] +from_source('walkF', 'Walk_Loop') +for tag, th in DIRS: + wd = 0.095 if abs(th) < 60 or abs(th) > 120 else 0.12 + if tag != 'F': + gait('walk' + tag, th, 1.35, 1.1, 0.62, lift=0.075, bob=0.02, width=wd, lean=0.03, arm=0.12) + if True: + gait('crouch' + tag, th, 1.1, 1.15, 0.65, crouch=0.30, lift=0.07, bob=0.012, width=wd + 0.03, lean=0.06, arm=0.08) + gait('jog' + tag, th, 3.4, 0.74, 0.40, lift=0.13, bob=0.025, width=wd - 0.01, lean=0.06 if abs(th) < 100 else -0.02, arm=0.22) +gait('sprintF', 0, 6.0, 0.64, 0.34, lift=0.17, bob=0.04, width=0.08, lean=0.1, arm=0.34, heel=0.6) +META['proneCrawl'] = {'duration': 1.6, 'stride': 0.9, 'speed': 0.56} +gait('turnStep', 0, 0.0, 0.9, 0.6, lift=0.05, bob=0.008, width=0.1, lean=0.0, arm=0.0) +gait('crouchTurnStep', 0, 0.0, 1.0, 0.62, crouch=0.30, lift=0.045, bob=0.006, width=0.13, lean=0.06, arm=0.0) + +# ---------------- captured locomotion (CMU motion capture, retargeted; see mocap.py and mocap_list.py) +import mocap as MC, mocap_list as ML +CMU_DIR = L_.WORK + '/cmu/data/' +OUR_LEG = R.len['thigh_l'] + R.len['calf_l'] +HIPMID = (HIPS['l'] + HIPS['r']) / 2 +_TK = {} +MOCAP_CHECK = {} +def mocap_clip(name, spec): + key = (spec['trial'], spec['t0'], spec['t1'], bool(spec.get('mirror'))) + if key not in _TK: _TK[key] = MC.Take(CMU_DIR, key[0], key[1], key[2], mirror=key[3]) + tk = _TK[key] + frames, T, v, th, flags = MC.build_cycle(tk, OUR_LEG, ANK['l'].z, theta=spec.get('theta'), hip_yaw=spec.get('hip_yaw', 0.0), + crouch=spec.get('crouch', 0.0), crouch_lean=spec.get('lean', 0.0), out_fps=FPS, + speed_scale=spec.get('speed', 1.0), stride_scale=spec.get('stride', 1.0), foot_len=R.len['foot_l']) + n = len(frames) + AUX = {'HIPMID': HIPMID, 'ANKZ': ANK['l'].z} + def f(t): + i = int(round(t * FPS)) % n + L = R.rest(); W = R.W(L) + MC.pose(R, L, W, frames[i], AUX) + return finalize(L, W) + CLIPS[name] = (f, T, True) + META[name] = {'duration': T, 'stride': v * T, 'speed': v, 'theta': spec.get('theta', round(th, 1)), 'mocap': 1} + MOCAP_CHECK[name] = (frames, flags, T, v, th) + print('mocap', name, spec['trial'], 'T %.3f v %.2f th %.0f frames %d' % (T, v, th, n)) + +for nm, spec in ML.TAKES.items(): + if ONLY and nm not in ONLY: continue + mocap_clip(nm, spec) + +def check_mocap(): + """Slide of planted feet in the baked pose (world, with the clip's travel added) and leg IK reach error.""" + for nm, (frames, flags, T, v, th) in list(MOCAP_CHECK.items()): + if nm.endswith('#game'): continue + fn = CLIPS[nm][0]; n = len(frames) + d = Vector((math.sin(math.radians(th)), -math.cos(math.radians(th)), 0)) * v + slide = []; reach = [] + prev = None; pq = None; pop = (0, '') + for i in range(n + 1): + t = (i % n) / FPS + L = fn(t); W = R.W(L) + tt = i / FPS + Bq = {b: L[b].to_quaternion() for b in R.bones if not b.startswith(('index', 'middle', 'ring', 'pinky', 'thumb'))} + if pq: + for b in Bq: + ang = math.degrees(Bq[b].rotation_difference(pq[b]).angle) + if ang > 180: ang = 360 - ang + if ang > pop[0]: pop = (ang, '%s@%d' % (b, i)) + pq = Bq + if os.environ.get('PDBG') == nm: + F = frames[i % n]; X = W['thigh_l'].to_3x3() + print(' %2d thighX %s thighY %s ank %s hip %s knee %s' % (i, tuple(round(v, 2) for v in X.col[0]), tuple(round(v, 2) for v in X.col[1]), + tuple(round(v, 2) for v in F['lfoot']), tuple(round(v, 2) for v in F['lfemur']), tuple(round(v, 2) for v in F['ltibia']))) + cur = {s: (W['foot_' + s].translation + d * tt, W['ball_' + s].translation + d * tt) for s in 'lr'} + for s in 'lr': + reach.append((W['foot_' + s].translation - frames[i % n][s + 'foot']).length) + if prev is not None: + for s in 'lr': + if flags[s][i % n] and flags[s][(i - 1) % n]: + slide.append(min((cur[s][0] - prev[s][0]).length, (cur[s][1] - prev[s][1]).length) * FPS) + prev = cur + if os.environ.get('MDBG') == nm and i < n: + F = frames[i % n] + print(' %2d L%d R%d ballL %+.3f %+.3f %.3f tgt %+.3f %+.3f %.3f ankz %.3f' % (i, flags['l'][i % n], flags['r'][i % n], + cur['l'][1].x, cur['l'][1].y, W['ball_l'].translation.z, (F['ltoes'] + d * tt).x, (F['ltoes'] + d * tt).y, F['ltoes'].z, F['lfoot'].z)) + slide.sort(); reach.sort() + # the game helper's measure on the baked loop (two cycles, 30 fps): contact = lowest 2.5 cm (ankle) / 2 cm + # (ball) of the travel, 3+ frames; drift = largest horizontal move from the contact start + P = [] + for i in range(2 * n): + L = fn((i % n) / FPS); W = R.W(L); tt = i / FPS + P.append({s: (W['foot_' + s].translation + d * tt, W['ball_' + s].translation + d * tt) for s in 'lr'}) + def wins(hs, tol): + m = min(hs); out = []; st = -1 + for i in range(len(hs) + 1): + c = i < len(hs) and hs[i] <= m + tol + if c and st < 0: st = i + if not c and st >= 0: + if i - st >= 2: out.append((st, i)) + st = -1 + return out + gd = [] + for s in 'lr': + for k, tol in ((0, 0.025), (1, 0.02)): + for a, b in wins([p[s][k].z for p in P], tol): + gd.append(max(((P[j][s][k] - P[a][s][k]).xy.length for j in range(a, b)), default=0)) + gd.sort() + MOCAP_CHECK[nm + '#game'] = gd + print('game-measure %-9s contacts %d median %.1f max %.1f cm' % (nm, len(gd), gd[len(gd) // 2] * 100 if gd else 0, gd[-1] * 100 if gd else 0)) + print('check %-9s planted heel-or-ball speed median %.3f p90 %.3f m/s | ankle reach err median %.1f max %.1f cm | max bone step %.0f deg %s' % ( + nm, slide[len(slide) // 2], slide[int(len(slide) * 0.9)], reach[len(reach) // 2] * 100, reach[-1] * 100, pop[0], pop[1])) + +# ---------------- run +def build(names=None): + solve_grips() + made = [] + for name, (fn, length, loop) in CLIPS.items(): + if names and name not in names: continue + n = max(2, int(round(length * FPS)) + 1) + frames = [] + for i in range(n): + t = i / FPS + if loop and i == n - 1: t = 0.0 # seamless loop: last frame == first + L = fn(min(t, length)) + frames.append(R.basis(L)) + act = A.make_action(arm, name, frames, R.bones) + made.append(act) + print('clip', name, n, 'frames') + return made + +made = build(ONLY) +check_mocap() +# grips json (Blender armature/weapon space; exported as empties in weapons.glb) +gj = {k: [list(v.to_translation()), list(v.to_quaternion())] for k, v in GRIP.items()} +json.dump(gj, open(L_.WORK + '/grips.json', 'w'), indent=1) +json.dump({k: {kk: round(vv, 4) for kk, vv in v.items()} for k, v in META.items()}, open(L_.WORK + '/out/anims.json', 'w'), indent=1) +# export: skeleton only + clips as NLA tracks +for o in list(bpy.data.objects): + if o != arm: bpy.data.objects.remove(o) +arm.animation_data_create() +arm.animation_data.action = None +for t in list(arm.animation_data.nla_tracks): arm.animation_data.nla_tracks.remove(t) +for a in made: + tr = arm.animation_data.nla_tracks.new(); tr.name = a.name + st = tr.strips.new(a.name, 0, a) +bpy.context.scene.render.fps = FPS +bpy.context.scene.frame_start = 0 +bpy.ops.export_scene.gltf(filepath=OUT, export_format='GLB', export_animation_mode='NLA_TRACKS', export_def_bones=False, + export_optimize_animation_size=True, export_force_sampling=True) +bpy.ops.wm.save_as_mainfile(filepath=L_.WORK + '/anims.blend') diff --git a/e63334287a3deaa3/ironveil/tools/chars/assemble.py b/e63334287a3deaa3/ironveil/tools/chars/assemble.py new file mode 100644 index 00000000..7d41d37b --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/assemble.py @@ -0,0 +1,154 @@ +# Assemble a baked character into its final GLB (mesh + hair mesh + skeleton, no clips unless asked). +import bpy, sys, os, math +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import mhlib as L, geo as G, pipe as PP + + +LOD_TRIS = (('LOD1', 5000), ('LOD2', 1800)) # mid and far LODs (same skeleton, material and UVs) +def make_lods(low, name): + """Decimated copies of the finished low mesh, made before morphs are added (decimation drops shape keys).""" + tris = sum(len(p.vertices) - 2 for p in low.data.polygons) + out = [] + for suf, target in LOD_TRIS: + c = low.copy(); c.data = low.data.copy(); c.name = name + suf; c.data.name = name + suf + bpy.context.scene.collection.objects.link(c) + for m in list(c.modifiers): c.modifiers.remove(m) + if c.data.shape_keys: c.shape_key_clear() + PP.decimate(c, min(1.0, target / tris)) + print('lod', c.name, sum(len(p.vertices) - 2 for p in c.data.polygons)) + out.append(c) + return out + +MORPHS = {'hero': ['blink'], 'ally': ['blink'], 'enemy': ['faceB', 'faceC']} +def add_morphs(kind, lows, parts): + """Face morph targets from morphs.py (work/morph_.npz), matched to the final meshes by vertex position.""" + import numpy as np, morphs as MO + path = L.WORK + '/morph_%s.npz' % kind + if not os.path.exists(path): print('no morph data', path); return + npz = dict(np.load(path)); names = MORPHS[kind] + for low in (lows if isinstance(lows, list) else [lows]): + print('morphs', low.name, MO.apply(low, 'body', npz, names)) + part_of = {'Hair': 'hair', 'Brows': 'brows', 'Lashes': 'lashes', 'Eyes': 'eyes'} + for o, _, _ in parts: + print('morphs', o.name, MO.apply(o, part_of.get(o.name, 'body'), npz, names)) + +def assemble(blend, name, td, out, hair_parts, helmet_trim=True, with_anims=(), extra_meshes=()): + bpy.ops.wm.open_mainfile(filepath=blend) + rig = bpy.data.objects['Armature'] + low = bpy.data.objects[name] + # one material, one UV map + mat = PP.final_material(name + 'Mat', {'albedo': td + '/albedo.jpg', 'normal': td + '/normal.jpg', 'orm': td + '/orm.jpg'}) + low.data.materials.clear(); low.data.materials.append(mat) + for p in low.data.polygons: p.material_index = 0 + for uv in list(low.data.uv_layers): + if uv.name != 'atlas': low.data.uv_layers.remove(uv) + low.data.uv_layers['atlas'].name = 'UVMap' + # hair / eyes / brows / lashes in a small alpha atlas + objs = [] + for objname, img, rect in hair_parts: + o = bpy.data.objects[objname] + for m in list(o.modifiers): o.modifiers.remove(m) + objs.append((o, img, rect)) + PP.hair_atlas(objs, td + '/hair.png', 1024) + lods = make_lods(low, name) + add_morphs(name.lower(), low, objs) + # eyes keep their own glossy material (a sharp catchlight); the rest of the cards share the alpha atlas + eyes = [o for o, _, _ in objs if o.name == 'Eyes'][0] + eyes.name = name + 'Eyes'; eyes.data.name = name + 'Eyes' + em = PP.final_material(name + 'EyeMat', {'albedo': td + '/hair.png'}, alpha=False, rough=0.08) + eyes.data.materials.clear(); eyes.data.materials.append(em) + for p in eyes.data.polygons: p.material_index = 0 + hair = G.join([o for o, _, _ in objs if o is not eyes], name + 'Hair') + hm = PP.final_material(name + 'HairMat', {'albedo': td + '/hair.png'}, alpha=True, rough=0.5) + hair.data.materials.clear(); hair.data.materials.append(hm) + for p in hair.data.polygons: p.material_index = 0 + keep = {rig.name, low.name, hair.name, eyes.name} | set(extra_meshes) | {o.name for o in lods} + for o in list(bpy.data.objects): + if o.name not in keep: bpy.data.objects.remove(o) + for o in [low, hair, eyes] + lods + [bpy.data.objects[e] for e in extra_meshes]: + for m in list(o.modifiers): o.modifiers.remove(m) + o.parent = rig + o.modifiers.new('Armature', 'ARMATURE').object = rig + # drop empty / helper vertex groups + for vg in list(o.vertex_groups): + if vg.name not in rig.data.bones: o.vertex_groups.remove(vg) + rig.animation_data_clear() + if with_anims: + rig.animation_data_create() + for n in with_anims: + a = bpy.data.actions.get(n) + if a: + t = rig.animation_data.nla_tracks.new(); t.name = n; t.strips.new(n, int(a.frame_range[0]), a) + for o in bpy.context.scene.objects: o.select_set(True) + bpy.ops.export_scene.gltf(filepath=out, export_format='GLB', export_animation_mode='NLA_TRACKS' if with_anims else 'ACTIONS', + export_animations=bool(with_anims), export_def_bones=False, export_tangents=False, + export_image_format='AUTO', export_jpeg_quality=88, export_yup=True, use_selection=False) + return low, hair + +if __name__ == '__main__': + kind = sys.argv[-2]; out = sys.argv[-1] + if kind in ('hero', 'ally'): + nm = kind.capitalize() + td = L.WORK + '/tex_' + kind + assemble(L.WORK + '/%s_baked.blend' % kind, nm, td, out, [ + ('Hair', L.MHA + '/hair/short02/short02_diffuse.png', (0, 0, 0.5, 0.5)), + ('Brows', L.MHA + '/eyebrows/%s/%s.png' % (('eyebrow001',) * 2 if kind == 'hero' else ('eyebrow009',) * 2), (0.5, 0, 0.5, 0.25)), + ('Lashes', L.MHA + '/eyelashes/eyelashes01/eyelashes01.png', (0.5, 0.25, 0.5, 0.25)), + ('Eyes', L.MHA + '/eyes/materials/%s_eye.png' % ('brownlight' if kind == 'hero' else 'grey'), (0, 0.5, 0.5, 0.5))], + with_anims=[]) + +def assemble_enemy(out): + bpy.ops.wm.open_mainfile(filepath=L.WORK + '/enemy_baked.blend') + rig = bpy.data.objects['Armature'] + keep = ['Armature'] + for kind in ('rifleman', 'officer', 'sniper', 'gunner'): + name = kind.capitalize(); td = L.WORK + '/tex_' + kind + mat = PP.final_material(name + 'Mat', {'albedo': td + '/albedo.jpg', 'normal': td + '/normal.jpg', 'orm': td + '/orm.jpg'}) + old = bpy.data.objects.get(name + 'LOD') + if old: bpy.data.objects.remove(old) + for on in (name,): + o = bpy.data.objects[on] + o.data.materials.clear(); o.data.materials.append(mat) + for p in o.data.polygons: p.material_index = 0 + for uv in list(o.data.uv_layers): + if uv.name != 'atlas': o.data.uv_layers.remove(uv) + o.data.uv_layers['atlas'].name = 'UVMap' + keep.append(on) + keep += [c.name for c in make_lods(bpy.data.objects[name], name)] + td = L.WORK + '/tex_enemy'; os.makedirs(td, exist_ok=True) + parts = [] + for objname, img, rect in [('Hair', L.MHA + '/hair/short02/short02_diffuse.png', (0, 0, 0.5, 0.5)), + ('Brows', L.MHA + '/eyebrows/eyebrow005/eyebrow005.png', (0.5, 0, 0.5, 0.25)), + ('Lashes', L.MHA + '/eyelashes/eyelashes01/eyelashes01.png', (0.5, 0.25, 0.5, 0.25)), + ('Eyes', L.MHA + '/eyes/materials/blue_eye.png', (0, 0.5, 0.5, 0.5))]: + o = bpy.data.objects[objname] + for m in list(o.modifiers): o.modifiers.remove(m) + parts.append((o, img, rect)) + PP.hair_atlas(parts, td + '/hair.png', 1024) + add_morphs('enemy', [bpy.data.objects[k.capitalize()] for k in ('rifleman', 'officer', 'sniper', 'gunner')], parts) + eyes = bpy.data.objects['Eyes']; eyes.name = 'EnemyEyes'; eyes.data.name = 'EnemyEyes' + em = PP.final_material('EnemyEyeMat', {'albedo': td + '/hair.png'}, alpha=False, rough=0.08) + eyes.data.materials.clear(); eyes.data.materials.append(em) + for p in eyes.data.polygons: p.material_index = 0 + keep.append('EnemyEyes') + hair = G.join([o for o, _, _ in parts if o is not eyes], 'EnemyHair') + hm = PP.final_material('EnemyHairMat', {'albedo': td + '/hair.png'}, alpha=True, rough=0.5) + hair.data.materials.clear(); hair.data.materials.append(hm) + for p in hair.data.polygons: p.material_index = 0 + keep.append('EnemyHair') + for o in list(bpy.data.objects): + if o.name not in keep: bpy.data.objects.remove(o) + for on in keep[1:]: + o = bpy.data.objects[on] + for m in list(o.modifiers): o.modifiers.remove(m) + o.parent = rig + o.modifiers.new('Armature', 'ARMATURE').object = rig + for vg in list(o.vertex_groups): + if vg.name not in rig.data.bones: o.vertex_groups.remove(vg) + rig.animation_data_clear() + for o in bpy.context.scene.objects: o.select_set(True) + bpy.ops.export_scene.gltf(filepath=out, export_format='GLB', export_animations=False, export_def_bones=False, export_tangents=False, + export_image_format='AUTO', export_jpeg_quality=88, export_yup=True) + +if __name__ == '__main__' and sys.argv[-2] == 'enemy': + assemble_enemy(sys.argv[-1]) diff --git a/e63334287a3deaa3/ironveil/tools/chars/build_enemy.py b/e63334287a3deaa3/ironveil/tools/chars/build_enemy.py new file mode 100644 index 00000000..37a6f0a4 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/build_enemy.py @@ -0,0 +1,68 @@ +import bpy, sys, os, math, time +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import numpy as np +import mhlib as L, geo as G, mats as MT, pipe as PP, outfits as O +from mathutils import Vector + +KINDS = (os.environ.get('KINDS') or 'rifleman,officer,sniper,gunner').split(',') +SIZE = int(os.environ.get('SIZE') or 1024) +T0 = time.time() +def log(*a): print('[%5.1fs]' % (time.time() - T0), *a, flush=True) + +bpy.ops.wm.read_factory_settings(use_empty=True) +import humans as HU +H = L.build_human(**HU.ENEMY) +log('human', max(v.co.z for v in H['body'].data.vertices)) +body = H['body']; P = G.coords(body.data) +mats = O.materials_enemy(knee=PP.J(H, 'calf_l').z) +import wear as WR +import glob +# a different skin per kind (with the three face morphs that gives twelve combinations) +SKIN = {'rifleman': 'young_caucasian_male2', 'officer': 'middleage_caucasian_male', 'sniper': 'young_caucasian_male', 'gunner': 'old_caucasian_male'} +SKINMAT = {k: WR.skin('e_skin_' + k, glob.glob(L.MHA + '/skins/%s/*.png' % v)[0], grime=0.3) for k, v in SKIN.items()} +# the hair under a helmet or cap crown is never seen: trim it (inside a shell a little smaller than the helmet) +_hel, _hc, _hr = O.helmet_stahl(H) +PP.trim_hair(H['hair'], _hc + Vector((0, 0, 0.02)), (_hr[0] - 0.02, _hr[1] - 0.02)) +bpy.data.objects.remove(_hel) +log('hair tris after trim', G.tris(H['hair'])) +UPPER = {'rifleman': 'tunic', 'gunner': 'tunic', 'officer': 'coat', 'sniper': 'smock'} +lows = [] +for kind in KINDS: + up = UPPER[kind] + labels = O.label_enemy(H, P, up) + disp = {up: 0.009, 'trousers': 0.006, 'boot': 0.004, 'skin': 0.0} + smooth = {up: 1.0, 'trousers': 0.8, 'boot': 1.0, 'skin': 0.0} + alpha = {up: 0.4, 'trousers': 0.35, 'boot': 0.85} + slack = {up: 0.008 if kind != 'sniper' else 0.014, 'trousers': 0.007, 'boot': 0.005} + if kind == 'officer': slack[up] = 0.01 + cloth = PP.cloth_body(H, labels, disp, smooth, alpha=alpha, slack=slack, name='Cloth_' + kind) + gear = O.gear_enemy(H, cloth, kind) + if kind == 'officer': + capparts, hc, hr = O.peaked_cap(H) + gear += capparts + else: + hel, hc, hr = O.helmet_stahl(H) + gear.append((hel, 'helmetcamo' if kind == 'sniper' else 'helmet')) + for ob, mn in gear: + if ob.name.startswith(('Helmet', 'Cap')): continue + G.transfer_weights(ob, cloth) + mats['skin'] = SKINMAT[kind] + PP.assign_mats(cloth, mats) + for ob, mn in gear: + ob.data.materials.clear(); ob.data.materials.append(mats[mn]) + if 'UVMap' not in ob.data.uv_layers: ob.data.uv_layers.new(name='UVMap') + log(kind, 'geometry, gear', len(gear)) + name = kind.capitalize() + lf = (lambda up_: (lambda H_, P_: O.label_enemy(H_, P_, up_)))(up) + low = PP.finish(H, name, cloth, gear, labels, {up: 0.0065, 'trousers': 0.0075, 'boot': 0.002}, size=SIZE, + out_dir=L.WORK + '/tex_' + kind, low_ratio=0.24, log=log, label_fn=lf) + # LOD at ~40% + lod = low.copy(); lod.data = low.data.copy(); lod.name = name + 'LOD'; G.link(lod) + PP.decimate(lod, 0.4) + log(kind, 'tris', G.tris(low), 'lod', G.tris(lod)) + # tidy: remove the build pieces + for ob, mn in gear: bpy.data.objects.remove(ob) + bpy.data.objects.remove(cloth) + lows.append(low) +bpy.ops.wm.save_as_mainfile(filepath=L.WORK + '/enemy_baked.blend') +log('saved') diff --git a/e63334287a3deaa3/ironveil/tools/chars/build_hero.py b/e63334287a3deaa3/ironveil/tools/chars/build_hero.py new file mode 100644 index 00000000..d1ebd6ba --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/build_hero.py @@ -0,0 +1,80 @@ +import bpy, sys, os, math, time +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import numpy as np +import mhlib as L, geo as G, mats as MT, pipe as PP, outfits as O +from mathutils import Vector + +MODE = sys.argv[-1] # 'preview' or 'bake' +KIND = os.environ.get('KIND', 'hero') +NAME = KIND.capitalize() +SIZE = 2048 if KIND == 'hero' else 1024 +T0 = time.time() +def log(*a): print('[%5.1fs]' % (time.time() - T0), *a, flush=True) + +bpy.ops.wm.read_factory_settings(use_empty=True) +import humans as HU +H = L.build_human(**HU.PARAMS[KIND]) +log('human built', max(v.co.z for v in H['body'].data.vertices)) +body = H['body'] +P = G.coords(body.data) +labels = O.label_hero(H, P) +cloth = PP.cloth_body(H, labels, + disp={'jacket': 0.008, 'trousers': 0.005, 'boot': 0.004, 'glove': 0.002, 'skin': 0.0}, + smooth={'jacket': 1.0, 'trousers': 0.8, 'boot': 1.0, 'glove': 0.3, 'skin': 0.0}, + alpha={'jacket': 0.4, 'trousers': 0.35, 'boot': 0.9}, slack={'jacket': 0.003, 'trousers': 0.005, 'boot': 0.006}, + torso_dilate=0.04) +log('cloth body') +gear = O.gear_hero(H, cloth) +if KIND == 'hero': + helmet, hc, hr = O.cap_comforter(H) + gear += [(helmet, 'wool')] +else: + helmet, hc, hr = O.helmet_m1(H) + gear += [(helmet, 'helmet')] + [(x, 'canvas') for x in O.scrim_bits(hc, hr)] +if H.get('hair'): PP.trim_hair(H['hair'], hc, hr) +for ob, mn in gear: + if ob.name.startswith(('Helmet', 'Straps', 'Scrim', 'Cap')): continue + G.transfer_weights(ob, cloth) +log('gear', len(gear)) +mats = O.materials_hero(knee=PP.J(H, 'calf_l').z) +import wear as WR +mats['skin'] = WR.skin('skin', H['skin_png'], grime=0.4, beard=1.0 if KIND == 'hero' else 0.45, scars=(KIND == 'hero'), tan=0.45) +PP.assign_mats(cloth, mats) +for ob, mn in gear: + ob.data.materials.clear(); ob.data.materials.append(mats[mn]) + if 'UVMap' not in ob.data.uv_layers: ob.data.uv_layers.new(name='UVMap') + +# trim hair that sits inside the helmet +hair = H.get('hair') +bpy.ops.wm.save_as_mainfile(filepath=L.WORK + '/%s_geo.blend' % KIND) +log('saved geo') + +# ---------- low ---------- +low = cloth.copy(); low.data = cloth.data.copy(); low.name = NAME + 'Low'; G.link(low) +protect = [i for i, l in enumerate(labels) if l == 'skin'] +PP.decimate(low, 0.42, protect=protect) +log('low body tris', G.tris(low)) +gl = [] +for ob, mn in gear: + if ob.get('hi_only'): continue + c = ob.copy(); c.data = ob.data.copy(); G.link(c); gl.append(c) +low = G.join([low] + gl, NAME) +log('low total tris', G.tris(low)) +bpy.ops.wm.save_as_mainfile(filepath=L.WORK + '/%s_low.blend' % KIND) + +if MODE == 'bake': + # reload clean geo stage + bpy.ops.wm.open_mainfile(filepath=L.WORK + '/%s_geo.blend' % KIND) + import importlib + cloth = bpy.data.objects['Cloth'] + labels = list(cloth['vlabels']) + gear = [] + for o in bpy.data.objects: + if o.type == 'MESH' and o.name not in ('Cloth', 'Body', 'Eyes', 'Brows', 'Lashes', 'Hair') and not o.name.startswith(NAME + 'Low'): + gear.append((o, o.data.materials[0].name)) + H = {'J': {}, 'body': bpy.data.objects['Body']} + rig = bpy.data.objects['Armature'] + for b in rig.data.bones: H['J'][b.name] = (rig.matrix_world @ b.head_local, rig.matrix_world @ b.tail_local) + TD = L.WORK + '/tex_' + KIND + low = PP.finish(H, NAME, cloth, gear, labels, {'jacket': 0.0065, 'trousers': 0.0075, 'boot': 0.002}, size=SIZE, out_dir=TD, log=log, label_fn=O.label_hero, low_ratio=0.42) + bpy.ops.wm.save_as_mainfile(filepath=L.WORK + '/%s_baked.blend' % KIND) diff --git a/e63334287a3deaa3/ironveil/tools/chars/build_weapons.py b/e63334287a3deaa3/ironveil/tools/chars/build_weapons.py new file mode 100644 index 00000000..22ed8c0f --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/build_weapons.py @@ -0,0 +1,62 @@ +import bpy, sys, os, json, math +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import numpy as np +import mhlib as L, geo as G, mats as MT, weapons as WP, pipe as PP +from mathutils import Vector, Matrix, Quaternion + +MODE = sys.argv[-1] +bpy.ops.wm.read_factory_settings(use_empty=True) +M = WP.materials() +obs = [b(M) for b in WP.BUILDERS] +for o in obs: + print(o.name, G.tris(o)) +bpy.ops.wm.save_as_mainfile(filepath=L.WORK + '/weapons_geo.blend') + +if MODE in ('bake', 'export'): + TD = L.WORK + '/tex_weapons'; os.makedirs(TD, exist_ok=True) + sc = bpy.context.scene + sc.world = bpy.data.worlds.new('W'); sc.world.light_settings.distance = 0.05 + for i, o in enumerate(obs): o.location.x = i * 1.0 + for o in obs: + o.data.uv_layers.new(name='atlas'); o.data.uv_layers.active = o.data.uv_layers['atlas'] + for o in sc.objects: o.select_set(o in obs) + bpy.context.view_layer.objects.active = obs[0] + bpy.ops.object.mode_set(mode='EDIT') + bpy.ops.mesh.select_all(action='SELECT') + bpy.ops.uv.smart_project(angle_limit=math.radians(60), island_margin=0.003, area_weight=0.0, scale_to_bounds=False) + bpy.ops.uv.select_all(action='SELECT') + bpy.ops.uv.pack_islands(rotate=True, scale=True, margin=0.003) + bpy.ops.object.mode_set(mode='OBJECT') + size = 2048 + for kind in ('DIFFUSE', 'AO', 'ROUGHNESS', 'NORMAL', 'EMIT'): + img = bpy.data.images.new('w_' + kind, size, size, float_buffer=(kind == 'NORMAL')) + img.colorspace_settings.name = 'sRGB' if kind == 'DIFFUSE' else 'Non-Color' + sv = PP.metal_pass_begin(list(bpy.data.materials)) if kind == 'EMIT' else None + for m in bpy.data.materials: + if not m.node_tree: continue + n = m.node_tree.nodes.get('_bake') or m.node_tree.nodes.new('ShaderNodeTexImage'); n.name = '_bake'; n.image = img + m.node_tree.nodes.active = n + sc.render.engine = 'CYCLES'; sc.cycles.samples = {'AO': 32, 'NORMAL': 8, 'DIFFUSE': 4}.get(kind, 2) + kw = dict(type=kind, margin=8) + if kind == 'DIFFUSE': kw['pass_filter'] = {'COLOR'} + if kind == 'NORMAL': kw['normal_space'] = 'TANGENT' + bpy.ops.object.bake(**kw) + if sv: PP.metal_pass_end(sv) + img.filepath_raw = TD + '/_%s.png' % kind.lower(); img.file_format = 'PNG'; img.save() + print('baked', kind, flush=True) + from PIL import Image + d = np.asarray(Image.open(TD + '/_diffuse.png').convert('RGB')).astype(np.float32) / 255 + a = np.asarray(Image.open(TD + '/_ao.png').convert('L')).astype(np.float32) / 255 + Image.fromarray(np.clip((d * (0.4 + 0.6 * a[..., None])) * 255, 0, 255).astype(np.uint8)).save(TD + '/albedo.jpg', quality=90) + r = np.asarray(Image.open(TD + '/_roughness.png').convert('L')) + mt = np.asarray(Image.open(TD + '/_emit.png').convert('L')) + Image.fromarray(np.stack([np.full_like(r, 255), r, mt], -1)).save(TD + '/orm.jpg', quality=90) + Image.open(TD + '/_normal.png').convert('RGB').save(TD + '/normal.jpg', quality=92) + for o in obs: o.location.x = 0 + mat = PP.final_material('WeaponMat', {'albedo': TD + '/albedo.jpg', 'orm': TD + '/orm.jpg', 'normal': TD + '/normal.jpg'}) + for o in obs: + o.data.materials.clear(); o.data.materials.append(mat) + for p in o.data.polygons: p.material_index = 0 + for uv in list(o.data.uv_layers): + if uv.name != 'atlas': o.data.uv_layers.remove(uv) + bpy.ops.wm.save_as_mainfile(filepath=L.WORK + '/weapons_baked.blend') diff --git a/e63334287a3deaa3/ironveil/tools/chars/capture.js b/e63334287a3deaa3/ironveil/tools/chars/capture.js new file mode 100644 index 00000000..2bf28156 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/capture.js @@ -0,0 +1,23 @@ +// usage: node capture.js [kind] [weapon] [w h] +// Steps the drive-mode scenario deterministically at 30 fps; writes frames (unless outdir is '-') and prints the measurements. +const { chromium } = require(process.env.PLAYWRIGHT || 'playwright'); +const fs = require('fs'); +(async () => { + const [scen, out, kind = 'hero', weapon = 'rifleScoped', w = 640, h = 360] = process.argv.slice(2); + const b = await chromium.launch({ executablePath: process.env.CHROME || undefined, args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'] }); + const p = await b.newPage({ viewport: { width: +w, height: +h } }); + await p.route('**/*', r => /firebase|googleapis|google-analytics|googletagmanager|gstatic|pagead|adsbygoogle/.test(r.request().url()) ? r.abort() : r.continue()); + p.on('pageerror', e => console.log('pageerror:', String(e).slice(0, 400))); + await p.goto(`http://127.0.0.1:${process.env.PORT || 8981}/e63334287a3deaa3/ironveil/chars-test.html?drive=1&scenario=${scen}&kind=${kind}&weapon=${weapon}`); + await p.waitForFunction('window.DRIVE && window.DRIVE.a', null, { timeout: 120000 }); + await p.evaluate(() => { document.getElementById('ui').style.display = 'none'; document.getElementById('stats').style.display = 'none'; }); + const n = await p.evaluate(s => DRIVE.run(s, 30), scen); + if (out !== '-') fs.mkdirSync(out, { recursive: true }); + for (let i = 0; i < n; i++) { + await p.evaluate(() => DRIVE.step()); + if (out !== '-') await p.screenshot({ path: `${out}/f${String(i).padStart(4, '0')}.png` }); + } + const res = await p.evaluate(() => JSON.stringify(DRIVE.results())); + console.log(res); + await b.close(); +})().catch(e => { console.error(e); process.exit(1); }); diff --git a/e63334287a3deaa3/ironveil/tools/chars/closeups.sh b/e63334287a3deaa3/ironveil/tools/chars/closeups.sh new file mode 100755 index 00000000..a0eb520e --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/closeups.sh @@ -0,0 +1,12 @@ +#!/bin/bash +# closeups.sh kind out.png : back, back three-quarter, boots, helmet, face, front at 1-2 m, overcast, grey floor +. "$(dirname "$0")/env.sh" +k=$1; out=$2; T=$(mktemp -d); i=0 +for q in "cyaw=180&cpitch=8&cdist=1.5&cty=1.25" "cyaw=215&cpitch=8&cdist=2.2&cty=1.0" "cyaw=150&cpitch=12&cdist=0.9&cty=0.25" "cbone=Head&cyaw=200&cpitch=25&cdist=0.55" "cbone=Head&cyaw=20&cpitch=5&cdist=0.5" "cyaw=25&cpitch=6&cdist=2.2&cty=1.0"; do + i=$((i+1)); timeout 200 node "$HERE/shot.js" $T/p$i.png "/e63334287a3deaa3/ironveil/chars-test.html?shot=1&kind=$k&anim=idle&upper=holdRifle&t=0.5&weapon=rifleScoped&grey=1&light=overcast&$q" 400 500 >/dev/null +done +python3 -I -c " +import sys +from PIL import Image +ims=[Image.open(sys.argv[2]+'/p%d.png'%i) for i in range(1,7)] +c=Image.new('RGB',(1200,1000)); [c.paste(im,((i%3)*400,(i//3)*500)) for i,im in enumerate(ims)]; c.save(sys.argv[1])" $out $T diff --git a/e63334287a3deaa3/ironveil/tools/chars/cmu_scan.py b/e63334287a3deaa3/ironveil/tools/chars/cmu_scan.py new file mode 100644 index 00000000..a4214054 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/cmu_scan.py @@ -0,0 +1,29 @@ +import sys, numpy as np, math +sys.path.insert(0, '.') +import amc +D = '../work/cmu/data/' +for t in sys.argv[1:]: + s = t.split('_')[0] + F, fps = amc.load(D + s + '.asf', D + t + '.amc', step=4) + P = np.array([f['root'][0] for f in F]); n = len(F) + L = np.array([f['lfemur'][0] for f in F]); Rr = np.array([f['rfemur'][0] for f in F]) + left = L - Rr; left[:, 2] = 0; left /= np.linalg.norm(left, axis=1)[:, None] + fwd = np.cross(left, [0, 0, 1]) + k = 6 + rows = [] + for i in range(k, n - k, 6): + v = (P[i + k] - P[i - k]) / (2 * k / fps); v[2] = 0 + sp = np.linalg.norm(v) + th = math.degrees(math.atan2(v @ left[i], v @ fwd[i])) if sp > 0.1 else 0 + rows.append('%5.1fs %4.2fm/s %+4.0f' % (i / fps, sp, th)) + print(t, n, 'frames @', fps, 'hips h', round(float(np.mean(L[:, 2])), 2)) + print(' ' + ' | '.join(rows)) +# leg length ratio: mean hip height over hip-to-floor at full extension +import os +if os.environ.get('LEG'): + for t in sys.argv[1:]: + s = t.split('_')[0]; sk = amc.Skel(D + s + '.asf') + leg = sk.bones['lfemur']['len'] + sk.bones['ltibia']['len'] + F, fps = amc.load(D + s + '.asf', D + t + '.amc', step=4) + h = np.array([(f['lfemur'][0][2] + f['rfemur'][0][2]) / 2 - min(f['ltoes'][0][2], f['rtoes'][0][2]) for f in F]) + print(t, 'leg', round(leg, 3), 'hip-over-ball median', round(float(np.median(h)), 3), 'ratio', round(float(np.median(h)) / leg, 3)) diff --git a/e63334287a3deaa3/ironveil/tools/chars/detail.py b/e63334287a3deaa3/ironveil/tools/chars/detail.py new file mode 100644 index 00000000..24068c65 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/detail.py @@ -0,0 +1,102 @@ +# Tailored cloth detail on the high-poly garment before the bake (displacement along the normal, in metres): +# compression folds in the elbow crook and behind the knee, drag folds from the shoulder to the armpit, bunching +# above the belt, puckering where the trousers blouse over the boots, and sewn seams (a pressed groove with two +# rows of stitch dimples) down the outside of the legs, under the sleeves, down the back and over the shoulders. +import math +import numpy as np +from mathutils import Vector, noise +import geo as G + +def _seg(H, b): + h, t = H['J'][b] + return np.array(h), np.array(t) + +def _along(P, h, t): + ax = t - h; L = np.linalg.norm(ax); ax = ax / L + rel = P - h; s = rel @ ax + rad = rel - np.outer(s, ax) + return s, rad, ax, L + +def tailor(ob, H, labels, upper=('jacket', 'tunic', 'coat', 'smock'), lower=('trousers',), amp=1.0): + me = ob.data + P = G.coords(me); N = G.normals(me) + lab = np.array(labels) + up_m = np.isin(lab, upper); lo_m = np.isin(lab, lower) + d = np.zeros(len(P)) + sd = np.full(len(P), 1.0); ss = np.zeros(len(P)) # distance to the nearest seam, position along it + def seam(on, dist, along): + m = on & (np.abs(dist) < sd) + sd[m] = np.abs(dist)[m]; ss[m] = along[m] + nz = np.array([noise.noise(Vector((p[0] * 9, p[1] * 9, p[2] * 9))) for p in P]) + + for s_ in 'lr': + # elbow crook: compression rings, strongest on the inside of the bend (bind pose: crook faces forward, -Y) + h, t = _seg(H, 'lowerarm_' + s_) + s, rad, ax, L = _along(P, h, t) + rn = rad / np.maximum(np.linalg.norm(rad, axis=1), 1e-6)[:, None] + crook = np.clip(-rn[:, 1], 0, 1) * 0.8 + 0.2 + env = np.exp(-(s / 0.07) ** 2) * (np.linalg.norm(rad, axis=1) < 0.09) + d += up_m * env * crook * 0.0055 * np.sin(2 * np.pi * s / 0.026 + nz * 1.5) + # sleeve seam underneath the arm, from armpit to cuff (on the upper and lower arm) + for b in ('upperarm_' + s_, 'lowerarm_' + s_): + h, t = _seg(H, b); s, rad, ax, L = _along(P, h, t) + r = np.linalg.norm(rad, axis=1); rn = rad / np.maximum(r, 1e-6)[:, None] + ang = np.arccos(np.clip(-rn[:, 2], -1, 1)) # 0 straight under the arm + arc = ang * r + on = up_m & (s > -0.02) & (s < L + 0.02) & (r < 0.09) + seam(on, arc, s) + # knee: folds behind the knee and a softer set over the front + h, t = _seg(H, 'calf_' + s_) + s, rad, ax, L = _along(P, h, t) + rn = rad / np.maximum(np.linalg.norm(rad, axis=1), 1e-6)[:, None] + back = np.clip(rn[:, 1], 0, 1) * 0.75 + 0.25 + env = np.exp(-(s / 0.08) ** 2) * (np.linalg.norm(rad, axis=1) < 0.11) + d += lo_m * env * back * 0.005 * np.sin(2 * np.pi * s / 0.032 + nz * 1.8) + # outer leg seam from the hip to the hem (thigh and calf) + for b in ('thigh_' + s_, 'calf_' + s_): + h, t = _seg(H, b); s, rad, ax, L = _along(P, h, t) + r = np.linalg.norm(rad, axis=1); rn = rad / np.maximum(r, 1e-6)[:, None] + outward = 1.0 if s_ == 'l' else -1.0 + ang = np.arccos(np.clip(rn[:, 0] * outward, -1, 1)) + on = lo_m & (s > -0.03) & (s < L + 0.02) & (r < 0.13) + seam(on, ang * r, s) + # blousing over the boot top: vertical puckers just above the ankle band + h, t = _seg(H, 'calf_' + s_) + s, rad, ax, L = _along(P, h, t) + r = np.linalg.norm(rad, axis=1); rn = rad / np.maximum(r, 1e-6)[:, None] + th = np.arctan2(rn[:, 1], rn[:, 0]) + band = np.exp(-((s - (L - 0.17)) / 0.05) ** 2) + d += lo_m * band * 0.004 * (np.sin(th * 13 + nz * 2) * 0.5 + 0.5) + + # shoulder-to-armpit drag folds (diagonal ridges on chest and back between the collar bone and the armpit) + sh = np.array(H['J']['upperarm_l'][0]); pz = sh[2] + ax_ = np.abs(P[:, 0]) + reg = up_m & (ax_ > 0.06) & (ax_ < 0.2) & (P[:, 2] > pz - 0.2) & (P[:, 2] < pz + 0.02) + diag = (ax_ - 0.06) * 0.75 + (pz - P[:, 2]) * 0.65 + fade = np.clip(1 - np.abs(P[:, 2] - (pz - 0.09)) / 0.11, 0, 1) * np.clip((ax_ - 0.06) / 0.05, 0, 1) + d += reg * fade * 0.0045 * np.sin(2 * np.pi * diag / 0.045 + nz) + # bunching above the belt: horizontal ripples broken by noise + pel = np.array(H['J']['pelvis'][0]); wz = pel[2] + 0.075 + band = np.exp(-((P[:, 2] - (wz + 0.05)) / 0.04) ** 2) + d += up_m * band * 0.0045 * np.sin(2 * np.pi * (P[:, 2] - wz) / 0.02 + nz * 3.0) + # back centre seam and shoulder (yoke) seams + back = P[:, 1] > np.array(H['J']['spine_02'][0])[1] + seam(up_m & back & (P[:, 2] > wz) & (P[:, 2] < pz + 0.08), np.abs(P[:, 0]), P[:, 2]) + top = up_m & (ax_ > 0.07) & (ax_ < 0.2) & (P[:, 2] > pz - 0.02) + seam(top, np.abs(P[:, 1] - sh[1]), P[:, 0]) + + d *= amp + G.set_coords(me, P + N * d[:, None]) + # seams as mesh fields for the cloth shader (it draws the groove and stitches at texel resolution): + # seam_d = 0.05 - distance (0 = no seam nearby, also on pieces without the field), seam_s = along the seam + for nm, val in (('seam_d', np.clip(0.05 - sd, 0, 0.05)), ('seam_s', ss)): + a = me.attributes.get(nm) or me.attributes.new(nm, 'FLOAT', 'POINT') + a.data.foreach_set('value', val.astype(np.float32)) + return float(np.abs(d).max()), int((sd < 0.02).sum()) + +def _seam(dist, along, width=0.004, depth=0.0016, stitch=0.0055, row=0.0035): + """A pressed seam: groove of `width` at dist 0, plus two rows of stitch dimples `row` either side.""" + g = -depth * np.exp(-(dist / width) ** 2) + st = (0.5 + 0.5 * np.cos(2 * np.pi * along / stitch)) ** 6 + rows = np.exp(-((np.abs(dist) - row) / 0.0009) ** 2) + return g - 0.0007 * st * rows diff --git a/e63334287a3deaa3/ironveil/tools/chars/env.sh b/e63334287a3deaa3/ironveil/tools/chars/env.sh new file mode 100755 index 00000000..2df5ffe1 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/env.sh @@ -0,0 +1,13 @@ +# Shared paths for the build scripts. Override any of these in the environment. +# CHARS_WORK : working folder holding the downloaded sources (dl_mpfb, dl_mh, dl_ual, cmu), bvenv and out/ +# CHARS_ASSETS : the game's assets folder that pack.sh writes into +# CHARS_OUT : where videos, sheets and measurement JSON go +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +: "${CHARS_WORK:=$HERE/../work}" +if [ -z "$CHARS_ASSETS" ]; then + if [ -d "$HERE/../../assets" ]; then CHARS_ASSETS=$(cd "$HERE/../../assets" && pwd) + else echo "set CHARS_ASSETS to the game's assets folder" >&2; exit 1; fi +fi +: "${CHARS_OUT:=$HERE/../evidence}" +: "${PORT:=8981}" +export CHARS_WORK CHARS_ASSETS CHARS_OUT PORT HERE diff --git a/e63334287a3deaa3/ironveil/tools/chars/export_weapons.py b/e63334287a3deaa3/ironveil/tools/chars/export_weapons.py new file mode 100644 index 00000000..61d86e66 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/export_weapons.py @@ -0,0 +1,49 @@ +import bpy, sys, os, json, math +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import mhlib as L, geo as G +from mathutils import Vector, Matrix, Quaternion + +out = sys.argv[-1] +bpy.ops.wm.open_mainfile(filepath=L.WORK + '/weapons_baked.blend') +gj = json.load(open(L.WORK + '/grips.json')) +def M(k): + t, q = gj[k] + m = Quaternion(q).to_matrix().to_4x4(); m.translation = Vector(t); return m +GR, GRL, GP, GPL = M('rifle'), M('rifleL'), M('pistol'), M('pistolL') +RIFLE_GL = Vector((0, -0.30, 0.0)) +CONV = Matrix.Rotation(-math.pi / 2, 4, 'X') # glTF keeps Blender bone axes: hand frames need this extra factor +def add(name, m, parent, bone_frame=True): + if bone_frame: m = m @ CONV + e = bpy.data.objects.get(name) + if e is None: + e = bpy.data.objects.new(name, None); G.link(e); e.parent = parent + e.matrix_parent_inverse = Matrix() + e.matrix_basis = m + return e + +def T(rot_cols, trans): + m = Matrix(rot_cols).transposed().to_4x4(); m.translation = Vector(trans); return m + +for o in [o for o in bpy.data.objects if o.type == 'MESH' and o.parent is None]: + n = o.name + gl = bpy.data.objects.get(n + '_gripL') + glp = gl.matrix_basis.translation.copy() if gl else Vector() + if n in ('rifleScoped', 'enemyRifle', 'smg', 'enemySmg', 'mg'): + add(n + '_gripR', GR, o) + add(n + '_gripL', Matrix.Translation(glp - RIFLE_GL) @ GRL, o) + elif n == 'pistol': + add(n + '_gripR', GP, o) + add(n + '_gripL', GPL, o) + else: + # small items sit in a fist like a pistol grip: map item axes into pistol space, then hand = inv(T) @ GP + if n == 'knife': # blade forward-up out of the thumb side, pommel at the little finger + Tm = T(((1, 0, 0), (0, 0.30, -0.95), (0, 0.95, 0.30)), (0, 0.02, -0.05)) @ Matrix.Translation((0, -0.06, 0.004)) + elif n == 'grenade': + Tm = Matrix.Translation((0, 0.02, -0.055)) + else: # binoculars: tubes forward, centre in front of the palm + Tm = Matrix.Translation((0.04, -0.02, -0.05)) + add(n + '_gripR', Tm.inverted() @ GP, o) + if not gl: add(n + '_gripL', Matrix(), o, False) + o.location = (0, 0, 0) +for ob in bpy.context.scene.objects: ob.select_set(True) +bpy.ops.export_scene.gltf(filepath=out, export_format='GLB', export_image_format='AUTO', export_jpeg_quality=88) diff --git a/e63334287a3deaa3/ironveil/tools/chars/fetch.sh b/e63334287a3deaa3/ironveil/tools/chars/fetch.sh new file mode 100755 index 00000000..cdd7addf --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/fetch.sh @@ -0,0 +1,21 @@ +#!/bin/bash +# Downloads the CC0 / freely redistributable source data into $CHARS_WORK. Nothing downloaded here is committed; +# the game only ships the baked files in ../../assets. Licences and exact sources are in ../../CREDITS.md. +. "$(dirname "$0")/env.sh" +mkdir -p "$CHARS_WORK" && cd "$CHARS_WORK" || exit 1 +# Blender as a Python module (Python 3.13) +[ -d bvenv ] || { python3.13 -m venv bvenv && ./bvenv/bin/pip install -q bpy pillow numpy; } +# MakeHuman / MPFB data (CC0): base mesh, targets, rig weights, skins, proxies +mkdir -p dl_mpfb dl_mh +[ -d dl_mpfb/x ] || (cd dl_mpfb && curl -sSL -o mpfb2.zip https://files.makehumancommunity.org/plugins/mpfb2-latest.zip && unzip -q mpfb2.zip -d x) +[ -d dl_mh/x ] || (cd dl_mh && curl -sSL -o sys.zip https://files.makehumancommunity.org/asset_packs/makehuman_system_assets/makehuman_system_assets_cc0.zip && unzip -q sys.zip -d x) +# Quaternius Universal Animation Library, Standard (CC0): download by hand from +# https://quaternius.itch.io/universal-animation-library and put UAL1_Standard.glb and UAL2_Standard.glb in dl_ual/ +mkdir -p dl_ual; ls dl_ual/UAL1_Standard.glb dl_ual/UAL2_Standard.glb >/dev/null || echo "missing dl_ual/UAL*_Standard.glb (manual download)" +# CMU Graphics Lab Motion Capture Database (free to copy, modify and redistribute): only the trials anims_build.py uses +mkdir -p cmu/data; cd cmu/data +for t in $(python3 -I "$HERE/mocap_list.py"); do s=${t%_*} + [ -f $s.asf ] || curl -sS -m 60 -O http://mocap.cs.cmu.edu/subjects/$s/$s.asf + [ -f $t.amc ] || curl -sS -m 120 -O http://mocap.cs.cmu.edu/subjects/$s/$t.amc +done +echo fetched diff --git a/e63334287a3deaa3/ironveil/tools/chars/fp_arms.py b/e63334287a3deaa3/ironveil/tools/chars/fp_arms.py new file mode 100644 index 00000000..fcc6e58b --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/fp_arms.py @@ -0,0 +1,346 @@ +# First-person arms (IVChars.viewmodel): the hero's forearms and hands cut from the same MakeHuman body as hero.glb, +# with the raider smock's sleeves rolled to mid-forearm and a leather-strap wristwatch on the left wrist. +# Stage 'geo' (this file): mesh, sleeves, watch, the first-person skeleton and skin weights -> fp_geo.blend. +# fp_tex.py bakes the 2048 texture set, fp_clips.py authors the clips and exports fp.glb. +# +# First-person space (Blender): the eye at the origin, looking along +Y, up +Z, the player's right is +X. +# (glTF / three.js: the eye at the origin looking down -Z, up +Y, right +X: the camera's own frame.) +import bpy, bmesh, sys, os, math, time +import numpy as np +from mathutils import Vector, Matrix +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import mhlib as L, geo as G, humans as HU + +T0 = time.time() +def log(*a): print('[fp %5.1fs]' % (time.time() - T0), *a, flush=True) +OUT = os.environ.get('FP_WORK') or (L.WORK + '/fp') +os.makedirs(OUT, exist_ok=True) + +ARM = ('clavicle', 'upperarm', 'lowerarm', 'hand', 'index', 'middle', 'ring', 'pinky', 'thumb') +ROLL = (0.80, 0.86) # (kept for fp_tex) the sleeve's hem band, fractions of the forearm +SLEEVE_END = 0.86 # the smock sleeve ends here, over the glove's gauntlet cuff +CUT = 0.42 # keep the upper arm from this fraction of its length (shoulder = 0) +GLOVE_CUFF = (0.78, 1.04) # leather gauntlet cuff of the glove, from under the sleeve to the wrist crease +GLOVE_STRAP = 0.955 # wrist strap of the glove (both hands), buckle on the outer side +WATCH = 0.885 # wristwatch over the left glove cuff, between the sleeve hem and the strap +WRIST_RATIO = 0.62 # wrist width / widest forearm width after the taper (real forearms: about 0.6) + +# first-person bones that carry the weapon and props; their rest frame equals the glTF identity frame +WBONES = ['w_root', 'w_bolt', 'w_boltHandle', 'w_mag', 'w_trigger', 'w_hammer', 'w_charging', 'w_prop'] +WPARENT = {'w_root': 'fp_root', 'w_bolt': 'w_root', 'w_boltHandle': 'w_bolt', 'w_mag': 'w_root', 'w_trigger': 'w_root', + 'w_hammer': 'w_root', 'w_charging': 'w_root', 'w_prop': 'fp_root'} + +def side_bones(s): + return ['clavicle_' + s, 'upperarm_' + s, 'lowerarm_' + s, 'hand_' + s] + \ + [('%s_0%d_%s' % (f, i, s)) if i < 4 else ('%s_04_leaf_%s' % (f, s)) for f in ('index', 'middle', 'ring', 'pinky', 'thumb') for i in (1, 2, 3, 4)] + +def main(): + bpy.ops.wm.read_factory_settings(use_empty=True) + H = L.build_human(**HU.HERO) + body, rig, J = H['body'], H['rig'], H['J'] + eye = sum((v.co for v in H['eyes'].data.vertices), Vector()) / len(H['eyes'].data.vertices) + log('human built, eye', tuple(round(x, 3) for x in eye)) + names = {vg.index: vg.name for vg in body.vertex_groups} + me = body.data + P = np.array([v.co[:] for v in me.vertices]) + n = len(P) + top = [] + for v in me.vertices: + g = max(v.groups, key=lambda x: x.weight) if v.groups else None + top.append(names[g.group] if g else '') + # per-vertex arm parameters (T-pose: the arms lie along X; left arm +X) + keep = np.zeros(n, bool); fpar = np.full(n, -1.0); upar = np.full(n, -1.0); side = np.zeros(n) + for s, sg in (('l', 1.0), ('r', -1.0)): + S, E, W_ = J['upperarm_' + s][0], J['lowerarm_' + s][0], J['hand_' + s][0] + lu, lf = abs(E.x - S.x), abs(W_.x - E.x) + for i in range(n): + t = top[i] + if not t.endswith('_' + s) or not t.startswith(ARM): continue + a = sg * P[i, 0] + u = (a - sg * S.x) / lu + f = (a - sg * E.x) / lf + upar[i], fpar[i] = u, f + side[i] = sg + if u >= CUT: keep[i] = True + # a real wrist: MakeHuman's forearm stays thick to the wrist. Taper the last half of each forearm toward the bone + # line until the wrist is WRIST_RATIO of the forearm's widest width (the cross-section flattens: width more than + # depth). Done before the sleeves and the glove cuff are fitted, so they follow it. + for s, sg in (('l', 1.0), ('r', -1.0)): + E_, W2 = J['lowerarm_' + s][0], J['hand_' + s][0] + ax_ = np.array((W2 - E_).normalized()[:]); lf_ = (W2 - E_).length; e_ = np.array(E_[:]) + ids = np.array([i for i in range(n) if top[i].endswith('_' + s) and top[i].startswith(ARM)]) + Q = P[ids] - e_; f = Q @ ax_ / lf_ + rad = Q - np.outer(f * lf_, ax_) + def width(f0, f1): + m = (f > f0) & (f < f1) + return rad[m, 1].max() - rad[m, 1].min() + wmax = max(width(a, a + 0.08) for a in np.arange(0.05, 0.6, 0.05)) + ww = width(0.92, 0.98) + need = min(1.0, WRIST_RATIO * wmax / ww) + rise = np.clip((f - 0.42) / 0.50, 0, 1); rise = rise * rise * (3 - 2 * rise) + fall = 1 - np.clip((f - 0.98) / 0.16, 0, 1); fall = fall * fall * (3 - 2 * fall) + kw = 1 - (1 - need) * rise * fall; kd = 1 - (1 - need) * 0.55 * rise * fall + newP = e_ + np.outer(f * lf_, ax_) + rad * np.stack([np.ones_like(kw), kw, kd], 1) + for j, i in enumerate(ids): me.vertices[i].co = Vector(newP[j]) + P[ids] = newP + rad2 = newP - e_ - np.outer(f * lf_, ax_) + m2 = (f > 0.92) & (f < 0.98) + log('forearm', s, 'widest %.3f wrist %.3f -> %.3f (ratio %.2f -> %.2f)' % (wmax, ww, rad2[m2, 1].max() - rad2[m2, 1].min(), ww / wmax, (rad2[m2, 1].max() - rad2[m2, 1].min()) / wmax)) + # the whole body's surface, for placing the sleeves (their rays must hit skin that is about to be removed) + full = body.copy(); full.data = body.data.copy(); G.link(full) + bvh_full = G.bvh_of(full) + # skin faces: drop those wholly covered by the sleeve (upper arm, elbow and forearm up to the roll's lower part) + covered = (upar >= 0) & (fpar < ROLL[0] + 0.02) + bm = bmesh.new(); bm.from_mesh(me) + bm.verts.ensure_lookup_table() + dead = [f for f in bm.faces if not all(keep[v.index] for v in f.verts) or all(covered[v.index] for v in f.verts)] + bmesh.ops.delete(bm, geom=dead, context='FACES') + bm.to_mesh(me); bm.free() + # remove now-unused vertices of the rest of the body + bm = bmesh.new(); bm.from_mesh(me) + bmesh.ops.delete(bm, geom=[v for v in bm.verts if not v.link_faces], context='VERTS') + bm.to_mesh(me); bm.free() + for k in ('eyes', 'brows', 'lashes', 'hair'): + if H.get(k): bpy.data.objects.remove(H[k]) + skin = body; skin.name = 'Skin' + log('skin tris', G.tris(skin), 'verts', len(skin.data.vertices)) + # smooth the forearm silhouette: one level of subdivision on the forearm and wrist only (hands keep MakeHuman + # density, about 3k triangles each, which already models knuckles and finger pads) + P2 = np.array([v.co[:] for v in skin.data.vertices]) + sub = np.zeros(len(P2), bool) + for s, sg in (('l', 1.0), ('r', -1.0)): + E, W_ = J['lowerarm_' + s][0], J['hand_' + s][0] + a = sg * P2[:, 0] + sub |= (a > sg * E.x - 0.02) & (a < sg * W_.x + 0.012) & (np.sign(P2[:, 0]) == sg) + bm = bmesh.new(); bm.from_mesh(skin.data) + bm.verts.ensure_lookup_table() + edges = [e for e in bm.edges if all(sub[v.index] for v in e.verts)] + bmesh.ops.subdivide_edges(bm, edges=edges, cuts=1, use_grid_fill=True, smooth=0.5) + bm.to_mesh(skin.data); bm.free() + log('skin after forearm subdivision', G.tris(skin)) + + # full leather gloves: the whole hand and every finger stand 1.4 mm proud of the skin, with knuckle bulges over + # the knuckles and the middle finger joints (leather bunches there), and slightly fuller fingertips + gnames = {vg.index: vg.name for vg in skin.vertex_groups} + heads = {} + for s_ in ('l', 'r'): + for f_ in ('index', 'middle', 'ring', 'pinky', 'thumb'): + for k_ in (1, 2, 3): + bn = '%s_0%d_%s' % (f_, k_, s_) + if bn in J: heads[bn] = J[bn][0] + for v in skin.data.vertices: + g_ = max(v.groups, key=lambda x: x.weight) if v.groups else None + nm_ = gnames[g_.group] if g_ else '' + if not nm_.startswith(('hand_', 'index_', 'middle_', 'ring_', 'pinky_', 'thumb_')): continue + s_ = nm_[-1]; d_ = 0.0014 + dors_ = v.normal.z # T-pose, palms down: +Z is the back of the hand + for f_ in ('index', 'middle', 'ring', 'pinky'): + for k_, amp, rr in ((1, 0.0013, 0.0085), (2, 0.0008, 0.0065)): + h_ = heads.get('%s_0%d_%s' % (f_, k_, s_)) + if h_ is None: continue + dd = (v.co - h_).length + if dd < 2.5 * rr: d_ += amp * math.exp(-(dd / rr) ** 2) * max(0.0, min(1.0, (dors_ + 0.1) / 0.5)) + if nm_.endswith(('_03_' + s_,)) or '_04_leaf' in nm_: d_ += 0.0004 + v.co = v.co + v.normal * d_ + bvh = bvh_full + parts = [skin] + # ---------------- sleeves, glove cuffs, wrist straps + def cuff_off(fr): + """Gauntlet cuff stand-off from the skin: snug at the wrist, a little flare toward the sleeve.""" + u = max(0.0, min(1.0, (0.96 - fr) / (0.96 - GLOVE_CUFF[0]))) + return 0.0022 + 0.0026 * u * u + hits = {} + for s, sg in (('l', 1.0), ('r', -1.0)): + S, E, W_ = J['upperarm_' + s][0], J['lowerarm_' + s][0], J['hand_' + s][0] + lu, lf = (E - S).length, (W_ - E).length + st = [] + # the sleeve tube: from the cut to the hem over the glove cuff, ~8 mm stations. Heavy cloth: slack that grows + # toward the elbow, compression folds that bunch up toward the wrist and change the silhouette (6-7 mm deep), + # a few long diagonal twist folds along the forearm, and room at the hem for the glove cuff underneath + a0 = CUT * lu + total = lu - a0 + SLEEVE_END * lf + ns = max(8, int(total / 0.010)) + for k in range(ns + 1): + d = a0 + total * k / ns + if d <= lu: + c = S.lerp(E, d / lu); ax = (E - S).normalized() + else: + c = E.lerp(W_, (d - lu) / lf); ax = (W_ - E).normalized() + fr = (d - lu) / lf # forearm fraction (negative on the upper arm) + hem = max(0.0, min(1.0, (fr - 0.70) / 0.16)) + slack = 0.010 + 0.006 * math.exp(-((d - lu) / 0.05) ** 2) - 0.002 * max(0.0, min(1.0, fr / 0.6)) + 0.0045 * hem + def off(th, d=d, slack=slack, fr=fr, hem=hem): + bunch = max(0.0, min(1.0, (fr - 0.35) / 0.4)) # folds crowd toward the wrist + ph = 2 * math.pi * (d / (0.030 - 0.010 * bunch)) + 1.9 * math.sin(th * 2 + d * 30) + 0.9 * math.sin(th * 3.0 - d * 55) + env = 0.35 + 0.65 * max(0.0, min(1.0, (fr + 0.35) / 0.6)) + inner = 0.5 + 0.5 * max(0.0, math.cos(th + math.pi / 2 * sg)) + ring = (0.0040 + 0.0028 * bunch) * env * (0.55 + 0.6 * inner) * (0.5 + 0.5 * math.sin(ph)) ** 1.5 + twist = 0.0018 * max(0.0, math.sin(th * 2 - d * 18 + 0.7)) ** 3 * max(0.0, min(1.0, (fr + 0.1) / 0.4)) + lip = 0.0015 * math.exp(-((fr - SLEEVE_END) / 0.012) ** 2) # the turned hem stands a little proud + return slack + ring + twist + lip + st.append((c, ax, off, Vector((0, 0, 1)))) + sl = G.ring_loft(bvh, st, n=24, name='Sleeve_' + s) + # cuff tab with a button on the outer side of the hem (pinky side, +Y in the T-pose) + ax = (W_ - E).normalized(); c = E.lerp(W_, SLEEVE_END - 0.035) + dvec = Vector((0, 0.75, 0.66)).normalized() + hit = bvh.ray_cast(c + dvec * 0.1, -dvec, 0.2) + if hit[0] is not None: + zt = dvec; xt = ax; yt = zt.cross(xt).normalized(); xt = yt.cross(zt).normalized() + Mt = Matrix((xt, yt, zt)).transposed().to_4x4(); Mt.translation = hit[0] + zt * 0.0168 + tab = G.box('Tab_' + s, (0.040, 0.016, 0.0028), Mt, bev=0.0011, seg=1) + btn = G.lathe('Button_' + s, [(0.0, 0.0), (0.0058, 0.0), (0.0062, 0.0012), (0.0055, 0.0024), (0.0, 0.0028)], n=16, + M=Mt @ Matrix.Translation((0.010, 0, 0.0014))) + parts += [tab, btn] + # leather gauntlet cuff of the glove: from under the sleeve hem to the wrist, small creases round it + cs = [] + nc = 10 + for k in range(nc + 1): + fr = GLOVE_CUFF[0] + (GLOVE_CUFF[1] - GLOVE_CUFF[0]) * k / nc + c = E.lerp(W_, fr) + def off(th, fr=fr): + return cuff_off(fr) + 0.0006 * math.sin(th * 4 + fr * 60) * math.exp(-((fr - 0.92) / 0.05) ** 2) + cs.append((c, ax, off, Vector((0, 0, 1)))) + gc = G.ring_loft(bvh, cs, n=24, name='GloveCuff_' + s) + # wrist strap over the cuff, and a buckle on the pinky side + ss_ = [] + for k in range(5): + fr = GLOVE_STRAP - 0.026 + 0.052 * k / 4 + edge = 1.0 if k in (0, 4) else 0.0 + ss_.append((E.lerp(W_, fr), ax, cuff_off(fr) + 0.0008 + 0.0008 * (1 - edge), Vector((0, 0, 1)))) + gs = G.ring_loft(bvh, ss_, n=32, name='GloveStrap_' + s) + G.solidify(gs, 0.0016, offset=1.0) + c = E.lerp(W_, GLOVE_STRAP); dvec = Vector((0, 1.0, 0.25)).normalized() + hit = bvh.ray_cast(c + dvec * 0.1, -dvec, 0.2) + if hit[0] is not None: + zt = dvec; xt = ax; yt = zt.cross(xt).normalized(); xt = yt.cross(zt).normalized() + Mb = Matrix((xt, yt, zt)).transposed().to_4x4(); Mb.translation = hit[0] + zt * (cuff_off(GLOVE_STRAP) + 0.0036) + fr_ = [G.box('Buckle', (0.0022, 0.017, 0.0022), Mb @ Matrix.Translation((sx * 0.0075, 0, 0)), bev=0.0007, seg=1) for sx in (-1, 1)] + fr_ += [G.box('Buckle', (0.017, 0.0022, 0.0022), Mb @ Matrix.Translation((0, sy * 0.0075, 0)), bev=0.0007, seg=1) for sy in (-1, 1)] + fr_ += [G.box('Buckle', (0.0016, 0.015, 0.0016), Mb @ Matrix.Translation((0.001, 0, 0.0008)), bev=0.0005, seg=1)] + buckle = G.join(fr_, 'Buckle_' + s) + parts += [buckle] + parts += [sl, gc, gs] + log('sleeve', s, G.tris(sl), 'glove cuff', G.tris(gc), 'strap', G.tris(gs)) + # ---------------- wristwatch on the left wrist (dorsal side, +Z in the T-pose with palms down) + E, W_ = J['lowerarm_l'][0], J['hand_l'][0] + lf = (W_ - E).length; ax = (W_ - E).normalized() + ws = [] + for k in range(7): + fr = WATCH - 0.035 + 0.07 * k / 6 + c = E.lerp(W_, fr) + edge = 1.0 if k in (0, 6) else 0.0 + ws.append((c, ax, cuff_off(fr) + 0.0016 + 0.0012 * (1 - edge), Vector((0, 0, 1)))) + strap = G.ring_loft(bvh, ws, n=28, name='Strap') + G.solidify(strap, 0.0022, offset=1.0) + c = E.lerp(W_, WATCH) + hit = bvh.ray_cast(c + Vector((0, 0, 0.08)), Vector((0, 0, -1)), 0.2) + top = hit[0] + Vector((0, 0, 0.0035 + cuff_off(WATCH))) + # case, bezel, domed crystal: one lathe profile (r, z) from the back up, then the crown + prof = [(0.0, 0.0), (0.0145, 0.0), (0.0158, 0.0012), (0.0162, 0.0040), (0.0160, 0.0062), (0.0150, 0.0074), + (0.0146, 0.0080), (0.0140, 0.0086), (0.0128, 0.0088), (0.0125, 0.0089), (0.0100, 0.0094), (0.0060, 0.0098), (0.0, 0.0099)] + Mc = Matrix.Translation(top) + case = G.lathe('Case', [(r, z) for r, z in prof], n=28, M=Mc) + crown = G.lathe('Crown', [(0.0, 0.0), (0.0024, 0.0), (0.0026, 0.0008), (0.0026, 0.0034), (0.0022, 0.0040), (0.0, 0.0041)], n=12, + M=Matrix.Translation(top + Vector((0.0158, 0, 0.0042))) @ Matrix.Rotation(math.pi / 2, 4, 'Y')) + # lugs: four short bars that hold the strap ends, bevelled + lugs = [] + for sx in (-1, 1): + for sy in (-1, 1): + lg = G.box('Lug', (0.004, 0.0034, 0.003), Matrix.Translation(top + Vector((sx * 0.0145, sy * 0.0068, 0.0018))), bev=0.0009, seg=1) + lugs.append(lg) + watch = G.join([case, crown] + lugs, 'Watch') + parts += [strap, watch] + log('watch', G.tris(watch), 'strap', G.tris(strap)) + meta = {'watch_centre': list(top), 'watch_axis': [0, 0, 1]} + + # ---------------- weights for everything that is not skin + for o in parts[1:]: + G.transfer_weights(o, skin) + bpy.data.objects.remove(full) + # forearm twist: move part of each forearm vertex's lowerarm weight to a twist bone, growing toward the wrist + for o in parts: + for s, sg in (('l', 1.0), ('r', -1.0)): + E, W_ = J['lowerarm_' + s][0], J['hand_' + s][0] + lf = (W_ - E).length + src = o.vertex_groups.get('lowerarm_' + s) + if src is None: continue + dst = o.vertex_groups.get('lowerarm_twist_' + s) or o.vertex_groups.new(name='lowerarm_twist_' + s) + for v in o.data.vertices: + for g in v.groups: + if g.group == src.index and g.weight > 0: + f = (sg * v.co.x - sg * E.x) / lf + t = max(0.0, min(1.0, (f - 0.15) / 0.8)) ** 1.2 + w = g.weight + src.add([v.index], w * (1 - t), 'REPLACE'); dst.add([v.index], w * t, 'REPLACE') + # material regions (face attribute 'region'): 0 glove leather (the hand), 1 sleeve cloth, 2 glove cuff leather, + # 3 watch strap, 4 watch case, 5 crystal, 6 glove wrist strap, 7 buckle and button + def region_of(nm): + for pre, r in (('Sleeve', 1), ('Tab', 1), ('GloveCuff', 2), ('Strap', 3), ('Watch', 4), ('GloveStrap', 6), ('Buckle', 7), ('Button', 7)): + if nm.startswith(pre): return r + return 0 + for o in parts: + r = 0 if o is parts[0] else region_of(o.name) + at = o.data.attributes.new('region', 'INT', 'FACE') + vals = [r] * len(o.data.polygons) + if o.name == 'Watch': + for p in o.data.polygons: + cz = sum((o.data.vertices[i].co.z for i in p.vertices), 0.0) / len(p.vertices) + cxy = sum(((o.data.vertices[i].co - top).xy.length for i in p.vertices), 0.0) / len(p.vertices) + if cz > top.z + 0.0088 and cxy < 0.0127: vals[p.index] = 5 + at.data.foreach_set('value', vals) + arms = G.join(parts, 'FPArms') + # sleeve cloth is seen from the inside when the camera looks down the arm: keep it closed by solidify + log('arms tris', G.tris(arms)) + + # ---------------- first-person skeleton: clavicles to fingertips, forearm twist, weapon and prop bones + fpa = bpy.data.armatures.new('FPRig'); fpo = bpy.data.objects.new('FPRig', fpa); G.link(fpo) + L.set_active(fpo); bpy.ops.object.mode_set(mode='EDIT') + eb = fpa.edit_bones + root = eb.new('fp_root'); root.head = eye; root.tail = eye + Vector((0, 0, 0.05)) + src = {b.name: b for b in rig.data.bones} + for s in ('l', 'r'): + for bn in side_bones(s): + b = src[bn]; e = eb.new(bn) + e.head = rig.matrix_world @ b.head_local; e.tail = rig.matrix_world @ b.tail_local + e.matrix = rig.matrix_world @ b.matrix_local; e.length = b.length + for bn in side_bones(s): + p = src[bn].parent + eb[bn].parent = eb[p.name] if p and p.name in eb else root + lo = eb['lowerarm_' + s] + tw = eb.new('lowerarm_twist_' + s) + tw.matrix = lo.matrix.copy() + tw.head = lo.head.lerp(lo.tail, 0.5); tw.tail = lo.head.lerp(lo.tail, 0.95); tw.roll = lo.roll + tw.parent = lo + for wb in WBONES: + e = eb.new(wb) + e.matrix = Matrix(((1, 0, 0, eye.x), (0, 0, -1, eye.y), (0, 1, 0, eye.z), (0, 0, 0, 1))) + e.length = 0.03 + for wb in WBONES: eb[wb].parent = eb[WPARENT[wb]] + bpy.ops.object.mode_set(mode='OBJECT') + # move everything into first-person space: eye at the origin, facing +Y + M = Matrix.Rotation(math.pi, 4, 'Z') @ Matrix.Translation(-eye) + arms.data.transform(M) + fpo.matrix_world = M + L.set_active(fpo); bpy.ops.object.transform_apply(location=True, rotation=True, scale=True) + # the weapon bones were built with glTF-identity frames in the old space; rebuild them after the turn + bpy.ops.object.mode_set(mode='EDIT') + for wb in WBONES: + e = fpa.edit_bones[wb] + e.matrix = Matrix(((1, 0, 0, 0), (0, 0, -1, 0), (0, 1, 0, 0), (0, 0, 0, 1))); e.length = 0.03 + bpy.ops.object.mode_set(mode='OBJECT') + meta['watch_centre'] = list(M @ Vector(meta['watch_centre'])) + meta['watch_axis'] = [0, 0, 1] + # bind + for vg in list(arms.vertex_groups): + if vg.name not in fpa.bones: arms.vertex_groups.remove(vg) + arms.parent = fpo; arms.matrix_parent_inverse = Matrix() + arms.modifiers.new('Armature', 'ARMATURE').object = fpo + # tidy: drop the third-person rig and the UAL import + for o in list(bpy.data.objects): + if o not in (arms, fpo): bpy.data.objects.remove(o) + arms['meta'] = str(meta) + bpy.ops.wm.save_as_mainfile(filepath=OUT + '/fp_geo.blend') + log('saved', OUT + '/fp_geo.blend', 'tris', G.tris(arms), 'verts', len(arms.data.vertices), 'bones', len(fpa.bones)) + +if __name__ == '__main__': + main() diff --git a/e63334287a3deaa3/ironveil/tools/chars/fp_clips.py b/e63334287a3deaa3/ironveil/tools/chars/fp_clips.py new file mode 100644 index 00000000..31c05848 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/fp_clips.py @@ -0,0 +1,1018 @@ +# First-person clips: poses the fp_geo.blend arms around each first-person weapon and writes fp.glb (arms + clips). +# usage: CHARS_WORK=... bvenv/bin/python fp_clips.py [preview|export] +# preview: renders stills of the key poses from the first-person camera (Cycles, quick) to $FP_WORK/preview +# export: writes $FP_WORK/fp.glb and $FP_WORK/fp.json (clip lengths, events, sockets, grip fit report) +# Needs $FP_WORK/fp_geo.blend (fp_arms.py) with textures from fp_tex.py when present, and $FP_WORK/weapons_plain.glb +# (fp_unpack.mjs of assets/weapons.glb). +import bpy, sys, os, math, json, time +import numpy as np +from mathutils import Vector, Matrix, Quaternion +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import mhlib as ML +import anim_lib as AL +import fp_lib as F +from fp_lib import pose_w, blend_m, rot + +T0 = time.time() +def log(*a): print('[clips %5.1fs]' % (time.time() - T0), *a, flush=True) +FPW = os.environ.get('FP_WORK') or (ML.WORK + '/fp') +MODE = sys.argv[-1] if sys.argv[-1] in ('preview', 'export', 'diag') else 'preview' +# diag: KINDS=rifleScoped ONLY=reload,boltCycle -> per-frame penetration by side and bone group, no export +FPS = 30 + +bpy.ops.wm.open_mainfile(filepath=FPW + ('/fp_tex.blend' if os.path.exists(FPW + '/fp_tex.blend') else '/fp_geo.blend')) +arm = bpy.data.objects['FPRig']; mesh = bpy.data.objects['FPArms'] +_g = bpy.data.node_groups.get('glTF Material Output') +if _g: _g.name = 'glTF Settings' # our one-socket group; the importer would try to extend it +bpy.ops.import_scene.gltf(filepath=FPW + '/weapons_plain.glb') +for o in bpy.data.objects: + if o not in (arm, mesh): o.hide_render = True +rig = AL.Rig(arm) +skin = F.Skin(mesh, rig) +WPN = {k: F.Weapon(k) for k in ('rifleScoped', 'smg', 'pistol', 'grenade', 'binoculars')} +log('loaded', {k: list(w.empty) for k, w in WPN.items() if k in ('rifleScoped', 'smg', 'pistol')}) + +def rest(): + L = rig.rest(); return L, rig.W(L) + +# shoulders: first-person rigs carry the shoulders forward and in (the head is down on the stock); never seen +SHOULDER = {'r': Vector((0.30, 0.05, -0.50)), 'l': Vector((-0.08, 0.10, -0.45))} +REACH = 0.93 # a shoulder moves toward its hand when the hand is further than this share of the arm's reach +POLE = {'r': Vector((0.55, -0.3, -1.0)), 'l': Vector((-0.4, -0.1, -1.0))} # elbows down and a little out +POLE_K = {'pistol': {'r': Vector((1.0, -0.3, -0.6)), 'l': Vector((-0.6, -0.1, -1.0))}} # as in g7 + +# ------------------------------------------------------------------------------------------------ base poses +# per weapon: hip (weapon pose at the hip), ads (sight on the camera axis), sprint carry, low (lowered) +def ads_pose(k, extra_back=0.0): + """Sight line on the lens axis: the scope's eye point at the eye (rifle), or the rear and front sights aligned on + the axis with the rear sight REAR[k] metres in front of the eye (iron sights).""" + w = WPN[k] + if 'scopeEye' in w.empty: + R = F.RZ180.copy(); R.translation = -(F.RZ180.to_3x3() @ w.E('scopeEye').translation) + Vector((0, extra_back, 0)) + return R + r_, f_ = w.E('sightRear').translation, w.E('sightFront').translation + d = (f_ - r_).normalized() # in the weapon frame, roughly -Y + R3 = (F.RZ180.to_3x3() @ d).rotation_difference(Vector((0, 1, 0))).to_matrix() @ F.RZ180.to_3x3() + R = R3.to_4x4(); R.translation = Vector((0, REAR[k], 0)) - R3 @ r_ + return R +REAR = {'smg': 0.20, 'pistol': float(os.environ.get('PREAR', 0.50))} + +BASE = { + 'rifleScoped': dict(hip=pose_w(tuple(float(v) for v in os.environ.get('RIFLE_HIP', '0.20,0.58,-0.27').split(',')), + yaw=float(os.environ.get('RIFLE_YAW', 5.0)), pitch=-1.6, roll=float(os.environ.get('RIFLE_ROLL', -8.0))), + sprint=pose_w((0.06, 0.40, -0.25), yaw=38, pitch=14, roll=-55), + low=pose_w((0.16, 0.16, -0.32), yaw=10, pitch=-30, roll=-10)), + 'smg': dict(hip=pose_w((0.13, 0.33, -0.098), yaw=0.6, pitch=-1.2, roll=-4.0), + sprint=pose_w((0.05, 0.36, -0.23), yaw=38, pitch=12, roll=-55), + low=pose_w((0.16, 0.17, -0.32), yaw=10, pitch=-30, roll=-10)), + # pistol at the hip: compact, low and right like the long guns (the old pose sat in the middle with both arms + # rising from below the frame) + 'pistol': dict(hip=pose_w((0.15, 0.37, -0.155), yaw=4.0, pitch=0.0, roll=-6.0), + sprint=pose_w((0.10, 0.34, -0.22), yaw=15, pitch=-40, roll=-20), + low=pose_w((0.12, 0.22, -0.32), yaw=8, pitch=-45, roll=-10)), +} +for k in BASE: BASE[k]['ads'] = ads_pose(k) +# Hip framing from the composition search (FRAME=1 ... diag): muzzle just below and right of the crosshair, the +# left glove on the fore-end fully in frame, the right glove's upper half at the bottom right, each hand at most +# about 12% of the screen width. (target position, yaw, pitch, roll changes about the grip) +HIPFIX = {'rifleScoped': ((0.26, 0.535, -0.23), 0.4, 8.2, -14.5), + 'smg': (None, 0.0, 0.0, 0.0), + 'pistol': ((0.148, 0.46, -0.138), -7.5, 8.2, 4.0)} +def _hipfix(k): + pos, yw, pt, rl = HIPFIX[k] + W = BASE[k]['hip']; t = W.translation + if pos is None: pos = (t.x, t.y, t.z + 0.015) # SMG: only lifted so the left hand clears the bottom edge + M = rot('Z', yw) @ rot('X', pt) @ rot('Y', rl) @ Matrix(W.to_3x3()).to_4x4(); M.translation = Vector(pos) + return M +if not os.environ.get('NOHIPFIX'): + for k in BASE: BASE[k]['hip'] = _hipfix(k) + +# Pistol shoulders follow the pose: at the hip they sit low and wide so the right forearm enters from the lower +# right corner; in ADS they come up toward the sight line (isosceles, head down between the arms) so the arms run +# along the view axis and the forearms hide behind the hands. +SH_PISTOL = {'hip': {'r': Vector((0.22, 0.0, -0.40)), 'l': Vector((-0.07, 0.02, -0.42))}, + 'ads': {'r': Vector([float(v) for v in os.environ.get('SH_PADS', '0.15,0.0,-0.24').split(',')]), + 'l': Vector([-float(v) if i == 0 else float(v) for i, v in enumerate(os.environ.get('SH_PADS', '0.15,0.0,-0.24').split(','))])}} +# A real upper body behind the camera. Long guns: the butt plate sits in the right shoulder pocket, so the right +# shoulder joint is just outside, behind and above the butt; the left shoulder is a shoulder-width to the left and +# bladed forward. Computed from the weapon's hip and ADS poses (the body is carried with the framed gun: the whole +# assembly is moved, never single joints) and blended between them by how far the gun is toward ADS. Pistol: +# shoulders where a body puts them, both arms extended forward. +BUTT = {'rifleScoped': Vector((0.0, 0.35, -0.08)), 'smg': Vector((0.0, 0.37, -0.03))} +def body_shoulders(k, Ww): + b = Ww @ BUTT[k] + r = b + Vector((0.045, -0.05, 0.015)) + return {'r': r, 'l': r + Vector((-0.34, 0.09, 0.0))} +SH_BODY = {} +def _sh_init(): + for k in BUTT: + SH_BODY[k] = {'hip': body_shoulders(k, BASE[k]['hip']), 'ads': body_shoulders(k, BASE[k]['ads'])} + SH_BODY['pistol'] = {'hip': {'r': Vector((0.17, -0.04, -0.24)), 'l': Vector((-0.17, -0.02, -0.24))}, + 'ads': {'r': Vector((0.15, 0.02, -0.22)), 'l': Vector((-0.15, 0.03, -0.22))}} +OLD = bool(os.environ.get('OLDPOSTURE')) # the posture of 836d9e6, for before/after measurements +def shoulders_for(k, Ww): + if OLD or k == 'pistol': # pistol: the g7 posture the coordinator accepted (the body-based one put the left + if k != 'pistol': return SHOULDER_K.get(k) or SHOULDER # forearm across the middle of the screen) + H = BASE[k]['hip'].translation; A = BASE[k]['ads'].translation + a = AL.smooth(max(0.0, min(1.0, 1 - (Ww.translation - A).length / max(1e-6, (H - A).length)))) + return {s: SH_PISTOL['hip'][s].lerp(SH_PISTOL['ads'][s], a) for s in ('l', 'r')} + if not SH_BODY: _sh_init() + H = BASE[k]['hip'].translation; A = BASE[k]['ads'].translation + a = AL.smooth(max(0.0, min(1.0, 1 - (Ww.translation - A).length / max(1e-6, (H - A).length)))) + return {s: SH_BODY[k]['hip'][s].lerp(SH_BODY[k]['ads'][s], a) for s in ('l', 'r')} + +def joint_stats(W, s): + """Wrist flexion (+ toward the palm) and deviation, elbow angle, elbow height above the wrist (m) and forearm + twist (deg) of side s for the world bone matrices W.""" + fa = (W['lowerarm_' + s].to_3x3() @ Vector((0, 1, 0))).normalized() + ua = (W['upperarm_' + s].to_3x3() @ Vector((0, 1, 0))).normalized() + hy = (W['hand_' + s].to_3x3() @ Vector((0, 1, 0))).normalized() + pn = F.palm_normal(rig, W, s); pn = (pn - fa * pn.dot(fa)).normalized(); side_ = fa.cross(pn).normalized() + flex = math.degrees(math.atan2(hy.dot(pn), hy.dot(fa))); dev = math.degrees(math.atan2(hy.dot(side_), hy.dot(fa))) + elbow = 180 - math.degrees(math.acos(max(-1, min(1, ua.dot(fa))))) + above = W['lowerarm_' + s].translation.z - W['hand_' + s].translation.z + lo = W['lowerarm_' + s] + hx = (W['hand_' + s].to_3x3() @ rig.Rr['hand_' + s].inverted() @ rig.Rr['lowerarm_' + s] @ Vector((1, 0, 0))) + lx = lo.to_3x3() @ Vector((1, 0, 0)) + a_ = hx - fa * hx.dot(fa); b_ = lx - fa * lx.dot(fa) + tw = math.degrees(math.atan2(b_.normalized().cross(a_.normalized()).dot(fa), b_.normalized().dot(a_.normalized()))) if a_.length > 1e-6 and b_.length > 1e-6 else 0.0 + return flex, dev, elbow, above, tw + +def joint_cost(W, s): + if OLD: return 0.0 + flex, dev, elbow, above, tw = joint_stats(W, s) + c = (max(0.0, abs(flex) - 25) / 10) ** 2 + (max(0.0, abs(dev) - 12) / 6) ** 2 + c += (max(0.0, 35 - elbow) / 10) ** 2 + (max(0.0, elbow - 150) / 10) ** 2 + (max(0.0, above + 0.02) / 0.015) ** 2 + return c + +# ------------------------------------------------------------------------------------------------ grips +# Hand frames from the weapon's real shape (sections measured on the meshes): where the palm centre sits, which way +# the straight fingers point and which way the palm faces, all in the weapon frame. The fit then slides the palm +# until it touches without sinking in, and the fingers close joint by joint on the surface. +def nz(*v): return Vector(v).normalized() +GRIPSPEC = { + # rifle (ray-probed scan): stock wrist at y 0.04..0.08 is 26-32 mm wide, z -0.059..-0.010; the fore-end at + # y -0.255 is 36 mm wide with its underside at z -0.024 + ('rifleScoped', 'gripR'): dict(pc=(-0.022, 0.074, -0.026), dir=nz(0.25, -0.55, -0.8), palm=nz(0.75, 0.0, -0.66), bound=(0.005, 0.010, 0.006)), + ('rifleScoped', 'gripL'): dict(pc=tuple(float(v) for v in os.environ.get('RGL_PC', '0.020,-0.255,-0.031').split(',')), + dir=nz(*[float(v) for v in os.environ.get('RGL_DIR', '-1,-0.35,0.05').split(',')]), + palm=nz(*[float(v) for v in os.environ.get('RGL_PALM', '-0.3,0,1').split(',')]), bound=(0.006, 0.015, 0.004)), + ('smg', 'gripR'): dict(pc=(-0.022, 0.072, -0.070), dir=nz(0.15, -1, -0.25), palm=nz(1, -0.5, 0)), + ('smg', 'gripL'): dict(pc=(0.004, -0.20, -0.017), dir=nz(-1, -0.25, 0.05), palm=nz(-0.25, 0, 1)), + # palm round onto the backstrap with the web high under the slide, so the camera behind the gun sees the hand, not a bare backstrap + ('pistol', 'gripR'): dict(pc=tuple(float(v) for v in os.environ.get('PGR_PC', '-0.019,0.064,-0.024').split(',')), + dir=nz(*[float(v) for v in os.environ.get('PGR_DIR', '0.15,-1,-0.25').split(',')]), + palm=nz(*[float(v) for v in os.environ.get('PGR_PALM', '1,-1,0').split(',')]), + thumb=tuple(float(v) for v in os.environ.get('PGR_THUMB', '').split(',') if v) or None, + bound=(0.008, 0.008, 0.004)), # keep the web high under the slide + ('pistol', 'gripL'): dict(pc=tuple(float(v) for v in os.environ.get('PGL_PC', '0.014,0.060,-0.058').split(',')), + dir=nz(*[float(v) for v in os.environ.get('PGL_DIR', '-0.35,-1,-0.35').split(',')]), palm=nz(-1, 0.35, 0.15), fixed=True), +} +PALM = {} +for s_ in ('l', 'r'): + ids = [i for i, b in enumerate(skin.dom) if b == 'hand_' + s_ and skin.N[i][2] < -0.5] + PALM[s_] = Vector(skin.P[ids].mean(0)) +GRIP = {} # (kind, name) -> {'off': Vector (weapon frame), 'fingers': {...}, 'pen': (n, deep)} + +def hand_matrix(s, pc, d, palm): + """Hand bone matrix (armature space) putting the palm centre at pc, straight fingers along d, palm facing palm.""" + R = rig.hand_rot(s, d, palm) + head = rig.Mr['hand_' + s].translation + wrist = pc - (R @ rig.Rr['hand_' + s].transposed()) @ (PALM[s] - head) + M = R.to_4x4(); M.translation = wrist + return M + +def hand_frame(k, s, W, which=None, off=None): + nm = which or ('gripR' if s == 'r' else 'gripL') + g = GRIPSPEC[(k, nm)] + o = off if off is not None else GRIP.get((k, nm), {}).get('off', Vector()) + R3 = W.to_3x3() + return hand_matrix(s, W @ (Vector(g['pc']) + o), R3 @ g['dir'], R3 @ g['palm']) + +def solve_grip(k, nm, s, trigger=False, Wf=None, bvh=None, all_fingers=False): + """Fit the hand on the weapon: alternate (1) a search over the palm offset and a small turn of the hand, scored + by every hand vertex inside the weapon plus palm contact, and (2) closing the fingers on the surface.""" + w = WPN[k]; W = BASE[k]['hip']; g = GRIPSPEC[(k, nm)] + Wf = Wf or W + bvh = bvh or w.bvh['body']; Minv = Wf.inverted() + hand_ids = skin.verts_of(('hand_' + s, 'index_', 'middle_', 'ring_', 'pinky_', 'thumb_')) + hand_ids = np.array([i for i in hand_ids if skin.dom[i].endswith('_' + s)], int) + palm_ids = np.array([i for i in hand_ids if skin.dom[i] == 'hand_' + s and skin.N[i][2] < -0.3], int) + if g.get('fixed'): + ang = {'index': (1.15, 1.2, 0.7), 'middle': (1.2, 1.25, 0.7), 'ring': (1.25, 1.25, 0.7), 'pinky': (1.3, 1.25, 0.7), + 'thumb': (0.05, 0.05, 0.0, 0.1)} # wrapped over the firing hand, thumb forward along the frame + else: + ang = {'index': (0.3, 0.4, 0.2), 'middle': (0.5, 0.5, 0.3), 'ring': (0.5, 0.5, 0.3), 'pinky': (0.5, 0.5, 0.3), 'thumb': (0.1, 0.2, 0.2, 0.3)} + if not trigger and not all_fingers and not g.get('fixed'): ang['index'] = (0.10, 0.08, 0.05) + base_dir, base_palm = Vector(g['dir']), Vector(g['palm']) + def pose_with(x): + off = Vector(x[:3]) + R = Matrix.Rotation(x[3], 3, base_palm) @ Matrix.Rotation(x[4], 3, base_dir.cross(base_palm).normalized()) + g['dir'] = R @ base_dir; g['palm'] = R @ base_palm + L, Wd = rest() + for side in ('l', 'r'): F.place_shoulder(rig, L, Wd, side, shoulders_for(k, W)[side]) + R3 = Wf.to_3x3() + F.arm_to(rig, L, Wd, s, hand_matrix(s, Wf @ (Vector(g['pc']) + off), R3 @ g['dir'], R3 @ g['palm']), POLE_K.get(k, POLE)[s]) + g['dir'], g['palm'] = base_dir, base_palm + return L, Wd, R + def cost(x, fingers): + L, Wd, _ = pose_with(x) + F.set_fingers(rig, L, Wd, s, fingers) + P = skin.pose(Wd, hand_ids[::2]) + d = np.array([F.signed_dist(bvh, Minv @ Vector(p)) for p in P]) + for i in np.where(d < 0)[0]: # open scan meshes: a negative reading counts only if really inside + if not F.inside(bvh, Minv @ Vector(P[i])): d[i] = -d[i] + pen = np.clip(0.0008 - d, 0, None) + Pp = skin.pose(Wd, palm_ids[::2]) + dp = np.array([F.signed_dist(bvh, Minv @ Vector(p)) for p in Pp]) + near = np.sort(dp)[: max(4, len(dp) // 5)] + bnd = g.get('bound', (0.010, 0.020, 0.008)) # per-axis travel limits of the fit (weapon frame, metres) + over = sum(max(0.0, abs(x[i]) - bnd[i]) ** 2 for i in range(3)) * 1e6 if bnd else 0.0 + return float((pen ** 2).sum() * 6e5 + ((near.mean() - 0.003) ** 2) * 3e4 + Vector(x[:3]).length ** 2 * 60 + (x[3] ** 2 + x[4] ** 2) * 0.5 + over + + joint_cost(Wd, s) * 2.0) + x = [0.0] * 5 + for rnd in range(3): + c0 = cost(x, ang); step = [0.006] * 3 + [0.12, 0.12] + while max(step[:3]) > 0.0008: + moved = False + for ax in range(5): + for sg in (-1, 1): + cand = list(x); cand[ax] += sg * step[ax] + c = cost(cand, ang) + if c < c0: c0, x, moved = c, cand, True + if not moved: step = [v * 0.5 for v in step] + if g.get('fixed'): break + L, Wd, R = pose_with(x) + fingers = ('middle', 'ring', 'pinky', 'thumb') + (('index',) if (trigger or all_fingers) else ()) + new = F.grasp_fingers(rig, skin, L, Wd, s, bvh, Minv, fingers=fingers, thumb_spread=0.35 if s == 'r' else 0.2) + ang.update(new) + if g.get('thumb'): ang['thumb'] = g['thumb'] # authored thumb (pistol: along the left of the frame) + L, Wd, R = pose_with(x) + g['dir'] = R @ base_dir; g['palm'] = R @ base_palm # keep the fitted turn in the spec + F.set_fingers(rig, L, Wd, s, ang) + pen = F.penetration(skin, Wd, bvh, Minv, idx=hand_ids) + GRIP[(k, nm)] = {'off': Vector(x[:3]), 'fingers': ang, 'pen': pen} + Rw = Wf.to_3x3().inverted() + act_palm = Rw @ F.palm_normal(rig, Wd, s) + act_dir = Rw @ (Wd['middle_01_' + s].translation - Wd['hand_' + s].translation).normalized() + log(' frame', k, nm, 'want dir', tuple(round(v, 2) for v in g['dir']), 'got', tuple(round(v, 2) for v in act_dir), + 'want palm', tuple(round(v, 2) for v in g['palm']), 'got', tuple(round(v, 2) for v in act_palm)) + log('grip', k, nm, 'offset', tuple(round(v, 4) for v in x), 'pen', pen, 'cost', round(c0, 3), + {f: tuple(round(v, 2) for v in a) for f, a in ang.items()}) + return GRIP[(k, nm)] + +# ------------------------------------------------------------------------------------------------ frame solve +LASTPOLE = {} +ARM_IDS = {s_: np.array([i for i in skin.verts_of(('lowerarm', 'upperarm')) if skin.dom[i].endswith('_' + s_)], int)[::4] for s_ in ('l', 'r')} +SHOULDER_K = {'pistol': {'r': Vector((0.17, 0.08, -0.48)), 'l': Vector((-0.02, 0.08, -0.48))}} +HAND_IDS = {s_: np.array([i for i in skin.verts_of(('hand_', 'index_', 'middle_', 'ring_', 'pinky_', 'thumb_')) if skin.dom[i].endswith('_' + s_)], int)[::5] for s_ in ('l', 'r')} +POLES = {'l': (0, -25, 25, -50, 50, -80, 80, -110, 110), 'r': (0, -20, 20, -40, 40, -65, 65, -90, 90, -120, 120)} +LASTNUDGE = {} +FORCE = {} # side -> offset Vector: second pass of a clip, the smoothed nudges applied without a search +def arm_pen(W2, s, bvh, Minv, hand=True): + """Clearance cost of one arm against the weapon: sum of (4 mm - signed distance) over sampled forearm, upper + arm and (optionally) hand vertices. A negative reading counts only if the ray-parity test agrees (open scans).""" + c = 0.0 + for ids in ((ARM_IDS[s], HAND_IDS[s]) if hand else (ARM_IDS[s],)): + for p in skin.pose(W2, ids): + q = Minv @ Vector(p); d = F.signed_dist(bvh, q) + if d < 0.004: + if d < -0.002 and not F.inside(bvh, q): continue + c += 0.004 - d + return c + +def frame(k, Ww, hands, fingers, parts=None, shoulders=None, prop=None, nudge=None): + """One pose. Ww: weapon pose; hands: side -> hand bone matrix; fingers: side -> angles; + parts: part -> delta matrix; prop: (kind, matrix) for the w_prop bone (scale 0 when None); + nudge: side -> True when that hand is travelling (not holding anything) and may be moved off its path to keep + the hand and forearm out of the weapon.""" + L, W = rest() + for s in ('l', 'r'): + F.place_shoulder(rig, L, W, s, (shoulders or shoulders_for(k, Ww))[s]) + w = WPN[k] + Minv = Ww.inverted() + bvh = w.bvh['body'] + for s in ('r', 'l'): + if s not in hands: continue + # elbow: of several pole directions round the shoulder-wrist line, take the one whose forearm and hand stay + # out of the weapon, preferring small and steady turns + def solve(H): + ax = (H.translation - W['upperarm_' + s].translation).normalized() + best = None + for a_ in POLES[s]: + pole = Quaternion(ax, math.radians(a_)) @ POLE_K.get(k, POLE)[s] + L2 = {b: m.copy() for b, m in L.items()}; W2 = {b: m.copy() for b, m in W.items()} + F.arm_to(rig, L2, W2, s, H, pole) + pen = arm_pen(W2, s, bvh, Minv, hand=bool((nudge or {}).get(s))) + c = pen + abs(a_) * 0.00004 + abs(a_ - LASTPOLE.get(s, 0)) * 0.0002 + joint_cost(W2, s) * 0.002 + if best is None or c < best[0] - 1e-9: best = (c, L2, W2, a_, pen) + return best + if FORCE.get(s) is not None: + H = hands[s].copy(); H.translation = H.translation + FORCE[s] + best = solve(H); LASTNUDGE[s] = FORCE[s] + elif (best := solve(hands[s])) and (nudge or {}).get(s) and best[4] > 0.004: + # a hand in transit that still cuts the weapon: try moving it out (weapon left/right/below/above, and + # back toward the eye), the smallest move that clears wins; steady from frame to frame + R3 = Ww.to_3x3() + last = LASTNUDGE.get(s, Vector()) + cands = [(best[4] + last.length * 0.08, best, Vector())] + for dv in ((-1, 0, 0), (1, 0, 0), (0, 0, -1), (0, 0, 1)): + for m in (0.02, 0.04, 0.07): + off = (R3 @ Vector(dv)).normalized() * m + H = hands[s].copy(); H.translation = H.translation + off + b2 = solve(H) + cands.append((b2[4] + m * 0.12 + (off - last).length * 0.08, b2, off)) + _, best, off = min(cands, key=lambda x: x[0]) + LASTNUDGE[s] = off + else: + LASTNUDGE[s] = Vector() + L, W = best[1], best[2]; LASTPOLE[s] = best[3] + for s in ('r', 'l'): + if s in fingers: F.set_fingers(rig, L, W, s, fingers[s]) + rig.set_world(L, W, 'w_root', Ww @ F.RX90) + for p in ('bolt', 'boltHandle', 'mag', 'trigger', 'hammer', 'charging'): + if p not in w.empty: continue + D = (parts or {}).get(p, Matrix()) + par = 'w_bolt' if p == 'boltHandle' else 'w_root' + # parts are keyed in their parent's frame: world = weapon @ part rest @ delta (boltHandle rides the bolt) + if p == 'boltHandle': + Db = (parts or {}).get('bolt', Matrix()) + Mw = Ww @ w.empty['bolt'] @ Db @ w.empty['bolt'].inverted() @ w.empty['boltHandle'] @ D + else: + Mw = Ww @ w.empty[p] @ D + if (parts or {}).get(p + '_world') is not None: Mw = parts[p + '_world'] + rig.set_world(L, W, 'w_' + p, Mw @ F.RX90) + S = {} + if prop: + rig.set_world(L, W, 'w_prop', prop[1] @ F.RX90) + return L, W + +# ------------------------------------------------------------------------------------------------ preview +def apply_pose(L): + for b, (t, q) in rig.basis(L).items(): + pb = arm.pose.bones[b]; pb.rotation_mode = 'QUATERNION'; pb.rotation_quaternion = q; pb.location = t + +PROPSHOW = [None] +def place_weapon(k, W): + for kk in WPN: + root = WPN[kk].root + root.hide_render = kk != k + for c in root.children_recursive: c.hide_render = kk != k + if PROPSHOW[0]: + pr = WPN[PROPSHOW[0]].root; pr.hide_render = False + for c in pr.children_recursive: c.hide_render = False + pr.matrix_world = W['w_prop'] @ F.RX90.inverted() + root = WPN[k].root + root.matrix_world = W[ 'w_root'] @ F.RX90.inverted() + for p in ('bolt', 'boltHandle', 'mag', 'trigger', 'hammer', 'charging'): + o = bpy.data.objects.get(k + '_' + p) + if o is not None: + o.matrix_world = W['w_' + p] @ F.RX90.inverted() + +def setup_render(): + sc = bpy.context.scene + cam = bpy.data.objects.get('FPCam') + if cam is None: + cam = bpy.data.objects.new('FPCam', bpy.data.cameras.new('FPCam')); sc.collection.objects.link(cam) + cam.data.sensor_fit = 'VERTICAL'; cam.data.angle = math.radians(55); cam.data.clip_start = 0.01 + cam.location = (0, 0, 0); cam.rotation_euler = (math.pi / 2, 0, 0) # look along +Y, up +Z + sc.camera = cam + w = bpy.data.worlds.new('w'); sc.world = w + w.use_nodes = True; w.node_tree.nodes['Background'].inputs[0].default_value = (0.55, 0.6, 0.65, 1) + w.node_tree.nodes['Background'].inputs[1].default_value = 0.8 + sun = bpy.data.objects.new('sun', bpy.data.lights.new('sun', 'SUN')); sc.collection.objects.link(sun) + sun.rotation_euler = (math.radians(50), math.radians(-20), math.radians(30)); sun.data.energy = 2.5 + sc.render.engine = os.environ.get('ENGINE', 'CYCLES'); sc.cycles.samples = int(os.environ.get('SAMPLES', 24)); sc.cycles.device = 'CPU' + if sc.render.engine == 'BLENDER_WORKBENCH': # quick grip checks: studio light, material colours + sc.display.shading.light = 'STUDIO'; sc.display.shading.color_type = 'MATERIAL' + sc.render.threads_mode = 'FIXED'; sc.render.threads = 2 + sc.render.resolution_x = int(os.environ.get('RW', 960)); sc.render.resolution_y = int(os.environ.get('RH', 540)) + sc.view_settings.view_transform = 'AgX' + if not mesh.data.materials: + m = bpy.data.materials.new('skin_preview'); m.diffuse_color = (0.6, 0.42, 0.33, 1) + m.node_tree.nodes['Principled BSDF'].inputs['Base Color'].default_value = (0.55, 0.36, 0.27, 1) + mesh.data.materials.append(m) + +def render(path, L, W, k, view=None): + apply_pose(L); place_weapon(k, W) + cam = bpy.data.objects['FPCam'] + if view: # close-up: camera at view[0] looking at view[1] + cam.location = view[0]; d = (Vector(view[1]) - Vector(view[0])) + cam.rotation_euler = d.to_track_quat('-Z', 'Z').to_euler(); cam.data.angle = math.radians(view[2] if len(view) > 2 else 40) + else: + cam.location = (0, 0, 0); cam.rotation_euler = (math.pi / 2 + math.radians(float(os.environ.get('LOOK', 0))), 0, 0) + cam.data.angle = math.radians(float(os.environ.get('FOV', 55))) + bpy.context.view_layer.update() + bpy.context.scene.render.filepath = path + bpy.ops.render.render(write_still=True) + +# ------------------------------------------------------------------------------------------------ part grips +def part_box(k, part): + V = WPN[k].verts[part] + return Vector(V.min(0)), Vector(V.max(0)) + +def add_part_specs(k): + """Hand frames on moving parts, in the part's own pivot frame: the left hand on the magazine (palm on its left + side, fingers round the front), the right hand pinching a bolt knob or charging knob, the left hand over the slide.""" + w = WPN[k] + if 'mag' in w.bvh: + lo, hi = part_box(k, 'mag') + if hi.z - lo.z < 0.09: # a short box magazine: gripped from the left and below, fingers wrapped round its + # front, thumb behind it on the release (the old cupped, upturned palm read as an open hand) + GRIPSPEC[(k, 'magL')] = dict(part='mag', pc=(hi.x + 0.012, (lo.y + hi.y) / 2 + 0.006, lo.z + (hi.z - lo.z) * 0.15), + dir=nz(0.1, -1, -0.35), palm=nz(-1, 0, 0.35)) + else: # a long magazine: palm on its left side, fingers round the front + GRIPSPEC[(k, 'magL')] = dict(part='mag', pc=(hi.x + 0.011, (lo.y + hi.y) / 2 + 0.004, lo.z + (hi.z - lo.z) * 0.38), + dir=nz(0.05, -1, -0.15), palm=nz(-1, 0, 0.1)) + for part in ('boltHandle', 'charging'): + if part in w.bvh: + V = w.verts[part] + if part == 'boltHandle': + i = int(np.argmax(V[:, 0] ** 2 + (V[:, 2]) ** 2)); knob = Vector(V[i]) + else: + i = int(np.argmin(V[:, 0])); knob = Vector(V[i]) + GRIPSPEC[(k, part + 'R')] = dict(part=part, pc=tuple(knob + Vector((-0.024, 0.032, -0.018))), + dir=nz(0.25, -0.8, 0.45), palm=nz(0.65, -0.45, 0.55), knob=tuple(knob)) + if k == 'pistol': + lo, hi = part_box(k, 'bolt') + GRIPSPEC[(k, 'slideL')] = dict(part='bolt', pc=(0.0, hi.y - 0.022, hi.z + 0.013), dir=nz(-1, 0.15, -0.2), palm=nz(0, 0, -1)) + +def hand_on_part(k, s, W, nm, D=None, Dparent=None): + """Hand bone matrix for a part grip, with the part moved by D (and its parent bolt by Dparent).""" + g = GRIPSPEC[(k, nm)]; w = WPN[k]; part = g['part'] + Mp = W @ w.empty[part] @ (D or Matrix()) + if part == 'boltHandle': + Mp = W @ w.empty['bolt'] @ (Dparent or Matrix()) @ w.empty['bolt'].inverted() @ w.empty['boltHandle'] @ (D or Matrix()) + o = GRIP.get((k, nm), {}).get('off', Vector()) + R3 = Mp.to_3x3() + return hand_matrix(s, Mp @ (Vector(g['pc']) + o), R3 @ g['dir'], R3 @ g['palm']) + +def solve_part_grip(k, nm, s): + g = GRIPSPEC[(k, nm)]; part = g['part']; w = WPN[k] + W = BASE[k]['hip'] + Mp = W @ w.empty[part] + if part == 'boltHandle': Mp = W @ w.empty['bolt'] @ w.empty['bolt'].inverted() @ w.empty['boltHandle'] + G_ = solve_grip(k, nm, s, Wf=Mp, bvh=w.bvh[part], all_fingers=True) + if nm.endswith('R') and part in ('boltHandle', 'charging'): + # a pinch: thumb and index on the knob, the other fingers loosely curled out of the way + G_['fingers'].update({'middle': (0.9, 1.0, 0.6), 'ring': (1.0, 1.1, 0.6), 'pinky': (1.1, 1.1, 0.6)}) + return G_ + +# ------------------------------------------------------------------------------------------------ clip programs +K = AL.keys +def M_(a, b, t): return blend_m(a, b, AL.smooth(t)) +def rel(W, dx=0, dy=0, dz=0, yaw=0, pitch=0, roll=0): + """W moved in first-person space (metres) and turned about the weapon origin (degrees).""" + R = rot('Z', yaw) @ rot('X', pitch) @ rot('Y', roll) + M = W.copy(); o = M.translation.copy(); M.translation = Vector() + M = R @ M; M.translation = o + Vector((dx, dy, dz)) + return M +def wave(t, T, a): return a * math.sin(2 * math.pi * t / T) +def tr(v): return Matrix.Translation(Vector(v)) +def ramp(t, t0, t1): return AL.smooth((t - t0) / max(1e-6, t1 - t0)) +def bump(t, t0, t1, t2): return ramp(t, t0, t1) * (1 - ramp(t, t1, t2)) + +def grip_r(k, W): return hand_frame(k, 'r', W, 'gripR') +def grip_l(k, W): return hand_frame(k, 'l', W, 'gripL') +def fR(k, trig=0.0): + g = GRIP[(k, 'gripR')]['fingers'] + if trig > 0: + g = dict(g); idx = GRIP.get((k, 'gripR_trigger'), {}).get('fingers', {}).get('index', (0.55, 0.75, 0.35)) + g['index'] = tuple(a + (b - a) * trig for a, b in zip(g['index'], idx)) + return g +def fL(k): return GRIP[(k, 'gripL')]['fingers'] + +def pose_prop(s, M_hand, kind, along=0.0): + """Prop held in a hand: its root at the palm centre pushed out along the palm normal.""" + R3 = M_hand.to_3x3() @ rig.Rr['hand_' + s].transposed() + pc = M_hand.translation + R3 @ (PALM[s] - rig.Mr['hand_' + s].translation) + palm = (R3 @ Vector((0, 0, -1))).normalized() + fwd = (R3 @ (rig.Mr['middle_01_' + s].translation - rig.Mr['hand_' + s].translation)).normalized() + M = AL.Rig.frame_rot(Vector((0, -1, 0)), Vector((0, 0, -1)), fwd, palm).to_4x4() + M.translation = pc + palm * along + return M + +CLIPS = {} # name -> (duration, loop, fn(t) -> dict, events) +def clip(name, dur, loop=False, events=None): + def deco(fn): + CLIPS[name] = (dur, loop, fn, events or {}); return fn + return deco + +def make_clips(k): + B = BASE[k]; HIP, ADS, SPR, LOW = B['hip'], B['ads'], B['sprint'], B['low'] + w = WPN[k] + long_ = k != 'pistol' + def std(W, t=0.0, trig=0.0, parts=None, rh=None, lh=None, rf=None, lf=None, prop=None, hold=()): + return dict(W=W, rh=rh or grip_r(k, W), lh=lh or grip_l(k, W), rf=rf or fR(k, trig), lf=lf or fL(k), parts=parts or {}, prop=prop, hold=hold) + + @clip(k + '.idle', 3.0, loop=True) + def _(t): + return std(rel(HIP, dz=wave(t, 3.0, 0.0018), dx=wave(t + 0.4, 3.0, 0.0008), pitch=wave(t, 3.0, 0.35))) + + @clip(k + '.ads', 3.0, loop=True) + def _(t): + return std(rel(ADS, dz=wave(t, 3.0, 0.0005), pitch=wave(t, 3.0, 0.08)), trig=0.35) + + # the raise from the hip to the sights, sampled by the ADS amount: vm.drive holds this clip at time = state.ads, + # so every in-between pose is solved with the hands on the grips (blending the hip and ADS clips in the mixer + # let the right hand swing off the gun mid-raise). The gun travels on a slight low arc. + @clip(k + '.adsRaise', 1.0) + def _(t): + W = rel(blend_m(HIP, ADS, t), dz=-0.025 * math.sin(math.pi * t)) + return std(W, trig=0.35 * t) + + fire_T = {'rifleScoped': 0.45, 'smg': 0.11, 'pistol': 0.3}[k] + @clip(k + '.fire', fire_T, events={'shot': 0.02}) + def _(t): + tg = bump(t, 0.0, 0.025, fire_T * 0.6) + parts = {'trigger': rot('X', -14 * tg)} + if k == 'pistol': + sl = bump(t, 0.005, 0.035, 0.09) + parts['bolt'] = tr((0, 0.034 * sl, 0)); parts['hammer'] = rot('X', -40 * min(1, sl * 1.5)) + if k == 'smg': + parts['bolt'] = tr((0, 0.05 * bump(t, 0.0, 0.035, 0.08), 0)) + kick = bump(t, 0.0, 0.03, fire_T * 0.9) + return std(rel(HIP, dy=-0.012 * kick, pitch=1.2 * kick), trig=1.0, parts=parts) + + @clip(k + '.fireAds', fire_T, events={'shot': 0.02}) + def _(t): + d = CLIPS[k + '.fire'][2](t); kick = bump(t, 0.0, 0.03, fire_T * 0.9) + d['W'] = rel(ADS, dy=-0.008 * kick, pitch=0.6 * kick); d['rh'] = grip_r(k, d['W']); d['lh'] = grip_l(k, d['W']) + return d + + OFF = rel(HIP, dz=-0.32, dy=-0.05, dx=0.06, pitch=-55, roll=-25, yaw=-10) + @clip(k + '.draw', 0.65, events={'ready': 0.6}) + def _(t): + u = ramp(t, 0, 0.55) + W = M_(OFF, HIP, u) if u < 1 else HIP + W = rel(W, roll=-6 * bump(t, 0.3, 0.5, 0.65)) + return std(W) + + @clip(k + '.holster', 0.5) + def _(t): + return std(M_(HIP, OFF, ramp(t, 0, 0.5))) + + @clip(k + '.sprint', 0.7, loop=True) + def _(t): + W = rel(SPR, dz=wave(t, 0.7, 0.008), dx=wave(t, 1.4, 0.006), roll=wave(t, 1.4, 2.0)) + return std(W) + + @clip(k + '.sprintIn', 0.3) + def _(t): return std(M_(HIP, SPR, ramp(t, 0, 0.3))) + + @clip(k + '.sprintOut', 0.3) + def _(t): return std(M_(SPR, HIP, ramp(t, 0, 0.3))) + + # ---- magazine reloads + if 'mag' in w.empty: + mag_down = Vector((0, 0.0 if long_ else 0.012, -1)).normalized() + RLD = rel(HIP, dx=-0.04, dz=0.055 if long_ else 0.03, dy=0.0, roll=28 if long_ else 15, pitch=10, yaw=-6) + if k == 'smg': # the SMG's hip is close to the eye: push it out and tip it instead of lifting it into view + RLD = rel(HIP, dx=-0.025, dy=0.07, dz=-0.01, roll=22, pitch=16, yaw=-8) + T_ = 2.5 if long_ else 1.9 + def reload_fn(t, empty): + u_in = ramp(t, 0.0, 0.3); u_out = ramp(t, T_ - 0.45, T_ - 0.05) + W = M_(HIP, RLD, u_in) if t < T_ - 0.45 else M_(RLD, HIP, u_out) + # magazine: out 0.55-0.8, away (hidden) by 1.1, a full one appears below at 1.25, in 1.55-1.75 + s1 = 0.30 if not long_ else 0.32 + out = ramp(t, 0.55, 0.8) * 0.11 + ramp(t, 0.8, 1.1) * 0.25 + inn = (1 - ramp(t, 1.25, 1.62)) * 0.30 if t >= 1.15 else None + vis = 0.0 if 1.1 <= t < 1.15 else 1.0 + off = (out if t < 1.15 else inn) + if empty and not long_ and t < 0.55: off = 0.0 + Dm = tr(mag_down * off) + if t >= 1.15 and t < 1.62: Dm = Dm @ rot('Y', -25 * (1 - ramp(t, 1.15, 1.62))) + Dm = Dm @ Matrix.Diagonal((vis, vis, vis, 1.0)) + parts = {'mag': Dm} + # left hand: fore-end -> magazine (0.3-0.55) -> rides with it (0.55-1.75), slap at 1.72 -> fore-end (1.8-2.1) + gl = grip_l(k, W) + gm = hand_on_part(k, 'l', W, 'magL', D=tr(mag_down * off) @ (rot('Y', -25 * (1 - ramp(t, 1.15, 1.62))) if t >= 1.15 and t < 1.62 else Matrix())) + if t < 0.55: lh = M_(gl, gm, ramp(t, 0.28, 0.55)); lf = F.mix_fingers(fL(k), GRIP[(k, 'magL')]['fingers'], ramp(t, 0.3, 0.55)) + elif t < 1.75: lh = gm; lf = GRIP[(k, 'magL')]['fingers'] + else: + lh = M_(gm, gl, ramp(t, 1.8, 2.1 if long_ else 1.65 + 0.25)); lf = F.mix_fingers(GRIP[(k, 'magL')]['fingers'], fL(k), ramp(t, 1.75, 2.05)) + if 1.1 <= t < 1.2: lh = M_(gm, gm, 0) + return std(W, parts=parts, lh=lh, lf=lf, hold=('l',) if 0.55 <= t < 1.75 else ()) + ev = {'magOut': 0.6, 'magIn': 1.62, 'done': T_ - 0.1} + @clip(k + '.reload', T_, events=ev) + def _(t): return reload_fn(t, False) + if k == 'pistol': + TE = T_ + 0.55 + @clip(k + '.reloadEmpty', TE, events=dict(ev, slide=T_ + 0.2, done=TE - 0.1)) + def _(t): + if t < T_ - 0.45: d = reload_fn(t, True); d['parts']['bolt'] = tr((0, 0.034, 0)); return d + # overhand: the left hand grips the slide, pulls it back and lets it go + W = RLD + pull = bump(t, T_ - 0.15, T_ + 0.12, T_ + 0.2) + Db = tr((0, 0.034 * (1 if t < T_ - 0.15 else pull), 0)) if t < T_ + 0.2 else Matrix() + gs = hand_on_part(k, 'l', W, 'slideL', D=tr((0, 0.034 * max(pull, 0), 0))) + u = ramp(t, T_ - 0.45, T_ - 0.15) + lh = M_(grip_l(k, W), gs, u) if t < T_ + 0.2 else M_(gs, grip_l(k, HIP), ramp(t, T_ + 0.2, TE - 0.05)) + Wt = W if t < T_ + 0.2 else M_(RLD, HIP, ramp(t, T_ + 0.2, TE - 0.05)) + if t >= T_ + 0.2: lh = M_(gs, grip_l(k, Wt), ramp(t, T_ + 0.2, TE - 0.05)) + lf = GRIP[(k, 'slideL')]['fingers'] if T_ - 0.2 < t < T_ + 0.25 else fL(k) + return std(Wt, parts={'bolt': Db}, lh=lh, lf=lf, hold=('l',) if T_ - 0.15 <= t < T_ + 0.2 else ()) + + # ---- bolt / charging handle cycle with the right hand (rifle bolt, SMG charging knob) + part = 'boltHandle' if k == 'rifleScoped' else ('charging' if k == 'smg' else None) + if part: + TB = 1.05 if k == 'rifleScoped' else 0.75 + CYC = rel(HIP, roll=7, pitch=-3, dz=-0.012) + def cycle_parts(t): + if k == 'rifleScoped': + up = bump(t, 0.25, 0.36, 0.86) if t < 0.86 else 0.0 + back = bump(t, 0.38, 0.56, 0.74) + return {'boltHandle': rot('Y', 62 * up), 'bolt': tr((0, 0.078 * back, 0))}, up, back + back = bump(t, 0.2, 0.38, 0.44) + return {'charging': tr((0, 0.06 * back, 0)), 'bolt': tr((0, 0.06 * back, 0))}, 0, back + def cycle_fn(t, base=None, t0=0.0): + tt = t - t0 + Wb = base or HIP + W = M_(Wb, CYC, ramp(tt, 0.0, 0.2)) if tt < TB - 0.2 else M_(CYC, Wb, ramp(tt, TB - 0.2, TB)) + parts, up, back = cycle_parts(tt) + if k == 'rifleScoped': + Dp = parts['boltHandle']; Dpar = parts['bolt'] + gk = hand_on_part(k, 'r', W, part + 'R', D=Dp, Dparent=Dpar) + else: + gk = hand_on_part(k, 'r', W, part + 'R', D=parts['charging']) + gr = grip_r(k, W) + if tt < 0.24: rh = M_(gr, gk, ramp(tt, 0.05, 0.24)); rf = F.mix_fingers(fR(k), GRIP[(k, part + 'R')]['fingers'], ramp(tt, 0.08, 0.24)) + elif tt < TB - 0.2: rh = gk; rf = GRIP[(k, part + 'R')]['fingers'] + else: rh = M_(gk, gr, ramp(tt, TB - 0.2, TB - 0.02)); rf = F.mix_fingers(GRIP[(k, part + 'R')]['fingers'], fR(k), ramp(tt, TB - 0.2, TB - 0.05)) + return std(W, parts=parts, rh=rh, rf=rf, hold=('r',) if 0.24 <= tt < TB - 0.2 else ()) + name = '.boltCycle' if k == 'rifleScoped' else '.charge' + @clip(k + name, TB, events={'boltUp': 0.3, 'boltBack': 0.5, 'eject': 0.52, 'boltForward': 0.7, 'boltDown': 0.84} if k == 'rifleScoped' else {'charge': 0.36}) + def _(t): return cycle_fn(t) + if 'mag' in w.empty: + TR = CLIPS[k + '.reload'][0] + @clip(k + '.reloadEmpty', TR + TB - 0.2, events=dict(CLIPS[k + '.reload'][3], boltBack=TR - 0.2 + 0.5, done=TR + TB - 0.3)) + def _(t): + if t < TR - 0.45: return CLIPS[k + '.reload'][2](t) + if t < TR - 0.2: + d = CLIPS[k + '.reload'][2](t); return d + return cycle_fn(t, t0=TR - 0.2) + + # ---- grenade: weapon low and right, left hand takes a grenade from the belt, pin, throw + @clip(k + '.grenade', 1.55, events={'pin': 0.62, 'release': 1.04, 'done': 1.45}) + def _(t): + W = M_(HIP, LOW, ramp(t, 0.0, 0.25)) if t < 1.15 else M_(LOW, HIP, ramp(t, 1.15, 1.5)) + gl = grip_l(k, HIP) + belt = hand_matrix('l', Vector((-0.12, 0.05, -0.55)), nz(0.2, 1, 0.3), nz(0.3, 0, 1)) + hold = hand_matrix('l', Vector((-0.05, 0.30, -0.16)), nz(0.35, 0.6, 0.7), nz(0.6, -0.2, -0.2)) + wind = hand_matrix('l', Vector((-0.22, 0.02, 0.05)), nz(0.1, -0.3, 1), nz(0.7, 0.6, 0)) + throw = hand_matrix('l', Vector((-0.02, 0.62, 0.04)), nz(0.1, 1, 0.3), nz(0.0, 0.3, -1)) + trk = [(0.0, gl), (0.25, belt), (0.42, belt), (0.62, hold), (0.82, wind), (1.01, wind), (1.13, throw), (1.22, throw), (1.5, grip_l(k, HIP))] + lh = trk[0][1] + for (t0, a), (t1, b) in zip(trk, trk[1:]): + if t0 <= t <= t1: lh = M_(a, b, (t - t0) / (t1 - t0)); break + if t > 1.5: lh = grip_l(k, HIP) + lf = F.mix_fingers(fL(k), F.RELAXED, ramp(t, 0.0, 0.2)) + hold_f = {'index': (0.8, 0.9, 0.5), 'middle': (0.9, 1.0, 0.5), 'ring': (0.95, 1.0, 0.5), 'pinky': (1.0, 1.0, 0.5), 'thumb': (0.3, 0.3, 0.2, 0.5)} + if 0.3 < t < 1.04: lf = F.mix_fingers(F.RELAXED, hold_f, ramp(t, 0.3, 0.45)) + elif t >= 1.04: lf = F.mix_fingers(F.FLAT, fL(k), ramp(t, 1.15, 1.45)) + prop = ('grenade', pose_prop('l', lh, 'grenade', 0.03)) if 0.33 <= t < 1.06 else None + return std(W, lh=lh, lf=lf, prop=prop) + + # the same grenade motion cut in three parts so the game can cook it: pull (ends holding the grenade with the pin + # out), cook (a held loop), throw (wind and release, then back to the weapon) + G_ = CLIPS[k + '.grenade'][2] + @clip(k + '.grenadePull', 0.66, events={'pin': 0.62}) + def _(t): return G_(t) + @clip(k + '.grenadeCook', 1.0, loop=True) + def _(t): + d = G_(0.66); d['W'] = rel(d['W'], dz=wave(t, 1.0, 0.002)); return d + @clip(k + '.grenadeThrow', 0.89, events={'release': 0.38, 'done': 0.8}) + def _(t): return G_(0.66 + t) + + # ---- melee: a butt stroke with the long guns, a downward pistol-butt blow with the pistol + @clip(k + '.melee', 0.8, events={'hit': 0.32}) + def _(t): + if long_: + wind = rel(HIP, dx=0.06, dy=-0.06, dz=0.02, yaw=-25, roll=-10) + hit = rel(HIP, dx=-0.08, dy=0.18, dz=0.08, yaw=55, pitch=10, roll=-60) + else: + wind = rel(HIP, dz=0.08, dy=-0.04, pitch=35) + hit = rel(HIP, dz=-0.06, dy=0.16, pitch=-55, roll=-10) + trk = [(0.0, HIP), (0.15, wind), (0.32, hit), (0.42, hit), (0.8, HIP)] + W = HIP + for (t0, a), (t1, b) in zip(trk, trk[1:]): + if t0 <= t <= t1: W = M_(a, b, (t - t0) / (t1 - t0)); break + return std(W) + + # ---- interact: weapon dips right, left hand reaches out flat and back + @clip(k + '.interact', 0.9, events={'touch': 0.45}) + def _(t): + W = M_(HIP, rel(HIP, dx=0.05, dz=-0.08, roll=-20, pitch=-10), bump(t, 0.0, 0.2, 0.85)) + reach = hand_matrix('l', Vector((-0.02, 0.50, -0.06)), nz(0.15, 1, 0.25), nz(0.1, 0.5, -0.8)) + gl = grip_l(k, W) + lh = M_(gl, reach, ramp(t, 0.1, 0.42)) if t < 0.5 else M_(reach, gl, ramp(t, 0.55, 0.88)) + lf = F.mix_fingers(fL(k), F.FLAT, bump(t, 0.1, 0.35, 0.85)) + return std(W, lh=lh, lf=lf) + + # ---- binoculars: weapon low, left hand brings the binoculars to the eyes (hold the last frame) + def bino(t, lower=False): + u = ramp(t, 0.15, 0.85) + if lower: u = 1 - ramp(t, 0.0, 0.6) + W = M_(HIP, LOW, ramp(t, 0.0, 0.3) if not lower else 1 - ramp(t, 0.4, 0.8)) + b = WPN['binoculars']; eye = b.E('scopeEye') if 'scopeEye' in b.empty else Matrix.Translation((0, 0.06, 0.02)) + at_eye = F.RZ180.copy(); at_eye.translation = -(F.RZ180.to_3x3() @ eye.translation) + start = rel(at_eye, dz=-0.42, dy=0.05, pitch=-40, roll=20) + Mb = M_(start, at_eye, u) + # the left hand holds the binoculars by the gripR frame of the small item (mirror of a right-hand hold) + lh = hand_matrix('l', Mb @ Vector((0.045, 0.02, -0.025)), (Mb.to_3x3() @ Vector((-0.2, -1, 0))).normalized(), (Mb.to_3x3() @ Vector((-1, 0, 0.2))).normalized()) + gl = grip_l(k, W) + if not lower: + lh = M_(gl, lh, ramp(t, 0.0, 0.25)) if t < 0.25 else lh + else: + lh = M_(lh, grip_l(k, HIP), ramp(t, 0.6, 1.0)) if t > 0.6 else lh + lf = {'index': (0.7, 0.8, 0.5), 'middle': (0.8, 0.9, 0.5), 'ring': (0.85, 0.9, 0.5), 'pinky': (0.9, 0.9, 0.5), 'thumb': (0.3, 0.3, 0.2, 0.5)} + vis = (0.15 < t) if not lower else (t < 0.6) + return std(W, lh=lh, lf=lf, prop=('binoculars', Mb) if vis else None, hold=('l',) if vis else ()) + @clip(k + '.binoculars', 1.0, events={'atEye': 0.85}) + def _(t): return bino(t) + @clip(k + '.binocularsLower', 1.0) + def _(t): return bino(t, lower=True) + +# ------------------------------------------------------------------------------------------------ bake clips +PROPBONES = {'grenade': 'w_prop', 'binoculars': 'w_prop'} +def solve_frame(k, d): + # a hand may be nudged clear only while it travels: not on its weapon grip and not holding a part (d['hold']) + nud = {} + for s, key, g in (('r', 'rh', grip_r), ('l', 'lh', grip_l)): + nud[s] = s not in d.get('hold', ()) and (d[key].translation - g(k, d['W']).translation).length > 0.003 + L, W = frame(k, d['W'], {'r': d['rh'], 'l': d['lh']}, {'r': d['rf'], 'l': d['lf']}, parts=d['parts'], + prop=d['prop'], nudge=nud) + if d['prop'] is None: + M = W['w_root'].copy(); M = M @ Matrix.Diagonal((0.0001, 0.0001, 0.0001, 1.0)); rig.set_world(L, W, 'w_prop', M) + return L, W + +LOC = ('clavicle_l', 'clavicle_r') + tuple(F_ for F_ in ('w_root', 'w_bolt', 'w_boltHandle', 'w_mag', 'w_trigger', 'w_hammer', 'w_charging', 'w_prop')) +def write_action(name, frames): + """frames: list of local pose dicts L. Rotation for every bone, location for clavicles and weapon bones, + scale for the magazine and prop bones (hidden = 0).""" + act = bpy.data.actions.get(name) + if act: bpy.data.actions.remove(act) + act = bpy.data.actions.new(name) + slot = act.slots.new('OBJECT', arm.name) + cb = act.layers.new('Layer').strips.new(type='KEYFRAME').channelbag(slot, ensure=True) + n = len(frames) + for b in rig.bones: + if b == 'fp_root': continue + Bs = [rig.Lr[b].inverted() @ L[b] for L in frames] + qs = [M.to_quaternion() for M in Bs] + for i in range(1, n): + if qs[i].dot(qs[i - 1]) < 0: qs[i] = -qs[i] + chans = [('rotation_quaternion', 4, lambda i, c: qs[i][c])] + if b in LOC: chans.append(('location', 3, lambda i, c: Bs[i].to_translation()[c])) + if b in ('w_mag', 'w_prop'): chans.append(('scale', 3, lambda i, c: Bs[i].to_scale()[c])) + for prop, nc, get in chans: + for c in range(nc): + fc = cb.fcurves.new('pose.bones["%s"].%s' % (b, prop), index=c, group_name=b) + fc.keyframe_points.add(n) + co = [] + for i in range(n): co += [float(i), get(i, c)] + fc.keyframe_points.foreach_set('co', co) + fc.keyframe_points.foreach_set('interpolation', [1] * n) + fc.update() + act.use_fake_user = True + return act + +def bake_kind(k, report): + solve_grip(k, 'gripR', 'r', trigger=False) + solve_grip(k, 'gripL', 'l', trigger=True) + # trigger finger on the trigger: close the index on the trigger blade + L, Wd = rest() + for side in ('l', 'r'): F.place_shoulder(rig, L, Wd, side, shoulders_for(k, BASE[k]['hip'])[side]) + W = BASE[k]['hip']; F.arm_to(rig, L, Wd, 'r', grip_r(k, W), POLE_K.get(k, POLE)['r']) + ang = F.grasp_fingers(rig, skin, L, Wd, 'r', WPN[k].bvh['trigger'] if 'trigger' in WPN[k].bvh else WPN[k].bvh['body'], + (W @ WPN[k].empty['trigger']).inverted() if 'trigger' in WPN[k].empty else W.inverted(), fingers=('index',), + start={'index': (0.25, 0.3, 0.15)}) + GRIP[(k, 'gripR_trigger')] = {'fingers': ang} + add_part_specs(k) + for nm in [n for (kk, n) in GRIPSPEC if kk == k and n not in ('gripR', 'gripL')]: + solve_part_grip(k, nm, 'r' if nm.endswith('R') else 'l') + make_clips(k) + made = [] + only = [x for x in os.environ.get('ONLY', '').split(',') if x] + for name, (dur, loop, fn, ev) in CLIPS.items(): + if not name.startswith(k + '.'): continue + if only and name.split('.', 1)[1] not in only: continue + n = max(2, int(round(dur * FPS)) + (0 if loop else 1)) + frames = []; worst = (0, 0.0); near = 9.0 + # pass 1: hands in transit may be nudged out of the weapon; pass 2 applies the nudges dilated and smoothed + # over time (a nudge that came and went in one frame would pop) + LASTPOLE.clear(); LASTNUDGE.clear(); FORCE.clear() + offs = [] + for i in range(n): + solve_frame(k, fn(min(dur, i / FPS))) + offs.append({s: LASTNUDGE.get(s, Vector()).copy() for s in ('l', 'r')}) + sm = smooth_offsets(offs, loop) + nudged = {s: round(max(vlen(o[s]) for o in sm) * 1000, 1) for s in ('l', 'r')} + LASTPOLE.clear(); LASTNUDGE.clear() + hw = [] + js = {'l': [0, 0, 999, 0, -1, 0], 'r': [0, 0, 999, 0, -1, 0]} # worst |flex|, |dev|, min/max elbow, max above, |twist| + for i in range(n): + t = min(dur, i / FPS) + FORCE.clear(); FORCE.update(sm[i]) + L, W = solve_frame(k, fn(t)) + FORCE.clear() + frames.append(L) + hw.append(screen_width(W, 'r')) + for s_ in ('l', 'r'): + fl_, dv_, el_, ab_, tw_ = joint_stats(W, s_); j_ = js[s_] + j_[0] = max(j_[0], abs(fl_)); j_[1] = max(j_[1], abs(dv_)); j_[2] = min(j_[2], el_); j_[3] = max(j_[3], el_) + j_[4] = max(j_[4], ab_); j_[5] = max(j_[5], abs(tw_)) + if MODE == 'diag' and i == 0: + Ww0 = W['w_root'] @ F.RX90.inverted(); Mi0 = Ww0.inverted() + for s_ in ('l', 'r'): + pids = np.array([j for j in HAND_IDS[s_] if skin.dom[j] == 'hand_' + s_ and skin.N[j][2] < -0.3], int) + dd = sorted(F.signed_dist(WPN[k].bvh['body'], Mi0 @ Vector(p)) for p in skin.pose(W, pids)) + hc = Mi0 @ W['hand_' + s_].translation + tgt = Mi0 @ (d0 := fn(0.0))[('lh' if s_ == 'l' else 'rh')].translation + if s_ == 'l': + Q = proj(skin.pose(W, np.concatenate([ARM_IDS['l'], ARM_IDS['r'], HAND_IDS['l'], HAND_IDS['r']]))) + Q = Q[(Q[:, 1] <= 1) & (Q[:, 1] >= 0)] + log(' span', name, 'arms+hands in-frame x %.3f..%.3f (%.0f%% of width)' % (max(0, Q[:, 0].min()), min(1, Q[:, 0].max()), 100 * (min(1, Q[:, 0].max()) - max(0, Q[:, 0].min())))) + log(' contact', name, s_, 'palm nearest mm', [round(v * 1000, 1) for v in dd[:4]], 'wrist got', tuple(round(v, 3) for v in hc), 'wanted', tuple(round(v, 3) for v in tgt)) + if MODE == 'diag' and i % 2 == 0: + Ww = W['w_root'] @ F.RX90.inverted(); Mi = Ww.inverted(); row = [] + for s in ('l', 'r'): + for grp, pre in (('arm', ('lowerarm', 'upperarm')), ('hand', ('hand_', 'index_', 'middle_', 'ring_', 'pinky_', 'thumb_'))): + ids = np.array([j for j in skin.verts_of(pre) if skin.dom[j].endswith('_' + s)], int) + pn = F.penetration(skin, W, WPN[k].bvh['body'], Mi, idx=ids) + if pn[0]: row.append('%s.%s %d/%.1fmm' % (s, grp, pn[0], pn[1] * 1000)) + if row or i % 10 == 0: log(' %s t=%.2f hw=%.3f nudge l=%.0f r=%.0f mm %s' % (name, t, hw[-1], vlen(sm[i]['l']) * 1000, vlen(sm[i]['r']) * 1000, ' '.join(row))) + if i % 3 == 0: + # hand penetration against the weapon body, and the closest arm/weapon point to the eye (near plane) + Ww = W['w_root'] @ F.RX90.inverted() + pen = F.penetration(skin, W, WPN[k].bvh['body'], Ww.inverted(), idx=PEN_IDX) + if pen[0] > worst[0]: worst = pen + P = skin.pose(W) + near = min(near, float(np.min(np.linalg.norm(P, axis=1))), float(np.min(np.linalg.norm((np.array(Ww) @ WVH[k].T).T[:, :3], axis=1)))) + if MODE != 'diag': + act = write_action(name, frames); made.append(act) + report[name] = {'duration': round(dur, 3), 'loop': loop, 'events': ev, 'pen_max_verts': worst[0], 'pen_max_depth_mm': round(worst[1] * 1000, 1), + 'nudge_max_mm': nudged, + 'joints': {s_: {'wrist_flex_deg': round(js[s_][0], 1), 'wrist_dev_deg': round(js[s_][1], 1), 'elbow_min_deg': round(js[s_][2], 1), + 'elbow_max_deg': round(js[s_][3], 1), 'elbow_above_wrist_mm': round(js[s_][4] * 1000), 'twist_deg': round(js[s_][5], 1)} for s_ in ('l', 'r')}, 'handR_screen_width_max': round(max(hw), 3), 'handR_screen_width_t0': round(hw[0], 3), + 'nearest_to_eye_m': round(near, 3), 'prop': 'grenade' if '.grenade' in name else ('binoculars' if '.binoculars' in name else None), + 'hold': name.endswith(('.binoculars', '.grenadePull'))} + log(name, report[name]) + return made + +def vlen(v): return v.length if v is not None else 0.0 + +def smooth_offsets(offs, loop, reach=4, sigma=2.0): + """Per-frame hand nudges -> dilated (largest within +-reach frames, so the clearance is kept) then Gaussian + smoothed (sigma frames), per side.""" + n = len(offs); out = [{} for _ in range(n)] + for s in ('l', 'r'): + V = np.array([o[s][:] for o in offs]) + if not np.any(V): + for i in range(n): out[i][s] = None + continue + idx = lambda j: (j % n) if loop else min(n - 1, max(0, j)) + D = np.array([V[max((idx(j) for j in range(i - reach, i + reach + 1)), key=lambda j: np.linalg.norm(V[j]))] for i in range(n)]) + ks = np.arange(-3 * int(sigma), 3 * int(sigma) + 1); wk = np.exp(-0.5 * (ks / sigma) ** 2); wk /= wk.sum() + S = np.array([sum(wk[a] * D[idx(i + ks[a])] for a in range(len(ks))) for i in range(n)]) + for i in range(n): out[i][s] = Vector(S[i]) + return out + +def screen_width(W, s): + """Share of the screen width (16:9, vertical FOV 55) that the hand and fingers of side s cover, in-frame part.""" + P = skin.pose(W, HAND_IDS[s]) + y = np.maximum(P[:, 1], 1e-3); ty = math.tan(math.radians(27.5)) + xn = P[:, 0] / y / (ty * 16 / 9); zn = P[:, 2] / y / ty + m = (P[:, 1] > 0.01) & (np.abs(zn) <= 1) + if not np.any(m): return 0.0 + x = np.clip(xn[m], -1, 1) + return float((x.max() - x.min()) / 2) + +def proj(Pts): + """Screen fractions (x from the left, y from the top) of first-person points, 16:9, vertical FOV 55.""" + Pts = np.atleast_2d(Pts); ty = math.tan(math.radians(27.5)); y = np.maximum(Pts[:, 1], 1e-3) + return np.stack([0.5 + 0.5 * Pts[:, 0] / y / (ty * 16 / 9), 0.5 - 0.5 * Pts[:, 2] / y / ty], 1) + +def composition(k, W): + """Where the weapon and hands land on screen for the hip pose W (solved arms, grips as fitted).""" + d = {'W': W, 'rh': grip_r(k, W), 'lh': grip_l(k, W), 'rf': fR(k), 'lf': fL(k), 'parts': {}, 'prop': None} + L, Wb = solve_frame(k, d) + Ww = Wb['w_root'] @ F.RX90.inverted() + mz = proj(np.array((Ww @ WPN[k].empty['muzzle'].translation)[:]))[0] + wv = proj((np.array(Ww) @ WVH[k].T).T[:, :3]) + out = {'muzzle': mz, 'wbox': (wv[:, 0].min(), wv[:, 1].min())} + for s in ('l', 'r'): + q = proj(skin.pose(Wb, HAND_IDS[s])) + inn = q[(q[:, 0] <= 1) & (q[:, 1] <= 1) & (q[:, 0] >= 0)] + out['h' + s] = (q[:, 0].min(), q[:, 0].max(), q[:, 1].min(), q[:, 1].max(), + (inn[:, 0].max() - inn[:, 0].min()) if len(inn) else 0.0, len(inn) / max(1, len(q))) + return out + +def comp_cost(c, k='rifleScoped'): + mz = c['muzzle']; hl = c['hl']; hr = c['hr'] + e = 0.0 + if k == 'pistol': # compact, lower right: the gun and both gloves in frame, the right hand's top at about 0.74 + e += ((mz[0] - 0.64) / 0.03) ** 2 + ((mz[1] - 0.63) / 0.03) ** 2 + e += (((hr[0] + hr[1]) / 2 - 0.74) / 0.05) ** 2 + ((hr[2] - 0.74) / 0.04) ** 2 + ((1 - hr[5]) / 0.1) ** 2 + e += (max(0, hl[4] - 0.12) / 0.02) ** 2 + (max(0, hr[4] - 0.12) / 0.02) ** 2 + return e + e += ((mz[0] - 0.585) / 0.03) ** 2 + ((mz[1] - 0.59) / 0.03) ** 2 + e += (max(0, 0.52 - c['wbox'][0]) / 0.03) ** 2 + ((c['wbox'][1] - 0.56) / 0.05) ** 2 + e += (((hl[0] + hl[1]) / 2 - 0.615) / 0.05) ** 2 + (((hl[2] + hl[3]) / 2 - 0.75) / 0.05) ** 2 + (max(0, hl[3] - 0.97) / 0.02) ** 2 + e += (((hr[0] + hr[1]) / 2 - 0.85) / 0.05) ** 2 + ((hr[2] - 0.82) / 0.04) ** 2 + e += (max(0, hl[4] - 0.12) / 0.02) ** 2 + (max(0, hr[4] - 0.12) / 0.02) ** 2 + return e + +def frame_search(k): + """Coordinate search of the hip pose (position, yaw, pitch, roll) for the target composition.""" + x = list(BASE[k]['hip'].translation) + [0.0, 0.0, 0.0] + base = BASE[k]['hip'] + def pose(x): + return rel(base, dx=x[0] - base.translation.x, dy=x[1] - base.translation.y, dz=x[2] - base.translation.z, yaw=x[3], pitch=x[4], roll=x[5]) + ymax = 0.46 if k == 'pistol' else 0.62 + def cost(x): + LASTPOLE.clear() + lim = (max(0, abs(x[3]) - 10) ** 2 + max(0, abs(x[4]) - 8) ** 2 + max(0, -x[5] - 14) ** 2 + max(0, x[5] - 4) ** 2) * 0.5 + lim += (max(0, x[1] - ymax) / 0.01) ** 2 + (max(0, 0.30 - x[1]) / 0.01) ** 2 + return comp_cost(composition(k, pose(x)), k) + lim + c0 = cost(x); step = [0.02, 0.03, 0.02, 3.0, 3.0, 4.0] + for it in range(60): + moved = False + for i in range(6): + for sg in (-1, 1): + y = list(x); y[i] += sg * step[i]; c = cost(y) + if c < c0: x, c0, moved = y, c, True + if not moved: + step = [v * 0.5 for v in step] + if step[0] < 0.002: break + c = composition(k, pose(x)); W = pose(x) + e = W.to_euler('XYZ') + log('FRAME', k, 'cost %.2f' % c0, 'pos', tuple(round(v, 3) for v in W.translation), 'deltas yaw/pitch/roll', tuple(round(v, 1) for v in x[3:]), + {kk: tuple(round(float(v), 3) for v in vv) for kk, vv in c.items()}) + +PEN_IDX = None; WVH = {} +if __name__ == '__main__': + PEN_IDX = skin.verts_of(('hand_', 'index_', 'middle_', 'ring_', 'pinky_', 'thumb_', 'lowerarm')) + for kk in ('rifleScoped', 'smg', 'pistol'): + V = np.concatenate([np.array([(WPN[kk].root.matrix_world.inverted() @ o.matrix_world @ v.co)[:] for v in o.data.vertices]) for obs in WPN[kk].meshes.values() for o in obs]) + WVH[kk] = np.concatenate([V, np.ones((len(V), 1))], 1)[::7] + kinds = os.environ.get('KINDS', 'rifleScoped,smg,pistol').split(',') + if MODE == 'preview': + k = kinds[0] + setup_render(); os.makedirs(FPW + '/preview', exist_ok=True) + solve_grip(k, 'gripR', 'r'); solve_grip(k, 'gripL', 'l', trigger=True) + add_part_specs(k) + for nm in [n for (kk, n) in GRIPSPEC if kk == k and n not in ('gripR', 'gripL')]: + solve_part_grip(k, nm, 'r' if nm.endswith('R') else 'l') + GRIP[(k, 'gripR_trigger')] = {'fingers': {'index': (0.55, 0.75, 0.35)}} + make_clips(k) + for spec in os.environ.get('SHOTS', 'idle@0').split(','): + nm, tt = spec.split('@') + d_ = CLIPS[k + '.' + nm][2](float(tt)) + L, W = solve_frame(k, d_) + PROPSHOW[0] = d_['prop'][0] if d_['prop'] else None + render(FPW + '/preview/%s_%s_%s.png' % (k, nm, tt), L, W, k) + if os.environ.get('OUTSIDE'): + render(FPW + '/preview/%s_%s_%s_out.png' % (k, nm, tt), L, W, k, view=(Vector((0.75, -0.45, 0.35)), Vector((0.0, 0.25, -0.2)), 50)) + render(FPW + '/preview/%s_%s_%s_out2.png' % (k, nm, tt), L, W, k, view=(Vector((-0.2, 0.9, -0.5)), Vector((0.0, 0.2, -0.15)), 50)) + if os.environ.get('GRIPVIEW'): # close views of the right-hand grip: from the left side and from below-behind + g = W['w_root'] @ F.RX90.inverted() @ Vector([float(v) for v in os.environ.get('GRIPPT', '0,0.04,-0.04').split(',')]) + R3 = (W['w_root'] @ F.RX90.inverted()).to_3x3() + render(FPW + '/preview/%s_%s_%s_gl.png' % (k, nm, tt), L, W, k, view=(g + R3 @ Vector((0.28, 0.02, 0.03)), g, 30)) + render(FPW + '/preview/%s_%s_%s_gr.png' % (k, nm, tt), L, W, k, view=(g + R3 @ Vector((-0.28, 0.02, 0.03)), g, 30)) + render(FPW + '/preview/%s_%s_%s_gb.png' % (k, nm, tt), L, W, k, view=(g + R3 @ Vector((0.0, 0.28, 0.06)), g, 30)) + log('rendered', nm, tt) + else: + report = {}; made = [] + if os.environ.get('FRAME'): + for k in kinds: + solve_grip(k, 'gripR', 'r', trigger=False); solve_grip(k, 'gripL', 'l', trigger=True) + GRIP[(k, 'gripR_trigger')] = {'fingers': {'index': (0.55, 0.75, 0.35)}} + c = composition(k, BASE[k]['hip']); log('NOW', k, 'cost %.2f' % comp_cost(c, k), {kk: tuple(round(float(v), 3) for v in vv) for kk, vv in c.items()}) + frame_search(k) + sys.exit(0) + for k in kinds: made += bake_kind(k, report) + if MODE == 'diag': + json.dump(report, open(FPW + '/diag.json', 'w'), indent=1); log('diag written'); sys.exit(0) + # the ADS offset as a viewmodel-group transform (three.js frame): A @ hip = ads + C = Matrix.Rotation(-math.pi / 2, 4, 'X') + kinds_meta = {} + for k in kinds: + A = C @ (BASE[k]['ads'] @ BASE[k]['hip'].inverted()) @ C.inverted() + q = A.to_quaternion() + kinds_meta[k] = {'adsOffset': {'position': [round(x, 5) for x in A.translation], 'quaternion': [round(q.x, 5), round(q.y, 5), round(q.z, 5), round(q.w, 5)]}, + 'grips': {nm: {'pen_verts': g['pen'][0], 'pen_depth_mm': round(g['pen'][1] * 1000, 1)} for (kk, nm), g in GRIP.items() if kk == k and 'pen' in g}} + json.dump({'version': 1, 'kinds': kinds_meta, 'clips': report}, open(FPW + '/fp.json', 'w'), indent=1) + arm.animation_data_create(); arm.animation_data.action = None + for t in list(arm.animation_data.nla_tracks): arm.animation_data.nla_tracks.remove(t) + for a in made: + tr_ = arm.animation_data.nla_tracks.new(); tr_.name = a.name + tr_.strips.new(a.name, 0, a) + for o in list(bpy.data.objects): + if o not in (arm, mesh): bpy.data.objects.remove(o) + bpy.context.scene.render.fps = FPS; bpy.context.scene.frame_start = 0 + # rest pose for the bind: arms as in the idle of the first kind would hide nothing; keep the T-pose bind + bpy.ops.export_scene.gltf(filepath=FPW + '/fp.glb', export_format='GLB', export_animation_mode='NLA_TRACKS', + export_def_bones=False, export_optimize_animation_size=True, export_force_sampling=True, + export_image_format='AUTO') + log('exported', FPW + '/fp.glb', len(made), 'clips') diff --git a/e63334287a3deaa3/ironveil/tools/chars/fp_lib.py b/e63334287a3deaa3/ironveil/tools/chars/fp_lib.py new file mode 100644 index 00000000..8d2dfe13 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/fp_lib.py @@ -0,0 +1,325 @@ +# Shared helpers for the first-person clips (fp_clips.py): weapon frames, linear-blend skinning in numpy (the same +# maths three.js runs), two-bone arm IK with forearm twist, finger closing against the real weapon surface (BVH) and +# the hand-penetration measure. +# +# Frames (Blender, first-person space): eye at the origin, +Y forward, +Z up, +X right. +# A weapon pose W is the 4x4 that maps the weapon frame (barrel -Y, up +Z, right side -X, origin at the grip) into +# first-person space. The relation of a bone matrix M_b (armature space, Blender bone axes) to the glTF node frame is +# glTF = C * M_b (C = Rx(-90)), while objects and empties convert as C * M * C^-1. Hence: +# hand bone on a grip empty G: M_hand = W @ G @ RX90 +# weapon and part bones: M_w = W @ P @ D @ RX90 (P = part empty rest, D = its animated delta) +import bpy, math +import numpy as np +from mathutils import Vector, Matrix, Quaternion +from mathutils.bvhtree import BVHTree +import anim_lib as AL + +RX90 = Matrix.Rotation(math.pi / 2, 4, 'X') +RZ180 = Matrix.Rotation(math.pi, 4, 'Z') +FINGERS = ('index', 'middle', 'ring', 'pinky', 'thumb') + +def blend_m(A, B, t): + """Blend two rigid 4x4 matrices: translation lerp, rotation slerp.""" + t = max(0.0, min(1.0, t)) + qa, qb = A.to_quaternion(), B.to_quaternion() + if qa.dot(qb) < 0: qb = -qb + M = qa.slerp(qb, t).to_matrix().to_4x4() + M.translation = A.translation.lerp(B.translation, t) + return M + +def rot(axis, deg): + return Matrix.Rotation(math.radians(deg), 4, axis) + +def pose_w(pos, yaw=0.0, pitch=0.0, roll=0.0): + """Weapon pose: barrel along +Y (first-person forward), then yaw (+ = muzzle left), pitch (+ = muzzle up), + roll (+ = top of the weapon to the right, a cant), about the weapon origin.""" + R = rot('Z', yaw) @ rot('X', pitch) @ rot('Y', roll) @ RZ180 + R.translation = Vector(pos) + return R + +# ------------------------------------------------------------------------------------------------ weapons +class Weapon: + """An imported weapon (from the unpacked weapons.glb): rest frames of its empties, BVHs of its meshes.""" + def __init__(self, kind): + self.kind = kind + root = bpy.data.objects[kind] + self.root = root + inv = root.matrix_world.inverted() + self.empty = {} + self.parts = {} + for c in root.children_recursive: + nm = c.name.split('.')[0] + if c.type == 'EMPTY' and nm.startswith(kind + '_'): + key = nm[len(kind) + 1:] + self.empty[key] = inv @ c.matrix_world + # mesh parts: part name -> list of objects (body = everything not under a moving-part empty) + self.meshes = {} + for c in root.children_recursive: + if c.type != 'MESH': continue + nm = c.name.split('.')[0][len(kind) + 1:] + part = 'body' if nm == 'body' else nm.replace('_mesh', '') + self.meshes.setdefault(part, []).append(c) + self.moving = [p for p in self.meshes if p != 'body'] + self.bvh = {} + for part, obs in self.meshes.items(): + V, F = [], [] + # each part in its own pivot frame (body: weapon frame) + Pinv = self.empty[part].inverted() if part in self.empty else Matrix() + for o in obs: + M = Pinv @ inv @ o.matrix_world + base = len(V) + V += [M @ v.co for v in o.data.vertices] + F += [[base + i for i in p.vertices] for p in o.data.polygons] + self.bvh[part] = BVHTree.FromPolygons(V, F) + self.__dict__.setdefault('verts', {})[part] = np.array([v[:] for v in V]) + + def E(self, name): + return self.empty[name].copy() + + def hand_on(self, W, name): + """Hand bone matrix for the hand frame empty `name` (gripR, gripL) of this weapon posed at W.""" + return W @ self.empty[name] @ RX90 + + def part_world(self, W, part, D=None): + return W @ self.empty[part] @ (D or Matrix()) + +def signed_dist(bvh, p): + loc, nor, idx, d = bvh.find_nearest(p) + if loc is None: return 1.0 + return d if (p - loc).dot(nor) >= 0 else -d + +# ------------------------------------------------------------------------------------------------ skin +class Skin: + """Linear blend skinning of the arms mesh in numpy (4 strongest influences, as glTF/three.js).""" + def __init__(self, mesh, rig): + self.rig = rig + me = mesh.data + self.P = np.array([v.co[:] for v in me.vertices]) + self.N = np.array([v.normal[:] for v in me.vertices]) + names = {g.index: g.name for g in mesh.vertex_groups} + bones = rig.bones + self.bidx = {b: i for i, b in enumerate(bones)} + n = len(self.P) + J = np.zeros((n, 4), int); Wt = np.zeros((n, 4)) + for v in me.vertices: + gs = sorted([(g.weight, names[g.group]) for g in v.groups if g.weight > 0 and names[g.group] in self.bidx], reverse=True)[:4] + s = sum(w for w, _ in gs) or 1.0 + for k, (w, b) in enumerate(gs): + J[v.index, k] = self.bidx[b]; Wt[v.index, k] = w / s + self.J, self.Wt = J, Wt + self.dom = [bones[J[i, 0]] for i in range(n)] + self.inv = np.array([np.array(rig.Mr[b].inverted()) for b in bones]) + + def pose(self, W, idx=None): + """World positions of the vertices (all, or idx) for the world bone matrices W (dict).""" + S = np.array([np.array(W[b]) for b in self.rig.bones]) @ self.inv # (B,4,4) + J = self.J if idx is None else self.J[idx] + Wt = self.Wt if idx is None else self.Wt[idx] + P = self.P if idx is None else self.P[idx] + Ph = np.concatenate([P, np.ones((len(P), 1))], 1) + out = np.zeros((len(P), 3)) + for k in range(4): + M = S[J[:, k]] # (n,4,4) + out += Wt[:, k:k + 1] * np.einsum('nij,nj->ni', M, Ph)[:, :3] + return out + + def verts_of(self, prefixes): + return np.array([i for i, b in enumerate(self.dom) if b.startswith(prefixes)], int) + +# ------------------------------------------------------------------------------------------------ arms +HINGE = {'l': Vector((0, 0, 1)), 'r': Vector((0, 0, -1))} + +def place_shoulder(rig, L, W, s, target): + """Move the clavicle so the upper arm head lands at target (first-person shoulders are free to move).""" + cur = W['upperarm_' + s].translation + M = W['clavicle_' + s].copy(); M.translation = M.translation + (Vector(target) - cur) + rig.set_world(L, W, 'clavicle_' + s, M) + +def arm_to(rig, L, W, s, Mhand, pole, twist=0.7, reach=0.93): + """Two-bone IK of shoulder-elbow-wrist onto the hand bone matrix Mhand, elbow toward pole, forearm twist share. + When the wrist is beyond `reach` of the arm's length the shoulder is carried toward it (up to 0.32 m).""" + S = W['upperarm_' + s].translation; l1 = rig.len['upperarm_' + s]; l2 = rig.len['lowerarm_' + s] + d = Mhand.translation - S + if d.length > reach * (l1 + l2): + mv = min(0.32, d.length - reach * (l1 + l2)) # first-person shoulders are never seen + place_shoulder(rig, L, W, s, S + d.normalized() * mv) + rig.two_bone(L, W, 'upperarm_' + s, 'lowerarm_' + s, 'hand_' + s, Mhand.translation, pole, HINGE[s], + end_rot=Mhand.to_3x3()) + # forearm twist bone: a share of the hand's roll about the forearm axis + lo = W['lowerarm_' + s]; ax = (lo.to_3x3() @ Vector((0, 1, 0))).normalized() + hx = (W['hand_' + s].to_3x3() @ rig.Rr['hand_' + s].inverted() @ rig.Rr['lowerarm_' + s] @ Vector((1, 0, 0))) + lx = lo.to_3x3() @ Vector((1, 0, 0)) + a = hx - ax * hx.dot(ax); b = lx - ax * lx.dot(ax) + if a.length > 1e-6 and b.length > 1e-6: + ang = math.atan2(b.normalized().cross(a.normalized()).dot(ax), b.normalized().dot(a.normalized())) + tb = 'lowerarm_twist_' + s + rig.set_world(L, W, tb, W['lowerarm_' + s] @ rig.Lr[tb]) + rig.rot_world(L, W, tb, Quaternion(ax, ang * twist)) + # the hand is a child of the lower arm: restore its world matrix after the twist bone moved (it did not) + return W + +def palm_normal(rig, W, s): + return (rig.delta(W, 'hand_' + s) @ Vector((0, 0, -1))).normalized() + +def set_fingers(rig, L, W, s, ang): + """ang: finger -> (a1, a2, a3) curl angles in radians (+ toward the palm), thumb also takes 'spread' as a4.""" + palm = palm_normal(rig, W, s) + for f in FINGERS: + a = ang.get(f) + if a is None: continue + if f == 'thumb' and len(a) > 3 and a[3]: + b = 'thumb_01_' + s + d = (W[b].to_3x3() @ Vector((0, 1, 0))).normalized() + rig.rot_world(L, W, b, Quaternion(d, a[3] * (1 if s == 'r' else -1))) + for j in range(3): + b = '%s_0%d_%s' % (f, j + 1, s) + d = (W[b].to_3x3() @ Vector((0, 1, 0))).normalized() + ax = d.cross(palm).normalized() + rig.rot_world(L, W, b, Quaternion(ax, a[j])) + +def mix_fingers(A, B, t): + out = {} + for f in set(A) | set(B): + a = A.get(f, (0, 0, 0)); b = B.get(f, (0, 0, 0)) + n = max(len(a), len(b)) + a = tuple(a) + (0,) * (n - len(a)); b = tuple(b) + (0,) * (n - len(b)) + out[f] = tuple(x + (y - x) * t for x, y in zip(a, b)) + return out + +RELAXED = {'index': (0.25, 0.35, 0.2), 'middle': (0.35, 0.45, 0.25), 'ring': (0.45, 0.5, 0.3), 'pinky': (0.55, 0.55, 0.3), + 'thumb': (0.15, 0.2, 0.15, 0.1)} +FLAT = {'index': (0.05, 0.08, 0.05), 'middle': (0.06, 0.08, 0.05), 'ring': (0.08, 0.1, 0.05), 'pinky': (0.1, 0.1, 0.05), + 'thumb': (0.0, 0.05, 0.05, 0.0)} + +def close_fingers(rig, skin, L0, W0, s, bvh, Minv, fingers=('index', 'middle', 'ring', 'pinky'), start=None, + contact=0.0015, step=math.radians(2.5), maxa=(1.5, 1.7, 1.2), thumb_spread=0.0): + """Close each finger joint by joint (proximal first) until its skin touches the surface in `bvh` (given in the + frame Minv maps first-person space into). Returns finger -> (a1, a2, a3[, spread]).""" + out = {} + for f in fingers: + segs = ['%s_0%d_%s' % (f, j + 1, s) for j in range(3)] + idx = [skin.verts_of((segs[j],) + tuple(segs[j + 1:]) + ('%s_04_leaf_%s' % (f, s),)) for j in range(3)] + a = list((start or {}).get(f, (0.0, 0.0, 0.0)))[:3] + sp = (thumb_spread if f == 'thumb' else 0.0) + for j in range(3): + lo_, hi_ = a[j], maxa[j] + ang = lo_ + while ang <= hi_: + a[j] = ang + L = {k: v.copy() for k, v in L0.items()}; W = {k: v.copy() for k, v in W0.items()} + set_fingers(rig, L, W, s, {f: tuple(a) + ((sp,) if f == 'thumb' else ())}) + P = skin.pose(W, idx[j]) + dmin = min(signed_dist(bvh, Minv @ Vector(p)) for p in P[::2]) + if dmin < contact: + a[j] = max(lo_, ang - step * 0.5) + break + ang += step + else: + a[j] = hi_ + out[f] = tuple(a) + ((sp,) if f == 'thumb' else ()) + return out + +def inside(bvh, p, dirs=(Vector((0, 0, 1)), Vector((0, 0, -1)), Vector((1, 0, 0)), Vector((-1, 0, 0)), Vector((0, 1, 0)))): + """Ray-parity inside test, majority of five directions: robust where a scanned mesh is open or has inner faces, + which fool the nearest-face normal test (an open stock end reads as 'inside' from the face normal alone).""" + votes = 0 + for d in dirs: + o = Vector(p); hits = 0 + for _ in range(40): + loc, nor, idx, dist = bvh.ray_cast(o, d, 2.0) + if loc is None: break + hits += 1; o = loc + d * 1e-5 + votes += hits & 1 + return votes >= 3 + +def penetration(skin, W, bvh, Minv, tol=0.002, idx=None): + """Arm vertices inside the weapon by more than tol: count and deepest (m). A vertex counts only when both the + nearest-face test and the ray-parity test agree it is inside.""" + P = skin.pose(W, idx) + n, deep = 0, 0.0 + for p in P: + q = Minv @ Vector(p) + d = signed_dist(bvh, q) + if d < -tol and inside(bvh, q): + n += 1; deep = max(deep, -d) + return n, deep + +def wrap_fingers(rig, skin, L0, W0, s, bvh, Minv, fingers=('index', 'middle', 'ring', 'pinky', 'thumb'), start=None, + gap=0.0010, maxa=(1.5, 1.75, 1.3), thumb_spread=0.0, reach=None): + """Wrap each finger on the surface: coordinate descent on the three joint angles so that every phalanx just + touches (gap) and none sinks in. A phalanx that cannot reach the surface stops at the closest angle.""" + out = {} + for f in fingers: + segs = ['%s_0%d_%s' % (f, j + 1, s) for j in range(3)] + ids = [skin.verts_of((segs[j],) + (('%s_04_leaf_%s' % (f, s),) if j == 2 else ())) for j in range(3)] + ids = [i[::2] if len(i) > 40 else i for i in ids] + sp = thumb_spread if f == 'thumb' else 0.0 + def cost(a): + L = {k: v.copy() for k, v in L0.items()}; W = {k: v.copy() for k, v in W0.items()} + set_fingers(rig, L, W, s, {f: tuple(a) + ((sp,) if f == 'thumb' else ())}) + c = 0.0 + for j in range(3): + P = skin.pose(W, ids[j]) + ds = [signed_dist(bvh, Minv @ Vector(p)) for p in P] + d = min(ds) + if d < 0 and not any(inside(bvh, Minv @ Vector(P[i])) for i in range(len(P)) if ds[i] < 0): + d = min(abs(x) for x in ds) + pen = max(0.0, -(d - 0.0003)) + c += pen * pen * 4e6 + (d - gap) ** 2 * 1e3 * (1.0 if d < 0.02 else 0.3) + return c + sum(x * x for x in a) * 0.02 + a = list((start or {}).get(f, (0.3, 0.3, 0.2)))[:3] + c0 = cost(a); st = math.radians(8) + while st > math.radians(0.6): + moved = False + for j in range(3): + for sg in (1, -1): + b = a[:]; b[j] = max(-0.15, min(maxa[j], b[j] + sg * st)) + c = cost(b) + if c < c0 - 1e-9: a, c0, moved = b, c, True + if not moved: st *= 0.5 + out[f] = tuple(a) + ((sp,) if f == 'thumb' else ()) + return out + +def grasp_fingers(rig, skin, L0, W0, s, bvh, Minv, fingers=('index', 'middle', 'ring', 'pinky', 'thumb'), gap=0.0012, + thumb_spread=0.0, start=None, step=0.04): + """Grasp like a hand closing on an object: each finger curls with natural joint coupling until any of its + segments touches the surface (bvh, in the frame Minv maps first-person space into); then the middle and end + joints keep closing, then the end joint alone, each until it touches. Fingers never bend backwards and never + stay straight: a finger that reaches nothing ends in a relaxed curl. Returns finger -> angles (thumb + spread).""" + COUP = {'thumb': (0.45, 0.6, 0.55)} + out = {} + for f in fingers: + segs = ['%s_0%d_%s' % (f, j + 1, s) for j in range(3)] + ids = [skin.verts_of((segs[j],) + (('%s_04_leaf_%s' % (f, s),) if j == 2 else ())) for j in range(3)] + ids = [i[::2] if len(i) > 40 else i for i in ids] + sp = thumb_spread if f == 'thumb' else 0.0 + cp = COUP.get(f, (1.0, 1.15, 0.8)) + def touch(a, from_seg): + L = {k: v.copy() for k, v in L0.items()}; W = {k: v.copy() for k, v in W0.items()} + set_fingers(rig, L, W, s, {f: tuple(a) + ((sp,) if f == 'thumb' else ())}) + for j in range(from_seg, 3): + for p in skin.pose(W, ids[j]): + if signed_dist(bvh, Minv @ Vector(p)) < gap: return True + return False + a = list((start or {}).get(f, (0.0, 0.0, 0.0)))[:3] + a = [max(0.0, v) for v in a] + lim = (1.5, 1.7, 1.25) + touched = False + # stage 1: all three joints together + while a[0] < lim[0] and not touch(a, 0): + a = [min(lim[j], a[j] + step * cp[j]) for j in range(3)] + else: + touched = a[0] < lim[0] + if touched: a = [max(0.0, a[j] - 0.5 * step * cp[j]) for j in range(3)] + # stage 2: middle and end joints, stage 3: end joint, each until their own segments touch + for first in (1, 2): + n_ = 0 + while a[first] < lim[first] and not touch(a, first) and n_ < 60: + for j in range(first, 3): a[j] = min(lim[j], a[j] + step * cp[j] * 0.7) + n_ += 1 + if a[first] < lim[first] and n_: + for j in range(first, 3): a[j] = max(0.0, a[j] - 0.5 * step * cp[j] * 0.7) + if not touched and f != 'thumb': # nothing to hold: a relaxed curl, not a straight finger + a = [max(a[0], 0.55), max(a[1], 0.65), max(a[2], 0.45)] + out[f] = tuple(a) + ((sp,) if f == 'thumb' else ()) + return out diff --git a/e63334287a3deaa3/ironveil/tools/chars/fp_pack.mjs b/e63334287a3deaa3/ironveil/tools/chars/fp_pack.mjs new file mode 100644 index 00000000..c2337512 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/fp_pack.mjs @@ -0,0 +1,27 @@ +// Pack the first-person arms (fp_clips.py export) for the web: resampled clips, WebP textures, meshopt geometry. +// usage: GT_MODULES=/path/to/node_modules node fp_pack.mjs fp.glb out.glb +import path from 'path'; +const M = process.env.GT_MODULES || path.resolve('node_modules'); +const imp = (p) => import(path.join(M, p)); +const { NodeIO } = await imp('@gltf-transform/core/dist/index.js'); +const { ALL_EXTENSIONS } = await imp('@gltf-transform/extensions/dist/index.js'); +const { dedup, meshopt, textureCompress, resample, prune } = await imp('@gltf-transform/functions/dist/index.js'); +const { MeshoptEncoder } = await imp('meshoptimizer/index.js'); +const sharp = (await imp('sharp/dist/index.mjs')).default; +const [src, dst] = process.argv.slice(2); +await MeshoptEncoder.ready; +const io = new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({ 'meshopt.encoder': MeshoptEncoder }); +const doc = await io.read(src); +for (const m of doc.getRoot().listMaterials()) { + const orm = m.getMetallicRoughnessTexture(); + if (orm && !m.getOcclusionTexture()) { m.setOcclusionTexture(orm); m.getOcclusionTextureInfo().setTexCoord(0); } +} +await doc.transform( + prune({ keepLeaves: true }), dedup(), resample({ tolerance: 0.0002 }), + textureCompress({ encoder: sharp, targetFormat: 'webp', quality: 90, slots: /^(baseColorTexture)$/ }), + textureCompress({ encoder: sharp, targetFormat: 'webp', quality: 92, slots: /^(normalTexture)$/ }), + textureCompress({ encoder: sharp, targetFormat: 'webp', quality: 90, slots: /^(metallicRoughnessTexture|occlusionTexture)$/ }), + meshopt({ encoder: MeshoptEncoder, level: 'high' })); +await io.write(dst, doc); +for (const t of doc.getRoot().listTextures()) console.log('texture', t.getName() || t.getURI(), t.getMimeType(), t.getSize(), (t.getImage().byteLength / 1024).toFixed(0) + ' KB'); +console.log('animations', doc.getRoot().listAnimations().length); diff --git a/e63334287a3deaa3/ironveil/tools/chars/fp_tex.py b/e63334287a3deaa3/ironveil/tools/chars/fp_tex.py new file mode 100644 index 00000000..57de23f2 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/fp_tex.py @@ -0,0 +1,675 @@ +# First-person arms: UV atlas and the 2048 texture set (base colour, normal, occlusion-roughness-metal). +# usage: CHARS_WORK=... bvenv/bin/python fp_tex.py reads $FP_WORK/fp_geo.blend, writes fp_tex.blend + tex/*.png +# +# Cycles bakes only what it is good at: the rest-pose position and normal of every texel (float), the material region +# and ambient occlusion. Everything else is computed per texel in numpy from the 3D position on the arm: skin tone and +# mottling, forearm hair, knuckle wrinkles, palm and finger creases, nails with cuticles and dirt, back-of-hand +# tendons, veins, a healed scar, grime in the creases; the smock's invented brush-stroke camouflage, twill weave, +# fold creases and roll seam; the leather strap with stitching; the steel watch case and its dial. Heights become a +# tangent-space normal map using the texel's own position derivatives, so the bumps keep their real size in metres. +import bpy, sys, os, math, time +import numpy as np +from mathutils import Vector, Matrix +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import mhlib as ML + +T0 = time.time() +def log(*a): print('[tex %5.1fs]' % (time.time() - T0), *a, flush=True) +FPW = os.environ.get('FP_WORK') or (ML.WORK + '/fp') +SIZE = int(os.environ.get('SIZE', '2048')) +TD = FPW + '/tex'; os.makedirs(TD, exist_ok=True) + +bpy.ops.wm.open_mainfile(filepath=FPW + '/fp_geo.blend') +arm = bpy.data.objects['FPRig']; ob = bpy.data.objects['FPArms'] +me = ob.data +meta = eval(ob['meta']) + +# ---------------------------------------------------------------- UVs: smart projection, hands and forearms larger +def set_active(o): + for x in bpy.context.view_layer.objects: x.select_set(False) + bpy.context.view_layer.objects.active = o; o.select_set(True) +set_active(ob) +for uv in list(me.uv_layers): me.uv_layers.remove(uv) +me.uv_layers.new(name='atlas') +bpy.ops.object.mode_set(mode='EDIT') +bpy.ops.mesh.select_all(action='SELECT') +bpy.ops.uv.smart_project(angle_limit=math.radians(58), island_margin=0.0, area_weight=0.0, scale_to_bounds=False) +bpy.ops.object.mode_set(mode='OBJECT') +# texel density: hands and the bare forearm x1.5, the upper sleeve (rarely seen up close) x0.6 +reg = np.zeros(len(me.polygons), int); me.attributes['region'].data.foreach_get('value', reg) +names = {g.index: g.name for g in ob.vertex_groups} +dom = [] +for v in me.vertices: + g = max(v.groups, key=lambda x: x.weight) if v.groups else None + dom.append(names[g.group] if g else '') +uvd = me.uv_layers['atlas'].data +import bmesh +bm = bmesh.new(); bm.from_mesh(me) +uvl = bm.loops.layers.uv['atlas'] +bm.faces.ensure_lookup_table() +# islands by uv connectivity +from collections import defaultdict +parent = list(range(len(bm.faces))) +def find(a): + while parent[a] != a: parent[a] = parent[parent[a]]; a = parent[a] + return a +for e in bm.edges: + lf = e.link_faces + if len(lf) == 2: + f0, f1 = lf + ok = True + for v in e.verts: + u0 = [l[uvl].uv for l in f0.loops if l.vert == v][0]; u1 = [l[uvl].uv for l in f1.loops if l.vert == v][0] + if (u0 - u1).length > 1e-6: ok = False + if ok: parent[find(f0.index)] = find(f1.index) +isl = defaultdict(list) +for f in bm.faces: isl[find(f.index)].append(f) +for fs in isl.values(): + hand = sum(1 for f in fs for v in f.verts if dom[v.index].startswith(('hand', 'index', 'middle', 'ring', 'pinky', 'thumb', 'lowerarm'))) + tot = sum(len(f.verts) for f in fs) + r = reg[fs[0].index] + sc = 1.5 if (r == 0 and hand > tot * 0.5) else (1.4 if r in (3, 4, 5) else (0.6 if r == 1 and sum(f.calc_center_median().y for f in fs) / len(fs) < -0.02 else 1.0)) + if sc == 1.0: continue + c = sum((l[uvl].uv for f in fs for l in f.loops), Vector((0, 0))) / sum(len(f.loops) for f in fs) + for f in fs: + for l in f.loops: l[uvl].uv = c + (l[uvl].uv - c) * sc +bm.to_mesh(me); bm.free() +set_active(ob) +bpy.ops.object.mode_set(mode='EDIT'); bpy.ops.mesh.select_all(action='SELECT') +bpy.ops.uv.pack_islands(rotate=True, margin=0.004) +bpy.ops.object.mode_set(mode='OBJECT') +log('uv packed, islands', len(isl)) + +# ---------------------------------------------------------------- bakes +sc = bpy.context.scene +sc.render.engine = 'CYCLES'; sc.cycles.device = 'CPU'; sc.cycles.samples = 1 +sc.render.threads_mode = 'FIXED'; sc.render.threads = int(os.environ.get('BAKE_THREADS', '2')) +mat = bpy.data.materials.new('fp_arms'); me.materials.clear(); me.materials.append(mat) +nt = mat.node_tree; N = nt.nodes; Lk = nt.links +for n in list(N): N.remove(n) +out = N.new('ShaderNodeOutputMaterial'); em = N.new('ShaderNodeEmission'); Lk.new(em.outputs[0], out.inputs['Surface']) +geo = N.new('ShaderNodeNewGeometry'); att = N.new('ShaderNodeAttribute'); att.attribute_name = 'region'; att.attribute_type = 'GEOMETRY' +tex = N.new('ShaderNodeTexImage'); nt.nodes.active = tex + +def bake_emit(src, name, margin=24, samples=1): + img = bpy.data.images.new(name, SIZE, SIZE, alpha=True, float_buffer=True); img.colorspace_settings.name = 'Non-Color' + tex.image = img; nt.nodes.active = tex + for l in list(em.inputs[0].links): Lk.remove(l) + if src is not None: Lk.new(src, em.inputs[0]) + else: em.inputs[0].default_value = (1, 1, 1, 1) + sc.cycles.samples = samples + set_active(ob) + bpy.ops.object.bake(type='EMIT', margin=margin, use_clear=True) + a = np.array(img.pixels[:], dtype=np.float32).reshape(SIZE, SIZE, 4) + return a + +POS = bake_emit(geo.outputs['Position'], 'pos')[..., :3] +NRM = bake_emit(geo.outputs['Normal'], 'nrm')[..., :3] +REG = bake_emit(att.outputs['Fac'], 'reg', margin=24)[..., 0] +MASK = bake_emit(None, 'mask', margin=0)[..., 0] > 0.5 +log('baked attributes, coverage %.1f%%' % (MASK.mean() * 100)) +# ambient occlusion (rest pose; arms only) +img = bpy.data.images.new('ao', SIZE, SIZE, alpha=False, float_buffer=True); img.colorspace_settings.name = 'Non-Color' +tex.image = img; nt.nodes.active = tex +sc.cycles.samples = int(os.environ.get('AO_SAMPLES', '48')) +sc.world = bpy.data.worlds.new('w') if sc.world is None else sc.world +bpy.ops.object.bake(type='AO', margin=24, use_clear=True) +AO = np.array(img.pixels[:], dtype=np.float32).reshape(SIZE, SIZE, 4)[..., 0] +log('baked AO') + +# ---------------------------------------------------------------- procedural fields in numpy +H, Wd = SIZE, SIZE +P = POS.reshape(-1, 3).astype(np.float64); Nn = NRM.reshape(-1, 3).astype(np.float64) +Nn /= np.maximum(1e-6, np.linalg.norm(Nn, axis=1, keepdims=True)) +R = np.rint(REG.reshape(-1)).astype(int) +npx = len(P) +rng = np.random.default_rng(7) + +def hash3(ix, iy, iz, seed=0): + h = (ix * 73856093) ^ (iy * 19349663) ^ (iz * 83492791) ^ (seed * 2654435761) + h = (h ^ (h >> 13)) * 1274126177 + return ((h ^ (h >> 16)) & 0xFFFFFF) / float(0xFFFFFF) + +def vnoise(X, scale, seed=0): + """Smooth 3D value noise in [-1, 1] at the given feature size (m).""" + Q = X / scale + i = np.floor(Q).astype(np.int64); f = Q - i + u = f * f * (3 - 2 * f) + out = 0.0 + for dx in (0, 1): + for dy in (0, 1): + for dz in (0, 1): + w = (u[:, 0] if dx else 1 - u[:, 0]) * (u[:, 1] if dy else 1 - u[:, 1]) * (u[:, 2] if dz else 1 - u[:, 2]) + out = out + w * hash3(i[:, 0] + dx, i[:, 1] + dy, i[:, 2] + dz, seed) + return out * 2 - 1 + +def fbm(X, scale, oct=4, seed=0, gain=0.5): + s, a, t = scale, 1.0, 0.0 + tot = 0.0 + for o in range(oct): + t = t + a * vnoise(X, s, seed + o * 17); tot += a + s *= 0.5; a *= gain + return t / tot + +def seg_dist(X, a, b): + ab = b - a; L2 = max(1e-12, ab.dot(ab)) + t = np.clip(((X - a) @ ab) / L2, 0, 1) + Q = a + t[:, None] * ab + return np.linalg.norm(X - Q, axis=1), t + +def smooth01(x): x = np.clip(x, 0, 1); return x * x * (3 - 2 * x) +def lin(c): c = np.asarray(c, float); return np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4) + +# rest-pose bones (armature space = first-person space) +B = {b.name: (Vector(b.head_local), Vector(b.tail_local)) for b in arm.data.bones} +def bvec(n): h, t = B[n]; return np.array(h[:]), np.array(t[:]) + +ALB = np.zeros((npx, 3)); HGT = np.zeros(npx); RGH = np.full(npx, 0.6); MET = np.zeros(npx); AOM = np.ones(npx) + +# ======================================================================= skin +sk = np.where(R == 0)[0] +X = P[sk]; Nk = Nn[sk] +side = np.where(X[:, 0] > 0, 'r', 'l') +# nearest bone among forearm, hand and fingers of the texel's side +bones = ['lowerarm', 'hand'] + ['%s_0%d' % (f, i) for f in ('index', 'middle', 'ring', 'pinky', 'thumb') for i in (1, 2, 3)] +best = np.full(len(X), 1e9); bid = np.zeros(len(X), int); btt = np.zeros(len(X)) +for k, bn in enumerate(bones): + for s in ('l', 'r'): + m = side == s + a, b = bvec(bn + '_' + s) + if bn.startswith(('index', 'middle', 'ring', 'pinky')) and bn.endswith('03'): + b = b + (b - a) * 0.15 + d, t = seg_dist(X[m], a, b) + if bn == 'lowerarm': d = d * 0.6 # the forearm is thick: prefer it near its own surface + upd = d < best[m] + idx = np.where(m)[0][upd] + best[idx] = d[upd]; bid[idx] = k; btt[idx] = t[upd] +bname = np.array(bones)[bid] +# dorsal direction per texel: the hand's back is +Z in the T-pose (palms down) +dors = Nk[:, 2] # +1 back of hand / top of fingers, -1 palm +is_hand = np.isin(bid, [1]) +is_finger = bid >= 2 +is_fore = bid == 0 +fore_t = np.zeros(len(X)) +for s, sg in (('l', -1.0), ('r', 1.0)): + m = side == s + a, b = bvec('lowerarm_' + s) + _, t = seg_dist(X[m], a, b); fore_t[m] = t +log('skin texels', len(X)) + +# --- base tone: weathered, tanned forearms, paler palms, warm knuckles and fingertips +tan = lin([0.47, 0.34, 0.26]); pale = lin([0.55, 0.41, 0.33]); red = lin([0.55, 0.32, 0.27]) +handness = np.where(is_fore, smooth01((fore_t - 0.80) / 0.25), 1.0) +palm_w = smooth01((-dors - 0.1) / 0.6) * (0.35 + 0.65 * handness) +alb = tan * (1 - palm_w[:, None]) + pale * palm_w[:, None] +mott = fbm(X, 0.02, 4, 1) * 0.07 + fbm(X, 0.004, 3, 2) * 0.04 +alb *= (1 + mott)[:, None] +# redness: knuckles (finger joints, dorsal), fingertips, palm heel +rednessmask = np.zeros(len(X)) +joint_d = np.full(len(X), 1.0) # distance along the finger to the nearest finger joint (m) +joint_dist3 = np.full(len(X), 1.0) +for f in ('index', 'middle', 'ring', 'pinky', 'thumb'): + for i in (1, 2, 3): + for s in ('l', 'r'): + a, b = bvec('%s_0%d_%s' % (f, i, s)) + m = (side == s) + ax = (b - a) / np.linalg.norm(b - a) + dj = (X[m] - a) @ ax + r3 = np.linalg.norm(X[m] - a, axis=1) + idx = np.where(m)[0] + upd = r3 < joint_dist3[idx] + joint_dist3[idx[upd]] = r3[upd]; joint_d[idx[upd]] = dj[upd] +knuck = np.exp(-(joint_dist3 / 0.013) ** 2) * smooth01(dors / 0.5 + 0.2) +tip = np.zeros(len(X)) +for f in ('index', 'middle', 'ring', 'pinky', 'thumb'): + for s in ('l', 'r'): + a, b = bvec('%s_03_%s' % (f, s)); m = side == s + tip[m] = np.maximum(tip[m], np.exp(-(np.linalg.norm(X[m] - b, axis=1) / 0.012) ** 2)) +# weathered: redder, rougher knuckles and fingertips, a sun-reddened outer forearm near the elbow +elbow = np.zeros(len(X)) +for s in ('l', 'r'): + a, b = bvec('lowerarm_' + s); m = side == s + elbow[m] = np.exp(-(np.linalg.norm(X[m] - a, axis=1) / 0.05) ** 2) +rednessmask = np.clip(knuck * 0.8 + tip * 0.55 + elbow * 0.5, 0, 1) +alb = alb * (1 - rednessmask[:, None] * 0.55) + red * rednessmask[:, None] * 0.55 +# the hand/forearm transition is smooth (no change of tone at the wrist): blend by the distance past the wrist +alb *= (1 - 0.08 * smooth01((dors + 0.2) / 0.8) * (1 - handness))[:, None] +hgt = np.zeros(len(X)) +# --- pores / fine skin +hgt += fbm(X, 0.0011, 2, 5) * 0.00006 + fbm(X, 0.0035, 2, 6) * 0.00005 +# --- knuckle wrinkles: bands across the finger on the back of each finger joint +fin_dors = smooth01((dors - 0.05) / 0.5) +for lam, amp, w in ((0.0017, 0.00011, 0.0052), (0.0011, 0.00005, 0.0035)): + ph = joint_d / lam * 2 * math.pi + fbm(X, 0.003, 2, 9) * 2.5 + hgt -= amp * np.exp(-(joint_d / w) ** 2) * (0.5 + 0.5 * np.cos(ph)) * fin_dors * (joint_dist3 < 0.02) +# --- palmar flexion creases at the finger joints, and the three palm lines +palmar = smooth01((-dors - 0.15) / 0.5) +hgt -= 0.00016 * np.exp(-(joint_d / 0.0011) ** 2) * palmar * (joint_dist3 < 0.016) +for s in ('l', 'r'): + m = (side == s) & is_hand + if not m.any(): continue + hh, ht = bvec('hand_' + s) + ih, _ = bvec('index_01_' + s); ph_, _ = bvec('pinky_01_' + s) + ax = (ht - hh) / np.linalg.norm(ht - hh) # wrist -> knuckles + across = (ih - ph_) / np.linalg.norm(ih - ph_) # pinky -> index + Lh = np.linalg.norm(ih - hh) + u = ((X[m] - hh) @ across) / 0.045 # -1 pinky side .. +1 index side + v = ((X[m] - hh) @ ax) / Lh # 0 wrist .. 1 knuckles + lines = 0 + for v0, v1, sl, amp in ((0.72, 0.62, 1.0, 0.00016), (0.58, 0.45, 1.0, 0.00014), (0.25, 0.5, -1.0, 0.00015)): + # each crease is a gentle curve v(u) + cv = v0 + (v1 - v0) * (u * sl + 1) / 2 + 0.05 * np.sin(u * 2.2) + d = (v - cv) * Lh + lines = lines - amp * np.exp(-(d / 0.0011) ** 2) * smooth01((1.0 - np.abs(u)) / 0.3) * (0.6 + 0.4 * fbm(X[m], 0.006, 2, 51)) + hgt[np.where(m)[0]] += lines * palmar[m] +# --- nails: plate on the back of each distal phalanx, cuticle groove, free edge, dirt beneath +nail = np.zeros(len(X)); nail_edge = np.zeros(len(X)); lunula = np.zeros(len(X)) +for f in ('index', 'middle', 'ring', 'pinky', 'thumb'): + for s in ('l', 'r'): + a, b = bvec('%s_03_%s' % (f, s)); m = (side == s) + ax = (b - a); Lb = np.linalg.norm(ax); ax = ax / Lb + q = X[m] - a + t = (q @ ax) / Lb + rad = q - np.outer(q @ ax, ax) + lat = np.linalg.norm(rad - np.outer(rad @ np.array([0, 0, 1.0]), [0, 0, 1.0]), axis=1) + top = Nk[m, 2] + w = 0.0062 if f != 'thumb' else 0.0072 + inside = smooth01((top - 0.35) / 0.25) * smooth01((w - lat) / 0.0012) * smooth01((t - 0.30) / 0.06) * smooth01((1.22 - t) / 0.05) + idx = np.where(m)[0] + nail[idx] = np.maximum(nail[idx], inside) + nail_edge[idx] = np.maximum(nail_edge[idx], inside * smooth01((t - 1.0) / 0.1)) + lunula[idx] = np.maximum(lunula[idx], inside * smooth01((0.42 - t) / 0.08)) +hgt += nail * 0.00032 - 0.00012 * np.exp(-((nail - 0.5) / 0.25) ** 2) * (nail > 0.02) +nail_col = lin([0.80, 0.60, 0.55]) +alb = alb * (1 - nail[:, None]) + nail_col * nail[:, None] +alb = alb + (lin([0.93, 0.88, 0.82]) - alb) * (nail_edge * 0.8)[:, None] +alb = alb + (lin([0.90, 0.80, 0.78]) - alb) * (lunula * 0.4)[:, None] +dirt_tip = nail_edge * 0.0 + tip * smooth01((-dors + 0.2) / 0.6) * 0.0 +# --- tendons on the back of the hand: ridges from each knuckle to the wrist +for s in ('l', 'r'): + m = (side == s) & (is_hand | (is_fore & (fore_t > 0.85))) + if not m.any(): continue + hh, _ = bvec('hand_' + s) + ten = np.zeros(m.sum()) + for f in ('index', 'middle', 'ring', 'pinky'): + k0, _ = bvec('%s_01_%s' % (f, s)) + d, t = seg_dist(X[m], hh + (k0 - hh) * 0.08, k0 - (k0 - hh) * 0.06) + ten = np.maximum(ten, np.exp(-(d / 0.0042) ** 2) * smooth01(t / 0.25) * smooth01((1 - t) / 0.3)) + hgt[np.where(m)[0]] += 0.0006 * ten * smooth01((dors[m] - 0.3) / 0.4) +# --- veins: wandering raised lines from the back of the hand up the forearm (rest pose, along the arm axis X) +vein = np.zeros(len(X)) +for s, sg in (('l', -1.0), ('r', 1.0)): + m = side == s + a, b = bvec('lowerarm_' + s); hh, _ = bvec('hand_' + s); k0, _ = bvec('middle_01_' + s) + for vi in range(6): + r2 = np.random.default_rng(31 + vi + (0 if s == 'l' else 50)) + # a vein path: from between the knuckles through the wrist, up the forearm, drifting around the arm + pts = [] + start = hh + (k0 - hh) * (0.55 + 0.1 * r2.random()) + np.array([0, (r2.random() - 0.5) * 0.04, 0.0]) + n_ = 36 + ang0 = (r2.random() - 0.5) * 1.6 + (math.pi if vi >= 4 else 0.0) # two on the inner forearm + for i in range(n_): + u = i / (n_ - 1) + c = start + (a + (b - a) * 0.25 - start) * u + ang = ang0 + 0.5 * math.sin(u * 7 + vi) + (r2.random() - 0.5) * 0.15 + rr = 0.0 if u < 0.15 else 1.0 + pts.append(c + np.array([0, math.sin(ang), math.cos(ang)]) * 0.06 * rr) + pts = np.array(pts) + # project each path point onto the skin: the nearest skin texel of this side + Xm = X[m] + for i in range(len(pts)): + j = np.argmin(np.sum((Xm[::25] - pts[i]) ** 2, 1)) * 25 + pts[i] = Xm[j] + for i in range(len(pts) - 1): + d, t = seg_dist(Xm, pts[i], pts[i + 1]) + wv = 0.0018 + 0.0006 * math.sin(i * 0.7 + vi) + vein[np.where(m)[0]] = np.maximum(vein[np.where(m)[0]], np.exp(-(d / wv) ** 2) * (0.6 + 0.4 * math.sin(i * 0.37 + vi * 2))) +vein *= np.where(is_fore, 0.75 + 0.25 * smooth01((dors + 0.2) / 0.6), smooth01((dors + 0.2) / 0.6) * is_hand) +hgt += vein * 0.0008 +alb = alb * (1 - vein[:, None] * 0.18) + lin([0.38, 0.36, 0.44]) * (vein[:, None] * 0.18) +# --- forearm hair: fine dark strands along the arm on the back and outer side, thin on the back of the hand +hair = np.zeros(len(X)) +for s in ('l', 'r'): + m = (side == s) & (is_fore | is_hand) + a, b = bvec('lowerarm_' + s) + ax = (b - a) / np.linalg.norm(b - a) + q = X[m] - a + sl = q @ ax + rad = q - np.outer(sl, ax) + th = np.arctan2(rad[:, 1], rad[:, 2]) + arc = th * 0.035 + for layer in range(3): + cu = sl / 0.0055 + layer * 0.37; cv = arc / 0.0011 + layer * 0.61 + iu = np.floor(cu).astype(np.int64); iv = np.floor(cv).astype(np.int64) + fu = cu - iu; fv = cv - iv + jit = hash3(iu, iv, np.full_like(iu, layer), 3) + on = hash3(iu, iv, np.full_like(iu, layer), 4) < 0.7 + # strand: a thin line across the cell, slightly slanted + dv = np.abs(fv - (0.2 + 0.6 * jit) - (fu - 0.5) * 0.35) + strand = np.exp(-(dv / 0.12) ** 2) * smooth01(fu / 0.15) * smooth01((1 - fu) / 0.15) * on + hair[np.where(m)[0]] = np.maximum(hair[np.where(m)[0]], strand) +hairmask = (0.35 + 0.65 * smooth01((dors + 0.35) / 0.5)) * is_fore * smooth01((fore_t - 0.35) / 0.15) + smooth01((dors + 0.35) / 0.5) * is_hand * 0.35 +hair *= hairmask +alb = alb * (1 - hair[:, None] * 0.75) + lin([0.10, 0.07, 0.05]) * (hair[:, None] * 0.75) +hgt += hair * 0.00004 +# --- healed scar: a pale raised line across the back of the right forearm, and a small nick on the left hand +scar = np.zeros(len(X)) +for s, f0, f1, dz, w in (('r', 0.55, 0.78, 0.6, 0.0016), ('l', 0.0, 0.0, 0.0, 0.0)): + if w == 0: continue + a, b = bvec('lowerarm_' + s) + p0 = a + (b - a) * f0 + np.array([0, -0.020, 0.030]); p1 = a + (b - a) * f1 + np.array([0, 0.012, 0.036]) + m = side == s + d, t = seg_dist(X[m], p0, p1) + ww = w * (0.5 + 0.5 * np.sin(np.pi * t)) + sc_ = np.exp(-(d / np.maximum(ww, 1e-4)) ** 2) * smooth01((dors[m] - 0.0) / 0.4) + scar[np.where(m)[0]] = sc_ +hh, _ = bvec('hand_l'); k0, _ = bvec('index_01_l') +d, t = seg_dist(X, hh + (k0 - hh) * 0.5 + np.array([0, 0.01, 0.02]), hh + (k0 - hh) * 0.75 + np.array([0, 0.016, 0.022])) +scar = np.maximum(scar, np.exp(-(d / 0.0011) ** 2) * (side == 'l') * smooth01(dors / 0.4) * 0.8) +hgt += scar * 0.00028 +alb = alb * (1 - scar[:, None] * 0.45) + lin([0.80, 0.62, 0.58]) * (scar[:, None] * 0.45) +hair *= (1 - scar) +# --- grime: dirt in creases (cavities), on the knuckles, palm heel and under the nail tips; a few mud specks +cav = np.clip(-hgt / 0.00025, 0, 1) +grime = np.clip(0.35 * fbm(X, 0.03, 3, 21) + 0.25, 0, 1) * 0.35 +grime += knuck * 0.25 + tip * smooth01((-dors) / 0.5) * 0.25 +grime += nail_edge * 0.7 +grime += cav * 0.55 +specks = (fbm(X, 0.0016, 2, 33) > 0.62) * smooth01((dors + 0.2) / 0.5) * 0.6 +grime = np.clip(grime + specks, 0, 1) +dirt = lin([0.20, 0.15, 0.10]) +alb = alb * (1 - grime[:, None] * 0.65) + dirt * (grime[:, None] * 0.65) +# roughness: oily-sheened back of the hand and forearm, drier rough knuckles and palms, dirt flat +rgh = 0.62 + 0.14 * fbm(X, 0.008, 3, 41) + 0.06 * fbm(X, 0.002, 2, 43) - 0.10 * smooth01((dors - 0.2) / 0.5) * (is_hand | is_fore) + 0.12 * knuck + 0.08 * palm_w +rgh = rgh + grime * 0.15 - scar * 0.12 +rgh = rgh * (1 - nail) + 0.28 * nail +# ---------------------------------------------------------------- full leather gloves over the whole hand +# Worn dark brown despatch-rider leather: pebbled grain, folds across every knuckle that are deeper on the back, +# fourchette seams along the sides of each finger, a seam round the base of the thumb, three stitched points on the +# back of the hand; polished and lighter where it rubs (fingertips, knuckles, heel of the palm), scuffs, dirt packed +# into the seams and creases. Everything below replaces the bare-skin fields computed above (kept for their masks). +is4 = np.isin(bname, ['%s_0%d' % (f, i) for f in ('index', 'middle', 'ring', 'pinky') for i in (1, 2, 3)]) +lea = lin([0.150, 0.094, 0.058]) +tone = fbm(X, 0.025, 3, 201) +alb = np.tile(lea, (len(X), 1)) * (1 + 0.20 * tone + 0.06 * fbm(X, 0.004, 2, 202))[:, None] +hgt = fbm(X, 0.0006, 2, 203) * 0.000045 + fbm(X, 0.0022, 2, 204) * 0.00003 # pebbled grain +# folds across the knuckles and finger joints (back of the hand), creases on the palm side +for lam, amp, w in ((0.0030, 0.00030, 0.0070), (0.0018, 0.00012, 0.0045)): + ph = joint_d / lam * 2 * math.pi + fbm(X, 0.004, 2, 9) * 2.8 + hgt -= amp * np.exp(-(joint_d / w) ** 2) * (0.5 + 0.5 * np.cos(ph)) * fin_dors * (joint_dist3 < 0.022) +hgt -= 0.00026 * np.exp(-(joint_d / 0.0018) ** 2) * palmar * (joint_dist3 < 0.017) +# fourchettes: a seam groove where the side panels meet, with stitches either side of it +side_g = np.exp(-(dors / 0.07) ** 2) * is4 +st_line = np.exp(-((np.abs(dors) - 0.13) / 0.035) ** 2) * is4 * (np.sin(joint_d / 0.0027 * 2 * math.pi) > 0.25) +hgt += -0.00022 * side_g + 0.00007 * st_line +# seam round the base of the thumb +thumb_seam = np.zeros(len(X)); thumb_st = np.zeros(len(X)) +for s_ in ('l', 'r'): + a_, b_ = bvec('thumb_01_' + s_); m_ = side == s_ + d3 = np.linalg.norm(X[m_] - a_, axis=1) + ring_ = np.exp(-((d3 - 0.017) / 0.0009) ** 2) + ang_ = np.arctan2(*(X[m_] - a_)[:, [1, 2]].T) + thumb_seam[m_] = ring_; thumb_st[m_] = np.exp(-((d3 - 0.0185) / 0.0006) ** 2) * (np.sin(ang_ * 0.017 / 0.0027 * 2 * math.pi) > 0.25) +hgt += -0.00020 * thumb_seam + 0.00006 * thumb_st +# three stitched points on the back of the hand, from between the knuckles toward the wrist +points = np.zeros(len(X)); pst = np.zeros(len(X)) +for s_ in ('l', 'r'): + m_ = (side == s_) & (is_hand | is4) + hh_, _ = bvec('hand_' + s_) + ks = [bvec('%s_01_%s' % (f, s_))[0] for f in ('index', 'middle', 'ring', 'pinky')] + for k0, k1 in zip(ks, ks[1:]): + mid = (k0 + k1) / 2 + d_, t_ = seg_dist(X[m_], mid - (mid - hh_) * 0.12, mid - (mid - hh_) * 0.55) + ridge = np.exp(-(d_ / 0.0010) ** 2) * smooth01((dors[m_] - 0.3) / 0.3) + sti = np.exp(-((d_ - 0.0016) / 0.0005) ** 2) * (np.sin(t_ * 0.03 / 0.0026 * 2 * math.pi) > 0.25) * smooth01((dors[m_] - 0.3) / 0.3) + idx_ = np.where(m_)[0] + points[idx_] = np.maximum(points[idx_], ridge); pst[idx_] = np.maximum(pst[idx_], sti) +hgt += 0.00010 * points + 0.00006 * pst +thread = lin([0.30, 0.25, 0.18]) +stitches = np.clip(st_line + thumb_st + pst, 0, 1) +alb = alb * (1 - stitches[:, None] * 0.45) + thread * (stitches[:, None] * 0.45) +# wear: polished lighter leather on fingertips, knuckles and the heel of the palm; scuffs; dirt in seams and folds +heel = np.zeros(len(X)) +for s_ in ('l', 'r'): + hh_, ht_ = bvec('hand_' + s_); m_ = (side == s_) + heel[m_] = np.exp(-(np.linalg.norm(X[m_] - (hh_ + (ht_ - hh_) * 0.25), axis=1) / 0.025) ** 2) * smooth01((-dors[m_] - 0.2) / 0.4) +# a worn ridge along the top of every finger and over the knuckles, lighter and smoother so the form reads by +# highlight at game size; darker seams between the fingers +ftop = smooth01((dors - 0.55) / 0.3) * (is4 | np.isin(bname, ['thumb_0%d' % i for i in (1, 2, 3)])) +pol = np.clip(tip * 1.0 + knuck * 1.1 + heel * 0.9 + ftop * 0.55, 0, 1) * (0.65 + 0.35 * fbm(X, 0.005, 2, 207)) +alb = alb * (1 - pol[:, None] * 0.65) + lin([0.29, 0.195, 0.12]) * (pol[:, None] * 0.65) +alb = alb * (1 - 0.55 * side_g)[:, None] +scuff = np.clip((fbm(X, 0.0035, 3, 209) - 0.35) * 3, 0, 1) * (0.4 + 0.6 * smooth01((dors + 0.2) / 0.6)) +alb = alb * (1 - scuff[:, None] * 0.35) + lin([0.30, 0.22, 0.15]) * (scuff[:, None] * 0.35) +cav = np.clip(-hgt / 0.00018, 0, 1) +dirt_ = np.clip(cav * 0.8 + 0.25 * np.clip(fbm(X, 0.02, 3, 211), 0, 1), 0, 1) +alb = alb * (1 - dirt_[:, None] * 0.55) + lin([0.055, 0.042, 0.030]) * (dirt_[:, None] * 0.55) +rgh = 0.64 + 0.08 * fbm(X, 0.01, 3, 213) - 0.14 * pol + 0.08 * scuff + 0.10 * dirt_ # worn areas about 0.5 +ALB[sk] = alb; HGT[sk] = hgt; RGH[sk] = rgh +log('skin done') + +# ======================================================================= smock sleeve and roll (regions 1, 2) +cl = np.where(R == 1)[0] +X = P[cl]; Nc = Nn[cl]; rc = R[cl] +side = np.where(X[:, 0] > 0, 'r', 'l') +# cylinder coordinates along each arm (upper arm + forearm chained) +s_al = np.zeros(len(X)); arcp = np.zeros(len(X)); fore = np.zeros(len(X)) +for s in ('l', 'r'): + m = side == s + ua, ub = bvec('upperarm_' + s); la, lb = bvec('lowerarm_' + s) + d1, t1 = seg_dist(X[m], ua, ub); d2, t2 = seg_dist(X[m], la, lb) + on_fore = d2 < d1 + Lu = np.linalg.norm(ub - ua) + sl = np.where(on_fore, Lu + t2 * np.linalg.norm(lb - la), t1 * Lu) + axs = np.where(on_fore[:, None], (lb - la) / np.linalg.norm(lb - la), (ub - ua) / Lu) + q = X[m] - np.where(on_fore[:, None], la, ua) + rad = q - np.sum(q * axs, 1)[:, None] * axs + th = np.arctan2(rad[:, 1], rad[:, 2]) + s_al[m] = sl; arcp[m] = th * 0.045; fore[m] = np.where(on_fore, t2, -1) +U2 = np.stack([s_al, arcp, np.zeros(len(X))], 1) +# invented camouflage: soft brush strokes, elongated around the arm, three colours over a sand base +# dark olive-brown smock: a low-contrast brush pattern several stops darker than the old sand base, so the sleeves +# sit in a muted scene instead of glowing +base = lin([0.190, 0.188, 0.150]) +c_brown = lin([0.165, 0.135, 0.100]); c_green = lin([0.140, 0.155, 0.115]); c_dark = lin([0.095, 0.095, 0.080]) +alb = np.tile(base, (len(X), 1)) +for col, seed, thr, sx, sy in ((c_green, 51, 0.12, 0.05, 0.11), (c_brown, 52, 0.18, 0.04, 0.09), (c_dark, 53, 0.42, 0.03, 0.07)): + Q = np.stack([s_al / sx, arcp / sy * 0.02 / 0.02, np.full(len(X), seed * 0.1)], 1) * 0.02 + nfield = fbm(Q, 0.02, 4, seed) + 0.25 * fbm(U2 * np.array([1, 3, 1]), 0.006, 2, seed + 7) + edge = smooth01((nfield - thr) / 0.06) + alb = alb * (1 - edge[:, None] * 0.6) + col * (edge[:, None] * 0.6) +# weave: a heavy twill, diagonal ribs about 1.4 mm apart, with thread-level noise +tw = (s_al + arcp * 0.9) / 0.0014 * 2 * math.pi +hgt = 0.00006 * np.sin(tw) + fbm(U2 * np.array([1, 1, 1]), 0.0007, 2, 61) * 0.00003 +# folds: soft compression creases ringing the arm near the roll and in the elbow pit (normal-map scale) +fold = np.sin(s_al / 0.016 * 2 * math.pi + 2.0 * np.sin(arcp / 0.03) + 0.6 * fbm(U2, 0.02, 2, 63) * 6) +hgt += 0.0005 * fold * smooth01((fore + 0.4) / 0.5) * (rc == 1) +# roll: two turns of cloth with a stitched hem along the lower turn and worn, lighter crests +ROLL = (0.76, 0.84) # the cuff band's span on the forearm: keep equal to fp_arms.ROLL +roll_u = np.zeros(len(X)) +for s in ('l', 'r'): + m = (side == s) & (rc == 2) + la, lb = bvec('lowerarm_' + s) + _, t = seg_dist(X[m], la, lb) + roll_u[m] = (t - ROLL[0]) / (ROLL[1] - ROLL[0]) +# The cuff is the smock's own cloth turned back: same camouflage, darker and dirtier from handling, a soft crest +# where it folds, a stitched hem and only a thin frayed lower edge. (The old mapping used the 0.30-0.50 span of the +# rolled sleeve, so on the 0.76-0.84 cuff the fray term was 1 everywhere and half the texels went cream.) +roll_u = np.clip(roll_u, 0, 1) +crest = np.abs(np.sin(roll_u * math.pi)) * (rc == 2) +fray = (rc == 2) * smooth01((roll_u - 0.93) / 0.05) * (np.sin(arcp / 0.0011 * 2 * math.pi + 3 * fbm(U2, 0.004, 2, 77)) > 0.35) +hgt += 0.0003 * crest +seam = (rc == 2) * np.exp(-((roll_u - 0.12) / 0.03) ** 2) +stitch = seam * (np.sin(arcp / 0.0032 * 2 * math.pi) > 0.2) +hgt -= 0.00012 * seam; hgt += 0.00008 * stitch +alb = alb * (1 + 0.06 * crest[:, None]) * (1 - 0.15 * seam[:, None]) +alb = alb + (lin([0.47, 0.43, 0.33]) - alb) * (fray[:, None] * 0.3) +hgt += fray * 0.00012 +alb = alb + (lin([0.42, 0.38, 0.29]) - alb) * (stitch[:, None] * 0.35) +# handling grime: the cuff is what touches everything; oil, mud and sweat darken it in blotches +cg = (rc == 2) * np.clip(0.55 + 0.6 * fbm(X, 0.012, 3, 79), 0, 1) +alb = alb * (1 - cg[:, None] * 0.38) + lin([0.17, 0.14, 0.10]) * (cg[:, None] * 0.38) +# wear and grime: darker in creases and the inside of the roll, dust on the crests, sweat at the cuff +g = np.clip(0.4 * fbm(X, 0.04, 3, 71) + 0.2, 0, 1) * 0.4 + np.clip(-fold, 0, 1) * 0.15 * (rc == 1) +alb = alb * (1 - g[:, None] * 0.45) + lin([0.25, 0.20, 0.14]) * (g[:, None] * 0.45) +alb = alb * (1 + 0.05 * fbm(U2, 0.0025, 2, 73))[:, None] +# a felled seam along the outside of the sleeve (back of the forearm), two rows of stitches +seam_o = np.exp(-(arcp / 0.0016) ** 2) +seam_st = np.exp(-((np.abs(arcp) - 0.0032) / 0.0006) ** 2) * (np.sin(s_al / 0.0030 * 2 * math.pi) > 0.3) +hgt += 0.00012 * seam_o - 0.0001 * np.exp(-((np.abs(arcp) - 0.0022) / 0.0006) ** 2) + 0.00005 * seam_st +alb = alb * (1 - 0.12 * seam_o[:, None]) * (1 - 0.2 * seam_st[:, None]) +# wet, muddy cuffs: the last part of the sleeve is dark with damp and splashed with mud; roughness drops where wet +wet = smooth01((fore - 0.62) / 0.2) * (fore >= 0) +mud = wet * smooth01((fbm(X, 0.012, 3, 77) + 0.1) / 0.3) +alb = alb * (1 - wet[:, None] * 0.38) +alb = alb * (1 - mud[:, None] * 0.6) + lin([0.115, 0.088, 0.060]) * (mud[:, None] * 0.6) +hgt += mud * fbm(X, 0.0015, 2, 78) * 0.00008 +ALB[cl] = alb; HGT[cl] = hgt; RGH[cl] = 0.86 + 0.06 * fbm(X, 0.02, 2, 75) - 0.22 * wet * (1 - mud * 0.5) +log('cloth done') + +# ======================================================================= strap, watch case, dial (regions 3, 4, 5) +# ======================================================================= glove cuff, glove strap, buckle (2, 6, 7) +for reg_, darker in ((2, 1.0), (6, 1.45)): + ix = np.where(R == reg_)[0] + if not len(ix): continue + X = P[ix]; Nr = Nn[ix] + fr_ = np.zeros(len(X)); th_ = np.zeros(len(X)) + for s_ in ('l', 'r'): + m_ = X[:, 0] > 0 if s_ == 'r' else X[:, 0] <= 0 + la_, lb_ = bvec('lowerarm_' + s_) + ax_ = (lb_ - la_) / np.linalg.norm(lb_ - la_) + _, t_ = seg_dist(X[m_], la_, lb_ + (lb_ - la_) * 0.1); fr_[m_] = t_ * 1.1 + q_ = X[m_] - la_; rad_ = q_ - np.outer(q_ @ ax_, ax_); th_[m_] = np.arctan2(rad_[:, 1], rad_[:, 2]) + alb = np.tile(lea * darker, (len(X), 1)) * (1 + 0.2 * fbm(X, 0.02, 3, 221 + reg_))[:, None] + hgt = fbm(X, 0.0006, 2, 223) * 0.00004 + if reg_ == 2: # creases round the cuff where the wrist bends, a stitched hem at the open end + hgt -= 0.00016 * (0.5 + 0.5 * np.sin(fr_ / 0.012 * 2 * math.pi + 2 * np.sin(th_ * 2))) * smooth01((fr_ - 0.84) / 0.06) + hem_ = np.exp(-((fr_ - 0.80) / 0.006) ** 2) + hst = hem_ * (np.sin(th_ * 0.028 / 0.0028 * 2 * math.pi) > 0.25) + hgt += 0.00006 * hst; alb = alb * (1 - hst[:, None] * 0.4) + thread * (hst[:, None] * 0.4) + else: # strap: stitched edges and a row of punched holes on the free end + edg = np.exp(-((np.abs(fr_ - 0.955) - 0.019) / 0.004) ** 2) + alb = alb * (1 - edg[:, None] * 0.25) + thread * (edg[:, None] * 0.25) + wr = np.clip((fbm(X, 0.004, 3, 225) - 0.2) * 2.5, 0, 1) * 0.6 + alb = alb * (1 - wr[:, None] * 0.4) + lin([0.25, 0.165, 0.10]) * (wr[:, None] * 0.4) + cav = np.clip(-hgt / 0.00015, 0, 1) + alb = alb * (1 - cav[:, None] * 0.5) + ALB[ix] = alb; HGT[ix] = hgt; RGH[ix] = 0.68 + 0.08 * fbm(X, 0.01, 2, 227) - 0.2 * wr +ix = np.where(R == 7)[0] +if len(ix): # buckles and buttons: dull blackened steel, bright where worn + X = P[ix] + w7 = np.clip((fbm(X, 0.0015, 2, 231) - 0.25) * 3, 0, 1) + ALB[ix] = lin([0.30, 0.29, 0.27]) * (1 - w7[:, None]) + lin([0.62, 0.61, 0.58]) * w7[:, None] + RGH[ix] = 0.55 - 0.2 * w7; MET[ix] = 1.0; HGT[ix] = 0.0 +log('glove cuffs done') + +wc = Vector(meta['watch_centre']); wcn = np.array(wc[:]) +st = np.where(R == 3)[0] +X = P[st] +q = X - wcn +along = q[:, 0] if False else None +# strap coordinates: across the strap = along the forearm (X in rest), around = angle about the forearm +la, lb = bvec('lowerarm_l') +ax = (lb - la) / np.linalg.norm(lb - la) +sl = (X - wcn) @ ax +rad = (X - wcn) - np.outer(sl, ax) +th = np.arctan2(rad[:, 1], rad[:, 2]) +leather = lin([0.20, 0.12, 0.07]) +edge = np.exp(-((np.abs(sl) - 0.0072) / 0.0007) ** 2) +stitch = edge * (np.sin(th * 0.024 / 0.0025 * 2 * math.pi) > 0.3) +holes = ((np.abs(sl) < 0.0012) & (np.abs(((th * 0.024) % 0.007) - 0.0035) < 0.0011) & (np.abs(th) > 1.2)).astype(float) +hgt = fbm(X, 0.0012, 2, 81) * 0.00004 - 0.00015 * holes + 0.00006 * stitch - 0.0001 * np.exp(-((np.abs(sl) - 0.0086) / 0.0005) ** 2) +alb = np.tile(leather, (len(X), 1)) * (1 + 0.15 * fbm(X, 0.004, 3, 83))[:, None] +alb = alb * (1 - holes[:, None] * 0.7) + lin([0.55, 0.47, 0.36]) * (stitch[:, None] * 0.6) +wear = smooth01((np.abs(sl) - 0.006) / 0.003) * 0.4 +alb = alb + (lin([0.36, 0.26, 0.17]) - alb) * wear[:, None] +ALB[st] = alb; HGT[st] = hgt; RGH[st] = 0.55 - 0.15 * wear + 0.05 * fbm(X, 0.005, 2, 85) +cs = np.where(R == 4)[0] +X = P[cs] +steel = lin([0.62, 0.62, 0.60]) +scr = np.clip(fbm(X, 0.0008, 2, 91) * 2 - 0.6, 0, 1) +ALB[cs] = steel * (0.85 + 0.15 * fbm(X, 0.003, 2, 93))[:, None] +RGH[cs] = 0.32 + 0.25 * scr + 0.1 * fbm(X, 0.004, 2, 95); MET[cs] = 1.0 +HGT[cs] = scr * 0.00002 +dl = np.where(R == 5)[0] +X = P[dl] +q = X - wcn +q[:, :2] = -q[:, :2] # 12 o'clock toward -Y, so the crown (3 o'clock) points at the hand +r = np.linalg.norm(q[:, :2], axis=1) +ang = np.arctan2(q[:, 0], q[:, 1]) +dialc = lin([0.05, 0.05, 0.05]) +lum = lin([0.85, 0.82, 0.70]) +mark = np.zeros(len(X)) +for h in range(12): + a0 = h / 12 * 2 * math.pi + da = np.abs((ang - a0 + math.pi) % (2 * math.pi) - math.pi) * r + big = h % 3 == 0 + mark = np.maximum(mark, (da < (0.0009 if big else 0.0005)) * (r > 0.0085) * (r < (0.0118 if big else 0.0112))) +def hand_(a0, length, width): + dirv = np.array([math.sin(a0), math.cos(a0)]) + t = q[:, :2] @ dirv + perp = np.abs(q[:, 0] * dirv[1] - q[:, 1] * dirv[0]) + return ((t > -0.001) & (t < length) & (perp < width * (1 - 0.6 * np.clip(t / length, 0, 1)))).astype(float) +hands = np.maximum(hand_(2 * math.pi * 10.2 / 12, 0.0072, 0.0009), hand_(2 * math.pi * 0.35, 0.0102, 0.0007)) +alb = np.tile(dialc, (len(X), 1)) +alb = alb * (1 - np.maximum(mark, hands)[:, None]) + lum * np.maximum(mark, hands)[:, None] +ALB[dl] = alb * 0.85; RGH[dl] = 0.06; MET[dl] = 0.0; HGT[dl] = 0.0 +log('watch done') + +# ======================================================================= normal map from heights +HGTi = HGT.reshape(H, Wd); Pimg = P.reshape(H, Wd, 3); Nimg = Nn.reshape(H, Wd, 3) +def grad(a, axis): + return (np.roll(a, -1, axis) - np.roll(a, 1, axis)) * 0.5 +dPu = grad(Pimg, 1); dPv = grad(Pimg, 0) # pixel rows run up the image (Blender pixel order) +dHu = grad(HGTi, 1); dHv = grad(HGTi, 0) +lu = np.linalg.norm(dPu, axis=2); lv = np.linalg.norm(dPv, axis=2) +ok = (lu > 1e-7) & (lv > 1e-7) & (lu < 0.01) & (lv < 0.01) +Tn = dPu / np.maximum(lu, 1e-9)[..., None]; Bn = dPv / np.maximum(lv, 1e-9)[..., None] +Tn = Tn - Nimg * np.sum(Tn * Nimg, 2)[..., None]; Tn /= np.maximum(1e-9, np.linalg.norm(Tn, axis=2))[..., None] +Bn = Bn - Nimg * np.sum(Bn * Nimg, 2)[..., None] - Tn * np.sum(Bn * Tn, 2)[..., None]; Bn /= np.maximum(1e-9, np.linalg.norm(Bn, axis=2))[..., None] +gu = np.where(ok, dHu / np.maximum(lu, 1e-9), 0); gv = np.where(ok, dHv / np.maximum(lv, 1e-9), 0) +gu = np.clip(gu, -1.5, 1.5); gv = np.clip(gv, -1.5, 1.5) +# handedness: B must be N x T for a right-handed tangent frame; if the island is mirrored, flip the v slope sign +hand_sign = np.sign(np.sum(np.cross(Nimg, Tn) * Bn, 2)); hand_sign[hand_sign == 0] = 1 +nx = -gu; ny = -gv * hand_sign; nz_ = np.ones_like(nx) +ln = np.sqrt(nx * nx + ny * ny + nz_ * nz_) +NOR = np.stack([nx / ln * 0.5 + 0.5, ny / ln * 0.5 + 0.5, nz_ / ln * 0.5 + 0.5], 2) + +# ======================================================================= write +def to_srgb(c): + c = np.clip(c, 0, 1); return np.where(c <= 0.0031308, c * 12.92, 1.055 * c ** (1 / 2.4) - 0.055) +def save(arr, name, srgb): + img = bpy.data.images.new(name, Wd, H, alpha=False) + a = np.ones((H, Wd, 4), np.float32); a[..., :3] = arr + img.colorspace_settings.name = 'sRGB' if srgb else 'Non-Color' + img.pixels.foreach_set(a.ravel()); img.update() + img.filepath_raw = TD + '/' + name + '.png'; img.file_format = 'PNG'; img.save() + return img +ao = np.clip(AO.reshape(-1) * 0.7 + 0.3, 0, 1) +# part of the occlusion also goes into the colour: three.js applies aoMap to ambient light only, and the creases +# between fingers, under the sleeve hem and round the cuff must stay dark under the sun and the lamp too +cloth_or_glove = (R == 0) | (R == 1) | (R == 2) | (R == 6) +ALB = ALB * np.where(cloth_or_glove, 0.45 + 0.55 * np.clip(AO.reshape(-1), 0, 1), 1.0)[:, None] +ALBi = to_srgb(ALB.reshape(H, Wd, 3)) +ORM = np.stack([ao, np.clip(RGH, 0.04, 1), MET], 1).reshape(H, Wd, 3) +np.savez_compressed(TD + '/fields.npz', alb=ALBi.astype(np.float32), nor=NOR.astype(np.float32), orm=ORM.astype(np.float32)) +i_alb = save(ALBi, 'fp_albedo', True); i_nor = save(NOR, 'fp_normal', False); i_orm = save(ORM, 'fp_orm', False) +log('textures written') + +# ---------------------------------------------------------------- final material (glTF: base colour, normal, ORM) +for n in list(N): N.remove(n) +out = N.new('ShaderNodeOutputMaterial'); bs = N.new('ShaderNodeBsdfPrincipled'); Lk.new(bs.outputs[0], out.inputs['Surface']) +ta = N.new('ShaderNodeTexImage'); ta.image = i_alb +tn = N.new('ShaderNodeTexImage'); tn.image = i_nor; tn.image.colorspace_settings.name = 'Non-Color' +to = N.new('ShaderNodeTexImage'); to.image = i_orm; to.image.colorspace_settings.name = 'Non-Color' +nm = N.new('ShaderNodeNormalMap'); sp = N.new('ShaderNodeSeparateColor') +Lk.new(ta.outputs[0], bs.inputs['Base Color']); Lk.new(tn.outputs[0], nm.inputs['Color']); Lk.new(nm.outputs[0], bs.inputs['Normal']) +Lk.new(to.outputs[0], sp.inputs[0]); Lk.new(sp.outputs['Green'], bs.inputs['Roughness']); Lk.new(sp.outputs['Blue'], bs.inputs['Metallic']) +grp = bpy.data.node_groups.get('glTF Material Output') or bpy.data.node_groups.new('glTF Material Output', 'ShaderNodeTree') +if 'Occlusion' not in [i.name for i in grp.interface.items_tree]: + grp.interface.new_socket('Occlusion', in_out='INPUT', socket_type='NodeSocketFloat') +g = N.new('ShaderNodeGroup'); g.node_tree = grp; Lk.new(sp.outputs['Red'], g.inputs['Occlusion']) +for img in list(bpy.data.images): + if img.name in ('pos', 'nrm', 'reg', 'mask', 'ao'): bpy.data.images.remove(img) +bpy.ops.wm.save_as_mainfile(filepath=FPW + '/fp_tex.blend') +log('saved fp_tex.blend') diff --git a/e63334287a3deaa3/ironveil/tools/chars/fp_unpack.mjs b/e63334287a3deaa3/ironveil/tools/chars/fp_unpack.mjs new file mode 100644 index 00000000..61044ee8 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/fp_unpack.mjs @@ -0,0 +1,17 @@ +// Decode the packed weapons.glb (meshopt geometry) into a plain GLB that Blender's importer reads, for fp_clips.py. +// usage: GT_MODULES=/path/to/node_modules node fp_unpack.mjs weapons.glb out.glb +import path from 'path'; +const M = process.env.GT_MODULES || path.resolve('node_modules'); +const imp = (p) => import(path.join(M, p)); +const { NodeIO } = await imp('@gltf-transform/core/dist/index.js'); +const { ALL_EXTENSIONS } = await imp('@gltf-transform/extensions/dist/index.js'); +const { dequantize } = await imp('@gltf-transform/functions/dist/index.js'); +const { MeshoptDecoder } = await imp('meshoptimizer/index.js'); +const [src, dst] = process.argv.slice(2); +await MeshoptDecoder.ready; +const io = new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({ 'meshopt.decoder': MeshoptDecoder }); +const doc = await io.read(src); +for (const e of doc.getRoot().listExtensionsUsed()) if (/meshopt|quantization/.test(e.extensionName)) e.dispose(); +await doc.transform(dequantize()); +await io.write(dst, doc); +console.log('wrote', dst); diff --git a/e63334287a3deaa3/ironveil/tools/chars/fpshots.js b/e63334287a3deaa3/ironveil/tools/chars/fpshots.js new file mode 100644 index 00000000..9f2c16c8 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/fpshots.js @@ -0,0 +1,19 @@ +// usage: node fpshots.js outdir W H name=query [name=query ...] +// One browser, many stills of chars-test.html (first-person mode and others). Prints each page's INFO as JSON lines. +const { chromium } = require(process.env.PLAYWRIGHT || 'playwright'); +(async () => { + const [out, w, h, ...jobs] = process.argv.slice(2); + const b = await chromium.launch(); + const p = await b.newPage({ viewport: { width: +w, height: +h } }); + p.on('pageerror', e => console.log('pageerror:', String(e).slice(0, 300))); + p.on('console', m => { if (m.type() === 'error') console.log('console:', m.text().slice(0, 200)); }); + for (const j of jobs) { + const i = j.indexOf('='), name = j.slice(0, i), q = j.slice(i + 1); + await p.goto(`http://127.0.0.1:${process.env.PORT || 8981}/e63334287a3deaa3/ironveil/chars-test.html?shot=1&${q}`); + await p.waitForFunction('window.READY||window.ERR', null, { timeout: 180000 }); + const info = await p.evaluate(() => JSON.stringify(window.ERR || window.INFO || {})); + await p.screenshot({ path: `${out}/${name}.png` }); + console.log(name, info.slice(0, 600)); + } + await b.close(); +})().catch(e => { console.error(e); process.exit(1); }); diff --git a/e63334287a3deaa3/ironveil/tools/chars/fpvideo.js b/e63334287a3deaa3/ironveil/tools/chars/fpvideo.js new file mode 100644 index 00000000..9ee4faf1 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/fpvideo.js @@ -0,0 +1,23 @@ +// usage: node fpvideo.js out.mp4 "fp=rifleScoped&clip=reload&light=overcast" seconds [W H] +// Steps the first-person viewmodel at 30 fps in chars-test.html and encodes the frames with ffmpeg. +const { chromium } = require(process.env.PLAYWRIGHT || 'playwright'); +const fs = require('fs'), path = require('path'), { execFileSync } = require('child_process'); +(async () => { + const [out, q, secs, w = 1280, h = 720] = process.argv.slice(2); + const dir = fs.mkdtempSync(path.join(path.dirname(out), '.frames-')); + const b = await chromium.launch(); + const p = await b.newPage({ viewport: { width: +w, height: +h } }); + p.on('pageerror', e => console.log('pageerror:', String(e).slice(0, 300))); + await p.goto(`http://127.0.0.1:${process.env.PORT || 8981}/e63334287a3deaa3/ironveil/chars-test.html?shot=1&t=0&${q}`); + await p.waitForFunction('window.READY||window.ERR', null, { timeout: 180000 }); + const n = Math.round(+secs * 30), evs = []; + for (let i = 0; i < n; i++) { + const e = await p.evaluate(() => window.FP.step(1 / 30)); + if (e && e.length) evs.push(...e.map(x => `${(i / 30).toFixed(2)}s ${x.name}`)); + await p.screenshot({ path: path.join(dir, `f${String(i).padStart(4, '0')}.png`) }); + } + await b.close(); + execFileSync('ffmpeg', ['-y', '-loglevel', 'error', '-framerate', '30', '-i', path.join(dir, 'f%04d.png'), '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-crf', '20', out]); + fs.rmSync(dir, { recursive: true }); + console.log(out, n, 'frames; events:', evs.join(', ')); +})().catch(e => { console.error(e); process.exit(1); }); diff --git a/e63334287a3deaa3/ironveil/tools/chars/gaits.js b/e63334287a3deaa3/ironveil/tools/chars/gaits.js new file mode 100644 index 00000000..46f1fcc3 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/gaits.js @@ -0,0 +1,33 @@ +// usage: node gaits.js [kind] : the game helper's foot-slide table (tests/measure.mjs method) on chars-test.html +const { chromium } = require(process.env.PLAYWRIGHT || 'playwright'); +(async () => { + const kind = process.argv[2] || 'hero'; + const b = await chromium.launch({ executablePath: process.env.CHROME || undefined, args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'] }); + const p = await b.newPage({ viewport: { width: 200, height: 150 } }); + await p.route('**/*', r => /firebase|googleapis|google-analytics|googletagmanager|gstatic|pagead|adsbygoogle/.test(r.request().url()) ? r.abort() : r.continue()); + p.on('pageerror', e => console.log('pageerror:', String(e).slice(0, 300))); + await p.goto(`http://127.0.0.1:${process.env.PORT || 8981}/e63334287a3deaa3/ironveil/chars-test.html?drive=1&scenario=measure&kind=${kind}&weapon=smg`); + await p.waitForFunction('window.DRIVE && window.DRIVE.a', null, { timeout: 120000 }); + const F = { faceCam: 1 }; + const gaits = [['walk (aiming)', { w: 1, aim: 1 }], ['jog', { w: 1, ...F }], ['sprint', { w: 1, shift: 1 }], ['backward jog', { s: 1, ...F }], + ['strafe left', { a: 1, ...F }], ['strafe right', { d: 1, ...F }], ['diagonal fwd-left', { w: 1, a: 1, ...F }], ['diagonal back-right', { s: 1, d: 1, ...F }], + ['crouch walk', { w: 1, crouch: 1, ...F }], ['between: stick 0.6', { w: 1, stick: 0.6, ...F }], ['between: stick 0.8', { w: 1, stick: 0.8, ...F }], ['prone crawl', { w: 1, prone: 1 }]]; + const cm = x => (x * 100).toFixed(1); + console.log('gait'.padEnd(22), 'speed', 'n', 'median', 'p90', 'max', 'heel/toe'); + for (const [n, k] of gaits) { + const r = await p.evaluate(k => window.GAIT(k), k); + console.log(n.padEnd(22), r.speed.toFixed(2), r.n, cm(r.med), cm(r.p90), cm(r.max), cm(r.heel) + '/' + cm(r.toe)); + } + for (const [n, k] of [['sprint -> stop', { w: 1, shift: 1 }], ['jog -> stop', { w: 1, faceCam: 1 }], ['walk -> stop', { w: 1, aim: 1 }]]) { + const r = await p.evaluate(k => window.GSTOP(k), k); + console.log(n.padEnd(22), 'contacts', r.n, 'max', cm(r.max), 'median', cm(r.med), 'still after', r.still.toFixed(2)); + } + const T = [['steady jog (baseline)', { w: 1, faceCam: 1 }, { w: 1, faceCam: 1 }, 120, 60], ['idle -> walk', {}, { w: 1, aim: 1 }, 60, 60], + ['walk -> jog', { w: 1, aim: 1 }, { w: 1, faceCam: 1 }, 90, 60], ['jog -> sprint', { w: 1, faceCam: 1 }, { w: 1, shift: 1 }, 90, 60], + ['sprint -> stop', { w: 1, shift: 1 }, {}, 120, 60], ['stand -> crouch', {}, { crouch: 1 }, 60, 60], ['crouch -> prone', { crouch: 1 }, { prone: 1 }, 60, 90], + ['prone -> stand', { prone: 1 }, {}, 60, 90], ['aim on (still)', {}, { aim: 1 }, 60, 60], ['aim off (still)', { aim: 1 }, {}, 60, 60], + ['reversal at sprint', { w: 1, shift: 1 }, { s: 1, faceCam: 1 }, 120, 90], ['reversal at jog', { w: 1, faceCam: 1 }, { s: 1, faceCam: 1 }, 120, 90]]; + console.log('\npops (deg at 60 fps)'); + for (const [n, a, c, n1, n2] of T) { const r = await p.evaluate(([a, c, n1, n2]) => window.GPOP(a, c, n1, n2), [a, c, n1, n2]); console.log(n.padEnd(24), r.pop.toFixed(1), '(' + r.bone + ', frame ' + r.frame + ')'); } + await b.close(); +})().catch(e => { console.error(e); process.exit(1); }); diff --git a/e63334287a3deaa3/ironveil/tools/chars/geo.py b/e63334287a3deaa3/ironveil/tools/chars/geo.py new file mode 100644 index 00000000..39ab857b --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/geo.py @@ -0,0 +1,222 @@ +# Geometry helpers for outfits: smoothing, displacement, ring lofts, straps, boxes. +import bpy, bmesh, math +import numpy as np +from mathutils import Vector, Matrix, noise +from mathutils.bvhtree import BVHTree + +def link(ob): + bpy.context.scene.collection.objects.link(ob); return ob + +def mesh_obj(name, verts, faces, smooth=True): + me = bpy.data.meshes.new(name) + me.from_pydata([tuple(v) for v in verts], [], faces) + me.validate() + for p in me.polygons: p.use_smooth = smooth + return link(bpy.data.objects.new(name, me)) + +def coords(me): + a = np.zeros(len(me.vertices) * 3); me.vertices.foreach_get('co', a); return a.reshape(-1, 3) + +def set_coords(me, a): + me.vertices.foreach_set('co', a.reshape(-1)); me.update() + +def normals(me): + me.update() + a = np.zeros(len(me.vertices) * 3) + try: + me.vertices.foreach_get('normal', a) + except Exception: + a = np.array([v.normal for v in me.vertices]).reshape(-1) + return a.reshape(-1, 3) + +def adjacency(me): + nb = [[] for _ in me.vertices] + for e in me.edges: + a, b = e.vertices + nb[a].append(b); nb[b].append(a) + return nb + +def taubin(me, mask, iters=10, lam=0.5, mu=-0.53): + """Smooth only masked verts (mask: float 0..1 per vertex).""" + P = coords(me) + nb = adjacency(me) + idx = [i for i in range(len(P)) if mask[i] > 0] + for it in range(iters * 2): + f = lam if it % 2 == 0 else mu + Q = P.copy() + avg = np.array([P[n].mean(axis=0) if n else P[i] for i, n in enumerate(nb)]) + Q = P + f * np.asarray(mask)[:, None] * (avg - P) + P = Q + set_coords(me, P) + +def diffuse_scalar(me, s, iters=3, fixed=None): + nb = adjacency(me) + s = np.array(s, dtype=float) + for _ in range(iters): + t = s.copy() + for i, n in enumerate(nb): + if fixed is not None and fixed[i]: continue + if n: t[i] = 0.5 * s[i] + 0.5 * s[n].mean() + s = t + return s + +def displace(me, amount): + P = coords(me); N = normals(me) + set_coords(me, P + N * np.asarray(amount)[:, None]) + +def bvh_of(ob): + dg = bpy.context.evaluated_depsgraph_get() + return BVHTree.FromObject(ob, dg) + +def ring_loft(bvh, stations, n=24, close_top=False, close_bottom=False, name='ring', phase=0.0): + """stations: list of (center Vector, axis Vector, offset float or fn(theta), up Vector ref). + Casts rays from center perpendicular to axis; builds a tube.""" + rings = [] + for st in stations: + c, ax, off = st[0], st[1].normalized(), st[2] + ref = st[3] if len(st) > 3 else Vector((0, -1, 0)) + u = (ref - ax * ref.dot(ax)).normalized(); v = ax.cross(u) + ring = [] + for k in range(n): + th = phase + 2 * math.pi * k / n + d = (u * math.cos(th) + v * math.sin(th)) + hit = bvh.ray_cast(c, d, 1.0) + r = (hit[0] - c).length if hit[0] is not None else 0.1 + o = off(th) if callable(off) else off + ring.append(c + d * (r + o)) + rings.append(ring) + verts = [p for r in rings for p in r] + faces = [] + for i in range(len(rings) - 1): + for k in range(n): + a = i * n + k; b = i * n + (k + 1) % n + faces.append([a, b, b + n, a + n]) + if close_bottom: faces.append(list(range(n))[::-1]) + if close_top: faces.append([len(rings) * n - n + k for k in range(n)]) + return mesh_obj(name, verts, faces) + +def solidify(ob, t, offset=-1.0): + m = ob.modifiers.new('sol', 'SOLIDIFY'); m.thickness = t; m.offset = offset; m.use_even_offset = True + apply_mods(ob) + +def bevel(ob, w, seg=1, limit='ANGLE'): + m = ob.modifiers.new('bev', 'BEVEL'); m.width = w; m.segments = seg; m.limit_method = limit + if limit == 'ANGLE': m.angle_limit = math.radians(40) + apply_mods(ob) + +def subsurf(ob, lv=1, simple=False): + m = ob.modifiers.new('ss', 'SUBSURF'); m.levels = lv; m.render_levels = lv + if simple: m.subdivision_type = 'SIMPLE' + apply_mods(ob) + +def apply_mods(ob): + from mhlib import set_active + set_active(ob) + for m in list(ob.modifiers): + if m.type == 'ARMATURE': continue + bpy.ops.object.modifier_apply(modifier=m.name) + +def box(name, size, M, bev=0.004, seg=2): + """Box of size (sx,sy,sz) placed by matrix M (local z = outward normal).""" + bm = bmesh.new() + bmesh.ops.create_cube(bm, size=1.0) + for v in bm.verts: + v.co = Vector((v.co.x * size[0], v.co.y * size[1], v.co.z * size[2])) + if bev > 0: + bmesh.ops.bevel(bm, geom=list(bm.edges), offset=bev, segments=seg, affect='EDGES', profile=0.5) + for v in bm.verts: v.co = M @ v.co + me = bpy.data.meshes.new(name); bm.to_mesh(me); bm.free() + for p in me.polygons: p.use_smooth = True + ob = link(bpy.data.objects.new(name, me)) + ob.data.shade_smooth() if hasattr(ob.data, 'shade_smooth') else None + return ob + +def surface_frame(bvh, origin, direction, up=Vector((0, 0, 1)), push=0.0): + """Ray from origin along direction to the surface; returns matrix with z = normal at hit, y ~ up.""" + hit = bvh.ray_cast(origin, direction.normalized(), 2.0) + if hit[0] is None: return None + p, n = hit[0], hit[1] + if n.dot(direction) > 0: n = -n + n = -direction.normalized() * 0.5 + n * 0.5; n.normalize() + x = up.cross(n).normalized(); y = n.cross(x) + M = Matrix((x, y, n)).transposed().to_4x4() + M.translation = p + n * push + return M + +def strap(bvh, pts, width, offset, name='strap', thick=0.004, steps=40): + """Ribbon following a polyline projected on the body surface.""" + # resample + P = [Vector(p) for p in pts] + L = [0] + for i in range(1, len(P)): L.append(L[-1] + (P[i] - P[i - 1]).length) + tot = L[-1] + samples = [] + for s in range(steps + 1): + d = tot * s / steps + i = max(1, min(len(P) - 1, next((k for k in range(1, len(P)) if L[k] >= d), len(P) - 1))) + t = (d - L[i - 1]) / max(1e-6, (L[i] - L[i - 1])) + samples.append(P[i - 1].lerp(P[i], t)) + proj = [] + for q in samples: + loc, nor, _, _ = bvh.find_nearest(q) + proj.append((loc, nor)) + verts, faces = [], [] + for i, (loc, nor) in enumerate(proj): + a = proj[max(0, i - 1)][0]; b = proj[min(len(proj) - 1, i + 1)][0] + tan = (b - a).normalized() + side = tan.cross(nor).normalized() + base = loc + nor * offset + verts += [base - side * width / 2, base + side * width / 2] + for i in range(len(proj) - 1): + a = 2 * i + faces.append([a, a + 1, a + 3, a + 2]) + ob = mesh_obj(name, verts, faces) + solidify(ob, thick, offset=1.0) + return ob + +def lathe(name, profile, n=32, sx=1.0, sy=1.0, M=None, cap_top=True): + """profile: list of (r, z) from top/inside; revolved around z, scaled in x/y.""" + verts, faces = [], [] + for k in range(n): + th = 2 * math.pi * k / n + for r, z in profile: + verts.append(Vector((r * math.cos(th) * sx, r * math.sin(th) * sy, z))) + m = len(profile) + for k in range(n): + k2 = (k + 1) % n + for j in range(m - 1): + faces.append([k * m + j, k * m + j + 1, k2 * m + j + 1, k2 * m + j]) + if M is not None: verts = [M @ v for v in verts] + return mesh_obj(name, verts, faces) + +def join(obs, name): + from mhlib import set_active + obs = [o for o in obs if o is not None] + set_active(obs[0]) + for o in obs: o.select_set(True) + bpy.ops.object.join() + obs[0].name = name; obs[0].data.name = name + return obs[0] + +def transfer_weights(dst, src): + from mhlib import set_active + for vg in src.vertex_groups: + if vg.name not in dst.vertex_groups: dst.vertex_groups.new(name=vg.name) + m = dst.modifiers.new('dt', 'DATA_TRANSFER') + m.object = src; m.use_vert_data = True + m.data_types_verts = {'VGROUP_WEIGHTS'} + m.vert_mapping = 'POLYINTERP_NEAREST' + m.layers_vgroup_select_src = 'ALL'; m.layers_vgroup_select_dst = 'NAME' + set_active(dst) + bpy.ops.object.modifier_apply(modifier=m.name) + +def rigid_weights(ob, bone): + for vg in list(ob.vertex_groups): ob.vertex_groups.remove(vg) + vg = ob.vertex_groups.new(name=bone) + vg.add(list(range(len(ob.data.vertices))), 1.0, 'REPLACE') + +def set_mat(ob, mat): + ob.data.materials.clear(); ob.data.materials.append(mat) + +def tris(ob): + return sum(len(p.vertices) - 2 for p in ob.data.polygons) diff --git a/e63334287a3deaa3/ironveil/tools/chars/gripopt.js b/e63334287a3deaa3/ironveil/tools/chars/gripopt.js new file mode 100644 index 00000000..0c4ae367 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/gripopt.js @@ -0,0 +1,50 @@ +// usage: node gripopt.js weapon cls upperClip -- searches the per-class grip offset and curl scale in one page +// session and prints the best settings by (hand vertices inside the weapon) + a small cost for moving the weapon. +const { chromium } = require(process.env.PLAYWRIGHT || 'playwright'); +(async () => { + const [w, cls, up, sx] = process.argv.slice(2); + const b = await chromium.launch({ executablePath: process.env.CHROME || undefined, args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'] }); + const p = await b.newPage({ viewport: { width: 200, height: 200 } }); + await p.route('**/*', r => /firebase|googleapis|google-analytics|googletagmanager|gstatic|pagead|adsbygoogle/.test(r.request().url()) ? r.abort() : r.continue()); + await p.goto(`http://127.0.0.1:${process.env.PORT || 8981}/e63334287a3deaa3/ironveil/chars-test.html?shot=1&kind=hero&anim=idle&upper=${up}&t=0.6&weapon=${w}&pen=1`); + await p.waitForFunction('window.READY||window.ERR', null, { timeout: 120000 }); + const res = await p.evaluate(([w, cls, process_start_x]) => { + const a = window.ACTOR, G = IVChars.grips[cls]; + const gun = a.held; + const base = JSON.parse(JSON.stringify(G)); + function evalCfg(roff, loff, rs, ls) { + for (const k of ['index', 'middle', 'ring', 'pinky', 'thumb', 'trigger']) { if (base.r[k] != null) G.r[k] = base.r[k] * rs; if (base.l[k] != null) G.l[k] = base.l[k] * ls; } + G.r.off = roff; G.l.off = loff; + a.attach(gun, 'handR'); + for (let i = 0; i < 3; i++) a.update(1 / 30); + const pen = window.handPen(a, gun); + return pen; + } + // pattern search: try +/- step on each offset axis and on the curl scale; keep improvements; halve the step + function search(side, start) { + let cur = start.slice(), curS = 1, step = 0.008; + const f = (o, sc) => { const pen = side === 'r' ? evalCfg(o, [0, 0, 0], sc, 1) : evalCfg(R.off, o, R.s, sc); + if (Math.max(Math.abs(o[0]), Math.abs(o[1]), Math.abs(o[2])) > 0.045 || sc < 0.5 || sc > 1.4) return { cost: 1e9, pen }; + return { cost: pen[side] + 150 * Math.hypot(o[0], o[1], o[2]) + 20 * Math.abs(sc - 1), pen }; }; + let best = f(cur, curS); + while (step > 0.0015) { + let moved = false; + for (let ax = 0; ax < 4; ax++) for (const sg of [-1, 1]) { + const o = cur.slice(); let sc = curS; + if (ax < 3) o[ax] += sg * step; else sc = Math.max(0.3, curS + sg * step * 15); + const r = f(o, sc); + if (r.cost < best.cost) { best = r; cur = o; curS = sc; moved = true; } + } + if (!moved) step /= 2; + } + return { off: cur.map(x => +x.toFixed(4)), s: +curS.toFixed(2), pen: best.pen }; + } + var R = { off: [0, 0, 0], s: 1 }; + R = search('r', [process_start_x[0] || 0, process_start_x[1] || 0, process_start_x[2] || 0]); + const L = search('l', [0, 0, 0]); + const fin = evalCfg(R.off, L.off, R.s, L.s); + return { roff: R.off, rs: R.s, loff: L.off, ls: L.s, final: { r: fin.r, l: fin.l, by: fin.by } }; + }, [w, cls, (sx || '0').split(':').map(Number)]); + console.log(JSON.stringify(res)); + await b.close(); +})().catch(e => { console.error(e); process.exit(1); }); diff --git a/e63334287a3deaa3/ironveil/tools/chars/handsheet.sh b/e63334287a3deaa3/ironveil/tools/chars/handsheet.sh new file mode 100755 index 00000000..c0980a20 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/handsheet.sh @@ -0,0 +1,12 @@ +#!/bin/bash +# handsheet.sh out.png weapon upper grips-json : three close-ups of each hand +. "$(dirname "$0")/env.sh" +out=$1; w=$2; up=$3; g=$(python3 -c "import urllib.parse,sys;print(urllib.parse.quote(sys.argv[1]))" "${4:-{\}}"); T=$(mktemp -d); i=0 +for c in "cbone=hand_r&cyaw=-90&cpitch=10" "cbone=hand_r&cyaw=180&cpitch=70" "cbone=hand_r&cyaw=-60&cpitch=-50" "cbone=hand_l&cyaw=-90&cpitch=10" "cbone=hand_l&cyaw=90&cpitch=10" "cbone=hand_l&cyaw=-30&cpitch=-60"; do + i=$((i+1)); timeout 200 node "$HERE/shot.js" $T/h$i.png "/e63334287a3deaa3/ironveil/chars-test.html?shot=1&kind=hero&anim=idle&upper=$up&t=0.6&weapon=$w&cdist=0.3&grips=$g&$c" 360 360 >/dev/null +done +python3 -I -c " +import sys +from PIL import Image +ims=[Image.open(sys.argv[2]+'/h%d.png'%i) for i in range(1,7)] +c=Image.new('RGB',(1080,720)); [c.paste(im,((i%3)*360,(i//3)*360)) for i,im in enumerate(ims)]; c.save(sys.argv[1])" $out $T diff --git a/e63334287a3deaa3/ironveil/tools/chars/humans.py b/e63334287a3deaa3/ironveil/tools/chars/humans.py new file mode 100644 index 00000000..6605679b --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/humans.py @@ -0,0 +1,22 @@ +# The MakeHuman build parameters of each character (shared by the build scripts and morphs.py, so morphs match). +# The hero is a wartime raider (HERO.md): lean and athletic, broad shoulders, narrow waist and hips, hard face. +RAIDER_BODY = [('hip/hip-scale-horiz-decr', 0.35), ('hip/hip-scale-depth-decr', 0.3), ('buttocks/buttocks-volume-decr', 0.85), ('stomach/stomach-pregnant-decr', 0.45), + ('torso/torso-vshape-incr', 0.2), ('torso/measure-waist-circ-decr', 0.15), ('torso/torso-muscle-dorsi-incr', 0.15), + ('arms/l-lowerarm-muscle-incr', 0.4), ('arms/r-lowerarm-muscle-incr', 0.4), + ('hands/l-hand-fingers-diameter-incr', 0.15), ('hands/r-hand-fingers-diameter-incr', 0.15), + ('hands/measure-wrist-circ-incr', 0.2)] +HERO = dict(height=0.55, muscle=0.78, weight=0.43, prop=0.85, skin='young_caucasian_male', brows='eyebrow001', + face=RAIDER_BODY + [('head/head-square', 0.45), ('chin/chin-prominent-incr', 0.4), ('chin/chin-width-incr', 0.25), + ('nose/nose-scale-vert-incr', 0.2), ('nose/nose-hump-incr', 0.35), ('mouth/mouth-scale-horiz-decr', 0.1), + ('cheek/l-cheek-bones-incr', 0.55), ('cheek/r-cheek-bones-incr', 0.55), + ('cheek/l-cheek-volume-decr', 0.45), ('cheek/r-cheek-volume-decr', 0.45), + ('eyebrows/eyebrows-trans-down', 0.5), ('eyebrows/eyebrows-angle-down', 0.25), ('neck/neck-scale-horiz-incr', 0.5)]) +ALLY = dict(height=0.45, muscle=0.65, weight=0.55, prop=0.85, skin='middleage_caucasian_male', brows='eyebrow009', + face=[('head/head-round', 0.3), ('nose/nose-scale-horiz-incr', 0.35), ('nose/nose-trans-down', 0.2), ('chin/chin-width-incr', 0.3), + ('mouth/mouth-scale-horiz-incr', 0.2), ('eyebrows/eyebrows-angle-down', 0.3), ('cheek/l-cheek-volume-incr', 0.25), + ('cheek/r-cheek-volume-incr', 0.25)]) +ENEMY = dict(height=0.55, muscle=0.7, weight=0.45, prop=0.8, skin='young_caucasian_male2', brows='eyebrow005', hair='short02', + face=[('head/head-oval', 0.4), ('nose/nose-scale-horiz-decr', 0.3), ('nose/nose-point-width-decr', 0.2), + ('chin/chin-width-decr', 0.3), ('mouth/mouth-scale-horiz-incr', 0.15), ('eyebrows/eyebrows-trans-up', 0.2), + ('cheek/l-cheek-volume-decr', 0.3), ('cheek/r-cheek-volume-decr', 0.3)]) +PARAMS = {'hero': HERO, 'ally': ALLY, 'enemy': ENEMY} diff --git a/e63334287a3deaa3/ironveil/tools/chars/mats.py b/e63334287a3deaa3/ironveil/tools/chars/mats.py new file mode 100644 index 00000000..b7a3d653 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/mats.py @@ -0,0 +1,108 @@ +# Procedural bake materials (Blender nodes). Colors are given as sRGB hex. +import bpy + +def lin(h): + h = h.lstrip('#') + c = [int(h[i:i + 2], 16) / 255 for i in (0, 2, 4)] + return tuple(((x / 12.92) if x <= 0.04045 else ((x + 0.055) / 1.055) ** 2.4) for x in c) + (1.0,) + +def _n(nt, t, loc=(0, 0), **kw): + n = nt.nodes.new(t); n.location = loc + for k, v in kw.items(): setattr(n, k, v) + return n + +def fabric(name, col, col2=None, rough=0.85, scale=18.0, mottle=0.18, dirt=None, dirt_amt=0.0, weave=0.0, + camo=None, image=None, uv='UVMap', metal=0.0, stripes=None): + """col: base sRGB; col2: second tone for large-scale mottling; camo: list of hex for blotch camo; + image: path of an image texture sampled with the given UV map (skin).""" + m = bpy.data.materials.get(name) or bpy.data.materials.new(name) + m.use_nodes = True + nt = m.node_tree; nt.nodes.clear() + out = _n(nt, 'ShaderNodeOutputMaterial', (900, 0)) + bsdf = _n(nt, 'ShaderNodeBsdfPrincipled', (600, 0)) + nt.links.new(bsdf.outputs[0], out.inputs[0]) + bsdf.inputs['Roughness'].default_value = rough + bsdf.inputs['Metallic'].default_value = metal + tc = _n(nt, 'ShaderNodeTexCoord', (-900, 0)) + if image: + uvn = _n(nt, 'ShaderNodeUVMap', (-700, 200)); uvn.uv_map = uv + tex = _n(nt, 'ShaderNodeTexImage', (-400, 200)) + tex.image = bpy.data.images.load(image, check_existing=True) + nt.links.new(uvn.outputs[0], tex.inputs[0]) + base = tex.outputs[0] + if col: # tint (multiply) + mix = _n(nt, 'ShaderNodeMix', (0, 200)); mix.data_type = 'RGBA'; mix.blend_type = 'MULTIPLY' + mix.inputs['Factor'].default_value = 1.0 + nt.links.new(base, mix.inputs[6]); mix.inputs[7].default_value = lin(col) + base = mix.outputs[2] + nt.links.new(base, bsdf.inputs['Base Color']) + return m + # large mottling + nz = _n(nt, 'ShaderNodeTexNoise', (-600, 0)) + nz.inputs['Scale'].default_value = scale * 0.25; nz.inputs['Detail'].default_value = 6.0 + nt.links.new(tc.outputs['Object'], nz.inputs['Vector']) + ramp = _n(nt, 'ShaderNodeValToRGB', (-350, 0)) + ramp.color_ramp.elements[0].position = 0.5 - mottle; ramp.color_ramp.elements[1].position = 0.5 + mottle + ramp.color_ramp.elements[0].color = lin(col) + ramp.color_ramp.elements[1].color = lin(col2 or col) + nt.links.new(nz.outputs['Fac'], ramp.inputs[0]) + base = ramp.outputs[0] + if camo: + vz = _n(nt, 'ShaderNodeTexNoise', (-600, 400)) + vz.inputs['Scale'].default_value = 7.0; vz.inputs['Detail'].default_value = 3.0 + vz.inputs['Roughness'].default_value = 0.55 + nt.links.new(tc.outputs['Object'], vz.inputs['Vector']) + cr = _n(nt, 'ShaderNodeValToRGB', (-350, 400)); cr.color_ramp.interpolation = 'CONSTANT' + els = cr.color_ramp.elements + k = len(camo) + els[0].position = 0.0; els[0].color = lin(camo[0]) + els[1].position = 1.0 / k * 1.0 + 0.32; els[1].color = lin(camo[1]) + for i in range(2, k): + e = els.new(0.32 + i / k * 0.45); e.color = lin(camo[i]) + nt.links.new(vz.outputs['Fac'], cr.inputs[0]) + mixc = _n(nt, 'ShaderNodeMix', (-100, 200)); mixc.data_type = 'RGBA'; mixc.blend_type = 'MULTIPLY' + mixc.inputs['Factor'].default_value = 1.0 + nt.links.new(cr.outputs[0], mixc.inputs[6]) + # base mottle used as brightness variation + bw = _n(nt, 'ShaderNodeMix', (-200, 0)); bw.data_type = 'RGBA'; bw.blend_type = 'MIX' + bw.inputs['Factor'].default_value = 0.0 + nt.links.new(ramp.outputs[0], bw.inputs[6]) + gray = _n(nt, 'ShaderNodeRGBToBW', (-150, -100)); nt.links.new(ramp.outputs[0], gray.inputs[0]) + # normalise: multiply camo by (gray/graybase)*~1 + sc = _n(nt, 'ShaderNodeMath', (-100, -100)); sc.operation = 'MULTIPLY' + b = lin(col); g0 = 0.2126 * b[0] + 0.7152 * b[1] + 0.0722 * b[2] + nt.links.new(gray.outputs[0], sc.inputs[0]); sc.inputs[1].default_value = 1.0 / max(g0, 1e-3) + comb = _n(nt, 'ShaderNodeCombineColor', (-50, -100)) + for i in range(3): nt.links.new(sc.outputs[0], comb.inputs[i]) + nt.links.new(comb.outputs[0], mixc.inputs[7]) + base = mixc.outputs[2] + if weave > 0: + wv = _n(nt, 'ShaderNodeTexWave', (-600, -300)); wv.wave_type = 'BANDS' + wv.inputs['Scale'].default_value = 260.0; wv.inputs['Distortion'].default_value = 2.0 + nt.links.new(tc.outputs['Object'], wv.inputs['Vector']) + mw = _n(nt, 'ShaderNodeMix', (100, 0)); mw.data_type = 'RGBA'; mw.blend_type = 'MULTIPLY' + mw.inputs['Factor'].default_value = weave + nt.links.new(base, mw.inputs[6]); nt.links.new(wv.outputs[0], mw.inputs[7]) + base = mw.outputs[2] + if dirt: + dz = _n(nt, 'ShaderNodeTexNoise', (-600, -600)) + dz.inputs['Scale'].default_value = 3.0; dz.inputs['Detail'].default_value = 8.0 + nt.links.new(tc.outputs['Object'], dz.inputs['Vector']) + sep = _n(nt, 'ShaderNodeSeparateXYZ', (-600, -800)); nt.links.new(tc.outputs['Object'], sep.inputs[0]) + # more dirt low on the body (z small) + mz = _n(nt, 'ShaderNodeMapRange', (-400, -800)) + mz.inputs['From Min'].default_value = 0.0; mz.inputs['From Max'].default_value = 0.9 + mz.inputs['To Min'].default_value = 1.0; mz.inputs['To Max'].default_value = 0.15 + nt.links.new(sep.outputs['Z'], mz.inputs['Value']) + mul = _n(nt, 'ShaderNodeMath', (-250, -700)); mul.operation = 'MULTIPLY' + nt.links.new(dz.outputs['Fac'], mul.inputs[0]); nt.links.new(mz.outputs[0], mul.inputs[1]) + mr = _n(nt, 'ShaderNodeMapRange', (-100, -700)) + mr.inputs['From Min'].default_value = 0.35; mr.inputs['From Max'].default_value = 0.75 + mr.inputs['To Min'].default_value = 0.0; mr.inputs['To Max'].default_value = dirt_amt + nt.links.new(mul.outputs[0], mr.inputs['Value']) + md = _n(nt, 'ShaderNodeMix', (300, -200)); md.data_type = 'RGBA'; md.blend_type = 'MIX' + nt.links.new(mr.outputs[0], md.inputs['Factor']) + nt.links.new(base, md.inputs[6]); md.inputs[7].default_value = lin(dirt) + base = md.outputs[2] + nt.links.new(base, bsdf.inputs['Base Color']) + return m diff --git a/e63334287a3deaa3/ironveil/tools/chars/mhlib.py b/e63334287a3deaa3/ironveil/tools/chars/mhlib.py new file mode 100644 index 00000000..863ac6cd --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/mhlib.py @@ -0,0 +1,396 @@ +# Helpers: build a MakeHuman (CC0 data) human in Blender without MPFB code, +# rig it on the Quaternius UAL skeleton (CC0) so UAL clips play unchanged. +import bpy, bmesh, gzip, json, os, math, random +from mathutils import Vector, Matrix, Quaternion + +WORK = os.environ.get('CHARS_WORK') or os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/work' +MPFB = WORK + '/dl_mpfb/x/mpfb/data' +MHA = WORK + '/dl_mh/x' +UAL1 = WORK + '/dl_ual/UAL1_Standard.glb' +UAL2 = WORK + '/dl_ual/UAL2_Standard.glb' + +def mh2b(x, y, z): # MakeHuman (dm, Y-up, +Z front) -> Blender (m, Z-up, -Y front) + return Vector((x * 0.1, -z * 0.1, y * 0.1)) + +_base = None +def load_base(): + global _base + if _base: return _base + V, VT, F = [], [], [] + for ln in open(MPFB + '/3dobjs/base.obj'): + if ln.startswith('v '): + V.append([float(a) for a in ln.split()[1:4]]) + elif ln.startswith('vt '): + VT.append([float(a) for a in ln.split()[1:3]]) + elif ln.startswith('f '): + parts = [p.split('/') for p in ln.split()[1:]] + F.append(([int(p[0]) - 1 for p in parts], [int(p[1]) - 1 for p in parts])) + _base = (V, VT, F) + return _base + +def read_target(path): + out = [] + op = gzip.open if path.endswith('.gz') else open + with op(path, 'rt') as f: + for ln in f: + ln = ln.strip() + if not ln or ln[0] == '#': continue + a = ln.split() + out.append((int(a[0]), float(a[1]), float(a[2]), float(a[3]))) + return out + +def apply_targets(V, targets): + V = [list(v) for v in V] + for rel, w in targets: + if abs(w) < 1e-6: continue + p = MPFB + '/targets/' + rel + if not p.endswith('.gz'): p += '.target.gz' + for i, dx, dy, dz in read_target(p): + V[i][0] += dx * w; V[i][1] += dy * w; V[i][2] += dz * w + return V + +def macro_targets(height=0.6, muscle=0.6, weight=0.5, prop=0.7, race='caucasian'): + t = [] + # muscle blend between average and max (0.5..1) + mm = max(0.0, (muscle - 0.5) * 2) + ww = (weight - 0.5) * 2 + wnames = [('averageweight', 1 - abs(ww)), ('maxweight' if ww > 0 else 'minweight', abs(ww))] + for mname, mw in [('averagemuscle', 1 - mm), ('maxmuscle', mm)]: + for wname, wgt in wnames: + if mw * wgt > 0: + t.append(('macrodetails/universal-male-young-%s-%s' % (mname, wname), mw * wgt)) + h = (height - 0.5) * 2 + if h: + t.append(('macrodetails/height/male-young-%s-%s-%s' % (mname, wname, 'maxheight' if h > 0 else 'minheight'), mw * wgt * abs(h))) + pp = (prop - 0.5) * 2 + if pp: + t.append(('macrodetails/proportions/male-young-%s-%s-idealproportions' % (mname, wname), mw * wgt * pp)) + t.append(('macrodetails/%s-male-young' % race, 1.0)) + return t + +_groups = None +def vgroups(): + global _groups + if not _groups: + _groups = json.load(open(MPFB + '/mesh_metadata/basemesh_vertex_groups.json')) + return _groups + +def group_verts(name): + out = [] + for a, b in vgroups()[name]: + out.extend(range(a, b + 1)) + return out + +def joint_pos(V, cube): + idx = group_verts(cube) + s = Vector() + for i in idx: s += mh2b(*V[i]) + return s / len(idx) + +def make_body_mesh(name, V): + """Body (no helpers) as a Blender mesh with MH UVs. Returns obj and map newidx->baseidx.""" + _, VT, F = load_base() + body = set(group_verts('body')) + used = sorted(body) + remap = {b: i for i, b in enumerate(used)} + faces, fuv = [], [] + for fv, ft in F: + if all(v in body for v in fv): + faces.append([remap[v] for v in fv]); fuv.append(ft) + me = bpy.data.meshes.new(name) + me.from_pydata([mh2b(*V[b]) for b in used], [], faces) + uv = me.uv_layers.new(name='UVMap') + k = 0 + for p, ft in zip(me.polygons, fuv): + for li, t in zip(p.loop_indices, ft): + uv.data[li].uv = VT[t] + for p in me.polygons: p.use_smooth = True + ob = bpy.data.objects.new(name, me) + bpy.context.scene.collection.objects.link(ob) + return ob, used + +def load_obj_simple(path): + V, VT, F = [], [], [] + for ln in open(path): + if ln.startswith('v '): V.append([float(a) for a in ln.split()[1:4]]) + elif ln.startswith('vt '): VT.append([float(a) for a in ln.split()[1:3]]) + elif ln.startswith('f '): + parts = [p.split('/') for p in ln.split()[1:]] + F.append(([int(p[0]) - 1 for p in parts], [int(p[1]) - 1 if len(p) > 1 and p[1] else 0 for p in parts])) + return V, VT, F + +def fit_mhclo(path, V, name): + """Fit a MakeHuman proxy (eyes, brows, lashes, hair) to morphed base verts V. Returns obj and refs.""" + d = os.path.dirname(path) + refs, scales = [], {} + objf = None + inverts = False + for ln in open(path): + s = ln.strip() + if not s or s.startswith('#'): continue + a = s.split() + if a[0] in ('x_scale', 'y_scale', 'z_scale'): + scales[a[0][0]] = (int(a[1]), int(a[2]), float(a[3])) + elif a[0] == 'obj_file': + objf = a[1] + elif a[0] == 'verts': + inverts = True + elif inverts and a[0][0].isdigit(): + if len(a) == 1: + refs.append(([int(a[0])], [1.0], (0, 0, 0))) + else: + refs.append(([int(a[0]), int(a[1]), int(a[2])], [float(a[3]), float(a[4]), float(a[5])], (float(a[6]), float(a[7]), float(a[8])))) + elif inverts and not a[0][0].isdigit() and a[0] not in ('verts',): + if a[0] in ('weights', 'delete_verts'): inverts = False + def sc(ax): + if ax not in scales: return 1.0 + i, j, den = scales[ax] + k = 'xyz'.index(ax) + return abs(V[i][k] - V[j][k]) / den + sx, sy, sz = sc('x'), sc('y'), sc('z') + OV, OVT, OF = load_obj_simple(d + '/' + objf) + pts = [] + for vi, ws, off in refs: + p = [0.0, 0.0, 0.0] + for v, w in zip(vi, ws): + for k in range(3): p[k] += V[v][k] * w + p[0] += off[0] * sx; p[1] += off[1] * sy; p[2] += off[2] * sz + pts.append(mh2b(*p)) + me = bpy.data.meshes.new(name) + me.from_pydata(pts, [], [f for f, _ in OF]) + uv = me.uv_layers.new(name='UVMap') + for p, (_, ft) in zip(me.polygons, OF): + for li, t in zip(p.loop_indices, ft): + uv.data[li].uv = OVT[t] if OVT else (0, 0) + for p in me.polygons: p.use_smooth = True + ob = bpy.data.objects.new(name, me) + bpy.context.scene.collection.objects.link(ob) + return ob, refs + +def set_active(ob): + for o in bpy.context.scene.objects: + if o is not None: o.select_set(False) + bpy.context.view_layer.objects.active = ob + ob.select_set(True) + +def build_mh_armature(V, name='MHRig'): + rig = json.load(open(MPFB + '/rigs/standard/rig.game_engine.json')) + arm = bpy.data.armatures.new(name) + ob = bpy.data.objects.new(name, arm) + bpy.context.scene.collection.objects.link(ob) + set_active(ob) + bpy.ops.object.mode_set(mode='EDIT') + for bn, d in rig.items(): + eb = arm.edit_bones.new(bn) + eb.head = joint_pos(V, d['head']['cube_name']) + if d['tail']['strategy'] == 'CUBE': + eb.tail = joint_pos(V, d['tail']['cube_name']) + else: + s = Vector() + for i in d['tail']['vertex_indices']: s += mh2b(*V[i]) + eb.tail = s / len(d['tail']['vertex_indices']) + if (eb.tail - eb.head).length < 1e-4: eb.tail = eb.head + Vector((0, 0, 0.05)) + eb.roll = d['roll'] + for bn, d in rig.items(): + if d['parent']: + arm.edit_bones[bn].parent = arm.edit_bones[d['parent']] + bpy.ops.object.mode_set(mode='OBJECT') + return ob + +_w = None +def mh_weights(): + global _w + if not _w: + _w = json.load(open(MPFB + '/rigs/standard/weights.game_engine.json'))['weights'] + return _w + +def add_body_weights(ob, used): + W = mh_weights() + remap = {b: i for i, b in enumerate(used)} + for bn, lst in W.items(): + vg = ob.vertex_groups.get(bn) or ob.vertex_groups.new(name=bn) + for vi, w in lst: + if vi in remap: vg.add([remap[vi]], w, 'REPLACE') + +def add_proxy_weights(ob, refs): + W = mh_weights() + per = {} + for bn, lst in W.items(): + for vi, w in lst: + per.setdefault(vi, {})[bn] = w + for pi, (vi, ws, _) in enumerate(refs): + acc = {} + for v, w in zip(vi, ws): + for bn, bw in per.get(v, {}).items(): + acc[bn] = acc.get(bn, 0) + bw * w + for bn, w in acc.items(): + if w < 1e-4: continue + vg = ob.vertex_groups.get(bn) or ob.vertex_groups.new(name=bn) + vg.add([pi], w, 'REPLACE') + +def import_ual(path=UAL1): + before = set(bpy.data.objects) + bpy.ops.import_scene.gltf(filepath=path) + new = [o for o in bpy.data.objects if o not in before] + arm = [o for o in new if o.type == 'ARMATURE'][0] + for o in new: + if o.type == 'MESH': bpy.data.objects.remove(o) + return arm + +NAME_MAP = {'Root': 'root', 'head': 'Head'} +def ual_name(mh): + return NAME_MAP.get(mh, mh) + +def repose_to(mhrig, ual, meshes): + """Pose MH rig so each bone points like the UAL rest bone, then bake into meshes and make it rest.""" + set_active(mhrig) + bpy.ops.object.mode_set(mode='POSE') + ub = ual.data.bones + uw = ual.matrix_world + order = [] + def walk(b): + order.append(b.name) + for c in b.children: walk(c) + for b in mhrig.data.bones: + if b.parent is None: walk(b) + for bn in order: + un = ual_name(bn) + if un not in ub or bn == 'Root': continue + pb = mhrig.pose.bones[bn] + bpy.context.view_layer.update() + cur = (pb.tail - pb.head).normalized() + u = ub[un] + want = ((uw @ u.tail_local) - (uw @ u.head_local)).normalized() + q = cur.rotation_difference(want) + M = pb.matrix.copy() + h = M.to_translation() + R = q.to_matrix().to_4x4() @ Matrix(M.to_3x3()).to_4x4() + R.translation = h + pb.matrix = R + bpy.context.view_layer.update() + # twist forearms so the knuckle line matches UAL (palms down) + for side in 'lr': + pb = mhrig.pose.bones['lowerarm_' + side] + bpy.context.view_layer.update() + P = mhrig.pose.bones + cur = (P['pinky_01_' + side].head - P['index_01_' + side].head) + axis = (pb.tail - pb.head).normalized() + want = (uw @ ub['pinky_01_' + side].head_local) - (uw @ ub['index_01_' + side].head_local) + c = (cur - axis * cur.dot(axis)).normalized(); w2 = (want - axis * want.dot(axis)).normalized() + ang = math.atan2(axis.dot(c.cross(w2)), c.dot(w2)) + M = pb.matrix.copy(); h = M.to_translation() + R = Quaternion(axis, ang).to_matrix().to_4x4() @ Matrix(M.to_3x3()).to_4x4(); R.translation = h + pb.matrix = R + bpy.context.view_layer.update() + # re-aim hand and fingers after twist + for bn in ['hand_' + side] + [f + '_0%d_' % i + side for f in ('index', 'middle', 'ring', 'pinky', 'thumb') for i in (1, 2, 3)]: + pb2 = P[bn]; bpy.context.view_layer.update() + cur = (pb2.tail - pb2.head).normalized(); u = ub[ual_name(bn)] + want = ((uw @ u.tail_local) - (uw @ u.head_local)).normalized() + q = cur.rotation_difference(want) + M = pb2.matrix.copy(); h = M.to_translation() + R = q.to_matrix().to_4x4() @ Matrix(M.to_3x3()).to_4x4(); R.translation = h + pb2.matrix = R + bpy.context.view_layer.update() + bpy.ops.object.mode_set(mode='OBJECT') + for m in meshes: + mod = m.modifiers.new('arm', 'ARMATURE'); mod.object = mhrig + set_active(m) + bpy.ops.object.modifier_apply(modifier=mod.name) + # posed joint positions + J = {} + for pb in mhrig.pose.bones: + J[pb.name] = (mhrig.matrix_world @ pb.head, mhrig.matrix_world @ pb.tail) + return J + +def make_final_rig(ual, J, name='Armature'): + """Copy the UAL armature and move its joints to the MH joint positions (orientations unchanged).""" + ob = ual.copy(); ob.data = ual.data.copy(); ob.name = name; ob.data.name = name + ob.animation_data_clear() + bpy.context.scene.collection.objects.link(ob) + set_active(ob) + bpy.ops.object.mode_set(mode='EDIT') + eb = ob.data.edit_bones + inv = ob.matrix_world.inverted() + info = {} + for b in eb: + info[b.name] = (b.head.copy(), b.tail.copy(), b.roll, b.parent.name if b.parent else None, b.use_connect) + for b in eb: b.use_connect = False + mh_of = {ual_name(k): k for k in J} + newhead = {} + for b in eb: + if b.name in mh_of: + newhead[b.name] = inv @ J[mh_of[b.name]][0] + for b in eb: + if b.name not in newhead: + # leaf bones: put at the parent's MH tail + p = b.parent + if p is not None and p.name in mh_of: + newhead[b.name] = inv @ J[mh_of[p.name]][1] + else: + newhead[b.name] = b.head.copy() + for b in eb: + h0, t0, roll, par, con = info[b.name] + d = (t0 - h0) + L0 = d.length + # new length = distance to a child joint if there is one, else scale old + kids = [c for c in b.children] + if kids: + L = (newhead[kids[0].name] - newhead[b.name]).length + if b.name == 'root' or L < 1e-3: L = L0 + elif b.name in mh_of: + L = (J[mh_of[b.name]][1] - J[mh_of[b.name]][0]).length + else: + L = L0 * 0.9 + b.head = newhead[b.name] + b.tail = newhead[b.name] + d.normalized() * max(L, 0.01) + b.roll = roll + hr = eb['hand_r'] + w = eb.new('weapon_r') + w.head = hr.head.copy(); w.tail = hr.tail.copy(); w.roll = hr.roll; w.parent = hr + bpy.ops.object.mode_set(mode='OBJECT') + return ob + +def bind(meshes, rig): + for m in meshes: + for v in list(m.vertex_groups): + if v.name in NAME_MAP: v.name = NAME_MAP[v.name] + m.parent = rig + mod = m.modifiers.new('Armature', 'ARMATURE'); mod.object = rig + +def build_human(height=0.5, muscle=0.72, weight=0.45, prop=0.8, face=(), skin='young_caucasian_male', + brows='eyebrow001', hair='short02', seed=1): + """Returns dict(rig, body, eyes, brows, lashes, hair, J, skin_png). Body is in UAL T-pose, feet at z=0.""" + import glob + ual = import_ual(UAL1); ual.name = 'UAL' + V0, VT, F = load_base() + V = apply_targets(V0, macro_targets(height, muscle, weight, prop) + list(face)) + body, used = make_body_mesh('Body', V) + add_body_weights(body, used) + parts = {'body': body} + for path, nm in [(MHA + '/eyes/low-poly/low-poly.mhclo', 'eyes'), + (MHA + '/eyebrows/%s/%s.mhclo' % (brows, brows), 'brows'), + (MHA + '/eyelashes/eyelashes01/eyelashes01.mhclo', 'lashes')] + \ + ([(MHA + '/hair/%s/%s.mhclo' % (hair, hair), 'hair')] if hair else []): + ob, refs = fit_mhclo(path, V, nm.capitalize()) + add_proxy_weights(ob, refs) + parts[nm] = ob + mh = build_mh_armature(V) + J = repose_to(mh, ual, list(parts.values())) + minz = min(v.co.z for v in body.data.vertices) + for p in parts.values(): + for v in p.data.vertices: v.co.z -= minz + J = {k: (h - Vector((0, 0, minz)), t - Vector((0, 0, minz))) for k, (h, t) in J.items()} + rig = make_final_rig(ual, J) + bpy.data.objects.remove(mh) + for p in parts.values(): + for v in list(p.vertex_groups): + if v.name in NAME_MAP: v.name = NAME_MAP[v.name] + parts['rig'] = rig; parts['ual'] = ual + parts['J'] = {ual_name(k): v for k, v in J.items()} + parts['skin_png'] = glob.glob(MHA + '/skins/%s/*.png' % skin)[0] + parts['brows_png'] = MHA + '/eyebrows/%s/%s.png' % (brows, brows) + parts['lashes_png'] = MHA + '/eyelashes/eyelashes01/eyelashes01.png' + parts['hair_png'] = glob.glob(MHA + '/hair/%s/*diffuse*.png' % hair)[0] if hair else None + parts['eye_png'] = MHA + '/eyes/materials/brown_eye.png' + return parts diff --git a/e63334287a3deaa3/ironveil/tools/chars/mocap.py b/e63334287a3deaa3/ironveil/tools/chars/mocap.py new file mode 100644 index 00000000..1a7c16e8 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/mocap.py @@ -0,0 +1,437 @@ +# Retarget CMU motion capture onto the shared UAL-named skeleton as clean, in-place locomotion loops. +# +# Works on joint positions (amc.py forward kinematics), then poses our rig with aim constraints and two-bone IK: +# 1. cut a segment of a take, optionally mirror it (swap left and right), turn it so the body faces -Y +# 2. find foot contacts; pick the left-contact -> left-contact cycle that loops best, remove the residual drift +# 3. warp time so the left foot lands at phase 0 and the right foot at phase 0.5 +# 4. scale to our leg length; optionally turn the hips toward a travel direction (derived diagonals) or lower the pelvis +# 5. pin every planted foot on a straight line moving at exactly -velocity (no sliding in the bake); spread the +# correction over the swing so the swing still lands where the pin needs it +# 6. pose the rig frame by frame (pelvis frame, spine/neck/head aims, arm IK with elbow poles, leg IK with knee poles) +import math, numpy as np +from mathutils import Vector, Quaternion, Matrix +import amc + +FWD = Vector((0, -1, 0)); LEFT = Vector((1, 0, 0)); UP = Vector((0, 0, 1)) +SIDED = ['hipjoint', 'femur', 'tibia', 'foot', 'toes', 'clavicle', 'humerus', 'radius', 'wrist', 'hand', 'fingers', 'thumb'] +# Capture rate: most subjects are 120 Hz; these were recorded at 60 Hz (checked: vertical hip acceleration in the +# flight phase of their runs is about 4 g when read as 120 Hz, and their walking cadence is double a human one). +RATE60 = {'139', '141', '143'} +UPPER = ['lowerback', 'upperback', 'thorax', 'lowerneck', 'upperneck', 'head'] + [s + n for s in 'lr' for n in ('clavicle', 'humerus', 'radius', 'wrist', 'hand', 'fingers', 'thumb')] + +def smooth01(a, b, t): + x = max(0.0, min(1.0, (t - a) / (b - a))); return x * x * (3 - 2 * x) + +def V(a): return Vector((float(a[0]), float(a[1]), float(a[2]))) + +class Take: + """A segment of a CMU trial as joint start/end positions, facing -Y, in metres (Z up).""" + def __init__(self, data_dir, trial, t0, t1, mirror=False, fps=60): + s = trial.split('_')[0] + self.sk = amc.Skel(data_dir + s + '.asf') + cap = 60 if s in RATE60 else 120 + F, _ = amc.load(data_dir + s + '.asf', data_dir + trial + '.amc', step=max(1, int(round(cap / fps)))) + self.fps = cap / max(1, int(round(cap / fps))) + i0, i1 = int(t0 * self.fps), min(len(F) - 1, int(t1 * self.fps)) + F = F[i0:i1 + 1] + self.n = len(F) + J = {nm: [np.array([f[nm][k] for f in F]) for k in (0, 1)] for nm in F[0]} + self.leg = self.sk.bones['lfemur']['len'] + self.sk.bones['ltibia']['len'] + if mirror: + def sw(n): + for b in SIDED: + if n == 'l' + b: return 'r' + b + if n == 'r' + b: return 'l' + b + return n + J2 = {} + for n, (a, b) in J.items(): + a = a.copy(); b = b.copy(); a[:, 0] *= -1; b[:, 0] *= -1 + J2[sw(n)] = [a, b] + J = J2 + L = J['lfemur'][0]; R = J['rfemur'][0] + left = (L - R).mean(0); left[2] = 0; left /= np.linalg.norm(left) + fwd = np.cross(left, [0, 0, 1]) + ang = math.atan2(fwd[0], -fwd[1]) + c, sn = math.cos(-ang), math.sin(-ang) + Rz = np.array([[c, -sn, 0], [sn, c, 0], [0, 0, 1]]) + for n in J: J[n] = [J[n][0] @ Rz.T, J[n][1] @ Rz.T] + self.J = J + self.mid = (J['lfemur'][0] + J['rfemur'][0]) / 2 + tt = np.arange(self.n) / self.fps + self.vel = np.array([np.polyfit(tt, self.mid[:, 0], 1)[0], np.polyfit(tt, self.mid[:, 1], 1)[0], 0.0]) + + def foot_pts(self, s): + return self.J[s + 'foot'][0], self.J[s + 'toes'][0], self.J[s + 'toes'][1] # ankle, ball, toe tip + + def contacts(self, s): + an, ba, tip = self.foot_pts(s) + sp = np.r_[0, np.linalg.norm(np.diff(ba[:, :2], axis=0), axis=1) * self.fps] + spa = np.r_[0, np.linalg.norm(np.diff(an[:, :2], axis=0), axis=1) * self.fps] + v = max(0.3, float(np.linalg.norm(self.vel))) + lowb = ba[:, 2] < np.percentile(ba[:, 2], 8) + 0.035 + lowa = an[:, 2] < np.percentile(an[:, 2], 8) + 0.035 + c = (lowb | lowa) & (np.minimum(sp, spa) < 0.2 + 0.25 * v) + # close one-frame gaps, drop one-frame blips + for i in range(1, self.n - 1): + if not c[i] and c[i - 1] and c[i + 1]: c[i] = True + for i in range(1, self.n - 1): + if c[i] and not c[i - 1] and not c[i + 1]: c[i] = False + return c + + def strikes(self, s): + c = self.contacts(s) + return [i for i in range(1, self.n) if c[i] and not c[i - 1]] + + def best_cycle(self): + """(a, r, b, shift): strikes of one foot at a and b, the other foot at r. shift 0.5 when the cycle starts on the + right foot (output phase 0 is always the left contact).""" + Ls, Rs = self.strikes('l'), self.strikes('r') + best = None + P = self.inplace_all() + for A_, B_, shift in ((Ls, Rs, 0.0), (Rs, Ls, 0.5)): + for a, b in zip(A_, A_[1:]): + r = [x for x in B_ if a < x < b] + if len(r) != 1: continue + d = sum(float(np.linalg.norm(P[n][b] - P[n][a])) for n in ('lfoot', 'rfoot', 'lwrist', 'rwrist', 'head')) + score = d + 0.002 * abs((a + b) / 2 - self.n / 2) + shift * 0.01 + if best is None or score < best[0]: best = (score, a, r[0], b, shift) + if best is None: raise RuntimeError('no full cycle: strikes L %s R %s' % (Ls, Rs)) + return best[1:] + + def inplace_all(self): + tt = np.arange(self.n) / self.fps + drift = np.outer(tt, self.vel) + drift -= drift.mean(0) + return {n: self.J[n][0] - drift - np.r_[self.mid[:, :2].mean(0), 0] for n in self.J} | \ + {n + '>': self.J[n][1] - drift - np.r_[self.mid[:, :2].mean(0), 0] for n in self.J} + + +def build_cycle(tk, our_leg, ank_rest_z, theta=None, hip_yaw=0.0, crouch=0.0, crouch_lean=0.0, n_out=None, out_fps=30, + speed_scale=1.0, stride_scale=1.0, cycle=None, foot_len=None): + """Returns (frames, T, speed, theta_deg): frames = list of dict joint -> Vector (our scale, in place, -Y forward).""" + a, r, b, shift = cycle or tk.best_cycle() + P = tk.inplace_all() + k = our_leg / tk.leg + src_T = (b - a) / tk.fps + v_src = tk.vel * k + th_src = math.degrees(math.atan2(v_src[0], -v_src[1])) + th = th_src if theta is None else theta + n = n_out or max(8, int(round(src_T / speed_scale * out_fps))) + T = n / out_fps # whole frames at the clip rate, so the loop closes exactly + speed = float(np.linalg.norm(v_src[:2])) + dist = speed * src_T * stride_scale # metres per cycle + vel = Vector((math.sin(math.radians(th)), -math.cos(math.radians(th)), 0)) * dist / T + # floor: ball height while planted + cl, cr = tk.contacts('l'), tk.contacts('r') + names = [nm for nm in P] + seam = {nm: P[nm][b] - P[nm][a] for nm in names} + + def src_at(p): + p = (p + shift) % 1.0 + f = a + (r - a) * 2 * p if p < 0.5 else r + (b - r) * (2 * p - 1) + i = int(math.floor(f)); u = f - i; i2 = min(i + 1, tk.n - 1) + lin = (f - a) / (b - a) + return {nm: (P[nm][i] * (1 - u) + P[nm][i2] * u) - seam[nm] * lin for nm in names}, f + + raw = [src_at(i / n) for i in range(n)] + # contact flags in output phase + def cflag(c, f): + i = int(round(f)); return bool(c[min(max(i, 0), tk.n - 1)]) + flags = {'l': [cflag(cl, f) for _, f in raw], 'r': [cflag(cr, f) for _, f in raw]} + # make sure each foot is planted at its own strike frame (phase 0 left, 0.5 right) + flags['l'][0] = True; flags['r'][n // 2] = True + # longer steps (stride_scale): feet and knees move further from the hips along the travel line + if abs(stride_scale - 1) > 1e-3: + dvec = np.array([math.sin(math.radians(th)), -math.cos(math.radians(th)), 0.0]) + for J, f in raw: + hm = (J['lfemur'] + J['rfemur']) / 2 + for nm in list(J): + base = nm.rstrip('>') + w = 1.0 if base[1:] in ('foot', 'toes') or nm in ('ltibia>', 'rtibia>') else (0.5 if base[1:] == 'tibia' else 0.0) + if base[0] not in 'lr' or not w: continue + along = float((J[nm] - hm) @ dvec) + J[nm] = J[nm] + dvec * along * (stride_scale - 1) * w + ball_z = [] + for s in 'lr': + for i in range(n): + if flags[s][i]: ball_z.append(raw[i][0][s + 'toes'][2]) + floor = float(np.median(ball_z)) if ball_z else 0.0 + # scale about the hips' ground point; then lift so the planted ankle sits at our rest ankle height + frames = [] + for (J, f) in raw: + F = {} + for nm, p in J.items(): + q = np.array(p, dtype=float); q[2] -= floor + F[nm] = Vector(q * k) + frames.append(F) + # our foot length: keep the captured ankle->ball direction, put the ball where our ball is + if foot_len: + for F in frames: + for s in 'lr': + an, to, tip = F[s + 'foot'], F[s + 'toes'], F[s + 'toes>'] + nb = an + (to - an).normalized() * foot_len + F[s + 'toes>'] = tip + (nb - to); F[s + 'toes'] = nb + # floor: the ball sits at our rest ball height (1 cm) when the foot is flat in stance + bz = [] + for s in 'lr': + for i in range(n): + if flags[s][i]: bz.append(frames[i][s + 'toes'].z) + dz = 0.012 - float(np.percentile(bz, 25)) + for F in frames: + for nm in F: F[nm].z += dz + # derived directions: turn the hips (and legs) toward travel, counter-turn the upper body progressively + TW = {'lowerback>': 0.55, 'upperback': 0.55, 'upperback>': 0.2, 'thorax': 0.2} + def share(nm): + if nm in TW: return TW[nm] + if nm.rstrip('>') in UPPER and nm != 'lowerback': return 0.0 + return 1.0 + if abs(hip_yaw) > 1e-4: + for F in frames: + piv = (F['lfemur'] + F['rfemur']) / 2; piv.z = 0 + for nm in list(F): + amt = share(nm) + if amt: F[nm] = piv + Quaternion(UP, hip_yaw * amt) @ (F[nm] - piv) + # crouch: lower everything above the ankles (legs solve it with IK later), pitch the trunk forward about the hips + if crouch > 0: + FEET = ('lfoot', 'rfoot', 'ltoes', 'rtoes', 'ltoes>', 'rtoes>', 'lfoot>', 'rfoot>', 'ltibia>', 'rtibia>') + for F in frames: + for nm in list(F): + if nm in FEET: continue + F[nm] = F[nm] - Vector((0, 0, crouch)) + if crouch_lean: + piv = (F['lfemur'] + F['rfemur']) / 2 + for nm in list(F): + amt = 1.0 - share(nm) if nm.rstrip('>') in UPPER or nm in TW else 0.0 + if nm.rstrip('>') in UPPER and nm != 'lowerback': amt = 1.0 + if amt: F[nm] = piv + Quaternion(LEFT, crouch_lean * amt) @ (F[nm] - piv) + # contact flags as the feet actually behave: a foot counts as planted while its ball or heel is within a couple of + # centimetres of the floor next to a detected contact (so heel-off to toe-off is pinned too); small gaps closed + for s in 'lr': + fl = flags[s]; orig = list(fl) + bzs = [F[s + 'toes'].z for F in frames]; azs = [F[s + 'foot'].z for F in frames] + bmin, amin = min(bzs), min(azs) + low = [bzs[j] <= bmin + 0.022 or azs[j] <= amin + 0.02 for j in range(n)] + for _ in range(n): + ch = False + for j in range(n): + if not fl[j] and low[j] and (fl[(j - 1) % n] or fl[(j + 1) % n]): fl[j] = True; ch = True + if not ch: break + for gap in (1, 2, 3, 4): + for j in range(n): + if fl[j] and not fl[(j + 1) % n] and fl[(j + gap + 1) % n]: + for g in range(1, gap + 1): fl[(j + g) % n] = True + if sum(fl) > 0.72 * n or all(fl): # a shuffling foot that never clears the floor: keep the detected contacts + fl[:] = orig + # foot pinning: each planted foot moves at exactly -vel (in place) on a straight line + dt = T / n + for s in 'lr': + fl = flags[s] + corr = [None] * n + i = 0 + # contact runs (cyclic) + runs = [] + start = None + for j in range(n): + if fl[j] and (j == 0 or not fl[j - 1]): start = j + if fl[j] and (j == n - 1 or not fl[j + 1]): runs.append((start, j)) + if len(runs) >= 2 and runs[0][0] == 0 and runs[-1][1] == n - 1: + runs = [(runs[-1][0] - n, runs[0][1])] + runs[1:-1] + for (j0, j1) in runs: + jm = (j0 + j1) // 2 + ref = {nm: frames[jm % n][s + nm] for nm in ('foot', 'toes', 'toes>')} + for j in range(j0, j1 + 1): + jj = j % n + # pin the heel (ankle) while the foot is flat, the ball once the heel has lifted + drift = vel * ((j - jm) * dt) + ca = (ref['foot'] - drift) - frames[jj][s + 'foot'] + cb = (ref['toes'] - drift) - frames[jj][s + 'toes'] + w = min(1.0, max(0.0, (frames[jj][s + 'foot'].z - ank_rest_z - 0.01) / 0.04)) + c = ca.lerp(cb, w); c.z = 0 + corr[jj] = c + # interpolate corrections across swings (cyclic), smoothstep + known = [j for j in range(n) if corr[j] is not None] + if not known: continue + for j in range(n): + if corr[j] is not None: continue + prv = max([x for x in known if x < j], default=known[-1] - n) + nxt = min([x for x in known if x > j], default=known[0] + n) + u = (j - prv) / (nxt - prv); u = u * u * (3 - 2 * u) + corr[j] = corr[prv % n].lerp(corr[nxt % n], u) + for j in range(n): + for nm in ('foot', 'toes', 'toes>', 'tibia>'): + key = s + nm + if key in frames[j]: frames[j][key] = frames[j][key] + corr[j] + # planted heel/ball never under the floor + for j in range(n): + for nm in ('toes', 'toes>'): + p = frames[j][s + nm] + if p.z < 0.01: frames[j][s + nm] = Vector((p.x, p.y, 0.01)) + # flat-foot stance: while heel and ball are both down the whole foot is held (ankle pinned, foot direction + # frozen), so neither the heel nor the ball creeps; before that the heel is the pivot (heel strike), after it + # the ball is (heel off). Every pinned point moves at exactly -vel in place. + for s in 'lr': + fl = flags[s] + runs = []; start = None + for j in range(n): + if fl[j] and (j == 0 or not fl[j - 1]): start = j + if fl[j] and (j == n - 1 or not fl[j + 1]): runs.append((start, j)) + if len(runs) >= 2 and runs[0][0] == 0 and runs[-1][1] == n - 1: + runs = [(runs[-1][0] - n, runs[0][1])] + runs[1:-1] + for (j0, j1) in runs: + idx = list(range(j0, j1 + 1)) + az = [frames[j % n][s + 'foot'].z for j in idx]; bz = [frames[j % n][s + 'toes'].z for j in idx] + amin, bmin = min(az), min(bz) + flat = [a <= amin + 0.012 and b <= bmin + 0.012 for a, b in zip(az, bz)] + if not any(flat): continue + f0 = flat.index(True); f1 = len(flat) - 1 - flat[::-1].index(True) + J0, J1 = idx[f0], idx[f1] + A0 = frames[J0 % n][s + 'foot'].copy() + fd = frames[J0 % n][s + 'toes'] - A0; fd.z = min(fd.z, 0.0); fd = fd.normalized() * (frames[J0 % n][s + 'toes'] - A0).length + for j in idx: + F = frames[j % n] + tip_off = F[s + 'toes>'] - F[s + 'toes'] + rel = F[s + 'toes'] - F[s + 'foot'] + ball_first = (F[s + 'toes'].z - bmin) < (F[s + 'foot'].z - amin) # which end is on the floor + if j < J0: # landing: the end that touched first is the pivot (heel walking forward, toe backing) + if ball_first: + to = A0 + fd - vel * ((j - J0) * dt); to.z = F[s + 'toes'].z; an = to - rel + else: + an = A0 - vel * ((j - J0) * dt); an.z = F[s + 'foot'].z; to = an + rel + elif j <= J1: # flat + an = A0 - vel * ((j - J0) * dt); to = an + fd + else: # leaving: the end still on the floor is the pivot + if ball_first: + B1 = A0 + fd - vel * ((J1 - J0) * dt) + to = B1 - vel * ((j - J1) * dt); to.z = F[s + 'toes'].z; an = to - rel + else: + an = A0 - vel * ((j - J0) * dt); an.z = F[s + 'foot'].z; to = an + rel + F[s + 'foot'] = an; F[s + 'toes'] = to; F[s + 'toes>'] = to + tip_off + # swing clearance: a swinging foot lifts at least 5 cm (heel) / 4 cm (ball) at mid-swing, so a shuffled side step + # never drags along the ground (and is not mistaken for a sliding contact) + for s in 'lr': + fl = flags[s] + amin = min(F[s + 'foot'].z for F in frames); bmin = min(F[s + 'toes'].z for F in frames) + j = 0 + sw = [] + for j in range(n): + if not fl[j] and fl[(j - 1) % n]: + k = j; L_ = 0 + while not fl[k % n] and L_ < n: k += 1; L_ += 1 + sw.append((j, L_)) + for j0, L_ in sw: + for i in range(L_): + u = (i + 1) / (L_ + 1); env = math.sin(math.pi * u) + F = frames[(j0 + i) % n] + da = max(0.0, amin + 0.05 * env - F[s + 'foot'].z); db = max(0.0, bmin + 0.04 * env - F[s + 'toes'].z) + lift = max(da, db) + if lift > 0: + for nm in ('foot', 'toes', 'toes>'): + F[s + nm] = F[s + nm] + Vector((0, 0, lift)) + # swing ends: the foot travels with the planted line for the first part of the swing (it leaves the floor + # before it moves forward) and reaches its landing spot before the last part (it comes down, it does not skid in) + for s in 'lr': + fl = flags[s] + sw = [] + for j in range(n): + if not fl[j] and fl[(j - 1) % n]: + k = j; L_ = 0 + while not fl[k % n] and L_ < n: k += 1; L_ += 1 + sw.append((j, L_)) + if vel.length > 4.5: break # not for the sprint (its swing is short and fast and already lands clean) + for j0, L_ in sw: + if L_ < 4: continue + jl, je = j0 - 1, j0 + L_ # last planted frame before, first planted frame after + Fl, Fe = frames[jl % n], frames[je % n] + for i in range(L_): + j = j0 + i; F = frames[j % n]; u = (i + 1) / (L_ + 1) + lift = Fl[s + 'toes'] - vel * ((j - jl) * dt) # where a still-planted ball would be + land = Fe[s + 'foot'] - vel * ((j - je) * dt) # where the landing heel's line is + cur_b, cur_a = F[s + 'toes'], F[s + 'foot'] + w0 = 1 - smooth01(0.0, 0.3, u) # stick to the lift-off line early on + w1 = smooth01(0.62, 0.9, u) # be over the landing spot late + dx = Vector((0, 0, 0)) + if w0 > 0: dx += (Vector((lift.x, lift.y, 0)) - Vector((cur_b.x, cur_b.y, 0))) * w0 + if w1 > 0: dx += (Vector((land.x, land.y, 0)) - Vector((cur_a.x, cur_a.y, 0))) * w1 + for nm in ('foot', 'toes', 'toes>'): + F[s + nm] = F[s + nm] + dx + # toes: less flex than captured (the captured toe segment is short and noisy) and smoothed over time + for s in 'lr': + tips = [] + for F in frames: + an, to, tip = F[s + 'foot'], F[s + 'toes'], F[s + 'toes>'] + ln = (tip - to).length + d_ = (tip - to).normalized().lerp((to - an).normalized(), 0.45).normalized() + tips.append(d_ * ln) + for j, F in enumerate(frames): + d_ = (tips[j - 1] + tips[j] * 2 + tips[(j + 1) % n]) / 4 + F[s + 'toes>'] = F[s + 'toes'] + d_ + # legs never over-stretched: lower the body (not the feet) where an ankle is out of reach, smoothed over time + reach = our_leg * 0.985 + need = [] + for F in frames: + d = 0.0 + for s in 'lr': + h, a_ = F[s + 'femur'], F[s + 'foot'] + hz = a_.z + math.sqrt(max(0.0, reach * reach - ((h.x - a_.x) ** 2 + (h.y - a_.y) ** 2))) + d = max(d, h.z - hz) + need.append(d) + drop = [max(need[(j + o) % n] * (1 - abs(o) / 4.0) for o in range(-3, 4)) for j in range(n)] + FEET = ('lfoot', 'rfoot', 'ltoes', 'rtoes', 'ltoes>', 'rtoes>', 'lfoot>', 'rfoot>', 'ltibia>', 'rtibia>') + for F, d in zip(frames, drop): + if d <= 0: continue + for nm in F: + if nm not in FEET: F[nm] = F[nm] - Vector((0, 0, d)) + return frames, T, dist / T, th, flags + + +def pose(R, L, W, F, A): + """Pose the rig from one retargeted frame. A: dict with PEL0, HIPMID (rest), helpers two_bone etc.""" + hipL, hipR = F['lfemur'], F['rfemur'] + mid = (hipL + hipR) / 2 + left = (hipL - hipR).normalized() + up = (F['lowerback>'] - F['lowerback']).normalized() + D = R.frame_rot(UP, LEFT, up, left) + M = (D.to_4x4() @ Matrix.Translation(-A['HIPMID']) @ R.Mr['pelvis']) + M.translation = mid + D @ (R.Mr['pelvis'].translation - A['HIPMID']) + R.set_world(L, W, 'pelvis', M) + sl = (F['lhumerus'] - F['rhumerus']).normalized() + for b, seg, ref in (('spine_01', 'lowerback', left), ('spine_02', 'upperback', (left + sl).normalized()), + ('spine_03', 'thorax', sl), ('neck_01', 'lowerneck', sl), ('Head', 'upperneck', sl)): + d = F[seg + '>'] - F[seg] + if seg == 'upperneck': d = (F['head>'] - F['upperneck']) + R.aim_bone(L, W, b, d.normalized(), ref, LEFT) + for s in 'lr': + cl = F[s + 'humerus'] - F[s + 'clavicle'] + if cl.length > 1e-4: + R.aim_bone(L, W, 'clavicle_' + s, cl.normalized()) + sh, el, wr = F[s + 'humerus'], F[s + 'radius'], F[s + 'wrist'] + ua, fa = (el - sh).normalized(), (wr - el).normalized() + o = W['upperarm_' + s].translation + tgt = o + ua * R.len['upperarm_' + s] + fa * R.len['lowerarm_' + s] + side = left if s == 'l' else -left + pole = el - (sh + wr) * 0.5 - left.cross(up).normalized() * 0.03 + side * 0.02 + hinge = Vector((0, 0, -1)) if s == 'l' else Vector((0, 0, 1)) + R.two_bone(L, W, 'upperarm_' + s, 'lowerarm_' + s, 'hand_' + s, tgt, pole.normalized(), hinge) + hd = F[s + 'hand>'] - F[s + 'hand'] if s + 'hand>' in F else None + if hd is not None and hd.length > 1e-4: + R.aim_bone(L, W, 'hand_' + s, hd.normalized()) + for s in 'lr': + hp, kn, an = F[s + 'femur'], F[s + 'tibia'], F[s + 'foot'] + # knee direction from the capture, biased toward the pelvis' forward so a straight leg cannot flip the twist + fwd = left.cross(up).normalized() + pole = (kn - (hp + an) * 0.5) + fwd * 0.12 + pole = pole.normalized() + # our foot is not the captured foot's length: once the heel is up, place the ankle so our ball lands on the + # captured (pinned) ball instead of the ankle + to = F[s + 'toes'] + w = min(1.0, max(0.0, (an.z - A['ANKZ'] - 0.01) / 0.04)) + if w > 0 and (to - an).length > 1e-4: + an = an.lerp(to - (to - an).normalized() * R.len['foot_' + s], w) + R.two_bone(L, W, 'thigh_' + s, 'calf_' + s, 'foot_' + s, an, pole, Vector((1, 0, 0))) + fd = F[s + 'toes'] - an + side = left.cross(UP).cross(UP) * -1 if False else left + if fd.length > 1e-4: + R.aim_bone(L, W, 'foot_' + s, fd.normalized(), side, LEFT) + td = F[s + 'toes>'] - F[s + 'toes'] + if 'ball_' + s in W and td.length > 1e-4: + R.aim_bone(L, W, 'ball_' + s, td.normalized(), side, LEFT) diff --git a/e63334287a3deaa3/ironveil/tools/chars/mocap_list.py b/e63334287a3deaa3/ironveil/tools/chars/mocap_list.py new file mode 100644 index 00000000..7e98e3f4 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/mocap_list.py @@ -0,0 +1,43 @@ +# The CMU motion-capture takes used for the locomotion loops (trial, start s, end s, options). Run directly to print +# the trial ids (fetch.sh downloads them). Source: CMU Graphics Lab Motion Capture Database, mocap.cs.cmu.edu +# ("The motion capture data may be copied, modified, or redistributed without permission."). +# theta : travel direction the loop is pinned to (0 forward, 90 left, 180 back, -90 right) +# mirror : left/right swapped (a captured right-side move used for the left, or the reverse) +# hip_yaw : derived direction: legs and hips turned this many radians toward travel, chest kept facing forward +# speed, stride : play faster (cadence) and lengthen the steps by these factors (slow captured side steps) +# crouch : derived crouch: pelvis lowered this many metres with the captured footfalls kept (knees bend by IK) +WALK = dict(trial='07_01', t0=0.2, t1=2.6) +BACK = dict(trial='09_12', t0=12.1, t1=15.5) +BDIAG = dict(trial='09_12', t0=8.1, t1=9.9) +JOG = dict(trial='09_01', t0=0.0, t1=1.25) +SIDE_L = dict(trial='143_40', t0=1.0, t1=3.6, speed=1.3, stride=1.3) +SIDE_R = dict(trial='143_40', t0=4.5, t1=7.3, speed=1.3, stride=1.3) +SNEAK_L = dict(trial='143_41', t0=5.1, t1=8.9, speed=1.4, stride=1.45) +SNEAK_R = dict(trial='143_41', t0=0.7, t1=4.2, speed=1.4, stride=1.45) +CR = dict(crouch=0.2, lean=0.0) # combat crouch: half squat, back fairly straight +TAKES = { + 'walkF': dict(WALK, theta=0), + 'walkFL': dict(WALK, theta=45, hip_yaw=0.42), + 'walkFR': dict(WALK, theta=-45, hip_yaw=-0.42), + 'walkL': dict(SIDE_L, theta=90), + 'walkR': dict(SIDE_R, theta=-90), + 'walkB': dict(BACK, theta=180), + 'walkBR': dict(BDIAG, theta=-135), + 'walkBL': dict(BDIAG, theta=135, mirror=True), + 'jogF': dict(JOG, theta=0), + 'jogFL': dict(JOG, theta=45, hip_yaw=0.38), + 'jogFR': dict(JOG, theta=-45, hip_yaw=-0.38), + 'jogL': dict(JOG, theta=90, hip_yaw=1.0), + 'jogR': dict(JOG, theta=-90, hip_yaw=-1.0), + 'sprintF': dict(trial='102_05', t0=0.0, t1=0.95, theta=0), + 'crouchF': dict(WALK, theta=0, **CR), + 'crouchFL': dict(WALK, theta=45, hip_yaw=0.42, **CR), + 'crouchFR': dict(WALK, theta=-45, hip_yaw=-0.42, **CR), + 'crouchL': dict(SNEAK_L, theta=90, crouch=0.18, lean=0.0), + 'crouchR': dict(SNEAK_R, theta=-90, crouch=0.18, lean=0.0), + 'crouchB': dict(BACK, theta=180, crouch=0.2, lean=0.0), + 'crouchBR': dict(BDIAG, theta=-135, crouch=0.2, lean=0.0), + 'crouchBL': dict(BDIAG, theta=135, mirror=True, crouch=0.2, lean=0.0), +} +if __name__ == '__main__': + print(' '.join(sorted({v['trial'] for v in TAKES.values()}))) diff --git a/e63334287a3deaa3/ironveil/tools/chars/morphs.py b/e63334287a3deaa3/ironveil/tools/chars/morphs.py new file mode 100644 index 00000000..1067107b --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/morphs.py @@ -0,0 +1,78 @@ +# Face morph targets (glTF morphs) for the characters, added at assembly time: +# enemies: 'faceB', 'faceC' - two more face shapes on the shared enemy head (the base face is 'faceA') +# hero and ally: 'blink' - both upper lids down +# Each morph is the difference between the character's own MakeHuman build and the same build with other face +# targets, taken after the re-pose to the game skeleton. `python morphs.py kind` (in Blender's Python) writes +# work/morph_.npz; assemble.py then maps it onto the final meshes by vertex position. +import bpy, sys, os +import numpy as np +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import mhlib as L, humans as HU + +EYELIDS = [(s + '-eye-' + t, w) for s in ('l', 'r') for t, w in (('height1-decr', 1.0), ('height2-decr', 1.0), ('height3-decr', 0.6), + ('eyefold-down', 0.6))] +ALT = { + 'enemy': { + 'faceB': [('head/head-square', 0.55), ('chin/chin-prominent-incr', 0.5), ('chin/chin-width-incr', 0.35), ('nose/nose-scale-horiz-incr', 0.4), + ('nose/nose-hump-incr', 0.5), ('eyebrows/eyebrows-trans-down', 0.5), ('cheek/l-cheek-bones-incr', 0.4), ('cheek/r-cheek-bones-incr', 0.4), + ('mouth/mouth-scale-horiz-decr', 0.25)], + 'faceC': [('head/head-round', 0.45), ('head/head-fat-incr', 0.35), ('nose/nose-trans-down', 0.3), ('nose/nose-scale-vert-incr', 0.35), + ('nose/nose-point-width-incr', 0.4), ('chin/chin-height-decr', 0.3), ('cheek/l-cheek-volume-incr', 0.4), + ('cheek/r-cheek-volume-incr', 0.4), ('mouth/mouth-lowerlip-volume-incr', 0.3), ('eyebrows/eyebrows-angle-down', 0.4)], + }, + 'hero': {'blink': 'EYELIDS'}, + 'ally': {'blink': 'EYELIDS'}, +} +PARTS = ('body', 'eyes', 'brows', 'lashes', 'hair') + +def positions(H): + return {k: np.array([tuple(v.co) for v in H[k].data.vertices]) for k in PARTS if H.get(k)} + +def build(params, face): + bpy.ops.wm.read_factory_settings(use_empty=True) + p = dict(params); p['face'] = face + return positions(L.build_human(**p)) + +if __name__ == '__main__': + kind = sys.argv[-1] + params = HU.PARAMS[kind] + base = build(params, params['face']) + out = {} + for k, v in base.items(): out['base_' + k] = v + for name, face in ALT['enemy' if kind == 'enemy' else kind].items(): + if face == 'EYELIDS': face = list(params['face']) + [('eyes/' + t, w) for t, w in EYELIDS] + alt = build(params, face) + for k, v in alt.items(): out[name + '_' + k] = v + print('morph', name, {k: float(np.abs(alt[k] - base[k]).max()) for k in alt}) + np.savez(L.WORK + '/morph_%s.npz' % kind, **out) + print('wrote', L.WORK + '/morph_%s.npz' % kind) + +GAIN = {'blink': 2.4, 'faceB': 1.8, 'faceC': 1.8} # MakeHuman targets are linear: the eyelid targets only half-close the eye + +def apply(obj, part, npz, names, tol=0.004): + """Add shape keys `names` to obj: each vertex takes the delta of the source part near its position + (inverse-distance mix of the 3 nearest source vertices within `tol`; nothing further away moves).""" + from mathutils import kdtree, Vector + base = npz['base_' + part] + kd = kdtree.KDTree(len(base)) + for i, p in enumerate(base): kd.insert(p, i) + kd.balance() + me = obj.data + if not me.shape_keys: obj.shape_key_add(name='Basis', from_mix=False) + near = [] + for v in me.vertices: + hits = [(i, d) for (_, i, d) in kd.find_n(v.co, 3) if d <= tol] + near.append(hits) + hit = 0 + for nm in names: + key = me.shape_keys.key_blocks.get(nm) or obj.shape_key_add(name=nm, from_mix=False) + key.value = 0.0 + if nm + '_' + part not in npz: continue + dl = (npz[nm + '_' + part] - base) * GAIN.get(nm, 1.0) + for v, hits in zip(me.vertices, near): + if not hits: continue + ws = [1.0 / max(d, 1e-5) for _, d in hits] + dd = sum((dl[i] * w for (i, _), w in zip(hits, ws)), np.zeros(3)) / sum(ws) + if np.any(np.abs(dd) > 1e-6): + key.data[v.index].co = v.co + Vector(dd); hit += 1 + return hit diff --git a/e63334287a3deaa3/ironveil/tools/chars/outfits.py b/e63334287a3deaa3/ironveil/tools/chars/outfits.py new file mode 100644 index 00000000..f8a4598c --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/outfits.py @@ -0,0 +1,616 @@ +# Outfits: build cloth body + gear for each character kind. +import bpy, math +import numpy as np +from mathutils import Vector, Matrix +import mhlib as L, geo as G, mats as MT, pipe as PP + +J = PP.J + +# ---------- shared bits ---------- +def envelope_rings(P, mask, center_xy, zs, offsets, n=28, name='env', yscale=1.0, phase=0.0, mins=None): + """Rings around a vertical axis using the max radial extent of masked verts in each z slice/sector.""" + cx, cy = center_xy + pts = P[mask] + rings = [] + for z, off in zip(zs, offsets): + sl = pts[np.abs(pts[:, 2] - z) < 0.018] + ring = [] + for k in range(n): + th = phase + 2 * math.pi * k / n + d = np.array([math.sin(th), -math.cos(th)]) # k=0 -> front (-Y) + if len(sl): + rel = sl[:, :2] - np.array([cx, cy]) + proj = rel @ d + perp = np.abs(rel @ np.array([-d[1], d[0]])) + cand = proj[perp < 0.03] + r = cand.max() if len(cand) else (proj.max() if len(proj) else 0.12) + else: + r = 0.12 + if mins: r = max(r, mins) + o = off(th) if callable(off) else off + ring.append(Vector((cx + d[0] * (r + o), cy + d[1] * (r + o), z))) + rings.append(ring) + # smooth each ring radially a bit (removes leg gaps) + for ring in rings: + c = Vector((cx, cy, ring[0].z)) + rad = [((p - c).length) for p in ring] + rad2 = [max(rad[i], 0.5 * (rad[i - 1] + rad[(i + 1) % n])) for i in range(n)] + for i in range(n): + dvec = (ring[i] - c); dvec.z = 0 + if dvec.length > 0: ring[i] = c + dvec.normalized() * rad2[i] + verts = [p for r in rings for p in r] + faces = [] + for i in range(len(rings) - 1): + for k in range(n): + a = i * n + k; b = i * n + (k + 1) % n + faces.append([a, a + n, b + n, b]) + return G.mesh_obj(name, verts, faces) + +def limb_ring(bvh, a, b, ts, offsets, n=16, name='limbring', ref=Vector((0, -1, 0))): + st = [] + for t, o in zip(ts, offsets): + c = a.lerp(b, t) + st.append((c, (b - a), o, ref)) + return G.ring_loft(bvh, st, n=n, name=name) + +def pouch(bvh, origin, direction, w, h, d, name, flap=True, up=Vector((0, 0, 1)), push=0.0): + M = G.surface_frame(bvh, origin, direction, up) + if M is None: return [] + Mc = M @ Matrix.Translation((0, 0, d / 2 + push)) + obs = [G.box(name, (w, h, d), Mc, bev=min(w, h, d) * 0.22, seg=1)] + if flap: + Mf = M @ Matrix.Translation((0, h * 0.28, d + push + 0.002)) @ Matrix.Rotation(-0.10, 4, 'X') + f = G.box(name + 'F', (w * 1.03, h * 0.42, 0.005), Mf, bev=0.0015, seg=1) + f['hi_only'] = True + obs.append(f) + # press stud near the flap's lower edge, and a stitched hem line along it + st = G.lathe(name + 'Stud', [(0.0, 0.004), (0.006, 0.0035), (0.0075, 0.0015), (0.0075, 0.0)], n=10, M=Mf @ Matrix.Translation((0, -h * 0.13, 0.0025))) + st['hi_only'] = True; obs.append(st) + hem = G.box(name + 'Hem', (w * 0.95, 0.0015, 0.0012), Mf @ Matrix.Translation((0, -h * 0.18, 0.0028)), bev=0.0005, seg=1) + hem['hi_only'] = True; obs.append(hem) + return obs + +def buckle(M, name, w=0.03, h=0.034, t=0.004, bar=0.004): + """A rectangular frame buckle with a centre bar (four sides and a bar, real geometry).""" + out = [] + for i, (x, y, sx, sy) in enumerate(((0, h / 2, w, bar), (0, -h / 2, w, bar), (w / 2, 0, bar, h), (-w / 2, 0, bar, h), (0, 0, bar * 0.8, h))): + out.append(G.box(name + str(i), (sx, sy, t), M @ Matrix.Translation((x, y, 0)), bev=0.0008, seg=1)) + return out + +def button(bvh, origin, direction, name, r=0.0075, up=Vector((0, 0, 1))): + """A flat sewn button (high-poly only: it is baked into the normal and colour maps).""" + M = G.surface_frame(bvh, origin, direction, up) + if M is None: return [] + b = G.box(name, (r * 2, r * 2, 0.0035), M @ Matrix.Translation((0, 0, 0.0025)), bev=r * 0.8, seg=3) + b['hi_only'] = True + return [b] + +def boot_details(P, bvh, out, laces=True, mat='boot', lace_mat='glove'): + """Crossed laces up the front of lace-up boots (high-poly only, baked into the boot maps).""" + feet = np.array([p[2] < 0.05 for p in P]) + for s in (-1, 1): + fm = feet & np.array([p[0] * s > 0 for p in P]) + F = P[fm] + fx = float(np.mean(F[:, 0])); y0, y1 = float(F[:, 1].min()), float(F[:, 1].max()) + w = float(F[:, 0].max() - F[:, 0].min()) + Fh = F[F[:, 1] > y1 - 0.07] + hx = float(np.mean(Fh[:, 0])); hw = float(Fh[:, 0].max() - Fh[:, 0].min()) + # heel block under the back of the sole (real geometry), tread bars and a toe-cap seam (baked detail) + out.append((G.box('Heel%d' % s, (hw + 0.02, 0.07, 0.022), Matrix.Translation((hx, y1 - 0.034, 0.011)), bev=0.004, seg=2), mat)) + for k in range(8): + yy = y0 + 0.025 + k * (y1 - y0 - 0.12) / 7 + t = G.box('Tread%d%d' % (s, k), (w * 0.8, 0.007, 0.005), Matrix.Translation((fx, yy, -0.0015)), bev=0.0015, seg=1) + t['hi_only'] = True; out.append((t, mat)) + Mt = G.surface_frame(bvh, Vector((fx, y0 + 0.05, 0.3)), Vector((0, 0, -1)), Vector((0, -1, 0))) + if Mt: + tc = G.box('ToeCap%d' % s, (w * 0.9, 0.003, 0.0018), Mt @ Matrix.Translation((0, 0, 0.001)), bev=0.0008, seg=1) + tc['hi_only'] = True; out.append((tc, mat)) + if laces: + for k in range(7): + z = 0.075 + k * 0.014 + o = Vector((fx, y0 - 0.2 + 0.05, z)); o.y = -0.4 + for a in (-0.45, 0.45): + M = G.surface_frame(bvh, Vector((fx, -0.4, z)), Vector((0, 1, 0))) + if M is None: continue + l = G.box('Lace%d%d%s' % (s, k, a > 0), (0.034, 0.0035, 0.003), M @ Matrix.Translation((0, 0, 0.0025)) @ Matrix.Rotation(a, 4, 'Z'), bev=0.001, seg=1) + l['hi_only'] = True; out.append((l, lace_mat)) + for sx in (-0.016, 0.016): # eyelets either side of the lacing + M = G.surface_frame(bvh, Vector((fx + sx, -0.4, z)), Vector((0, 1, 0))) + if M is None: continue + e = G.lathe('Eyelet%d%d%d' % (s, k, sx > 0), [(0.0015, 0.0012), (0.0032, 0.0012), (0.0034, 0.0), (0.0015, 0.0)], n=8, M=M) + e['hi_only'] = True; out.append((e, 'metal')) + +def helmet_m1(H, name='Helmet', net=True): + """US M1-style helmet shell: rounded dome, slight brim flare at the rim.""" + head = J(H, 'Head'); top = J(H, 'Head', 1) + body = H['body'] + P = G.coords(body.data) + W = PP.vweights(body) + hv = np.array([P[i] for i in range(len(P)) if W[i].get('Head', 0) > 0.6]) + mn, mx = hv.min(0), hv.max(0) + c = Vector(((mn[0] + mx[0]) / 2, (mn[1] + mx[1]) / 2 + 0.012, mx[2] - 0.088)) + prof = [] + rx, ry, hz = (mx[0] - mn[0]) / 2 + 0.026, (mx[1] - mn[1]) / 2 + 0.026, 0.118 + # dome from top (r=0) down to the rim, then rolled rim edge + for i in range(10): + a = (i / 9) * (math.pi / 2) + prof.append((math.sin(a), math.cos(a) * hz + 0.012)) + prof += [(1.02, 0.0), (1.06, -0.012), (1.065, -0.020), (1.03, -0.020), (0.97, -0.005)] + verts, faces = [], [] + n = 24 + for k in range(n): + th = 2 * math.pi * k / n + # brim lower at the back/sides, higher at the front (M1 profile) + dz = -0.022 * (0.5 + 0.5 * math.cos(th)) + 0.012 * max(0.0, -math.cos(th)) # th=0 back(+y) + for r, z in prof: + zz = z + (dz if z <= 0.02 else dz * max(0.0, 1 - (z - 0.02) / 0.06)) + verts.append(Vector((c.x + r * rx * math.sin(th), c.y + r * ry * math.cos(th), c.z + zz))) + m = len(prof) + for k in range(n): + k2 = (k + 1) % n + for j in range(m - 1): + faces.append([k * m + j, k2 * m + j, k2 * m + j + 1, k * m + j + 1]) + ob = G.mesh_obj(name, verts, faces) + G.rigid_weights(ob, 'Head') + return ob, c, (rx, ry) + +def cap_comforter(H, name='Cap'): + """Knitted wool cap comforter: a close dome over the skull, the turned-up double band low on the brow and ears, + the crown slouched a little to the back. Returns (obj, centre, radii) for trimming the hair beneath.""" + body = H['body']; P = G.coords(body.data); W = PP.vweights(body) + hv = np.array([P[i] for i in range(len(P)) if W[i].get('Head', 0) > 0.6]) + mn, mx = hv.min(0), hv.max(0) + c = Vector(((mn[0] + mx[0]) / 2, (mn[1] + mx[1]) / 2 + 0.010, mx[2] - 0.050)) + rx, ry, hz = (mx[0] - mn[0]) / 2 + 0.006, (mx[1] - mn[1]) / 2 + 0.006, 0.062 + prof = [] + for i in range(11): + a = (i / 10) * (math.pi / 2) + prof.append((math.sin(a), math.cos(a) * hz + 0.004)) + # the turned-up band: out, a rounded fold, and back in under the edge + prof += [(1.015, -0.006), (1.06, -0.012), (1.075, -0.026), (1.06, -0.040), (1.02, -0.044), (0.985, -0.040)] + verts, faces = [], [] + n = 28 + for k in range(n): + th = 2 * math.pi * k / n + lowz = -0.012 * (0.5 - 0.5 * math.cos(th)) # th=0 back: the band sits lower over the nape + for j, (r, z) in enumerate(prof): + slouch = 0.012 * max(0.0, math.cos(th)) * max(0.0, (z - 0.04) / 0.05) if j < 11 else 0.0 + verts.append(Vector((c.x + r * rx * math.sin(th), c.y + r * ry * math.cos(th) + slouch, c.z + z + (lowz if z < 0.02 else 0.0)))) + m = len(prof) + for k in range(n): + k2 = (k + 1) % n + for j in range(m - 1): + faces.append([k * m + j, k2 * m + j, k2 * m + j + 1, k * m + j + 1]) + ob = G.mesh_obj(name, verts, faces) + G.rigid_weights(ob, 'Head') + return ob, c + Vector((0, 0, -0.035)), (rx + 0.012, ry + 0.012) + +def scrim_bits(c, rr, name='Scrim', n=9, seed=3): + """Small strips of hessian tied into a helmet net (real geometry, rigid on the head).""" + import random + rnd = random.Random(seed); out = [] + for i in range(n): + th = rnd.uniform(0, 2 * math.pi); el = rnd.uniform(0.25, 1.0) + p = Vector((c.x + rr[0] * 1.03 * math.sin(th) * math.cos(el * 0.9), c.y + rr[1] * 1.03 * math.cos(th) * math.cos(el * 0.9), c.z + 0.115 * math.sin(el * 1.2) + 0.01)) + nrm = (p - Vector((c.x, c.y, c.z - 0.02))).normalized() + M = Matrix.Translation(p) @ nrm.to_track_quat('Z', 'Y').to_matrix().to_4x4() @ Matrix.Rotation(rnd.uniform(0, 3.1), 4, 'Z') + b = G.box(name + str(i), (rnd.uniform(0.012, 0.02), rnd.uniform(0.035, 0.055), 0.003), M, bev=0.001, seg=1) + G.rigid_weights(b, 'Head'); out.append(b) + return out + +def chin_straps(H, c, rr, name='Straps'): + body = H['body']; P = G.coords(body.data); W = PP.vweights(body) + hv = np.array([P[i] for i in range(len(P)) if W[i].get('Head', 0) > 0.8]) + chin = Vector((0.0, hv[:, 1].min() + 0.045, hv[:, 2].min() + 0.03)) + obs = [] + for s in (-1, 1): + a = Vector((c.x + s * rr[0] * 0.93, c.y - 0.01, c.z - 0.012)) + b = Vector((s * 0.035, chin.y + 0.02, chin.z - 0.005)) + mid = a.lerp(b, 0.45) + Vector((s * 0.018, -0.01, 0)) + verts, faces = [], [] + steps = 6 + for i in range(steps + 1): + t = i / steps + p = (a * (1 - t) ** 2 + mid * 2 * t * (1 - t) + b * t * t) + tan = ((b - a) * (1 - t) + (mid - a) * 0 + (b - mid) * t).normalized() + side = tan.cross(Vector((s, 0, 0))).normalized() * 0.008 + verts += [p - side, p + side] + for i in range(steps): + faces.append([2 * i, 2 * i + 2, 2 * i + 3, 2 * i + 1]) + o = G.mesh_obj(name + str(s), verts, faces) + G.solidify(o, 0.003, 0) + G.rigid_weights(o, 'Head') + obs.append(o) + return obs + +# ---------- hero ---------- +HERO_COL = dict(jacket='#67664a', jacket2='#57573c', trousers='#626145', boot='#3e2618', glove='#4c3624', + web='#8c805b', canvas='#7b7354', helmet='#4f4f37', metal='#3a3a36') + +ROLL_AT = 0.40 # the raider smock's sleeves are rolled to this fraction of the forearm (elbow 0, wrist 1) + +def label_hero(H, P): + boot_top = J(H, 'foot_l').z + 0.15 + waist = J(H, 'pelvis').z + 0.015 + ex, wx_ = abs(J(H, 'lowerarm_l').x), abs(J(H, 'hand_l').x) + lab = [] + for p in P: + x, y, z = p + if abs(x) > ex + (wx_ - ex) * (ROLL_AT - 0.04) and z > J(H, 'upperarm_l').z - 0.25: + lab.append('skin') # bare forearms and hands below the rolled sleeves (no gloves) + elif z > J(H, 'neck_01').z + 0.03 or (z > PP.neck_threshold(H, p) and abs(x) < 0.085): + lab.append('skin') + elif z < boot_top: + lab.append('boot') + elif z >= waist: + lab.append('jacket') + else: + lab.append('trousers') + return lab + +def materials_hero(knee=0.54): + import wear as WR + return { + 'skin': None, + # the raider smock: an invented brush-stroke camouflage, muted sand, green and brown + 'jacket': WR.cloth('jacket', '#7a7454', '#6a6448', fade=0.14, camo=('#8a8257', '#545b37', '#634a2e', '#36352a')), + 'trousers': WR.cloth('trousers', '#58503d', '#463f30', knee_z=knee, mud_amt=0.8), + 'boot': WR.leather('boot', '#3a2618', '#1e140c', mud_low=0.22, polish=0.62), + 'glove': WR.leather('glove', '#3e2c1e', '#2a1d14', polish=0.6), + 'web': WR.webbing('web', '#857a5a', '#6e6548'), + 'canvas': WR.webbing('canvas', '#736a4d', '#5e573f'), + 'helmet': WR.painted_metal('helmet', '#454634', '#393a2b'), + 'wool': WR.cloth('wool', '#38372d', '#2c2b24', fade=0.06, mud_amt=0.0, weave=0.9), + 'net': WR.webbing('net', '#3d3a28', '#2e2c1e'), + 'metal': WR.blued('metal', '#4a4b45', '#3e3f3a', park=True), + } + +def gear_hero(H, cloth): + """Webbing and kit for the paratrooper. Returns list of (obj, matname).""" + bvh = G.bvh_of(cloth) + P = G.coords(cloth.data) + out = [] + pz = J(H, 'pelvis').z + torso = np.array([abs(p[0]) < 0.24 for p in P]) + # collar (turned-down) + nk = J(H, 'neck_01') + zc = nk.z + col = envelope_rings(P, np.array([abs(p[0]) < 0.10 for p in P]), (0, nk.y + 0.01), [zc - 0.045, zc - 0.02, zc + 0.005, zc + 0.016], + [-0.004, 0.006, 0.008, 0.01], n=24, name='Collar') + G.solidify(col, 0.006, 1.0); out.append((col, 'jacket')) + # the smock ends at the belt: a short close hem, bloused a little over the belt (no flared skirt) + hips = np.array([abs(p[0]) < 0.25 and p[2] < pz + 0.1 for p in P]) + skirt = envelope_rings(P, hips, (0, J(H, 'pelvis').y + 0.01), [pz + 0.09, pz + 0.05, pz + 0.015, pz - 0.01], + [0.004, 0.008, 0.009, 0.004], n=32, name='Skirt') + G.solidify(skirt, 0.004, 1.0); out.append((skirt, 'jacket')) + # rolled sleeves: two turns of cloth at mid-forearm + for s_ in ('l', 'r'): + el = J(H, 'lowerarm_' + s_); wr = J(H, 'hand_' + s_) + ts = [ROLL_AT - 0.10 + 0.02 * i for i in range(8)] + offs = [0.002, 0.008, 0.012, 0.010, 0.011, 0.012, 0.008, 0.002] + out.append((limb_ring(bvh, el, wr, ts, offs, n=20, name='Roll' + s_), 'jacket')) + # cartridge belt + belt = envelope_rings(P, torso, (0, J(H, 'pelvis').y + 0.01), [pz + 0.075, pz + 0.01], [0.012, 0.014], n=32, name='Belt') + G.solidify(belt, 0.006, 1.0); out.append((belt, 'web')) + bvh2 = G.bvh_of(belt) + # pouches on belt (5 a side, front to hip) + cy = J(H, 'pelvis').y + for s in (-1, 1): + for k, ang in enumerate((24, 44)): + a = math.radians(ang) * s + d = Vector((math.sin(a), -math.cos(a), 0)) + o = Vector((0, cy, pz + 0.045)) - d * 0.0 + out += [(x, 'canvas') for x in pouch(bvh2, o + d * 0.4, -d, 0.058, 0.07, 0.032, 'Pouch%d%d' % (s, k), push=0.004)] + # canteen right-back hip, entrenching tool left-back + for s, nm, wh in ((-1, 'Canteen', (0.11, 0.15, 0.06)), (1, 'Satchel', (0.2, 0.15, 0.075))): + a = math.radians(140) * s + d = Vector((math.sin(a), -math.cos(a), 0)) + out += [(x, 'canvas') for x in pouch(bvh2, Vector((0, cy, pz + 0.0)) + d * 0.4, -d, wh[0], wh[1], wh[2], nm, push=0.004)] + # suspenders + sh = J(H, 'clavicle_l', 1) + for s in (-1, 1): + pts = [Vector((s * 0.085, cy - 0.3, pz + 0.07)), Vector((s * 0.10, cy - 0.3, pz + 0.3)), + Vector((s * 0.115, -0.25, sh.z + 0.02)), Vector((s * 0.125, sh.y, sh.z + 0.07)), + Vector((s * 0.12, 0.25, sh.z + 0.0)), Vector((s * 0.08, 0.3, pz + 0.30)), Vector((s * 0.07, 0.3, pz + 0.08))] + out.append((G.strap(bvh, pts, 0.034, 0.004, name='Susp%d' % s, thick=0.004, steps=22), 'web')) + # three magazine pouches high on the chest, a compass pouch on the belt + for k, xx in enumerate((-0.075, 0.0, 0.075)): + out += [(x, 'canvas') for x in pouch(bvh, Vector((xx, -0.4, sh.z - 0.16)), Vector((0, 1, 0)), 0.065, 0.12, 0.032, 'MagPouch%d' % k, push=0.006)] + out += [(x, 'canvas') for x in pouch(bvh2, Vector((-0.4 * math.sin(math.radians(62)), cy - 0.4 * math.cos(math.radians(62)), pz + 0.045)), + Vector((math.sin(math.radians(62)), math.cos(math.radians(62)), 0)), 0.06, 0.06, 0.03, 'Compass', push=0.004)] + # front closure: four buttons down the placket + for k in range(2): + out += [(x, 'metal') for x in button(bvh, Vector((0.0, -0.4, sh.z - 0.30 - k * 0.1)), Vector((0, 1, 0)), 'FrontBtn%d' % k)] + # toggle rope coiled at the left front of the belt + a_ = math.radians(-62); d_ = Vector((math.sin(a_), -math.cos(a_), 0)) + tp = Vector((0, cy, pz - 0.02)) + d_ * 0.0 + hitp = bvh2.ray_cast(Vector((0, cy, pz - 0.03)) + d_ * 0.4, -d_, 1.0)[0] + if hitp is not None: + Mt = Matrix.Translation(hitp + d_ * 0.02 + Vector((0, 0, -0.07))) @ Matrix(((0, 0, 1, 0), (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 0, 1))).inverted() + for r_ in range(3): + ring = G.lathe('Toggle%d' % r_, [(0.042 + 0.006 * r_ + 0.004 * math.cos(t * math.pi / 3), 0.004 * math.sin(t * math.pi / 3) + r_ * 0.006) for t in range(7)], + n=16, M=Matrix.Translation(hitp + d_ * 0.03 + Vector((0, 0, -0.06))) @ Matrix.Rotation(math.pi / 2, 4, 'X') @ Matrix.Rotation(-a_, 4, 'Y')) + out.append((ring, 'web')) + # thigh cargo pockets (outer front) + for s in (-1, 1): + th = J(H, 'thigh_l' if s > 0 else 'thigh_r'); kn = J(H, 'calf_l' if s > 0 else 'calf_r') + mid = th.lerp(kn, 0.52) + d = Vector((s * 0.75, -0.66, 0)).normalized() + out += [(x, 'trousers') for x in pouch(bvh, mid + d * 0.3, -d, 0.15, 0.19, 0.026, 'Cargo%d' % s, push=-0.004)] + # trousers bloused over the boot tops + for s in ('l', 'r'): + kn = J(H, 'calf_' + s); an = J(H, 'foot_' + s) + bl = limb_ring(bvh, kn, an, [0.58, 0.64, 0.71, 0.76], [-0.002, 0.014, 0.012, -0.004], n=16, name='Blouse' + s) + out.append((bl, 'trousers')) + # boot soles + feet = np.array([p[2] < 0.05 for p in P]) + for s in (-1, 1): + fm = feet & np.array([p[0] * s > 0 for p in P]) + fx = float(np.mean(P[fm][:, 0])); fy = float(np.mean(P[fm][:, 1])) + # the welt stands clear of the boot surface (and its folds) so the bake rays see the sole, not the boot + sole = envelope_rings(P, fm, (fx, fy), [0.0, 0.0, 0.022, 0.032], [-0.03, 0.012, 0.013, 0.003], n=20, name='Sole%d' % s) + out.append((sole, 'boot')) + boot_details(P, bvh, out, laces=True) + # musette bag on the back: body, flap with two straps and buckles, stitched edge, and a rolled blanket lashed on top + sp = J(H, 'spine_03') + pk = pouch(bvh, Vector((0, 0.5, sp.z + 0.08)), Vector((0, -1, 0)), 0.28, 0.24, 0.09, 'Musette', push=0.012) + out += [(x, 'canvas') for x in pk] + Mp = G.surface_frame(bvh, Vector((0, 0.5, sp.z + 0.08)), Vector((0, -1, 0)), Vector((0, 0, 1))) + if Mp: + Mo = Mp @ Matrix.Translation((0, 0, 0.012 + 0.09)) # outer face of the pack + for sx in (-0.075, 0.075): + out.append((G.box('PackStrap%d' % (sx > 0), (0.024, 0.2, 0.004), Mo @ Matrix.Translation((sx, -0.01, 0.003)), bev=0.001, seg=1), 'web')) + fr = buckle(Mo @ Matrix.Translation((sx, -0.075, 0.007)), 'PackBuckle%d' % (sx > 0)) + out += [(x, 'metal') for x in fr] + roll = G.lathe('PackRoll', [(0.0, 0.17), (0.045, 0.17), (0.052, 0.15), (0.054, 0.0), (0.052, -0.15), (0.045, -0.17), (0.0, -0.17)], n=12, + M=Mp @ Matrix.Translation((0, 0.135, 0.012 + 0.05)) @ Matrix.Rotation(math.pi / 2, 4, 'Y')) + out.append((roll, 'canvas')) + for sx in (-0.11, 0.11): + out.append((G.lathe('RollTie%d' % (sx > 0), [(0.0565, 0.009), (0.0565, -0.009)], n=12, cap_top=False, + M=Mp @ Matrix.Translation((sx, 0.135, 0.012 + 0.05)) @ Matrix.Rotation(math.pi / 2, 4, 'Y')), 'web')) + # buckles where the braces meet the belt, and at the front adjusters + for sxx in (-1, 1): + out += [(x, 'metal') for x in buckle(Matrix.Translation((sxx * 0.09, cy - 0.155, pz + 0.12)) @ Matrix.Rotation(math.pi / 2, 4, 'X'), 'BraceBuckle%d' % sxx)] + # pistol holster low on the right thigh, a lanyard up to the belt; fighting knife strapped to the left thigh + for s_, nm, sz, mat in ((-1, 'Holster', (0.075, 0.19, 0.045), 'boot'), (1, 'Knife', (0.035, 0.27, 0.018), 'boot')): + th = J(H, 'thigh_l' if s_ > 0 else 'thigh_r'); kn = J(H, 'calf_l' if s_ > 0 else 'calf_r') + mid = th.lerp(kn, 0.45 if s_ < 0 else 0.35) + d_ = Vector((s_ * (0.95 if s_ < 0 else 0.55), -0.3 if s_ < 0 else -0.83, 0)).normalized() + out += [(x, mat) for x in pouch(bvh, mid + d_ * 0.3, -d_, sz[0], sz[1], sz[2], nm, flap=s_ < 0, push=0.004)] + if s_ > 0: + out.append((G.box('KnifeGrip', (0.028, 0.024, 0.11), Matrix.Translation(mid + d_ * 0.11 + Vector((0, 0, 0.17))), bev=0.006, seg=2), 'boot')) + for zz in (0.05, -0.06): + out.append((G.strap(bvh, [mid + Vector((s_ * 0.0, -0.12, zz)), mid + Vector((s_ * 0.09, -0.04, zz)), mid + Vector((s_ * 0.09, 0.06, zz)), + mid + Vector((s_ * 0.0, 0.11, zz)), mid + Vector((-s_ * 0.08, 0.04, zz))], 0.018, 0.003, name='ThighStrap%d' % (zz > 0), thick=0.003, steps=16), 'web')) + else: + out.append((G.strap(bvh, [mid + d_ * 0.09 + Vector((0, 0, 0.09)), Vector((d_.x * 0.16, cy - 0.14, pz - 0.02)), Vector((0.05, cy - 0.16, pz + 0.03))], + 0.006, 0.002, name='Lanyard', thick=0.003, steps=18), 'web')) + import os as _os + if _os.environ.get('KIND') == 'ally': + # canvas leggings over the boot tops, laced up the side with two strap-and-buckle closures + for s_ in ('l', 'r'): + kn = J(H, 'calf_' + s_); an = J(H, 'foot_' + s_) + lg = limb_ring(bvh, kn, an, [0.6, 0.7, 0.8, 0.9, 0.97], [0.008, 0.009, 0.01, 0.012, 0.012], n=16, name='Legging' + s_) + out.append((lg, 'canvas')) + return out + +# ---------- enemies (one shared body; four outfits). No national or political insignia: the only marking is an +# invented plain white chevron on the left sleeve. +ENEMY_COL = dict(tunic='#5c6150', tunic2='#4c5143', trousers='#565a4b', boot='#1d1b19', leather='#211f1b', canvas='#6b6550', + helmet='#4b5047', coat='#5a5f53', band='#2f3a30', visor='#121212', metal='#4a4f42', chevron='#d6d2c4') + +def label_enemy(H, P, upper='tunic'): + wx = J(H, 'hand_l').x - 0.012 + boot_top = J(H, 'calf_l').z - 0.06 + waist = J(H, 'pelvis').z + 0.015 + lab = [] + for p in P: + x, y, z = p + if abs(x) > wx and z > J(H, 'upperarm_l').z - 0.25: + lab.append('skin') + elif z > J(H, 'neck_01').z + 0.03 or (z > PP.neck_threshold(H, p) and abs(x) < 0.085): + lab.append('skin') + elif z < boot_top: + lab.append('boot') + elif z >= waist: + lab.append(upper) + else: + lab.append('trousers') + return lab + +def materials_enemy(knee=0.54): + import wear as WR + camo = ['#3f4430', '#5c513a', '#2e3826', '#221f17'] + return { + 'tunic': WR.cloth('e_tunic', '#555a4c', '#464a3f', fade=0.12), + 'trousers': WR.cloth('e_trousers', '#4f5346', '#40443a', knee_z=knee, mud_amt=0.7), + 'coat': WR.cloth('e_coat', '#53574d', '#44483f', fade=0.1), + 'smock': WR.cloth('e_smock', '#4d4c36', '#424130', camo=camo, fade=0.1), + 'boot': WR.leather('e_boot', '#181614', '#0c0b0a', mud_low=0.3, polish=0.38), + 'leather': WR.leather('e_leather', '#1c1a17', '#100f0d', polish=0.5), + 'canvas': WR.webbing('e_canvas', '#5e5949', '#4d493c'), + 'helmet': WR.painted_metal('e_helmet', '#454a43', '#393d37'), + 'helmetcamo': WR.painted_metal('e_helmetcamo', '#4d4c36', '#424130', camo=camo[1:3]), + 'band': WR.cloth('e_band', '#2b342c', '#232a24', fade=0.05), + 'visor': WR.flat('e_visor', '#0d0d0d', rough=0.35), + 'metal': WR.painted_metal('e_metal', '#41463b', '#363a31', chip=0.7), + 'chevron': WR.cloth('e_chevron', '#c9c5b6', '#b5b1a2', fade=0.0, mud_amt=0.2), + } + +def helmet_stahl(H, name='Helmet'): + """Coal-scuttle style shell: dome, a step, then a flared skirt low at the sides and back, short visor at the front.""" + body = H['body']; P = G.coords(body.data); W = PP.vweights(body) + hv = np.array([P[i] for i in range(len(P)) if W[i].get('Head', 0) > 0.6]) + mn, mx = hv.min(0), hv.max(0) + c = Vector(((mn[0] + mx[0]) / 2, (mn[1] + mx[1]) / 2 + 0.012, mx[2] - 0.085)) + rx, ry = (mx[0] - mn[0]) / 2 + 0.024, (mx[1] - mn[1]) / 2 + 0.024 + n = 24 + verts, faces = [], [] + prof_n = 0 + for k in range(n): + th = 2 * math.pi * k / n # th=0 -> back (+y) + front = max(0.0, -math.cos(th)) # 1 at the front + side = abs(math.sin(th)) + drop = 0.075 * (1 - front) + 0.022 * front + 0.012 * side + flare = 1.18 - 0.08 * front + prof = [] + for i in range(8): + a = (i / 7) * (math.pi / 2) + prof.append((math.sin(a) * 1.0, math.cos(a) * 0.125 + 0.02)) + prof += [(1.04, 0.0), (1.05, -0.012)] # the step + prof += [(1.05 + (flare - 1.05) * 0.5, -drop * 0.6), (flare, -drop), (flare - 0.04, -drop - 0.004), (1.0, -0.01)] + prof_n = len(prof) + for r, z in prof: + verts.append(Vector((c.x + r * rx * math.sin(th), c.y + r * ry * math.cos(th), c.z + z))) + m = prof_n + for k in range(n): + k2 = (k + 1) % n + for j in range(m - 1): + faces.append([k * m + j, k2 * m + j, k2 * m + j + 1, k * m + j + 1]) + ob = G.mesh_obj(name, verts, faces) + G.rigid_weights(ob, 'Head') + return ob, c, (rx, ry) + +def peaked_cap(H, name='Cap'): + body = H['body']; P = G.coords(body.data); W = PP.vweights(body) + hv = np.array([P[i] for i in range(len(P)) if W[i].get('Head', 0) > 0.6]) + mn, mx = hv.min(0), hv.max(0) + c = Vector(((mn[0] + mx[0]) / 2, (mn[1] + mx[1]) / 2 + 0.012, mx[2] - 0.045)) + rx, ry = (mx[0] - mn[0]) / 2 + 0.008, (mx[1] - mn[1]) / 2 + 0.008 + out = [] + # band + band = G.lathe(name + 'Band', [(1.0, 0.0), (1.0, 0.035)], n=24, sx=rx, sy=ry, M=Matrix.Translation(c)) + G.solidify(band, 0.004, 1.0); out.append((band, 'band')) + # crown: wider than the band, raised at the front (saddle) + n = 24; verts = []; faces = [] + prof = [(1.0, 0.035), (1.18, 0.07), (1.2, 0.085), (1.0, 0.095), (0.6, 0.1), (0.0, 0.1)] + for k in range(n): + th = 2 * math.pi * k / n + front = max(0.0, -math.cos(th)) + for r, z in prof: + zz = z + (0.035 * front * front if z > 0.05 else 0.0) + verts.append(Vector((c.x + r * rx * math.sin(th), c.y + r * ry * math.cos(th), c.z + zz))) + m = len(prof) + for k in range(n): + k2 = (k + 1) % n + for j in range(m - 1): + faces.append([k * m + j, k2 * m + j, k2 * m + j + 1, k * m + j + 1]) + crown = G.mesh_obj(name + 'Crown', verts, faces); out.append((crown, 'coat')) + # visor: a curved plate at the front + vv = []; vf = [] + for i in range(9): + a = math.pi + (i - 4) / 4 * 0.9 + for rr, dz in ((1.0, 0.0), (1.45, -0.025)): + vv.append(Vector((c.x + rr * rx * math.sin(a), c.y + rr * ry * math.cos(a), c.z + 0.004 + dz))) + for i in range(8): + vf.append([2 * i, 2 * i + 2, 2 * i + 3, 2 * i + 1]) + vis = G.mesh_obj(name + 'Visor', vv, vf); G.solidify(vis, 0.004, 0); out.append((vis, 'visor')) + for o, _ in out: G.rigid_weights(o, 'Head') + return out, c, (rx, ry) + +def gear_enemy(H, cloth, kind): + bvh = G.bvh_of(cloth) + P = G.coords(cloth.data) + out = [] + pz = J(H, 'pelvis').z; cy = J(H, 'pelvis').y + torso = np.array([abs(p[0]) < 0.24 for p in P]) + nk = J(H, 'neck_01'); zc = nk.z + # high stand collar + col = envelope_rings(P, np.array([abs(p[0]) < 0.10 for p in P]), (0, nk.y + 0.01), [zc - 0.045, zc - 0.015, zc + 0.012, zc + 0.03], + [-0.004, 0.005, 0.007, 0.008], n=24, name='Collar') + G.solidify(col, 0.006, 1.0); out.append((col, 'band' if kind != 'sniper' else 'smock')) + long_ = kind in ('officer', 'sniper') + hips = np.array([abs(p[0]) < 0.25 and p[2] < pz + 0.1 for p in P]) + up = 'coat' if kind == 'officer' else ('smock' if kind == 'sniper' else 'tunic') + if kind == 'officer': + kz = J(H, 'calf_l').z + zs = [pz + 0.04, pz - 0.05, pz - 0.15, pz - 0.27, kz + 0.12, kz + 0.0] + offs = [0.008, 0.016, 0.03, 0.045, 0.06, 0.07] + legs = np.array([abs(p[0]) < 0.25 and p[2] < pz + 0.1 and p[2] > kz - 0.05 for p in P]) + skirt = envelope_rings(P, legs | hips, (0, cy + 0.01), zs, offs, n=32, name='Skirt') + elif kind == 'sniper': + zs = [pz + 0.04, pz - 0.05, pz - 0.14, pz - 0.24] + skirt = envelope_rings(P, hips, (0, cy + 0.01), zs, [0.008, 0.016, 0.028, 0.036], n=32, name='Skirt') + else: + skirt = envelope_rings(P, hips, (0, cy + 0.01), [pz + 0.04, pz - 0.03, pz - 0.10, pz - 0.16], [0.006, 0.012, 0.02, 0.026], n=32, name='Skirt') + G.solidify(skirt, 0.004, 1.0); out.append((skirt, up)) + # belt (black leather) with a plain buckle + belt = envelope_rings(P, torso, (0, cy + 0.01), [pz + 0.065, pz + 0.015], [0.014 if not long_ else 0.02, 0.016 if not long_ else 0.022], n=32, name='Belt') + G.solidify(belt, 0.005, 1.0); out.append((belt, 'leather')) + bvh2 = G.bvh_of(belt) + out += [(x, 'metal') for x in pouch(bvh2, Vector((0, cy - 0.4, pz + 0.04)), Vector((0, 1, 0)), 0.05, 0.042, 0.008, 'Buckle', flap=False)] + if kind in ('rifleman', 'gunner'): + if kind == 'rifleman': + for s in (-1, 1): + for k, ang in enumerate((20, 32, 44)): + a = math.radians(ang) * s; d = Vector((math.sin(a), -math.cos(a), 0)) + out += [(x, 'leather') for x in pouch(bvh2, Vector((0, cy, pz + 0.035)) + d * 0.4, -d, 0.045, 0.075, 0.034, 'Amm%d%d' % (s, k), push=0.004)] + else: + a = math.radians(-60); d = Vector((math.sin(a), -math.cos(a), 0)) + out += [(x, 'leather') for x in pouch(bvh2, Vector((0, cy, pz + 0.02)) + d * 0.4, -d, 0.09, 0.12, 0.04, 'Holster', push=0.004)] + out += [(x, 'leather') for x in pouch(bvh2, Vector((0, cy, pz + 0.035)) + Vector((0.55, -0.83, 0)) * 0.4, -Vector((0.55, -0.83, 0)), 0.08, 0.07, 0.03, 'ToolPouch', push=0.004)] + # Y-straps + sh = J(H, 'clavicle_l', 1) + for s in (-1, 1): + pts = [Vector((s * 0.10, cy - 0.3, pz + 0.07)), Vector((s * 0.11, cy - 0.3, pz + 0.3)), Vector((s * 0.12, -0.25, sh.z + 0.02)), + Vector((s * 0.125, sh.y, sh.z + 0.07)), Vector((s * 0.09, 0.25, sh.z - 0.02)), Vector((0.0, 0.3, sh.z - 0.2))] + out.append((G.strap(bvh, pts, 0.03, 0.004, name='Y%d' % s, thick=0.004, steps=20), 'leather')) + out.append((G.strap(bvh, [Vector((0, 0.3, sh.z - 0.2)), Vector((0, 0.3, pz + 0.07))], 0.03, 0.004, name='Yback', thick=0.004, steps=8), 'leather')) + # bread bag, canteen, fluted canister on the back + for s, nm, wh, mat in ((-1, 'Bread', (0.2, 0.17, 0.06), 'canvas'), (1, 'Etool', (0.12, 0.2, 0.04), 'leather')): + a = math.radians(140) * s; d = Vector((math.sin(a), -math.cos(a), 0)) + out += [(x, mat) for x in pouch(bvh2, Vector((0, cy, pz - 0.03)) + d * 0.4, -d, wh[0], wh[1], wh[2], nm, push=0.004)] + can = G.lathe('Canister', [(0.0, 0.135), (0.05, 0.135), (0.052, 0.12), (0.05, 0.10), (0.052, 0.07), (0.05, 0.04), (0.052, 0.01), (0.05, 0.0), (0.0, 0.0)], n=14, + M=Matrix.Translation((0.06, 0.2, pz - 0.18)) @ Matrix.Rotation(0.25, 4, 'Y')) + out.append((can, 'metal')) + if kind == 'gunner': + out += [(x, 'leather') for x in pouch(bvh, Vector((-0.02, 0.5, J(H, 'spine_03').z + 0.06)), Vector((0, -1, 0)), 0.09, 0.5, 0.07, 'BarrelCase', flap=False, push=0.01)] + elif kind == 'officer': + a = math.radians(-70); d = Vector((math.sin(a), -math.cos(a), 0)) + out += [(x, 'leather') for x in pouch(bvh2, Vector((0, cy, pz + 0.02)) + d * 0.4, -d, 0.09, 0.12, 0.04, 'Holster', push=0.004)] + # cross strap + sh = J(H, 'clavicle_r', 1) + out.append((G.strap(bvh, [Vector((0.12, -0.3, pz + 0.07)), Vector((0.0, -0.3, J(H, 'spine_03').z + 0.1)), Vector((-0.13, -0.2, sh.z + 0.03)), + Vector((-0.13, 0.2, sh.z + 0.02)), Vector((0.05, 0.3, J(H, 'spine_03').z + 0.05)), Vector((0.12, 0.3, pz + 0.07))], + 0.025, 0.004, name='Cross', thick=0.004, steps=24), 'leather')) + elif kind == 'sniper': + # binocular case and a small pouch + out += [(x, 'leather') for x in pouch(bvh2, Vector((0, cy, pz + 0.04)) + Vector((-0.5, -0.86, 0)) * 0.4, -Vector((-0.5, -0.86, 0)), 0.08, 0.1, 0.06, 'BinoCase', push=0.004)] + out += [(x, 'canvas') for x in pouch(bvh2, Vector((0, cy, pz - 0.02)) + Vector((0.77, 0.64, 0)) * 0.4, -Vector((0.77, 0.64, 0)), 0.2, 0.17, 0.06, 'Bread', push=0.004)] + # silhouette at a distance: rifleman = rolled blanket across the top of the back, gunner = a big pack under + # the barrel case, sniper = long smock and a scrim scarf, officer = cap and long coat + sp3 = J(H, 'spine_03') + if kind == 'rifleman' and False: # the roll's skin weights tore it into a flap over the shoulder: removed + roll = G.lathe('BlanketRoll', [(0.0, 0.2), (0.05, 0.2), (0.058, 0.17), (0.06, 0.0), (0.06, -0.17), (0.052, -0.2), (0.0, -0.2)], n=12, + M=Matrix.Translation((0, 0.14, sp3.z + 0.17)) @ Matrix.Rotation(math.pi / 2, 4, 'Y')) + out.append((roll, 'canvas')) + elif kind == 'gunner': + out += [(x, 'canvas') for x in pouch(bvh, Vector((0.03, 0.5, sp3.z - 0.06)), Vector((0, -1, 0)), 0.3, 0.3, 0.13, 'Pack', push=0.02)] + elif kind == 'sniper': + nk2 = J(H, 'neck_01') + sc = envelope_rings(P, np.array([abs(p[0]) < 0.12 for p in P]), (0, nk2.y + 0.01), [nk2.z - 0.07, nk2.z - 0.035, nk2.z - 0.005], + [0.014, 0.022, 0.018], n=20, name='Scarf') + G.solidify(sc, 0.008, 1.0); out.append((sc, 'smock')) + boot_details(P, bvh, out, laces=False) + # chevron on the left upper sleeve (the only marking; invented) + ua = J(H, 'upperarm_l'); el = J(H, 'lowerarm_l') + mid = ua.lerp(el, 0.45) + v = [mid + Vector((-0.03, -0.2, 0.025)), mid + Vector((0.0, -0.2, -0.01)), mid + Vector((0.03, -0.2, 0.025))] + ch = G.strap(bvh, v, 0.012, 0.0015, name='Chevron', thick=0.001, steps=10) + ch['hi_only'] = True + out.append((ch, 'chevron')) + # pocket shapes on the tunic front (high only) + sh = J(H, 'clavicle_l', 1) + for s in (-1, 1): + for nm, o, wh in (('Breast', Vector((s * 0.1, -0.4, sh.z - 0.17)), (0.12, 0.13)), ('Lower', Vector((s * 0.12, -0.4, pz - 0.06)), (0.16, 0.16))): + src = skirt if nm == 'Lower' else cloth + for x in pouch(G.bvh_of(src), o, Vector((0, 1, 0)), wh[0], wh[1], 0.006, nm + str(s), push=0.0): + x['hi_only'] = True; out.append((x, up)) + # boot soles + feet = np.array([p[2] < 0.05 for p in P]) + for s in (-1, 1): + fm = feet & np.array([p[0] * s > 0 for p in P]) + fx = float(np.mean(P[fm][:, 0])); fy = float(np.mean(P[fm][:, 1])) + sole = envelope_rings(P, fm, (fx, fy), [0.0, 0.0, 0.02, 0.03], [-0.03, 0.012, 0.013, 0.003], n=20, name='Sole%d' % s) + out.append((sole, 'boot')) + return out diff --git a/e63334287a3deaa3/ironveil/tools/chars/pack.sh b/e63334287a3deaa3/ironveil/tools/chars/pack.sh new file mode 100755 index 00000000..b6b1a7c9 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/pack.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# pack.sh name... : compress $CHARS_WORK/out/.glb into the game's assets folder with gltf-transform (meshopt). +# Needs node with @gltf-transform/cli available to npx. +. "$(dirname "$0")/env.sh" +T=$(mktemp -d) +# gltf-transform is installed with npm in $CHARS_WORK/../gt (npm i @gltf-transform/cli) or globally +[ -d "$CHARS_WORK/../gt/node_modules" ] && cd "$CHARS_WORK/../gt" +for n in "$@"; do + src=$CHARS_WORK/out/$n.glb + if [ "$n" = anims ]; then cp $CHARS_WORK/out/anims.json $CHARS_ASSETS/anims.json; npx gltf-transform resample $src $T/r.glb --tolerance 0.0001 >/dev/null 2>&1; src=$T/r.glb; fi + npx gltf-transform meshopt $src $CHARS_ASSETS/$n.glb --level high >/dev/null 2>&1 || cp $src $CHARS_ASSETS/$n.glb + ls -la $CHARS_ASSETS/$n.glb +done +rm -rf $T diff --git a/e63334287a3deaa3/ironveil/tools/chars/pen.sh b/e63334287a3deaa3/ironveil/tools/chars/pen.sh new file mode 100755 index 00000000..2efb630e --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/pen.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# pen.sh [kind] : hand vertices inside each weapon in the hold, aim and fire poses (needs the server on $PORT) +. "$(dirname "$0")/env.sh" +kind=${1:-hero} +for w in rifleScoped smg pistol enemyRifle mg; do + for u in hold aim fire; do + case "$w:$u" in + pistol:hold) up=holdPistol ;; pistol:aim) up=aimPistol ;; pistol:fire) up=firePistol ;; + *:hold) up=holdRifle ;; *:aim) up=aimIdle ;; *:fire) up=fire ;; + esac + r=$(timeout 200 node "$HERE/shot.js" "$CHARS_OUT/pen.png" "/e63334287a3deaa3/ironveil/chars-test.html?shot=1&kind=$kind&anim=idle&upper=$up&t=0.6&weapon=$w&pen=1" 300 300 2>&1 | grep -o '"pen":{[^}]*}') + echo "$w $u $r" + done +done diff --git a/e63334287a3deaa3/ironveil/tools/chars/pipe.py b/e63334287a3deaa3/ironveil/tools/chars/pipe.py new file mode 100644 index 00000000..b97a1ee4 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/pipe.py @@ -0,0 +1,465 @@ +# Shared outfit pipeline: cloth-from-body, folds, low/high, UV, bake, texture pack. +import bpy, bmesh, math, os +import numpy as np +from mathutils import Vector, Matrix, noise +import mhlib as L, geo as G, mats as MT + +def J(H, b, i=0): + return H['J'][b][i].copy() + +def vweights(ob): + names = {vg.index: vg.name for vg in ob.vertex_groups} + out = [] + for v in ob.data.vertices: + out.append({names[g.group]: g.weight for g in v.groups if g.weight > 0}) + return out + +def bone_sum(w, *keys): + return sum(x for k, x in w.items() if any(k.startswith(p) for p in keys)) + +class Regions: + """Per-vertex region labels on the body + displacement amounts + smoothing strength.""" + def __init__(self, body): + self.body = body + self.P = G.coords(body.data) + self.W = vweights(body) + self.label = ['skin'] * len(self.P) + +def neck_threshold(H, p, front_drop=0.06, base=0.0): + nz = J(H, 'neck_01').z; ny = J(H, 'neck_01').y + return nz + base + front_drop * (p[1] - ny) + +def cloth_body(H, labels, disp, smooth, folds_amp=0.0035, name='Cloth', alpha=None, slack=None, torso_dilate=0.06): + """Copy the body, smooth anatomy away and push cloth regions out. Returns (low_src, high).""" + body = H['body'] + ob = body.copy(); ob.data = body.data.copy(); ob.name = name; G.link(ob) + me = ob.data + n = len(me.vertices) + sm = np.array([smooth.get(labels[i], 0.0) for i in range(n)]) + sm = G.diffuse_scalar(me, sm, iters=2) + G.taubin(me, sm, iters=40) + sm2 = np.array([1.0 if labels[i] == 'boot' else 0.0 for i in range(n)]) + G.taubin(me, sm2 * 0.5, iters=40, mu=-0.0) + if alpha: + tubeify(ob, H, labels, alpha, slack or {}, torso_dilate=torso_dilate) + G.taubin(me, sm * 0.6, iters=6) + d = np.array([disp.get(labels[i], 0.0) for i in range(n)]) + d = G.diffuse_scalar(me, d, iters=2) + G.displace(me, d) + # material index per face from majority label + names = sorted(set(labels)) + for p in me.polygons: + ls = [labels[v] for v in p.vertices] + best = max(set(ls), key=ls.count) + p.material_index = names.index(best) + ob['labels'] = names + ob['vlabels'] = list(labels) + return ob + +def assign_mats(ob, mats): + names = list(ob['labels']) + me = ob.data + me.materials.clear() + for n in names: me.materials.append(mats[n]) + labels = list(ob['vlabels']) + for p in me.polygons: + ls = [labels[v] for v in p.vertices] + p.material_index = names.index(max(set(ls), key=ls.count)) + +def add_folds(ob, H, labels, amp, seed=0.0): + """Displace (high mesh) with cloth fold ridges running around the limbs.""" + me = ob.data + P = G.coords(me); N = G.normals(me) + W = vweights(ob) + segs = {} + for b in ('upperarm_l', 'upperarm_r', 'lowerarm_l', 'lowerarm_r', 'thigh_l', 'thigh_r', 'calf_l', 'calf_r', 'spine_01', 'spine_02', 'spine_03', 'pelvis'): + h, t = H['J'][b] + segs[b] = (np.array(h), np.array(t)) + joints = [np.array(J(H, k)) for k in ('lowerarm_l', 'lowerarm_r', 'calf_l', 'calf_r', 'upperarm_l', 'upperarm_r', 'thigh_l', 'thigh_r')] + out = P.copy() + for i in range(len(P)): + a = amp.get(labels[i] if i < len(labels) else 'skin', 0.0) + if a <= 0: continue + w = W[i] + if not w: continue + b = max(w, key=w.get) + key = next((k for k in segs if b.startswith(k[:-2]) and (k[-1] == b[-1] or k.startswith('spine') or k == 'pelvis')), None) + if b in segs: key = b + if key is None: continue + h, t = segs[key] + ax = t - h; L_ = np.linalg.norm(ax); ax /= L_ + rel = P[i] - h + s = rel.dot(ax) + radial = rel - ax * s + ang = math.atan2(radial[1], radial[0] if abs(ax[2]) > 0.5 else radial[2]) + jd = min(np.linalg.norm(P[i] - j) for j in joints) + env = 0.5 + 2.6 * math.exp(-(jd / 0.075) ** 2) # creases bunch at the elbows and knees + v = noise.noise(Vector((s * 30.0, math.cos(ang) * 1.3, math.sin(ang) * 1.3 + seed))) + v2 = noise.noise(Vector((s * 75.0 + 3.0, math.cos(ang) * 3.0, math.sin(ang) * 3.0 + seed))) + ridge = (1.0 - abs(v)) ** 3 * 1.0 + 0.25 * v2 + out[i] = P[i] + N[i] * (ridge * a * env) + G.set_coords(me, out) + +def make_high(cloth, H, labels_by_vertex, fold_amp, subdiv=1, label_fn=None): + hi = cloth.copy(); hi.data = cloth.data.copy(); hi.name = cloth.name + '_HI'; G.link(hi) + for m in list(hi.modifiers): hi.modifiers.remove(m) + # carry labels through subdivision by a float attribute per region index + names = cloth['labels'] + G.subsurf(hi, subdiv) + if label_fn is not None: + cs = [tuple(p.center) for p in hi.data.polygons] + fl = label_fn(H, cs) + for p, l in zip(hi.data.polygons, fl): + if l in names: p.material_index = names.index(l) + # recompute labels on the subdivided mesh from material index of faces + lab = ['skin'] * len(hi.data.vertices) + for p in hi.data.polygons: + for v in p.vertices: lab[v] = names[p.material_index] + add_folds(hi, H, lab, {k: v * 0.55 for k, v in fold_amp.items()}) # noise folds kept, but quieter + import detail + print('tailor', detail.tailor(hi, H, lab)) + return hi + +def decimate(ob, ratio, protect=None, protect_ratio=None): + if protect is not None: + vg = ob.vertex_groups.new(name='_protect') + vg.add(protect, 1.0, 'REPLACE') + m = ob.modifiers.new('dec', 'DECIMATE'); m.ratio = ratio + m.vertex_group = '_protect'; m.invert_vertex_group = True; m.vertex_group_factor = 1.0 + m.use_symmetry = True; m.symmetry_axis = 'X' + else: + m = ob.modifiers.new('dec', 'DECIMATE'); m.ratio = ratio; m.use_symmetry = True; m.symmetry_axis = 'X' + # armature modifier must not be applied + L.set_active(ob) + arm = [x for x in ob.modifiers if x.type == 'ARMATURE'] + for a in arm: ob.modifiers.remove(a) + bpy.ops.object.modifier_apply(modifier=m.name) + if protect is not None: ob.vertex_groups.remove(ob.vertex_groups['_protect']) + +def atlas_uv(ob, big_faces=None, big=2.0, margin=0.004): + """Smart-project the low mesh into a fresh 'atlas' UV map; scale chosen faces' islands up.""" + me = ob.data + uv = me.uv_layers.new(name='atlas') + me.uv_layers.active = uv + L.set_active(ob) + bpy.ops.object.mode_set(mode='EDIT') + bpy.ops.mesh.select_all(action='SELECT') + bpy.ops.uv.smart_project(angle_limit=math.radians(66), island_margin=margin, area_weight=0.0, scale_to_bounds=False) + bpy.ops.object.mode_set(mode='OBJECT') + if big_faces: + # scale those faces' UVs about their own island centres (islands may be shared, so scale per face-connected set) + bm = bmesh.new(); bm.from_mesh(me) + uvl = bm.loops.layers.uv['atlas'] + bm.faces.ensure_lookup_table() + sel = set(big_faces) + # islands by uv connectivity within selected faces + seen = set() + for fi in sel: + if fi in seen: continue + stack = [fi]; isl = [] + seen.add(fi) + while stack: + f = bm.faces[stack.pop()]; isl.append(f) + for e in f.edges: + for f2 in e.link_faces: + if f2.index in sel and f2.index not in seen: + # same uv island if shared edge uvs match + ok = True + for l in f.loops: + if l.edge == e: + a = l[uvl].uv; b = l.link_loop_next[uvl].uv + for l2 in f2.loops: + if l2.edge == e: + c = l2[uvl].uv; d = l2.link_loop_next[uvl].uv + if min((a - d).length + (b - c).length, (a - c).length + (b - d).length) > 1e-5: ok = False + if ok: + seen.add(f2.index); stack.append(f2.index) + cs = Vector((0, 0)); k = 0 + for f in isl: + for l in f.loops: cs += l[uvl].uv; k += 1 + cs /= k + done = set() + for f in isl: + for l in f.loops: + if l.index in done: continue + l[uvl].uv = cs + (l[uvl].uv - cs) * big + done.add(l.index) + bm.to_mesh(me); bm.free() + bpy.ops.object.mode_set(mode='EDIT') + bpy.ops.mesh.select_all(action='SELECT') + bpy.ops.uv.select_all(action='SELECT') + try: + bpy.ops.uv.pack_islands(rotate=True, scale=True, margin=margin, shape_method='CONCAVE') + except TypeError: + bpy.ops.uv.pack_islands(rotate=True, margin=margin) + bpy.ops.object.mode_set(mode='OBJECT') + +def bake(low, highs, size, kind, path, samples=64, extrusion=0.022, ray=0.05, margin=8, colorspace='sRGB'): + sc = bpy.context.scene + sc.render.engine = 'CYCLES'; sc.cycles.device = 'CPU'; sc.cycles.samples = samples + sc.render.threads_mode = 'FIXED'; sc.render.threads = int(os.environ.get('BAKE_THREADS', '2')) # shared machine + sc.render.bake.margin = margin + img = bpy.data.images.new('bake_' + kind, size, size, alpha=False, float_buffer=(kind == 'NORMAL')) + img.colorspace_settings.name = 'Non-Color' if kind in ('NORMAL', 'ROUGHNESS', 'AO', 'EMIT') else 'sRGB' + # every low material gets an active image node + for m in low.data.materials: + nt = m.node_tree + n = nt.nodes.get('_bake') or nt.nodes.new('ShaderNodeTexImage') + n.name = '_bake'; n.image = img + nt.nodes.active = n + low.data.uv_layers.active = low.data.uv_layers['atlas'] + for o in bpy.context.scene.objects: o.select_set(False) + for h in highs: + h.hide_render = False; h.select_set(True) + low.select_set(True); bpy.context.view_layer.objects.active = low + kw = dict(type=kind, use_selected_to_active=bool(highs), cage_extrusion=extrusion, max_ray_distance=ray, margin=margin) + if kind == 'DIFFUSE': + kw['pass_filter'] = {'COLOR'} + if kind == 'NORMAL': + kw['normal_space'] = 'TANGENT' + bpy.ops.object.bake(**kw) + img.filepath_raw = path + img.file_format = 'PNG' + img.save() + return path + +LIMBS = {'upperarm': 'arm', 'lowerarm': 'arm', 'thigh': 'leg', 'calf': 'leg', 'foot': 'foot', 'ball': 'foot'} + +def tubeify(ob, H, labels, alpha, slack, torso_dilate=0.06, torso_labels=('jacket',), nbins=24): + """Make cloth hang like fabric: limbs get rounder/looser cross-sections, torso loses its waist and belly shape. + alpha: {label: blend toward round section}, slack: {label: extra radius (m)}""" + me = ob.data + P = G.coords(me) + W = vweights(ob) + n = len(P) + new = np.zeros_like(P); wsum = np.zeros(n) + segs = {} + for b in ('upperarm_l', 'upperarm_r', 'lowerarm_l', 'lowerarm_r', 'thigh_l', 'thigh_r', 'calf_l', 'calf_r', 'foot_l', 'foot_r', 'ball_l', 'ball_r'): + h, t = H['J'][b] + segs[b] = (np.array(h), np.array(t)) + # per-segment radial profile + prof = {} + for b, (h, t) in segs.items(): + ax = t - h; Ln = np.linalg.norm(ax); ax = ax / Ln + idx = [i for i in range(n) if W[i].get(b, 0) > 0.3 and labels[i] != 'skin' and labels[i] != 'glove'] + if not idx: continue + rel = P[idx] - h + s = rel @ ax + rad = np.linalg.norm(rel - np.outer(s, ax), axis=1) + lo, hi = s.min(), s.max() + bins = np.clip(((s - lo) / max(1e-6, hi - lo) * nbins).astype(int), 0, nbins - 1) + rmax = np.zeros(nbins) + for k in range(nbins): + sel = rad[bins == k] + rmax[k] = np.percentile(sel, 85) if len(sel) else 0 + # fill gaps and smooth along the limb + for k in range(nbins): + if rmax[k] == 0: rmax[k] = rmax[max(0, k - 1)] + rmax = np.convolve(np.pad(rmax, 2, mode='edge'), np.ones(5) / 5, mode='valid') + prof[b] = (h, ax, lo, hi, rmax) + for i in range(n): + lab = labels[i] + a = alpha.get(lab, 0.0); sl = slack.get(lab, 0.0) + if a <= 0 and sl <= 0: continue + for b, w in W[i].items(): + if b not in prof or w < 0.02: continue + h, ax, lo, hi, rmax = prof[b] + rel = P[i] - h; s = rel @ ax + radv = rel - ax * s; r = np.linalg.norm(radv) + if r < 1e-6: continue + k = int(np.clip((s - lo) / max(1e-6, hi - lo) * nbins, 0, nbins - 1)) + r2 = (1 - a) * r + a * rmax[k] + sl + new[i] += w * (h + ax * s + radv / r * r2); wsum[i] += w + res = P.copy() + m = wsum > 0 + # verts only partly covered by limb bones keep the rest of their position + cov = np.clip(wsum, 0, 1) + res[m] = P[m] * (1 - cov[m, None]) + (new[m] / wsum[m, None]) * cov[m, None] + # torso dilation: radial distance from the spine axis -> max over a z window, per angle sector + tid = [i for i in range(n) if labels[i] in torso_labels and sum(W[i].get(b, 0) for b in ('spine_01', 'spine_02', 'spine_03', 'pelvis')) > 0.5] + if tid and torso_dilate > 0: + cy = float(np.mean(P[tid, 1])) + T = res[tid] + ang = np.arctan2(T[:, 0], -(T[:, 1] - cy)) + rr = np.hypot(T[:, 0], T[:, 1] - cy) + z = T[:, 2] + out = rr.copy() + for j in range(len(tid)): + sel = (np.abs(z - z[j]) < torso_dilate) & (np.abs(ang - ang[j]) < 0.12) + if sel.any(): + # only grow below the chest line (keeps shoulders) + out[j] = max(rr[j], 0.65 * rr[j] + 0.35 * rr[sel].max()) + for j, i in enumerate(tid): + sc = out[j] / max(rr[j], 1e-6) + res[i, 0] *= sc; res[i, 1] = cy + (res[i, 1] - cy) * sc + G.set_coords(me, res) + +def trim_hair(hair, c, rr, keep_below=0.0): + """Delete hair faces hidden under a helmet (centre c, radii rr).""" + import bmesh + bm = bmesh.new(); bm.from_mesh(hair.data) + kill = [] + for f in bm.faces: + inside = True + for v in f.verts: + p = v.co + dz = p.z - (c.z - 0.005) + e = ((p.x - c.x) / (rr[0] - 0.005)) ** 2 + ((p.y - c.y) / (rr[1] - 0.005)) ** 2 + if dz < 0 or e > 1.0: inside = False + if inside: kill.append(f) + bmesh.ops.delete(bm, geom=kill, context='FACES') + bm.to_mesh(hair.data); bm.free() + +def finish(H, name, cloth, gear, labels, fold_amp, size=2048, out_dir=None, low_ratio=0.32, big_skin=2.2, + ao_mix=0.6, extra_lows=(), log=print, decimate_extra=None, label_fn=None): + """cloth: processed cloth body with materials; gear: list of (obj, matname) already with materials. + Builds high + low, bakes textures, returns (low_obj, texture paths).""" + from PIL import Image + sc = bpy.context.scene + if not sc.world: + sc.world = bpy.data.worlds.new('W') + sc.world.light_settings.distance = 0.12 + # ---- high + hi = make_high(cloth, H, labels, fold_amp, label_fn=label_fn) + highs = [hi] + for ob, mn in gear: + c = ob.copy(); c.data = ob.data.copy(); G.link(c); highs.append(c) + for m in list(c.modifiers): c.modifiers.remove(m) + log('high tris', sum(G.tris(h) for h in highs)) + # ---- low + low = cloth.copy(); low.data = cloth.data.copy(); low.name = name + 'Low'; G.link(low) + decimate(low, low_ratio) + gl = [] + for ob, mn in gear: + if ob.get('hi_only'): continue + c = ob.copy(); c.data = ob.data.copy(); G.link(c); gl.append(c) + low = G.join([low] + gl, name) + for m in list(low.modifiers): low.modifiers.remove(m) + log('low tris', G.tris(low)) + # ---- UVs + skinmat = [i for i, m in enumerate(low.data.materials) if m and 'skin' in m.name] + big = [p.index for p in low.data.polygons if p.material_index in skinmat] + atlas_uv(low, big_faces=big, big=big_skin) + for o in [low]: + o.visible_diffuse = False; o.visible_glossy = False; o.visible_shadow = False + o.visible_transmission = False; o.visible_volume_scatter = False + for o in bpy.context.scene.objects: + o.hide_render = not (o in highs or o == low) + td = out_dir + os.makedirs(td, exist_ok=True) + t0 = __import__('time').time() + bake(low, highs, size, 'DIFFUSE', td + '/_diff.png', samples=2) + log('baked diffuse', __import__('time').time() - t0) + bake(low, highs, size, 'NORMAL', td + '/_nrm.png', samples=4) + log('baked normal') + bake(low, highs, size // 2, 'AO', td + '/_ao.png', samples=32) + log('baked ao') + bake(low, highs, size // 2, 'ROUGHNESS', td + '/_rough.png', samples=1) + log('baked rough') + allm = set() + for h in highs + [low]: + for m in h.data.materials: allm.add(m) + sv = metal_pass_begin(list(allm)) + bake(low, highs, size // 2, 'EMIT', td + '/_metal.png', samples=1) + metal_pass_end(sv) + log('baked metal') + # ---- composite + diff = np.asarray(Image.open(td + '/_diff.png').convert('RGB')).astype(np.float32) / 255 + ao = np.asarray(Image.open(td + '/_ao.png').convert('L').resize((size, size), Image.BILINEAR)).astype(np.float32) / 255 + alb = diff * (1 - ao_mix + ao_mix * ao)[..., None] + Image.fromarray(np.clip(alb * 255 + 0.5, 0, 255).astype(np.uint8)).save(td + '/albedo.jpg', quality=88) + fix_normals(td) + r = np.asarray(Image.open(td + '/_rough.png').convert('L')).astype(np.uint8) + mt = np.asarray(Image.open(td + '/_metal.png').convert('L')).astype(np.uint8) + orm = np.stack([np.full_like(r, 255), r, mt], -1) + Image.fromarray(orm).save(td + '/orm.jpg', quality=85) + for h in highs: bpy.data.objects.remove(h) + return low + +def fix_normals(td): + """Write normal.jpg from the baked _nrm.png. A tangent-space normal never points into the surface; texels that + do (blue well below half: the bake ray hit the wrong surface, e.g. a boot sole tucked against the boot) are + replaced by the flat normal so they do not catch the sky as white patches.""" + from PIL import Image + n = np.asarray(Image.open(td + '/_nrm.png').convert('RGB')).astype(np.float32) + bad = n[..., 2] < 150 + n[bad] = (128, 128, 255) + Image.fromarray(n.astype(np.uint8)).save(td + '/normal.jpg', quality=92) + return float(bad.mean()) + +def hair_atlas(parts, out_png, size=1024): + """parts: list of (obj, image_path, rect(x,y,w,h) in 0..1 with y from top). Remaps UVs; writes RGBA atlas.""" + from PIL import Image + atl = Image.new('RGBA', (size, size), (40, 30, 22, 0)) + for ob, img, (x, y, w, h) in parts: + im = Image.open(img).convert('RGBA').resize((int(w * size), int(h * size)), Image.LANCZOS) + if 'eyebrow' in img: + # the brow card is fine single hairs; under an alpha cut-off they break into dashes. Thicken the hair + # mass (grow, soften, re-threshold) so the cut-off keeps a continuous brow, with a ragged edge + from PIL import ImageFilter + r, g, b, al = im.split() + al = al.filter(ImageFilter.MaxFilter(3)).filter(ImageFilter.GaussianBlur(1.6)) + al = al.point(lambda v: max(0, min(255, int((v - 45) * 1.7)))) + rgb = Image.merge("RGB", (r, g, b)).filter(ImageFilter.MaxFilter(5)).point(lambda v: min(255, int(v * 1.25 + 12))) + im = Image.merge('RGBA', (*rgb.split(), al)) + atl.paste(im, (int(x * size), int(y * size))) + uv = ob.data.uv_layers['UVMap'] + for d in uv.data: + u, v = d.uv + d.uv = (x + (u % 1.0 if u != 1.0 else 1.0) * w, (1 - y - h) + (v % 1.0 if v != 1.0 else 1.0) * h) + # bleed colour into transparent texels so mips do not go dark + a = np.asarray(atl).astype(np.float32) + rgb = a[..., :3]; al = a[..., 3:] / 255 + atl.save(out_png) + return out_png + +def final_material(name, td, alpha=False, rough=None): + m = bpy.data.materials.new(name); m.use_nodes = True + nt = m.node_tree; b = nt.nodes['Principled BSDF'] + tex = nt.nodes.new('ShaderNodeTexImage'); tex.image = bpy.data.images.load(td['albedo']) + nt.links.new(tex.outputs[0], b.inputs['Base Color']) + if alpha: + nt.links.new(tex.outputs[1], b.inputs['Alpha']) + m.blend_method = 'CLIP' if hasattr(m, 'blend_method') else None + try: m.surface_render_method = 'DITHERED' + except Exception: pass + m.alpha_threshold = 0.5 if hasattr(m, 'alpha_threshold') else None + if 'normal' in td: + nm = nt.nodes.new('ShaderNodeNormalMap'); nt2 = nt.nodes.new('ShaderNodeTexImage') + nt2.image = bpy.data.images.load(td['normal']); nt2.image.colorspace_settings.name = 'Non-Color' + nt.links.new(nt2.outputs[0], nm.inputs['Color']); nt.links.new(nm.outputs[0], b.inputs['Normal']) + if 'orm' in td: + o = nt.nodes.new('ShaderNodeTexImage'); o.image = bpy.data.images.load(td['orm']); o.image.colorspace_settings.name = 'Non-Color' + sep = nt.nodes.new('ShaderNodeSeparateColor') + nt.links.new(o.outputs[0], sep.inputs[0]) + nt.links.new(sep.outputs[1], b.inputs['Roughness']); nt.links.new(sep.outputs[2], b.inputs['Metallic']) + else: + b.inputs['Roughness'].default_value = rough if rough is not None else 0.6 + b.inputs['Metallic'].default_value = 0.0 + return m + +def metal_pass_begin(mats_): + """Route each material's METAL value into an emission shader so it can be baked with type EMIT.""" + saved = [] + for m in mats_: + if not m or not m.use_nodes: continue + nt = m.node_tree + out = next((n for n in nt.nodes if n.type == 'OUTPUT_MATERIAL'), None) + mv = nt.nodes.get('METAL') + if out is None: continue + old = [l.from_socket for l in out.inputs[0].links] + em = nt.nodes.new('ShaderNodeEmission'); em.name = '_metal_em' + if mv is not None: + nt.links.new(mv.outputs[0], em.inputs['Color']) + else: + em.inputs['Color'].default_value = (0, 0, 0, 1) + nt.links.new(em.outputs[0], out.inputs[0]) + saved.append((m, old, em)) + return saved + +def metal_pass_end(saved): + for m, old, em in saved: + nt = m.node_tree + out = next((n for n in nt.nodes if n.type == 'OUTPUT_MATERIAL'), None) + nt.nodes.remove(em) + if old: nt.links.new(old[0], out.inputs[0]) diff --git a/e63334287a3deaa3/ironveil/tools/chars/posesheet.sh b/e63334287a3deaa3/ironveil/tools/chars/posesheet.sh new file mode 100755 index 00000000..aa862a9f --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/posesheet.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# posesheet.sh out.png : aim, crouch aim, prone aim, jog with the rifle from the player camera, 45 degrees behind +# and the side, on a mid-grey floor (one browser at a time) +. "$(dirname "$0")/env.sh" +out=$1; T=$(mktemp -d); i=0 +for pose in "anim=idle&upper=aimIdle" "anim=crouchIdle&upper=crouchAim" "anim=proneAim" "anim=jogF&upper=holdRifle" "anim=crouchF&upper=holdRifle"; do + for cam in "cam=ots2" "cam=ots45" "cam=side"; do + i=$((i+1)); timeout 200 node "$HERE/shot.js" $T/p$i.png "/e63334287a3deaa3/ironveil/chars-test.html?shot=1&kind=hero&$pose&t=0.5&weapon=rifleScoped&grey=1&$cam" 400 300 >/dev/null + done +done +python3 -I -c " +import sys +from PIL import Image +n=int(sys.argv[3]); ims=[Image.open(sys.argv[2]+'/p%d.png'%i) for i in range(1,n+1)] +c=Image.new('RGB',(1200,300*(n//3))); [c.paste(im,((i%3)*400,(i//3)*300)) for i,im in enumerate(ims)]; c.save(sys.argv[1])" $out $T $i diff --git a/e63334287a3deaa3/ironveil/tools/chars/pronechk.js b/e63334287a3deaa3/ironveil/tools/chars/pronechk.js new file mode 100644 index 00000000..2168f1f6 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/pronechk.js @@ -0,0 +1,28 @@ +// prone checks in drive mode: held-gun pitch (muzzle direction below horizontal, degrees) and left hand to +// fore-grip (cm) while prone still, prone aiming and crawling; plus the arm pop at jog->sprint and sprint->stop +const { chromium } = require(process.env.PLAYWRIGHT || 'playwright'); +(async () => { + const w = process.argv[2] || 'smg'; + const b = await chromium.launch({ executablePath: process.env.CHROME || undefined, args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'] }); + const p = await b.newPage({ viewport: { width: 200, height: 150 } }); + p.on('pageerror', e => console.log('pageerror:', String(e).slice(0, 300))); + await p.goto(`http://127.0.0.1:${process.env.PORT || 8981}/e63334287a3deaa3/ironveil/chars-test.html?drive=1&scenario=measure&kind=hero&weapon=${w}`); + await p.waitForFunction('window.DRIVE && window.DRIVE.a', null, { timeout: 120000 }); + const r = await p.evaluate(() => { + const a = DRIVE.a, out = [], v = new THREE.Vector3(), v2 = new THREE.Vector3(), q = new THREE.Quaternion(); + function run(keys, n) { const res = { pitch: [], grip: [] }; for (let i = 0; i < n; i++) { window.SIM(a, keys, 1 / 60); + a.root.updateMatrixWorld(true); const g = a.held; g.getWorldQuaternion(q); const f = new THREE.Vector3(0, 0, 1).applyQuaternion(q); + res.pitch.push(-Math.asin(f.y) * 57.3); if (g.userData.gripL) { g.userData.gripL.getWorldPosition(v); a.bones.hand_l.getWorldPosition(v2); res.grip.push(v.distanceTo(v2) * 100); } } + const m = x => x.reduce((s, y) => s + y, 0) / x.length; return { pitch: m(res.pitch.slice(-60)).toFixed(1), grip: m(res.grip.slice(-60)).toFixed(1), gripMax: Math.max(...res.grip.slice(-60)).toFixed(1) }; } + out.push(['stand', run({}, 120)]); + out.push(['prone still', run({ prone: 1 }, 150)]); + out.push(['prone aim', run({ prone: 1, aim: 1 }, 150)]); + out.push(['prone crawl', run({ prone: 1, w: 1 }, 150)]); + out.push(['stand aim', run({ aim: 1 }, 150)]); + out.push(['prone aim, camera 0.6 rad down', run({ prone: 1, aim: 1, pitch: -0.6 }, 150)]); + out.push(['prone aim, camera 1.0 rad down', run({ prone: 1, aim: 1, pitch: -1.0 }, 150)]); + return out.map(x => x[0].padEnd(32) + ' gun pitch ' + x[1].pitch + ' deg left hand to grip ' + x[1].grip + ' cm (max ' + x[1].gripMax + ')').join('\n'); + }); + console.log(r); + await b.close(); +})(); diff --git a/e63334287a3deaa3/ironveil/tools/chars/rebuild_all.sh b/e63334287a3deaa3/ironveil/tools/chars/rebuild_all.sh new file mode 100755 index 00000000..5caa113c --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/rebuild_all.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Rebuilds every character and clip file from the CC0 sources and packs them into the game's assets folder. +# Weapons are built by build_weapons.py / export_weapons.py (now owned by the weapons branch; run with WEAPONS=1). +. "$(dirname "$0")/env.sh" +cd "$CHARS_WORK" || exit 1 +B=./bvenv/bin/python; O=$PWD/out; mkdir -p $O +$B $HERE/build_hero.py bake > hero_build.log 2>&1; $B $HERE/assemble.py hero $O/hero.glb >> hero_build.log 2>&1; $HERE/pack.sh hero +KIND=ally $B $HERE/build_hero.py bake > ally_build.log 2>&1; $B $HERE/assemble.py ally $O/ally.glb >> ally_build.log 2>&1; $HERE/pack.sh ally +$B $HERE/build_enemy.py > enemy_build.log 2>&1; $B $HERE/assemble.py enemy $O/enemy.glb >> enemy_build.log 2>&1; $HERE/pack.sh enemy +$B $HERE/anims_build.py $O/anims.glb > anim.log 2>&1; $HERE/pack.sh anims +if [ -n "$WEAPONS" ]; then + $B $HERE/build_weapons.py bake > weapons_build.log 2>&1; $B $HERE/export_weapons.py $O/weapons.glb >> weapons_build.log 2>&1; $HERE/pack.sh weapons +fi +echo ALLDONE +grep -hE "rror|Trace" *_build.log anim.log diff --git a/e63334287a3deaa3/ironveil/tools/chars/sheet.sh b/e63334287a3deaa3/ironveil/tools/chars/sheet.sh new file mode 100755 index 00000000..f6f8d698 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/sheet.sh @@ -0,0 +1,11 @@ +#!/bin/bash +# sheet.sh out.png "query" t1 t2 ... : a row of 600x600 test-page shots at the given clip times (needs the server on $PORT). +. "$(dirname "$0")/env.sh" +out=$1; q=$2; shift 2; files=""; T=$(mktemp -d) +for t in "$@"; do f=$T/s_$t.png; node $HERE/shot.js $f "/e63334287a3deaa3/ironveil/chars-test.html?shot=1&t=$t&$q" 600 600 >/dev/null 2>&1; files="$files $f"; done +python3 -I -c " +import sys +from PIL import Image +fs=sys.argv[2:]; ims=[Image.open(f) for f in fs] +c=Image.new('RGB',(600*len(ims),600));[c.paste(im,(i*600,0)) for i,im in enumerate(ims)];c.save(sys.argv[1])" $out $files +rm -rf $T diff --git a/e63334287a3deaa3/ironveil/tools/chars/shot.js b/e63334287a3deaa3/ironveil/tools/chars/shot.js new file mode 100644 index 00000000..4376dad7 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/shot.js @@ -0,0 +1,16 @@ +// usage: node shot.js out.png "url-path-with-query" [w h] [waitExpr] +const { chromium } = require(process.env.PLAYWRIGHT || 'playwright'); +(async () => { + const [out, path, w = 900, h = 900, wait = 'window.READY||window.ERR'] = process.argv.slice(2); + const b = await chromium.launch({ executablePath: process.env.CHROME || undefined, args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'] }); + const p = await b.newPage({ viewport: { width: +w, height: +h } }); + await p.route('**/*', r => { const u = r.request().url(); if (/firebase|googleapis\.com\/identity|google-analytics|googletagmanager|gstatic\.com\/firebasejs|pagead|adsbygoogle/.test(u)) return r.abort(); return r.continue(); }); + p.on('console', m => { if (m.type() === 'error' || m.type() === 'warning') console.log('console:', m.text().slice(0, 300)); }); + p.on('pageerror', e => console.log('pageerror:', String(e).slice(0, 400))); + await p.goto(`http://127.0.0.1:${process.env.PORT || 8981}` + path); + await p.waitForFunction(wait, null, { timeout: 120000 }); + const info = await p.evaluate(() => JSON.stringify(window.ERR || window.INFO || {})); + console.log(info.slice(0, 1500)); + await p.screenshot({ path: out }); + await b.close(); +})().catch(e => { console.error(e); process.exit(1); }); diff --git a/e63334287a3deaa3/ironveil/tools/chars/spawnchk.js b/e63334287a3deaa3/ironveil/tools/chars/spawnchk.js new file mode 100644 index 00000000..d4c0ac3b --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/spawnchk.js @@ -0,0 +1,14 @@ +// spawn every kind and read the hands before any update (T-pose check, as the game measures it) +const { chromium } = require(process.env.PLAYWRIGHT || 'playwright'); +(async () => { + const b = await chromium.launch({ executablePath: process.env.CHROME || undefined, args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'] }); + const p = await b.newPage({ viewport: { width: 200, height: 150 } }); + await p.goto(`http://127.0.0.1:${process.env.PORT || 8981}/e63334287a3deaa3/ironveil/chars-test.html?shot=1&kind=hero&anim=idle&t=0.1`); + await p.waitForFunction('window.READY||window.ERR', null, { timeout: 120000 }); + console.log(await p.evaluate(() => { const out = [], v = new THREE.Vector3(), v2 = new THREE.Vector3(); + for (const k of ['hero', 'ally', 'rifleman', 'officer', 'sniper', 'gunner']) { const a = IVChars.spawn(k); a.root.updateMatrixWorld(true); + a.bone('hand_l').getWorldPosition(v); a.bone('hand_r').getWorldPosition(v2); + out.push(k + ' hands ' + v.y.toFixed(2) + '/' + v2.y.toFixed(2) + ' spread ' + v.distanceTo(v2).toFixed(2)); a.dispose(); } + return out.join('\n'); })); + await b.close(); +})(); diff --git a/e63334287a3deaa3/ironveil/tools/chars/stoptrace.js b/e63334287a3deaa3/ironveil/tools/chars/stoptrace.js new file mode 100644 index 00000000..7c23b408 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/stoptrace.js @@ -0,0 +1,12 @@ +const { chromium } = require(process.env.PLAYWRIGHT || 'playwright'); +(async () => { + const keys = JSON.parse(process.argv[2] || '{"w":1,"aim":1}'); + const b = await chromium.launch({ executablePath: process.env.CHROME || undefined, args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'] }); + const p = await b.newPage({ viewport: { width: 200, height: 150 } }); + p.on('pageerror', e => console.log('pageerror:', String(e).slice(0, 300))); + await p.goto(`http://127.0.0.1:${process.env.PORT || 8981}/e63334287a3deaa3/ironveil/chars-test.html?drive=1&scenario=measure&kind=hero&weapon=smg`); + await p.waitForFunction('window.DRIVE && window.DRIVE.a', null, { timeout: 120000 }); + const r = await p.evaluate(k => { window.TRACE = 1; return window.GSTOP(k); }, keys); + console.log('max', r.max, 'n', r.n); r.trace.forEach(t => console.log(t)); + await b.close(); +})(); diff --git a/e63334287a3deaa3/ironveil/tools/chars/turntable.sh b/e63334287a3deaa3/ironveil/tools/chars/turntable.sh new file mode 100755 index 00000000..338dba0b --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/turntable.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# turntable.sh kind out.png : the soldier at 2, 5 and 15 m, front three-quarter and back three-quarter, under the +# overcast day and under night_moon with a warm lamp, on the grey floor (one browser at a time per shot) +. "$(dirname "$0")/env.sh" +k=$1; out=$2; T=$(mktemp -d); i=0; W=${W:-rifleScoped} +for light in overcast night; do + for dist in 2 5 15; do + for yaw in 35 215; do + i=$((i+1)); ty=$(python3 -c "print({2:1.0,5:0.95,15:0.9}[$dist])") + timeout 200 node "$HERE/shot.js" $T/p$i.png "/e63334287a3deaa3/ironveil/chars-test.html?shot=1&kind=$k&anim=idle&upper=holdRifle&t=0.5&weapon=$W&grey=1&light=$light&cyaw=$yaw&cpitch=6&cdist=$((dist*1))&cty=$ty" 300 400 >/dev/null + done + done +done +python3 -I -c " +import sys +from PIL import Image +n=int(sys.argv[3]); ims=[Image.open(sys.argv[2]+'/p%d.png'%i) for i in range(1,n+1)] +c=Image.new('RGB',(300*6,400*2)); [c.paste(im,((i%6)*300,(i//6)*400)) for i,im in enumerate(ims)]; c.save(sys.argv[1])" $out $T $i diff --git a/e63334287a3deaa3/ironveil/tools/chars/videos.sh b/e63334287a3deaa3/ironveil/tools/chars/videos.sh new file mode 100755 index 00000000..796a6b1e --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/videos.sh @@ -0,0 +1,13 @@ +#!/bin/bash +# videos.sh [suffix] [scenario...] : renders the drive-mode scenarios to MP4 and writes their measurements as JSON. +# Needs the repo served on $PORT (python3 -m http.server $PORT from the repo root), node + playwright, ffmpeg. +. "$(dirname "$0")/env.sh" +suf=$1; shift +list=${*:-sprintReversal strafeCircleAim enemyPatrol startJogStop walkJogSprintStop walkJogSprintStopOTS slopeAndSteps stanceChain backOnly sprintBack} +mkdir -p $CHARS_OUT/videos; cd $HERE +for v in $list; do + k=hero; w=rifleScoped; [ $v = enemyPatrol ] && k=rifleman && w=enemyRifle + F=$(mktemp -d); node capture.js $v $F $k $w 854 480 > $CHARS_OUT/videos/$v$suf.json 2>&1 + ffmpeg -y -loglevel error -framerate 30 -i $F/f%04d.png -c:v libx264 -pix_fmt yuv420p -crf 22 $CHARS_OUT/videos/$v$suf.mp4; rm -rf $F; echo "done $v" +done +node capture.js measure - hero rifleScoped > $CHARS_OUT/videos/measure$suf.json 2>&1 diff --git a/e63334287a3deaa3/ironveil/tools/chars/weapons.py b/e63334287a3deaa3/ironveil/tools/chars/weapons.py new file mode 100644 index 00000000..a0a991a8 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/weapons.py @@ -0,0 +1,222 @@ +# Period-plausible weapon models built from code (no markings). Blender frame: barrel along -Y, up +Z, +# origin = right-hand grip point. Each weapon gets empties: muzzle, gripL (left-hand support point). +import bpy, bmesh, math, sys, os +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from mathutils import Vector, Matrix +import mhlib as L, geo as G, mats as MT + +def prof(name, pts, width, bev=0.003, x=0.0, seg=1): + """Side profile (y,z) list (counter-clockwise or not), extruded across X.""" + bm = bmesh.new() + vs = [bm.verts.new((x - width / 2, y, z)) for y, z in pts] + f = bm.faces.new(vs) + r = bmesh.ops.extrude_face_region(bm, geom=[f]) + nv = [e for e in r['geom'] if isinstance(e, bmesh.types.BMVert)] + bmesh.ops.translate(bm, verts=nv, vec=(width, 0, 0)) + bmesh.ops.recalc_face_normals(bm, faces=bm.faces) + me = bpy.data.meshes.new(name); bm.to_mesh(me); bm.free() + ob = G.link(bpy.data.objects.new(name, me)) + if bev > 0: + m = ob.modifiers.new('b', 'BEVEL'); m.width = bev; m.segments = seg; m.limit_method = 'ANGLE'; m.angle_limit = math.radians(30) + G.apply_mods(ob) + for p in ob.data.polygons: p.use_smooth = True + ob.data.set_sharp_from_angle(angle=math.radians(40)) if hasattr(ob.data, 'set_sharp_from_angle') else None + return ob + +def cyl(name, r, y0, y1, z=0.0, x=0.0, n=12, r1=None, axis='Y', caps=True): + """Cylinder along -Y from y0 to y1 (y1 < y0 is forward).""" + r1 = r if r1 is None else r1 + verts, faces = [], [] + for k in range(n): + a = 2 * math.pi * k / n + c, s = math.cos(a), math.sin(a) + if axis == 'Y': + verts += [(x + c * r, y0, z + s * r), (x + c * r1, y1, z + s * r1)] + elif axis == 'Z': + verts += [(x + c * r, z + s * r, y0), (x + c * r1, z + s * r1, y1)] + else: + verts += [(y0, x + c * r, z + s * r), (y1, x + c * r1, z + s * r1)] + for k in range(n): + a, b = 2 * k, 2 * ((k + 1) % n) + faces.append([a, b, b + 1, a + 1]) + if caps: + faces.append([2 * k for k in range(n)][::-1]); faces.append([2 * k + 1 for k in range(n)]) + ob = G.mesh_obj(name, verts, faces) + return ob + +def bx(name, cx, cy, cz, sx, sy, sz, bev=0.002): + return G.box(name, (sx, sy, sz), Matrix.Translation((cx, cy, cz)), bev=bev, seg=1) + +def empty(name, loc, parent, rot=None): + e = bpy.data.objects.new(name, None); G.link(e) + e.location = loc + if rot is not None: e.rotation_mode = 'QUATERNION'; e.rotation_quaternion = rot + e.parent = parent + return e + +def finish(name, parts, muzzle, gripL): + for ob, mat in parts: + ob.data.materials.clear(); ob.data.materials.append(mat) + ob = G.join([p for p, _ in parts], name) + G.link # noqa + empty(name + '_muzzle', muzzle, ob) + empty(name + '_gripL', gripL, ob) + return ob + +def materials(): + import wear as WR + return { + 'wood': WR.wood('w_wood'), + 'steel': WR.blued('w_steel'), + 'park': WR.blued('w_park', '#4c4e47', '#41433d', bright='#a8a8a0', park=True), + 'od': WR.painted_metal('w_od', '#45472f', '#383a27', chip=0.6), + 'black': WR.blued('w_black', '#262523', '#2e2c2a', bright='#6a6864', wear=0.6, park=True), + 'brass': WR.blued('w_brass', '#9a8048', '#80683a', bright='#c8b070', wear=0.5), + 'leather': WR.leather('w_leather', '#3a281b', '#24180f', polish=0.5), + 'glass': WR.flat('w_glass', '#0e1216', rough=0.08), + } + +def rifle_scoped(M): + """Bolt-action service rifle with a side-mounted-looking scope (generic). Length ~1.10 m.""" + p = [] + # stock: butt at +y 0.42, wrist at 0, fore-end to -0.46 + stock = [(0.345, -0.075), (0.345, 0.035), (0.24, 0.02), (0.09, 0.012), (0.04, 0.0), (0.0, 0.002), + (-0.06, 0.012), (-0.46, 0.014), (-0.47, -0.012), (-0.06, -0.02), (0.0, -0.045), (0.05, -0.06), + (0.11, -0.045), (0.24, -0.06)] + p.append((prof('stock', stock, 0.042, bev=0.006, seg=2), M['wood'])) + p.append((prof('handguard', [(-0.08, 0.026), (-0.40, 0.024), (-0.40, 0.012), (-0.08, 0.012)], 0.03, bev=0.004), M['wood'])) + p.append((cyl('barrel', 0.0085, -0.40, -0.68, z=0.020, n=10, r1=0.0075), M['steel'])) + p.append((cyl('receiver', 0.016, 0.03, -0.12, z=0.022, n=12), M['steel'])) + p.append((cyl('bolt', 0.004, 0.0, 0.0, z=0.03, n=6), M['steel'])) + bh = cyl('boltH', 0.004, 0.0, 0.0, n=6) + bm = bh.data + for v in bm.vertices: v.co = Vector((v.co.x * 1, v.co.y, v.co.z)) + p.append((cyl('boltArm', 0.0045, 0.02, 0.02, n=6, axis='X', z=0.03, x=0.0) if False else bx('boltArm', -0.035, 0.02, 0.022, 0.05, 0.008, 0.008), M['steel'])) + p.append((G.box('boltKnob', (0.014, 0.014, 0.014), Matrix.Translation((-0.062, 0.025, 0.012)), bev=0.005, seg=2), M['steel'])) + p.append((bx('guard', 0, -0.005, -0.035, 0.012, 0.07, 0.006), M['steel'])) + p.append((bx('mag', 0, -0.05, -0.02, 0.026, 0.07, 0.012), M['steel'])) + p.append((bx('band1', 0, -0.36, 0.02, 0.034, 0.012, 0.042), M['steel'])) + p.append((bx('fsight', 0, -0.665, 0.034, 0.004, 0.012, 0.016), M['steel'])) + p.append((bx('butt', 0, 0.347, -0.02, 0.044, 0.006, 0.11), M['steel'])) + # scope: tube with objective bell, eyepiece, two rings + sz = 0.072 + p.append((cyl('scope', 0.011, 0.11, -0.13, z=sz, n=14), M['steel'])) + p.append((cyl('scopeObj', 0.011, -0.13, -0.19, z=sz, n=14, r1=0.017), M['steel'])) + p.append((cyl('scopeEye', 0.015, 0.16, 0.11, z=sz, n=14, r1=0.011), M['steel'])) + p.append((cyl('lensO', 0.0165, -0.19, -0.192, z=sz, n=14), M['glass'])) + p.append((bx('ring1', 0, 0.06, 0.052, 0.012, 0.012, 0.036), M['steel'])) + p.append((bx('ring2', 0, -0.10, 0.052, 0.012, 0.012, 0.036), M['steel'])) + p.append((bx('turretT', 0, -0.01, sz + 0.016, 0.014, 0.014, 0.012), M['steel'])) + p.append((bx('turretS', 0.016, -0.01, sz, 0.012, 0.014, 0.014), M['steel'])) + for o, _ in p: + if o.name.startswith('boltH'): pass + bpy.data.objects.remove(bh) + return finish('rifleScoped', p, (0, -0.685, 0.02), (0, -0.30, 0.0)) + +def enemy_rifle(M): + p = [] + stock = [(0.35, -0.08), (0.35, 0.03), (0.24, 0.018), (0.09, 0.012), (0.04, 0.0), (0.0, 0.002), + (-0.06, 0.012), (-0.50, 0.014), (-0.52, -0.008), (-0.06, -0.022), (0.0, -0.05), (0.06, -0.062), + (0.12, -0.05), (0.24, -0.065)] + p.append((prof('stock', stock, 0.044, bev=0.006, seg=2), M['wood'])) + p.append((prof('handguard', [(-0.10, 0.026), (-0.36, 0.024), (-0.36, 0.012), (-0.10, 0.012)], 0.03, bev=0.004), M['wood'])) + p.append((cyl('barrel', 0.0085, -0.48, -0.72, z=0.018, n=10, r1=0.0075), M['steel'])) + p.append((cyl('receiver', 0.015, 0.03, -0.12, z=0.022, n=12), M['steel'])) + p.append((bx('boltArm', -0.03, 0.02, 0.012, 0.04, 0.008, 0.008), M['steel'])) + p.append((G.box('boltKnob', (0.016, 0.016, 0.016), Matrix.Translation((-0.052, 0.024, -0.002)), bev=0.006, seg=2), M['steel'])) + p.append((bx('guard', 0, -0.005, -0.035, 0.012, 0.07, 0.006), M['steel'])) + p.append((bx('band1', 0, -0.30, 0.02, 0.034, 0.012, 0.042), M['steel'])) + p.append((bx('band2', 0, -0.47, 0.016, 0.03, 0.025, 0.036), M['steel'])) + p.append((bx('rsight', 0, -0.14, 0.04, 0.02, 0.05, 0.008), M['steel'])) + p.append((bx('fsight', 0, -0.705, 0.034, 0.012, 0.012, 0.016), M['steel'])) + p.append((bx('butt', 0, 0.352, -0.025, 0.046, 0.006, 0.11), M['steel'])) + return finish('enemyRifle', p, (0, -0.725, 0.018), (0, -0.28, 0.0)) + +def smg(M): + """Allied-style SMG: wooden butt and fore-grip, finned barrel, stick magazine.""" + p = [] + p.append((prof('butt', [(0.36, -0.07), (0.36, 0.02), (0.12, 0.018), (0.07, 0.0), (0.07, -0.03), (0.16, -0.035)], 0.04, bev=0.006, seg=2), M['wood'])) + p.append((prof('grip', [(0.02, -0.0), (0.06, -0.0), (0.05, -0.10), (0.015, -0.10)], 0.03, bev=0.006, seg=2), M['wood'])) + p.append((prof('receiver', [(0.10, 0.04), (-0.17, 0.04), (-0.17, 0.0), (0.10, 0.0)], 0.036, bev=0.004), M['park'])) + p.append((prof('fgrip', [(-0.22, 0.0), (-0.18, 0.0), (-0.20, -0.10), (-0.235, -0.10)], 0.03, bev=0.006, seg=2), M['wood'])) + p.append((cyl('barrel', 0.012, -0.17, -0.34, z=0.022, n=10), M['park'])) + for i in range(5): + p.append((cyl('fin%d' % i, 0.017, -0.18 - i * 0.012, -0.185 - i * 0.012, z=0.022, n=10), M['park'])) + p.append((bx('mag', 0, -0.07, -0.08, 0.024, 0.04, 0.16), M['park'])) + p.append((bx('guard', 0, 0.0, -0.02, 0.01, 0.06, 0.006), M['park'])) + p.append((bx('rsight', 0, 0.06, 0.05, 0.012, 0.02, 0.016), M['park'])) + return finish('smg', p, (0, -0.345, 0.022), (0, -0.21, -0.08)) + +def enemy_smg(M): + p = [] + p.append((prof('receiver', [(0.08, 0.035), (-0.22, 0.035), (-0.22, 0.005), (0.08, 0.005)], 0.032, bev=0.004), M['steel'])) + p.append((cyl('barrel', 0.010, -0.22, -0.37, z=0.02, n=10), M['steel'])) + p.append((prof('grip', [(0.02, 0.005), (0.06, 0.005), (0.06, -0.09), (0.02, -0.09)], 0.03, bev=0.006, seg=2), M['black'])) + p.append((bx('mag', 0, -0.13, -0.10, 0.022, 0.032, 0.20), M['steel'])) + p.append((bx('magwell', 0, -0.13, -0.01, 0.028, 0.04, 0.04), M['steel'])) + # folding stock (skeletal) + p.append((bx('stockA', 0.012, 0.22, 0.0, 0.006, 0.28, 0.008), M['steel'])) + p.append((bx('stockB', -0.012, 0.22, 0.0, 0.006, 0.28, 0.008), M['steel'])) + p.append((bx('stockC', 0, 0.36, -0.03, 0.032, 0.012, 0.08), M['steel'])) + p.append((bx('fsight', 0, -0.36, 0.034, 0.008, 0.01, 0.014), M['steel'])) + return finish('enemySmg', p, (0, -0.375, 0.02), (0, -0.13, -0.04)) + +def pistol(M): + p = [] + p.append((prof('slide', [(0.03, 0.03), (-0.17, 0.03), (-0.17, 0.0), (0.03, 0.0)], 0.024, bev=0.003), M['park'])) + p.append((prof('frame', [(0.03, 0.0), (-0.12, 0.0), (-0.12, -0.012), (-0.01, -0.012), (0.0, -0.012)], 0.022, bev=0.002), M['park'])) + p.append((prof('grip', [(0.035, 0.0), (0.0, 0.0), (0.012, -0.11), (0.05, -0.11)], 0.028, bev=0.004, seg=2), M['wood'])) + p.append((bx('guard', 0, -0.03, -0.025, 0.008, 0.045, 0.004), M['park'])) + return finish('pistol', p, (0, -0.172, 0.018), (0, 0.005, -0.06)) + +def mg(M): + p = [] + p.append((cyl('shroud', 0.022, -0.05, -0.55, z=0.03, n=12), M['steel'])) + p.append((cyl('muzzleB', 0.016, -0.55, -0.62, z=0.03, n=10, r1=0.02), M['steel'])) + p.append((prof('receiver', [(0.15, 0.06), (-0.06, 0.06), (-0.06, 0.0), (0.15, 0.0)], 0.05, bev=0.004), M['steel'])) + p.append((prof('stock', [(0.50, -0.06), (0.50, 0.04), (0.15, 0.05), (0.15, 0.005), (0.30, -0.02)], 0.04, bev=0.006, seg=2), M['black'])) + p.append((prof('grip', [(0.06, 0.0), (0.10, 0.0), (0.09, -0.10), (0.055, -0.10)], 0.03, bev=0.006, seg=2), M['black'])) + p.append((bx('cover', 0, 0.04, 0.075, 0.052, 0.18, 0.03), M['steel'])) + p.append((bx('belt', -0.05, 0.0, 0.03, 0.06, 0.03, 0.01), M['brass'])) + # bipod legs folded forward under the shroud, spread slightly + for s in (-1, 1): + leg = cyl('bip%d' % s, 0.005, -0.48, -0.20, z=0.0, x=s * 0.03, n=6) + p.append((leg, M['steel'])) + p.append((bx('fsight', 0, -0.54, 0.06, 0.008, 0.01, 0.03), M['steel'])) + return finish('mg', p, (0, -0.625, 0.03), (0, 0.09, 0.0)) + +def knife(M): + p = [] + p.append((prof('blade', [(0.0, 0.006), (-0.17, 0.006), (-0.19, -0.004), (-0.17, -0.014), (0.0, -0.014)], 0.004, bev=0.001), M['park'])) + p.append((bx('guard', 0, 0.004, -0.004, 0.012, 0.008, 0.04), M['park'])) + p.append((cyl('handle', 0.012, 0.11, 0.008, z=-0.004, n=8, r1=0.013), M['leather'])) + p.append((cyl('pommel', 0.013, 0.12, 0.11, z=-0.004, n=8), M['park'])) + return finish('knife', p, (0, -0.19, 0.0), (0, 0.0, 0.0)) + +def binoculars(M): + p = [] + for s in (-1, 1): + p.append((cyl('tube%d' % s, 0.022, 0.06, -0.07, x=s * 0.035, n=12), M['black'])) + p.append((cyl('obj%d' % s, 0.026, -0.07, -0.10, x=s * 0.038, n=12), M['black'])) + p.append((cyl('eye%d' % s, 0.013, 0.09, 0.06, x=s * 0.03, n=10), M['black'])) + p.append((cyl('lens%d' % s, 0.024, -0.10, -0.101, x=s * 0.038, n=12), M['glass'])) + p.append((bx('bridge', 0, 0.0, 0.0, 0.03, 0.1, 0.02), M['black'])) + return finish('binoculars', p, (0, -0.10, 0.0), (0.035, 0.0, 0.0)) + +def grenade(M): + prof_ = [(0.0, 0.06), (0.012, 0.059), (0.02, 0.05), (0.028, 0.035), (0.03, 0.0), (0.028, -0.03), (0.02, -0.045), (0.0, -0.048)] + gr = G.lathe('body', [(r, z) for r, z in prof_], n=16, sx=1.0, sy=1.0) + for v in gr.data.vertices: + rr = math.hypot(v.co.x, v.co.y) + if rr < 1e-4: continue + th = math.atan2(v.co.y, v.co.x) + bump = 1.0 + 0.09 * max(0.0, math.cos(8 * th)) * max(0.0, math.cos(v.co.z * 95.0)) + v.co.x *= bump; v.co.y *= bump + p = [(gr, M['od'])] + p.append((cyl('fuse', 0.009, 0.075, 0.055, axis='Z', n=8), M['park'])) + p.append((bx('spoon', 0.012, 0.0, 0.045, 0.004, 0.012, 0.05), M['park'])) + ring = G.lathe('ring', [(0.011, 0.0), (0.013, 0.002), (0.011, 0.004)], n=8, M=Matrix.Translation((-0.014, 0, 0.07)) @ Matrix.Rotation(math.pi / 2, 4, 'Y')) + p.append((ring, M['park'])) + return finish('grenade', p, (0, 0, 0.07), (0, 0, 0)) + +BUILDERS = [rifle_scoped, smg, pistol, enemy_rifle, enemy_smg, mg, knife, binoculars, grenade] diff --git a/e63334287a3deaa3/ironveil/tools/chars/wear.py b/e63334287a3deaa3/ironveil/tools/chars/wear.py new file mode 100644 index 00000000..16bfd147 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/chars/wear.py @@ -0,0 +1,321 @@ +# Worn, gritty bake materials (Cycles nodes). Each material exposes: Base Color, Roughness, Normal (bump) on the +# Principled BSDF, and a value node named 'METAL' (0..1) baked separately through an emission pass. +# Wear is placed where it happens: edges (bevel-node edge mask), cavities (AO), low on the body (mud), knees, etc. +import bpy, math +from mats import lin + +class NB: + def __init__(self, name): + m = bpy.data.materials.get(name) or bpy.data.materials.new(name) + m.use_nodes = True + self.m = m; self.nt = m.node_tree; self.nt.nodes.clear(); self.x = -1600 + self.out = self.n('ShaderNodeOutputMaterial'); self.bsdf = self.n('ShaderNodeBsdfPrincipled') + self.link(self.bsdf.outputs[0], self.out.inputs[0]) + tc = self.n('ShaderNodeTexCoord'); self.obj = tc.outputs['Object'] + self.geo = self.n('ShaderNodeNewGeometry') + def n(self, t, **kw): + node = self.nt.nodes.new(t); node.location = (self.x, 0); self.x += 40 + for k, v in kw.items(): + if k in node.inputs: node.inputs[k].default_value = v + else: setattr(node, k, v) + return node + def link(self, a, b): self.nt.links.new(a, b) + def val(self, v): + n = self.n('ShaderNodeValue'); n.outputs[0].default_value = v; return n.outputs[0] + def col(self, h): + n = self.n('ShaderNodeRGB'); n.outputs[0].default_value = lin(h); return n.outputs[0] + def math(self, op, a, b=None, clamp=False): + n = self.n('ShaderNodeMath', operation=op); n.use_clamp = clamp + self._in(n.inputs[0], a) + if b is not None: self._in(n.inputs[1], b) + return n.outputs[0] + def _in(self, sock, v): + if isinstance(v, (int, float)): sock.default_value = v + else: self.link(v, sock) + def mix(self, a, b, fac, mode='MIX'): + n = self.n('ShaderNodeMix', data_type='RGBA', blend_type=mode) + self._in(n.inputs['Factor'], fac) + if isinstance(a, str): n.inputs[6].default_value = lin(a) + else: self.link(a, n.inputs[6]) + if isinstance(b, str): n.inputs[7].default_value = lin(b) + else: self.link(b, n.inputs[7]) + return n.outputs[2] + def mixf(self, a, b, fac): + n = self.n('ShaderNodeMix', data_type='FLOAT') + self._in(n.inputs['Factor'], fac); self._in(n.inputs[2], a); self._in(n.inputs[3], b) + return n.outputs[0] + def noise(self, scale, detail=4.0, rough=0.5, vec=None, dist=0.0, stretch=None, w=0.0): + v = vec or self.obj + if stretch: + mp = self.n('ShaderNodeMapping'); mp.inputs['Scale'].default_value = stretch + self.link(v, mp.inputs['Vector']); v = mp.outputs[0] + n = self.n('ShaderNodeTexNoise', noise_dimensions='4D') + n.inputs['Scale'].default_value = scale; n.inputs['Detail'].default_value = detail + n.inputs['Roughness'].default_value = rough; n.inputs['Distortion'].default_value = dist + n.inputs['W'].default_value = w + self.link(v, n.inputs['Vector']) + return n.outputs['Fac'] + def ramp(self, f, a, b): + """Map f from [a,b] to [0,1] with smoothstep.""" + n = self.n('ShaderNodeMapRange', interpolation_type='SMOOTHSTEP') + self._in(n.inputs['Value'], f); n.inputs['From Min'].default_value = a; n.inputs['From Max'].default_value = b + return n.outputs[0] + def edge(self, radius): + """Convex/concave edge mask from the bevel node (1 on worn edges).""" + bv = self.n('ShaderNodeBevel', samples=8); bv.inputs['Radius'].default_value = radius + dp = self.n('ShaderNodeVectorMath', operation='DOT_PRODUCT') + self.link(bv.outputs[0], dp.inputs[0]); self.link(self.geo.outputs['Normal'], dp.inputs[1]) + e = self.math('SUBTRACT', 1.0, dp.outputs['Value']) + return self.ramp(e, 0.005, 0.06) + def ao(self, dist=0.05): + a = self.n('ShaderNodeAmbientOcclusion', samples=8); a.inputs['Distance'].default_value = dist + return a.outputs['AO'] + def zcoord(self): + s = self.n('ShaderNodeSeparateXYZ'); self.link(self.obj, s.inputs[0]); return s + def finish(self, color, rough, bump_h=None, bump_s=0.3, metal=0.0, bump_dist=0.002): + self.link(color, self.bsdf.inputs['Base Color']) if not isinstance(color, str) else None + if isinstance(color, str): self.bsdf.inputs['Base Color'].default_value = lin(color) + self._in(self.bsdf.inputs['Roughness'], rough) + if bump_h is not None: + b = self.n('ShaderNodeBump'); b.inputs['Strength'].default_value = bump_s; b.inputs['Distance'].default_value = bump_dist + self.link(bump_h, b.inputs['Height']); self.link(b.outputs[0], self.bsdf.inputs['Normal']) + mv = self.n('ShaderNodeMath', operation='ADD'); mv.name = 'METAL'; mv.label = 'METAL' + self._in(mv.inputs[0], metal); mv.inputs[1].default_value = 0.0 + self.bsdf.inputs['Metallic'].default_value = 0.0 + return self.m + +def cloth(name, base, base2, knee_z=None, mud='#3b3326', fade=0.12, camo=None, mud_amt=0.6, weave=0.25): + """Field cloth: mottled, darker in creases, faded where exposed, dirty low down, mud on the knees, visible weave.""" + B = NB(name) + mott = B.noise(6.0, 6, 0.55) + c = B.mix(base, base2, B.ramp(mott, 0.35, 0.65)) + if camo: + blot = B.noise(5.5, 3, 0.6, dist=0.4, w=3.0) + c1 = B.mix(camo[0], camo[1], B.ramp(blot, 0.42, 0.46)) + blot2 = B.noise(8.0, 3, 0.6, dist=0.6, w=7.0) + c1 = B.mix(c1, camo[2], B.ramp(blot2, 0.58, 0.62)) + blot3 = B.noise(14.0, 2, 0.5, dist=0.8, w=11.0) + c1 = B.mix(c1, camo[3], B.ramp(blot3, 0.62, 0.65)) + c = B.mix(c, c1, 0.85) + ao = B.ao(0.06) + # creases darker, exposed panels sun-faded (lighter, greyer) + c = B.mix(B.mix(c, '#000000', 0.0), c, 1.0) + dark = B.math('SUBTRACT', 1.0, ao) + c = B.mix(c, '#14120e', B.math('MULTIPLY', B.ramp(dark, 0.05, 0.6), 0.55)) + c = B.mix(c, '#8a8878', B.math('MULTIPLY', B.ramp(ao, 0.85, 1.0), fade)) + z = B.zcoord() + # grime gets heavier toward the boots + low = B.ramp(z.outputs['Z'], 0.75, 0.05) + splat = B.ramp(B.noise(9.0, 8, 0.65), 0.38, 0.7) + c = B.mix(c, mud, B.math('MULTIPLY', B.math('MULTIPLY', low, splat), mud_amt)) + if knee_z: + kb = B.ramp(B.math('ABSOLUTE', B.math('SUBTRACT', z.outputs['Z'], knee_z)), 0.09, 0.0) + front = B.ramp(B.math('MULTIPLY', z.outputs['Y'], -1.0), -0.02, 0.06) + km = B.math('MULTIPLY', B.math('MULTIPLY', kb, front), B.ramp(B.noise(14.0, 6, 0.6), 0.3, 0.6)) + c = B.mix(c, mud, B.math('MULTIPLY', km, 0.85)) + # weave + creases (fine bump) + # twill weave (two crossing band sets at different scales), fine wrinkles and fuzz: the high-frequency normal detail + # that makes the cloth read as woven wool or cotton instead of a smooth shell + wv = B.n('ShaderNodeTexWave', wave_type='BANDS'); wv.inputs['Scale'].default_value = 260.0; wv.inputs['Distortion'].default_value = 2.0 + B.link(B.obj, wv.inputs['Vector']) + wv2 = B.n('ShaderNodeTexWave', wave_type='BANDS', bands_direction='Y'); wv2.inputs['Scale'].default_value = 300.0; wv2.inputs['Distortion'].default_value = 1.2 + B.link(B.obj, wv2.inputs['Vector']) + weave_h = B.math('MULTIPLY', B.math('ADD', wv.outputs['Fac'], B.math('MULTIPLY', wv2.outputs['Fac'], 0.7)), weave * 0.5) + wr = B.math('MULTIPLY', B.ramp(B.noise(22.0, 3, 0.6, stretch=(1.0, 1.0, 4.0)), 0.45, 0.6), 0.5) + # sewn seams from the garment's seam field (detail.tailor): a pressed groove and two rows of stitches + sa = B.n('ShaderNodeAttribute', attribute_name='seam_d'); sb = B.n('ShaderNodeAttribute', attribute_name='seam_s') + has = B.math('GREATER_THAN', sa.outputs['Fac'], 0.0001) + dist = B.math('SUBTRACT', 0.05, sa.outputs['Fac']) + groove = B.math('MULTIPLY', has, B.math('EXPONENT', B.math('MULTIPLY', B.math('POWER', B.math('DIVIDE', dist, 0.0035), 2.0), -1.0))) + stitch_row = B.math('EXPONENT', B.math('MULTIPLY', B.math('POWER', B.math('DIVIDE', B.math('SUBTRACT', dist, 0.0042), 0.0009), 2.0), -1.0)) + stitch_on = B.math('POWER', B.math('ADD', 0.5, B.math('MULTIPLY', 0.5, B.math('COSINE', B.math('MULTIPLY', sb.outputs['Fac'], 6.2832 / 0.0055)))), 4.0) + stitches = B.math('MULTIPLY', has, B.math('MULTIPLY', stitch_row, stitch_on)) + seam_h = B.math('ADD', B.math('MULTIPLY', groove, -0.9), B.math('MULTIPLY', stitches, 0.5)) + wr = B.math('ADD', wr, seam_h) + c = B.mix(c, '#2a2a1e', B.math('MULTIPLY', groove, 0.25)) + rough = B.mixf(0.86, 0.96, B.ramp(mott, 0.3, 0.7)) + # wear: rubbed shiny and a touch lighter at elbows, knees and seat and on the edges of pockets and seams + zc = B.zcoord() + ax = B.math('ABSOLUTE', zc.outputs['X']) + elbow = B.math('MULTIPLY', B.ramp(B.math('ABSOLUTE', B.math('SUBTRACT', ax, 0.46)), 0.07, 0.0), B.ramp(B.math('ABSOLUTE', B.math('SUBTRACT', zc.outputs['Z'], 1.47)), 0.08, 0.0)) + knee = B.ramp(B.math('ABSOLUTE', B.math('SUBTRACT', zc.outputs['Z'], knee_z or 0.52)), 0.08, 0.0) + seat = B.math('MULTIPLY', B.ramp(zc.outputs['Y'], 0.02, 0.09), B.ramp(B.math('ABSOLUTE', B.math('SUBTRACT', zc.outputs['Z'], 0.88)), 0.1, 0.0)) + worn = B.math('MULTIPLY', B.math('MAXIMUM', B.math('MAXIMUM', elbow, knee), B.math('MAXIMUM', seat, B.math('MULTIPLY', B.edge(0.004), 0.7))), B.ramp(B.noise(18.0, 4, 0.6), 0.3, 0.7)) + rough = B.mixf(rough, 0.64, B.math('MULTIPLY', worn, 0.85)) + c = B.mix(c, '#9a9680', B.math('MULTIPLY', worn, 0.18)) + # dust climbing from the boots to the knees (dry, pale, kills the sheen) under the mud + dust = B.math('MULTIPLY', B.ramp(zc.outputs['Z'], 0.62, 0.12), B.ramp(B.noise(6.0, 6, 0.6), 0.25, 0.65)) + c = B.mix(c, '#8b7e62', B.math('MULTIPLY', dust, 0.42)) + rough = B.mixf(rough, 0.99, dust) + # sweat darkening at the collar line and across the shoulders under the braces + sweat = B.math('MULTIPLY', B.ramp(B.math('ABSOLUTE', B.math('SUBTRACT', zc.outputs['Z'], 1.47)), 0.07, 0.0), B.ramp(ax, 0.2, 0.05)) + c = B.mix(c, '#1d1c14', B.math('MULTIPLY', sweat, 0.3)) + rough = B.mixf(rough, 0.78, B.math('MULTIPLY', sweat, 0.6)) + return B.finish(c, rough, bump_h=B.math('ADD', B.math('ADD', weave_h, wr), B.math('MULTIPLY', B.noise(35.0, 4), 0.35)), bump_s=0.42, bump_dist=0.004) + +def leather(name, base, base2='#100c09', mud='#3d3428', mud_low=0.0, polish=0.45): + B = NB(name) + grain = B.noise(180.0, 3, 0.6) + c = B.mix(base, base2, B.ramp(B.noise(7.0, 5, 0.6), 0.3, 0.7)) + e = B.edge(0.006) + scuff = B.ramp(B.noise(25.0, 6, 0.7, stretch=(1.0, 1.0, 6.0)), 0.55, 0.75) + wornc = B.mix(c, '#6a5848', 0.55) + c = B.mix(c, wornc, B.math('MAXIMUM', B.math('MULTIPLY', e, 0.8), B.math('MULTIPLY', scuff, 0.45))) + if mud_low > 0: + z = B.zcoord() + low = B.ramp(z.outputs['Z'], mud_low, 0.0) + c = B.mix(c, mud, B.math('MULTIPLY', low, B.ramp(B.noise(12.0, 8, 0.65), 0.3, 0.6))) + rough_mud = low + else: + rough_mud = 0.0 + rough = B.mixf(polish, 0.75, B.math('MAXIMUM', B.math('MAXIMUM', scuff, e), rough_mud)) + return B.finish(c, rough, bump_h=B.math('ADD', B.math('MULTIPLY', grain, 0.4), B.math('MULTIPLY', scuff, -0.3)), bump_s=0.4, bump_dist=0.004) + +def webbing(name, base, base2): + """Woven cotton webbing / canvas: strong weave, frayed lighter edges, sweat and dirt.""" + B = NB(name) + c = B.mix(base, base2, B.ramp(B.noise(8.0, 6, 0.6), 0.3, 0.7)) + e = B.edge(0.004) + fray = B.math('MULTIPLY', e, B.ramp(B.noise(200.0, 2, 0.5), 0.3, 0.7)) + c = B.mix(c, '#a49c80', B.math('MULTIPLY', fray, 0.7)) + ao = B.ao(0.04) + c = B.mix(c, '#1a1712', B.math('MULTIPLY', B.ramp(B.math('SUBTRACT', 1.0, ao), 0.05, 0.6), 0.5)) + c = B.mix(c, '#3a3226', B.math('MULTIPLY', B.ramp(B.noise(5.0, 8, 0.7), 0.55, 0.8), 0.5)) + wv1 = B.n('ShaderNodeTexWave', wave_type='BANDS'); wv1.inputs['Scale'].default_value = 520.0 + B.link(B.obj, wv1.inputs['Vector']) + wv2 = B.n('ShaderNodeTexWave', wave_type='BANDS', bands_direction='Y'); wv2.inputs['Scale'].default_value = 520.0 + B.link(B.obj, wv2.inputs['Vector']) + h = B.math('ADD', wv1.outputs['Fac'], wv2.outputs['Fac']) + return B.finish(c, B.mixf(0.88, 0.97, fray), bump_h=B.math('ADD', B.math('MULTIPLY', h, 0.08), B.math('MULTIPLY', fray, -0.4)), bump_s=0.4, bump_dist=0.004) + +def painted_metal(name, paint, paint2, steel='#34332f', rust='#4d3221', chip=0.55, scratch=0.5, camo=None): + """Helmet / canister paint: matte, chipped on rims and crown, scratched, a little rust in the deepest chips.""" + B = NB(name) + c = B.mix(paint, paint2, B.ramp(B.noise(9.0, 5, 0.6), 0.3, 0.7)) + if camo: + bl = B.noise(6.0, 3, 0.6, dist=0.5, w=2.0) + c = B.mix(c, camo[0], B.ramp(bl, 0.45, 0.48)) + bl2 = B.noise(9.0, 3, 0.6, dist=0.7, w=5.0) + c = B.mix(c, camo[1], B.ramp(bl2, 0.6, 0.63)) + e = B.edge(0.008) + z = B.zcoord() + crown = B.ramp(z.outputs['Z'], 1.80, 1.9) + rough_noise = B.noise(30.0, 8, 0.75) + chipmask = B.ramp(B.math('ADD', B.math('MULTIPLY', B.math('ADD', e, B.math('MULTIPLY', crown, 0.5)), chip), B.math('MULTIPLY', rough_noise, 0.6)), 0.47, 0.52) + scr = B.ramp(B.noise(40.0, 2, 0.5, stretch=(1.0, 14.0, 1.0), w=4.0), 0.72, 0.75) + scr2 = B.ramp(B.noise(40.0, 2, 0.5, stretch=(12.0, 1.0, 3.0), w=9.0), 0.73, 0.76) + sc = B.math('MULTIPLY', B.math('MAXIMUM', scr, scr2), scratch) + under = B.mix(steel, rust, B.ramp(B.noise(50.0, 4), 0.55, 0.75)) + c = B.mix(c, '#5a5a52', B.math('MULTIPLY', sc, 0.7)) + c = B.mix(c, under, chipmask) + ao = B.ao(0.03) + c = B.mix(c, '#121210', B.math('MULTIPLY', B.ramp(B.math('SUBTRACT', 1.0, ao), 0.05, 0.6), 0.45)) + rough = B.mixf(B.mixf(0.78, 0.6, sc), 0.42, chipmask) + h = B.math('SUBTRACT', B.math('MULTIPLY', B.math('SUBTRACT', 1.0, chipmask), 1.0), B.math('MULTIPLY', sc, 0.4)) + h = B.math('ADD', h, B.math('MULTIPLY', B.noise(120.0, 3), 0.15)) + return B.finish(c, rough, bump_h=h, bump_s=0.6, bump_dist=0.006, metal=B.math('MULTIPLY', chipmask, 0.9)) + +def skin(name, image, grime=0.35, uv='UVMap', beard=0.0, scars=False, tan=0.0): + """MakeHuman skin + dirt and sweat: grime in creases and on the cheeks/hands, a slightly sweaty sheen in patches.""" + B = NB(name) + uvn = B.n('ShaderNodeUVMap'); uvn.uv_map = uv + tex = B.n('ShaderNodeTexImage'); tex.image = bpy.data.images.load(image, check_existing=True) + B.link(uvn.outputs[0], tex.inputs[0]) + c = B.mix(tex.outputs[0], '#b8a090', 0.12) # less saturated, a bit paler: tired, cold + if tan > 0: c = B.mix(c, '#8a5d43', tan, mode='MULTIPLY') # weathered, sun-browned (raiders live outdoors) + ao = B.ao(0.02) + c = B.mix(c, '#3a2c22', B.math('MULTIPLY', B.ramp(B.math('SUBTRACT', 1.0, ao), 0.05, 0.5), 0.45)) + smudge = B.ramp(B.noise(7.0, 7, 0.7, dist=0.4), 0.55, 0.78) + c = B.mix(c, '#3d3226', B.math('MULTIPLY', smudge, grime)) + stub = B.ramp(B.noise(400.0, 2, 0.5), 0.55, 0.7) + sweat = B.ramp(B.noise(5.0, 3, 0.5, w=3.0), 0.5, 0.7) + # a few days' stubble on the jaw, upper lip and chin (bind pose: face front is -Y, jaw at about 1.55-1.63 m) + zc = B.zcoord() + jaw = B.math('MULTIPLY', B.math('MULTIPLY', B.ramp(B.math('ABSOLUTE', B.math('SUBTRACT', zc.outputs['Z'], 1.585)), 0.045, 0.015), + B.ramp(zc.outputs['Y'], 0.0, -0.06)), B.ramp(B.math('ABSOLUTE', zc.outputs['X']), 0.075, 0.05)) + c = B.mix(c, '#2b231d', B.math('MULTIPLY', B.math('MULTIPLY', jaw, B.ramp(B.noise(520.0, 2, 0.5), 0.45, 0.6)), 0.55)) + beard_h = None + if beard > 0: + # a short cropped beard: jaw, chin and moustache, dense strands with a soft, broken edge (no painted block) + X_, Y_, Z_ = zc.outputs['X'], zc.outputs['Y'], zc.outputs['Z'] + edge = B.ramp(B.noise(60.0, 3, 0.6), 0.35, 0.65) + jawb = B.math('MULTIPLY', B.ramp(B.math('ABSOLUTE', B.math('SUBTRACT', Z_, 1.592)), 0.05 + 0.006 * beard, 0.03), + B.ramp(Y_, -0.02, -0.075)) + jawb = B.math('MULTIPLY', jawb, B.ramp(B.math('ABSOLUTE', X_), 0.078, 0.06)) + must = B.math('MULTIPLY', B.math('MULTIPLY', B.ramp(B.math('ABSOLUTE', B.math('SUBTRACT', Z_, 1.652)), 0.011, 0.005), + B.ramp(B.math('ABSOLUTE', X_), 0.03, 0.022)), B.ramp(Y_, -0.2, -0.225)) + area = B.math('MULTIPLY', B.math('MAXIMUM', jawb, must), B.mixf(0.75, 1.0, edge)) + strands = B.ramp(B.noise(900.0, 2, 0.5, stretch=(1.0, 1.0, 3.0)), 0.38, 0.62) + dens = B.math('MULTIPLY', area, B.mixf(0.55, 1.0, strands)) + c = B.mix(c, '#231b15', B.math('MULTIPLY', dens, 0.92 * beard)) + beard_h = B.math('MULTIPLY', B.math('MULTIPLY', area, strands), 0.9 * beard) + if scars: + # two healed scars: through the left eyebrow and across the right side of the chin; pale, slightly raised + X_, Y_, Z_ = zc.outputs['X'], zc.outputs['Y'], zc.outputs['Z'] + sc_t = None + for x0, z0, k, hh in ((0.036, 1.737, 0.25, 0.016), (-0.016, 1.598, -1.6, 0.007)): + d = B.math('ABSOLUTE', B.math('SUBTRACT', B.math('SUBTRACT', X_, x0), B.math('MULTIPLY', B.math('SUBTRACT', Z_, z0), k))) + m = B.math('MULTIPLY', B.ramp(d, 0.0016, 0.0005), B.ramp(B.math('ABSOLUTE', B.math('SUBTRACT', Z_, z0)), hh, hh * 0.6)) + m = B.math('MULTIPLY', m, B.ramp(Y_, -0.15, -0.2)) + sc_t = m if sc_t is None else B.math('MAXIMUM', sc_t, m) + c = B.mix(c, '#c79a8a', B.math('MULTIPLY', sc_t, 0.75)) + beard_h = sc_t if beard_h is None else B.math('MAXIMUM', beard_h, B.math('MULTIPLY', sc_t, 1.2)) + # oilier T-zone (forehead, nose), drier cheeks; dirt in the creases already from the AO above + tz = B.math('MULTIPLY', B.ramp(zc.outputs['Z'], 1.6, 1.68), B.ramp(B.math('ABSOLUTE', zc.outputs['X']), 0.05, 0.02)) + rough = B.mixf(B.mixf(0.62, 0.42, sweat), 0.4, B.math('MULTIPLY', tz, 0.7)) + pores = B.math('MULTIPLY', B.noise(650.0, 2, 0.5), 0.35) + bh = B.math('ADD', B.math('ADD', B.math('MULTIPLY', B.noise(250.0, 3, 0.6), 0.5), pores), B.math('MULTIPLY', stub, 0.35)) + if beard_h is not None: bh = B.math('ADD', bh, beard_h) + return B.finish(c, rough, bump_h=bh, bump_s=0.22, bump_dist=0.002) + +def flat(name, col, rough=0.5, metal=0.0): + B = NB(name) + return B.finish(col, rough, metal=metal) + +# ---------------- weapons +def wood(name, base='#4a3423', dark='#22160c', axis='Y'): + """Oiled walnut stock: fine long grain lines, darker oil-soaked grip areas, dings and pale worn edges.""" + B = NB(name) + warp = B.noise(4.0, 3, 0.5) + vec = B.n('ShaderNodeVectorMath', operation='ADD') + B.link(B.obj, vec.inputs[0]) + cw = B.n('ShaderNodeCombineXYZ'); B.link(B.math('MULTIPLY', warp, 0.02), cw.inputs['X']); B.link(B.math('MULTIPLY', warp, 0.03), cw.inputs['Z']) + B.link(cw.outputs[0], vec.inputs[1]) + # long grain lines: sin(height across the stock * k + warp), so they run along the stock (weapon Y axis) + sep = B.n('ShaderNodeSeparateXYZ'); B.link(vec.outputs[0], sep.inputs[0]) + ph = B.math('ADD', B.math('MULTIPLY', sep.outputs['Z'], 420.0), B.math('MULTIPLY', B.noise(5.0, 3, 0.5, w=1.0), 9.0)) + bandv = B.math('MULTIPLY', B.math('ADD', B.math('SINE', ph), 1.0), 0.5) + fine = B.noise(140.0, 4, 0.6, stretch=(6.0, 0.25, 6.0)) + grain = B.math('ADD', B.math('MULTIPLY', B.math('POWER', bandv, 3.0), 0.6), B.math('MULTIPLY', fine, 0.5)) + c = B.mix(base, dark, B.ramp(grain, 0.35, 0.95)) + oil = B.ramp(B.noise(3.0, 3, 0.5, w=2.0), 0.45, 0.7) + c = B.mix(c, '#1a100a', B.math('MULTIPLY', oil, 0.35)) + e = B.edge(0.004) + c = B.mix(c, '#8a6a4a', B.math('MULTIPLY', e, 0.6)) + vor = B.n('ShaderNodeTexVoronoi', feature='F1'); vor.inputs['Scale'].default_value = 70.0 + B.link(B.obj, vor.inputs['Vector']) + ding = B.math('MULTIPLY', B.ramp(vor.outputs['Distance'], 0.12, 0.0), B.ramp(B.noise(18.0, 2, 0.5, w=6.0), 0.5, 0.58)) + c = B.mix(c, '#120a06', B.math('MULTIPLY', ding, 0.7)) + scr = B.ramp(B.noise(28.0, 2, 0.5, stretch=(1.0, 16.0, 1.0), w=2.0), 0.69, 0.72) + c = B.mix(c, '#7a5a3e', B.math('MULTIPLY', scr, 0.7)) + rough = B.mixf(B.mixf(B.mixf(0.5, 0.36, oil), 0.62, e), 0.78, B.math('MAXIMUM', ding, scr)) + h = B.math('SUBTRACT', B.math('MULTIPLY', grain, 0.15), B.math('ADD', B.math('MULTIPLY', ding, 1.0), B.math('MULTIPLY', scr, 0.5))) + return B.finish(c, rough, bump_h=h, bump_s=0.7, bump_dist=0.004) + +def blued(name, base='#4a4f58', base2='#3c4048', bright='#b8b8b2', wear=1.0, park=False): + """Blued (or parkerized) steel: dark finish, bright bare steel on edges and high points, fine scratches, holster wear.""" + B = NB(name) + c = B.mix(base, base2, B.ramp(B.noise(25.0, 5, 0.6), 0.3, 0.7)) + e = B.edge(0.0025) + worn = B.math('MULTIPLY', B.ramp(B.math('ADD', B.math('MULTIPLY', e, 1.2), B.math('MULTIPLY', B.noise(60.0, 6, 0.7), 0.5)), 0.75, 0.95), wear) + scr = B.ramp(B.noise(45.0, 2, 0.5, stretch=(1.0, 25.0, 1.0), w=5.0), 0.68, 0.71) + scr2 = B.ramp(B.noise(45.0, 2, 0.5, stretch=(20.0, 1.0, 6.0), w=8.0), 0.69, 0.72) + sc = B.math('MAXIMUM', scr, scr2) + c = B.mix(c, '#8a8a88', B.math('MULTIPLY', sc, 0.7)) + c = B.mix(c, bright, worn) + ao = B.ao(0.02) + c = B.mix(c, '#070707', B.math('MULTIPLY', B.ramp(B.math('SUBTRACT', 1.0, ao), 0.05, 0.6), 0.5)) + base_r = 0.62 if park else 0.38 + rough = B.mixf(B.mixf(base_r, 0.5, sc), 0.24, worn) + h = B.math('ADD', B.math('MULTIPLY', sc, -0.4), B.math('MULTIPLY', B.noise(300.0, 3), 0.08)) + return B.finish(c, rough, bump_h=h, bump_s=0.6, bump_dist=0.003, metal=B.math('ADD', 0.75, B.math('MULTIPLY', worn, 0.25))) diff --git a/e63334287a3deaa3/ironveil/tools/weapons/README.md b/e63334287a3deaa3/ironveil/tools/weapons/README.md new file mode 100644 index 00000000..5d8fc763 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/weapons/README.md @@ -0,0 +1,116 @@ +# Midnight Ops weapons: how to rebuild `assets/weapons.glb` + +Everything in `weapons.glb` is modelled and textured from these scripts. Nothing is downloaded and no outside +models or textures are used. The site has no build step; these files are only for changing the models later. + +## What you need + +- Blender as a Python module: `pip install bpy` (built and tested with bpy 5.3 on Python 3.13), plus `numpy` and `Pillow`. +- Node 18 or newer with `npm i @gltf-transform/core@4 @gltf-transform/extensions@4 @gltf-transform/functions@4 meshoptimizer sharp`. + +## Rebuild + +```sh +cd e63334287a3deaa3/ironveil/tools/weapons +BPY=python ./run.sh /tmp/wpn 2048 # rifle, smg and atlas sets; resumable, one Blender process at a time +GT_MODULES=/path/to/node_modules node pack.mjs /tmp/wpn/rifle.glb /tmp/wpn/smg.glb /tmp/wpn/atlas.glb ../../assets/weapons.glb +``` + +`run.sh` calls `build.py` in three steps per texture set: `prep` (model and unwrap, saved to a .blend), `bake` (one +weapon at a time: edge/cavity mask, colour, metal, roughness, normal) and `finish` (composite the set's maps and export). +It skips steps whose output already exists, so it can be stopped and restarted. Cycles uses 2 threads (`THREADS=4` for +more) and each step waits for 5 GB of free memory. Expect about an hour at 2048 on 2 threads. +`./run.sh /tmp/wpn 512 rifle` is a quick check of one set. `python preview.py out.glb rifleScoped,smg` exports +flat-coloured geometry in seconds for checking shapes. `python checknormals.py rifleScoped` lists parts with flipped +or open surfaces. + +## Files + +- `models.py`: one builder per weapon. Shapes are lofts, lathes and sweeps in real dimensions (metres). Blender frame: + barrel along -Y, up +Z, the weapon's right side is -X, origin at the right-hand grip. Each builder lists its moving + parts (with pivot points), empties (muzzle, ejection, scope eye), the left-hand point on the fore-end and the wear + zones (where hands, cheek and shoulder touch). +- `mats.py`: procedural materials (Cycles nodes) for blued and parkerized steel, bright steel, brass, walnut and beech, + leather, canvas, moulded plastic, checkered grips, painted metal and the knife blade. Wear is driven by a baked mask + (convex edges, cavities, occlusion) plus position: edges and corners go bright, hands polish and darken, sliding parts + get scratches along the slide, recesses keep dust and a little rust. +- `build.py`: three texture sets, `rifle` (player rifle, 2048), `smg` (player SMG, 2048) and `atlas` (everything else + plus the reduced rifle and SMG, 2048), each with albedo, normal and occlusion-roughness-metal maps. +- `run.sh`: the resumable driver. +- `assemble.py`: the node layout the game reads (see below) and the hand frames, which reuse `grips.json` from the + character clips so the hands land where they did on the first weapons. +- `pack.mjs`: merges the three set files into one scene, occlusion from the ORM map, WebP textures, meshopt geometry. +- `geo.py`: geometry helpers. + +## Node layout in `weapons.glb` + +One root per weapon, named by kind. glTF axes: barrel along +Z, up +Y, origin at the right-hand grip, metres. + +``` + root + _body everything that does not move + _ empty at the part's pivot; its mesh is the child __mesh + _muzzle +Z of the empty points out of the barrel + _ejection +Z points the way cases are thrown (rifles, SMGs, pistol, MG) + _scopeEye where the eye sits behind the scope or binoculars; +Z is the view direction + (a three.js camera looks down its own -Z, so rotate it 180 degrees about Y) + _gripR right-hand frame (attach() puts this on the hand's weapon bone) + _gripL left-hand frame on the fore-end (the left-hand IK target) +``` + +Animate moving parts by changing the `_` empty relative to its starting transform (store it first); +the mesh child carries a quantisation offset from meshopt and should not be moved directly. + +| kind | moving parts | empties | +|---|---|---| +| rifleScoped | bolt (rotate about Z to lift, then slide along -Z), trigger, sling, scopeLensFront, scopeLensRear | muzzle, ejection, scopeEye, gripR, gripL | +| smg | bolt, charging, mag, trigger, sling | muzzle, ejection, gripR, gripL | +| pistol | bolt (the slide), hammer, trigger, mag | muzzle, ejection, gripR, gripL | +| enemyRifle | bolt, trigger, sightRear, sling | muzzle, ejection, gripR, gripL | +| enemySmg | charging, mag, trigger, sightRear | muzzle, ejection, gripR, gripL | +| mg | cover, charging, trigger, sightRear, bipod (folded; rotate about X to deploy), belt | muzzle, ejection, gripR, gripL | +| knife, binoculars, grenade, stickGrenade | grenade: lever, pin | muzzle, gripR, gripL (binoculars also scopeEye) | +| rifleScopedLod, smgLod | none (reduced models, shared atlas) | muzzle, ejection, scopeEye, gripR, gripL | + +`IVChars.weapon(kind, { lod: true })` returns the reduced rifle or SMG for other characters and distance. + +## What is in the current file (3.45 MB) + +| weapon | triangles | draw calls | materials | +|---|---|---|---| +| rifleScoped | 10770 | 6 | wpn_glass, wpn_rifle | +| smg | 8140 | 6 | wpn_smg | +| binoculars | 1324 | 2 | wpn_atlas, wpn_glass | +| enemyRifle | 2998 | 5 | wpn_atlas | +| enemySmg | 2258 | 5 | wpn_atlas | +| grenade | 1490 | 3 | wpn_atlas | +| knife | 1454 | 1 | wpn_atlas | +| mg | 4060 | 7 | wpn_atlas | +| pistol | 4734 | 5 | wpn_atlas | +| rifleScopedLod | 3032 | 2 | wpn_atlas, wpn_glass | +| smgLod | 2108 | 1 | wpn_atlas | +| stickGrenade | 738 | 1 | wpn_atlas | + +| texture | format | bytes | +|---|---|---| +| rifle_normal | image/webp | 226 KB | +| rifle_albedo | image/webp | 286 KB | +| rifle_orm | image/webp | 444 KB | +| smg_normal | image/webp | 196 KB | +| smg_albedo | image/webp | 245 KB | +| smg_orm | image/webp | 342 KB | +| atlas_normal | image/webp | 196 KB | +| atlas_albedo | image/webp | 442 KB | +| atlas_orm | image/webp | 657 KB | + + + +Draw calls count one per mesh primitive; the glass lenses are a second material. `python stats.py weapons.glb` +prints this table for any build. + +## Hand frames + +The grip frames reuse the hand poses from the character clips (`grips.json`) and are then nudged per weapon +(`gripRoff` / `gripLoff` in `models.py`) by measuring how many hand vertices end up inside the weapon in the aim pose. +The clips close the fingers tighter than a real grip, so some finger penetration on the right hand remains whatever the +weapon shape; it needs per-weapon finger poses in the character clips. diff --git a/e63334287a3deaa3/ironveil/tools/weapons/assemble.py b/e63334287a3deaa3/ironveil/tools/weapons/assemble.py new file mode 100644 index 00000000..56ca3e65 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/weapons/assemble.py @@ -0,0 +1,89 @@ +# Turn Weapon objects into the node layout chars.js expects and export a GLB. +# root empty, origin at the right-hand grip +# _body static mesh (everything that does not move) +# _ empty at the part's pivot (bolt, mag, trigger, charging, sightRear, ...) +# __mesh the part's mesh +# _muzzle/_ejection/_scopeEye empties, +Z (glTF) = direction (down the barrel, out of the port, view) +# _gripR/_gripL hand frames (same conventions as the first weapons file) +import bpy, json, math, os +from mathutils import Vector, Matrix, Quaternion +import geo as G + +HERE = os.path.dirname(os.path.abspath(__file__)) +GJ = json.load(open(os.path.join(HERE, 'grips.json'))) +def _M(k): + t, q = GJ[k] + m = Quaternion(q).to_matrix().to_4x4(); m.translation = Vector(t); return m +GR, GRL, GP, GPL = _M('rifle'), _M('rifleL'), _M('pistol'), _M('pistolL') +RIFLE_GL = Vector((0, -0.30, 0.0)) +CONV = Matrix.Rotation(-math.pi / 2, 4, 'X') # hand-bone axes as glTF keeps them +LONG = ('rifleScoped', 'enemyRifle', 'smg', 'enemySmg', 'mg') + +def empty(name, parent, M=None, loc=None): + e = bpy.data.objects.new(name, None); G.link(e) + e.empty_display_size = 0.02 + e.parent = parent; e.matrix_parent_inverse = Matrix() + if M is not None: + e.matrix_basis = M + elif loc is not None: + e.location = loc + return e + +def dir_quat(f): + return Vector((0, -1, 0)).rotation_difference(Vector(f).normalized()) + +def small_item_frame(base): + """Small items sit in a fist like a pistol grip (same maps as the first file).""" + if base == 'knife': + return Matrix(((1, 0, 0, 0), (0, 0.30, 0.95, 0.02), (0, -0.95, 0.30, -0.05), (0, 0, 0, 1))) @ Matrix.Translation((0, -0.06, 0.004)) + if base in ('grenade',): + return Matrix.Translation((0, 0.02, -0.055)) + if base == 'stickGrenade': + return Matrix.Translation((0, 0.02, -0.035)) + return Matrix.Translation((0.04, -0.02, -0.05)) # binoculars + +def assemble(W, meshes): + """meshes: part -> joined mesh object (already final material). Returns the root.""" + k = W.kind + base = k[:-3] if k.endswith('Lod') else k + root = empty(k, None) + for part, ob in meshes.items(): + if part == 'body': + ob.name = k + '_body'; ob.data.name = k + '_body' + ob.parent = root; ob.matrix_parent_inverse = Matrix() + else: + piv = W.pivots.get(part, (0, 0, 0)) + e = empty(k + '_' + part, root, loc=Vector(piv)) + ob.name = k + '_' + part + '_mesh'; ob.data.name = ob.name + ob.parent = e + ob.matrix_parent_inverse = Matrix.Translation(-Vector(piv)) + for suf, (loc, fwd) in W.empties.items(): + M = dir_quat(fwd).to_matrix().to_4x4() if fwd else Matrix() + M.translation = Vector(loc) + empty(k + '_' + suf, root, M=M) + glp = Vector(W.gripL) + ro, lo = Matrix.Translation(Vector(W.gripRoff)), Matrix.Translation(Vector(W.gripLoff)) + if base in LONG: + empty(k + '_gripR', root, M=ro @ GR @ CONV) + empty(k + '_gripL', root, M=lo @ Matrix.Translation(glp - RIFLE_GL) @ GRL @ CONV) + elif base == 'pistol': + empty(k + '_gripR', root, M=ro @ GP @ CONV) + empty(k + '_gripL', root, M=lo @ GPL @ CONV) + else: + Tm = small_item_frame(base) + empty(k + '_gripR', root, M=Tm.inverted() @ GP @ CONV) + empty(k + '_gripL', root, M=Matrix()) + return root + +def export(path, roots): + for o in bpy.context.view_layer.objects: + o.select_set(False) + def sel(o): + o.select_set(True) + for c in o.children: + sel(c) + for r in roots: + sel(r) + bpy.ops.export_scene.gltf(filepath=path, export_format='GLB', use_selection=True, export_apply=False, + export_image_format='AUTO', export_jpeg_quality=90, export_extras=False, + export_yup=True, export_texcoords=True, export_normals=True, export_tangents=False) diff --git a/e63334287a3deaa3/ironveil/tools/weapons/build.py b/e63334287a3deaa3/ironveil/tools/weapons/build.py new file mode 100644 index 00000000..a20db73b --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/weapons/build.py @@ -0,0 +1,299 @@ +# Build the weapons in small, resumable steps (one Blender process at a time, one weapon per bake): +# python build.py prep SET OUT model + unwrap one texture set, save OUT/SET.blend and OUT/SET.json +# python build.py bake SET OUT SIZE KIND bake one weapon's masks, colour, metal, roughness, normal (skips done maps) +# python build.py finish SET OUT SIZE composite the weapons' maps into the set's textures, export OUT/SET.glb +# Sets: rifle (player rifle, 2048), smg (player SMG, 2048), atlas (everything else + the reduced rifle and SMG). +# Then: node pack.mjs OUT/rifle.glb OUT/smg.glb OUT/atlas.glb weapons.glb +# Env: THREADS (default 2) limits Cycles threads. +import bpy, sys, os, time, json, math +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import numpy as np +from types import SimpleNamespace +from PIL import Image, ImageDraw +import geo as G, models as MD, mats as MT, assemble as AS + +SETS = { + 'rifle': [('rifleScoped', True, 1.0)], + 'smg': [('smg', True, 1.0)], + 'atlas': [('pistol', True, 2.4), ('enemyRifle', True, 1.0), ('enemySmg', True, 1.15), ('mg', True, 1.0), + ('knife', True, 1.9), ('binoculars', True, 1.6), ('grenade', True, 1.8), ('stickGrenade', True, 1.4), + ('rifleScoped', False, 0.55), ('smg', False, 0.6)], +} +STEP, SET, OUT = sys.argv[1], sys.argv[2], sys.argv[3] +SIZE = int(sys.argv[4]) if len(sys.argv) > 4 else 2048 +KIND = sys.argv[5] if len(sys.argv) > 5 else None +TEX = os.path.join(OUT, 'tex'); os.makedirs(TEX, exist_ok=True) +BLEND = os.path.join(OUT, SET + '.blend'); META = os.path.join(OUT, SET + '.json') +T0 = time.time() +def log(*a): + print('[%6.1fs]' % (time.time() - T0), *a, flush=True) + +def setup_scene(): + sc = bpy.context.scene + sc.render.engine = 'CYCLES'; sc.cycles.device = 'CPU' + sc.render.threads_mode = 'FIXED'; sc.render.threads = int(os.environ.get('THREADS', '2')) + sc.render.bake.margin = 6 + if sc.world is None: + sc.world = bpy.data.worlds.new('W') + sc.world.color = (0, 0, 0) + return sc + +def placeholder(name): + return bpy.data.materials.get(name) or bpy.data.materials.new(name) + +# ======================================================================================== prep +def prep(): + bpy.ops.wm.read_factory_settings(use_empty=True) + setup_scene() + objs, meta, scales = [], {}, {} + for wi, (kind, hi, s_) in enumerate(SETS[SET]): + W = MD.BUILDERS[kind](hi) + if kind == 'rifleScoped' and hi: + W.zones['checkY'] = 0.3515 + if kind == 'pistol': + W.zones['serr'] = (0.0085, 0.0335, 0.0095) + parts = {} + for part, lst in W.parts.items(): + ps = [] + for ob, t in lst: + G.set_mat(ob, placeholder('PH|%s|%s' % (W.kind, t))); ps.append(ob) + j = G.join(ps, '%s|%s' % (W.kind, part)) if len(ps) > 1 else ps[0] + j.name = '%s|%s' % (W.kind, part) + G.smooth_by_angle(j, 33) + j['wkind'] = W.kind + j.location.x = wi * 0.6 # weapons apart so occlusion rays never meet another weapon + parts[part] = j.name; objs.append(j) + scales[j.name] = s_ * W.uvscale.get(part, 1.0) + meta[W.kind] = dict(kind=W.kind, hi=W.hi, zones=W.zones, empties=W.empties, pivots=W.pivots, gripL=W.gripL, + gripRoff=W.gripRoff, gripLoff=W.gripLoff, uvscale=W.uvscale, parts=parts, + tris={p: G.tris(bpy.data.objects[n]) for p, n in parts.items()}) + log(W.kind, sum(meta[W.kind]['tris'].values())) + unwrap(objs, scales) + bpy.ops.wm.save_as_mainfile(filepath=BLEND) + json.dump(meta, open(META, 'w'), indent=1) + log('saved', BLEND) + +def unwrap(objs, scales): + for o in objs: + uv = o.data.uv_layers.new(name='atlas'); o.data.uv_layers.active = uv + for l in list(o.data.uv_layers): + if l.name != 'atlas': + o.data.uv_layers.remove(l) + G.set_active(objs[0]) + for o in objs: o.select_set(True) + bpy.ops.object.mode_set(mode='EDIT') + bpy.ops.mesh.select_all(action='SELECT') + bpy.ops.uv.smart_project(angle_limit=math.radians(58), island_margin=0.002, area_weight=0.0, scale_to_bounds=False) + bpy.ops.object.mode_set(mode='OBJECT') + for o in objs: + s = scales.get(o.name, 1.0) + if abs(s - 1.0) > 1e-3: + uvd = o.data.uv_layers['atlas'].data + a = np.zeros(len(uvd) * 2); uvd.foreach_get('uv', a); a = a.reshape(-1, 2) + c = a.mean(axis=0); a = c + (a - c) * s + uvd.foreach_set('uv', a.reshape(-1)) + G.set_active(objs[0]) + for o in objs: o.select_set(True) + bpy.ops.object.mode_set(mode='EDIT') + bpy.ops.mesh.select_all(action='SELECT') + bpy.ops.uv.select_all(action='SELECT') + try: + bpy.ops.uv.pack_islands(rotate=True, scale=True, margin=0.0025, shape_method='CONCAVE', margin_method='FRACTION') + except TypeError: + bpy.ops.uv.pack_islands(rotate=True, margin=0.0025) + bpy.ops.object.mode_set(mode='OBJECT') + +# ======================================================================================== bake +def wmeta(m): + d = dict(m) + d['zones'] = {k: (tuple(tuple(x) if isinstance(x, list) else x for x in v) if isinstance(v, list) else v) for k, v in m['zones'].items()} + return SimpleNamespace(**d) + +def new_img(name, data): + img = bpy.data.images.new(name, SIZE, SIZE, alpha=True, float_buffer=False) + img.colorspace_settings.name = 'Non-Color' if data else 'sRGB' + img.generated_color = (0, 0, 0, 0) + return img + +def save(img, path): + img.filepath_raw = path; img.file_format = 'PNG'; img.save() + +def bake_pass(sc, objs, img, kind, samples): + sc.cycles.samples = samples + mats = set(s.material for o in objs for s in o.material_slots if s.material) + for m in mats: + nt = m.node_tree + n = nt.nodes.get('_bake') or nt.nodes.new('ShaderNodeTexImage') + n.name = '_bake'; n.image = img; nt.nodes.active = n + for o in sc.objects: o.select_set(False) + for o in objs: o.select_set(True) + bpy.context.view_layer.objects.active = objs[0] + kw = dict(type=kind, margin=6, use_clear=True) + if kind == 'NORMAL': kw['normal_space'] = 'TANGENT' + bpy.ops.object.bake(**kw) + for m in mats: + n = m.node_tree.nodes.get('_bake') + if n: m.node_tree.nodes.remove(n) + +def emit_route(mats, what): + sv = [] + for m in mats: + nt = m.node_tree + out = next(n for n in nt.nodes if n.type == 'OUTPUT_MATERIAL') + old = [l.from_socket for l in out.inputs[0].links] + em = nt.nodes.new('ShaderNodeEmission') + b = next((n for n in nt.nodes if n.type == 'BSDF_PRINCIPLED'), None) + src = None + if what == 'metal': + mv = nt.nodes.get('METAL'); src = mv.outputs[0] if mv else None + if src is None: em.inputs['Color'].default_value = (0, 0, 0, 1) + else: + sock = b.inputs['Base Color' if what == 'color' else 'Roughness'] + src = sock.links[0].from_socket if sock.links else None + if src is None: + v = sock.default_value + em.inputs['Color'].default_value = tuple(v) if what == 'color' else (v, v, v, 1) + if src is not None: nt.links.new(src, em.inputs['Color']) + nt.links.new(em.outputs[0], out.inputs[0]); sv.append((m, old, em, out)) + return sv + +def emit_restore(sv): + for m, old, em, out in sv: + m.node_tree.nodes.remove(em) + if old: m.node_tree.links.new(old[0], out.inputs[0]) + +def bake(): + bpy.ops.wm.open_mainfile(filepath=BLEND) + sc = setup_scene() + meta = json.load(open(META)) + W = wmeta(meta[KIND]) + objs = [o for o in sc.objects if o.get('wkind') == KIND and o.type == 'MESH'] + for o in sc.objects: + o.hide_render = o.get('wkind') != KIND + pre = os.path.join(TEX, '%s__%s_' % (SET, KIND)) + # masks + mpath = pre + 'mask.png' + if not os.path.exists(mpath): + saved = {o.name: [s.material for s in o.material_slots] for o in objs} + mm = MT.mask_material('MASK') + for o in objs: + for s in o.material_slots: s.material = mm + img = new_img('mask', True) + bake_pass(sc, objs, img, 'EMIT', 16); save(img, mpath) + for o in objs: + for s, m in zip(o.material_slots, saved[o.name]): s.material = m + log('mask') + mimg = bpy.data.images.load(mpath); mimg.colorspace_settings.name = 'Non-Color' + real = {} + for o in objs: + for s in o.material_slots: + _, k, t = s.material.name.split('|') + if t not in real: + if t == 'glass': + gm = bpy.data.materials.new('glassbake'); gm.use_nodes = True + gm.node_tree.nodes['Principled BSDF'].inputs['Base Color'].default_value = (0.02, 0.02, 0.02, 1) + real[t] = gm + else: + real[t] = MT.make(t, '%s_%s' % (k, t), W, mimg, seed=len(real) * 1.7 + (sum(map(ord, k)) % 7)) + s.material = real[t] + mats = list(real.values()) + for what, key, samples in (('color', 'color', 4), ('metal', 'metal', 2), ('rough', 'rough', 4)): + p = pre + key + '.png' + if os.path.exists(p): continue + sv = emit_route(mats, what) + img = new_img(key, key != 'color') + bake_pass(sc, objs, img, 'EMIT', samples); save(img, p) + emit_restore(sv); log(key) + p = pre + 'normal.png' + if not os.path.exists(p): + img = new_img('normal', True) + bake_pass(sc, objs, img, 'NORMAL', 4); save(img, p); log('normal') + log('baked', KIND) + +# ======================================================================================== finish +def coverage(objs): + """Rasterise the UV islands of objs into a boolean mask (where these objects own the texture).""" + im = Image.new('L', (SIZE, SIZE), 0); d = ImageDraw.Draw(im) + for o in objs: + me = o.data; uv = me.uv_layers['atlas'].data + for p in me.polygons: + pts = [(uv[li].uv[0] * SIZE, (1 - uv[li].uv[1]) * SIZE) for li in p.loop_indices] + d.polygon(pts, fill=255, outline=255) + return np.asarray(im) > 0 + +def load(path, mode): + im = Image.open(path).convert(mode) + return np.asarray(im).astype(np.float32) / 255.0 + +def finish(): + bpy.ops.wm.open_mainfile(filepath=BLEND) + sc = setup_scene() + meta = json.load(open(META)) + kinds = list(meta) + maps = {} + for key, mode in (('mask', 'RGBA'), ('color', 'RGBA'), ('metal', 'RGBA'), ('rough', 'RGBA'), ('normal', 'RGBA')): + acc = np.zeros((SIZE, SIZE, 4), np.float32) + own = np.zeros((SIZE, SIZE), bool) + # first the texels each weapon owns, then fill the bleed margins from whichever weapon baked them + imgs = {k: load(os.path.join(TEX, '%s__%s_%s.png' % (SET, k, key)), 'RGBA') for k in kinds} + for k in kinds: + cov = coverage([o for o in sc.objects if o.get('wkind') == k and o.type == 'MESH']) + acc[cov] = imgs[k][cov]; own |= cov + for k in kinds: + m = (~own) & (imgs[k][..., 3] > 0.5) + acc[m] = imgs[k][m]; own |= m + if key == 'normal': + acc[~own] = (0.5, 0.5, 1.0, 1.0) + maps[key] = acc[..., :3] + log('composited', key) + cav, occ = maps['mask'][..., 1], maps['mask'][..., 2] + alb = maps['color'] * (1.0 - 0.30 * cav)[..., None] + ao = np.clip(0.25 + 0.75 * occ, 0, 1) * (1.0 - 0.25 * cav) + orm = np.stack([ao, maps['rough'][..., 0], maps['metal'][..., 0]], -1) + def wr(a, name): + Image.fromarray(np.clip(a * 255 + 0.5, 0, 255).astype(np.uint8)).save(os.path.join(TEX, name)) + wr(alb, SET + '_albedo.png'); wr(orm, SET + '_orm.png'); wr(maps['normal'], SET + '_normal.png') + # final material + fm = bpy.data.materials.new('wpn_' + SET); fm.use_nodes = True + nt = fm.node_tree; b = nt.nodes['Principled BSDF'] + ta = nt.nodes.new('ShaderNodeTexImage'); ta.image = bpy.data.images.load(os.path.join(TEX, SET + '_albedo.png')) + nt.links.new(ta.outputs[0], b.inputs['Base Color']) + tn = nt.nodes.new('ShaderNodeTexImage'); tn.image = bpy.data.images.load(os.path.join(TEX, SET + '_normal.png')) + tn.image.colorspace_settings.name = 'Non-Color' + nm = nt.nodes.new('ShaderNodeNormalMap'); nm.uv_map = 'atlas' + nt.links.new(tn.outputs[0], nm.inputs['Color']); nt.links.new(nm.outputs[0], b.inputs['Normal']) + to = nt.nodes.new('ShaderNodeTexImage'); to.image = bpy.data.images.load(os.path.join(TEX, SET + '_orm.png')) + to.image.colorspace_settings.name = 'Non-Color' + sp = nt.nodes.new('ShaderNodeSeparateColor'); nt.links.new(to.outputs[0], sp.inputs[0]) + nt.links.new(sp.outputs[1], b.inputs['Roughness']); nt.links.new(sp.outputs[2], b.inputs['Metallic']) + glass = bpy.data.materials.new('wpn_glass'); glass.use_nodes = True + gb = glass.node_tree.nodes['Principled BSDF'] + gb.inputs['Base Color'].default_value = (0.045, 0.060, 0.050, 1) + gb.inputs['Roughness'].default_value = 0.04; gb.inputs['Metallic'].default_value = 0.0; gb.inputs['Alpha'].default_value = 0.45 + try: glass.surface_render_method = 'BLENDED' + except Exception: pass + roots = [] + for k in kinds: + m = meta[k] + meshes = {} + for part, oname in m['parts'].items(): + o = bpy.data.objects[oname]; o.location.x = 0 + mats_ = [glass if s.material and 'glass' in s.material.name else fm for s in o.material_slots] + uniq = [] + for x in mats_: + if x not in uniq: uniq.append(x) + remap = [uniq.index(x) for x in mats_] + idx = np.zeros(len(o.data.polygons), dtype=np.int32); o.data.polygons.foreach_get('material_index', idx) + idx = np.array([remap[i] for i in idx], dtype=np.int32) + o.data.materials.clear() + for x in uniq: o.data.materials.append(x) + o.data.polygons.foreach_set('material_index', idx); o.data.update() + meshes[part] = o + W = SimpleNamespace(kind=k, empties={s: (tuple(v[0]), tuple(v[1]) if v[1] else None) for s, v in m['empties'].items()}, + pivots={p: tuple(v) for p, v in m['pivots'].items()}, gripL=tuple(m['gripL']), + gripRoff=tuple(m['gripRoff']), gripLoff=tuple(m['gripLoff'])) + roots.append(AS.assemble(W, meshes)) + AS.export(os.path.join(OUT, SET + '.glb'), roots) + log('exported', SET) + +{'prep': prep, 'bake': bake, 'finish': finish}[STEP]() diff --git a/e63334287a3deaa3/ironveil/tools/weapons/checknormals.py b/e63334287a3deaa3/ironveil/tools/weapons/checknormals.py new file mode 100644 index 00000000..63fed5fe --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/weapons/checknormals.py @@ -0,0 +1,15 @@ +# Report source objects whose faces point inward (signed volume < 0) or that are open. +import bpy, sys, os, bmesh +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import models as MD +bpy.ops.wm.read_factory_settings(use_empty=True) +for k in sys.argv[1].split(','): + W = MD.BUILDERS[k](True) + for part, lst in W.parts.items(): + for ob, t in lst: + bm = bmesh.new(); bm.from_mesh(ob.data) + vol = bm.calc_volume(signed=True) + open_ = sum(1 for e in bm.edges if not e.is_manifold) + if vol < 0 or open_: + print(k, part, ob.name, 'vol=%.3g' % vol, 'open_edges=%d' % open_) + bm.free() diff --git a/e63334287a3deaa3/ironveil/tools/weapons/demark.py b/e63334287a3deaa3/ironveil/tools/weapons/demark.py new file mode 100644 index 00000000..fdfb6216 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/weapons/demark.py @@ -0,0 +1,119 @@ +# Remove stamped text, serial numbers, dates, proof marks and national emblems from the Poly Haven weapon textures. +# usage: python demark.py +# Each mark is a rectangle in 2048 px texture space. It is refilled the same way in the colour, normal and ARM maps: +# a smooth fill from the rectangle's border (Laplace) plus the fine detail of a clean patch nearby (the patch minus +# its own blur), blended with a soft edge. So the grain, scratches and weave carry on, and the lettering is gone. +import sys, os, glob +import numpy as np +from PIL import Image + +# set -> list of (x0, y0, x1, y1, dx, dy): rectangle and the offset of the clean patch its detail is taken from +MARKS = { + 'bolt_action_rifle_7_62': [ + (1676, 712, 1812, 770, 136, 0), # factory line on the barrel shank + (396, 1332, 538, 1376, 150, 0), # serial on the receiver + (474, 1452, 566, 1526, 120, 0), # emblem and date on the receiver ring + (1090, 1490, 1174, 1566, 0, -90), # emblem on the round plate + (116, 1560, 288, 1648, 300, 0), # letters, serial and proof marks on the butt top + (1630, 1380, 1842, 1518, 0, -250), # arsenal stamp and date on the stock side + (1454, 1654, 1570, 1690, 170, 0), # serial on the bottom metal + (1578, 128, 1666, 162, 0, 34), # small serial on the bolt + (2012, 1822, 2046, 1910, 0, -100), # small serial on the edge part + (236, 1126, 298, 1178, 0, 60), # proof marks + (500, 1006, 536, 1040, 0, 50), + (130, 1250, 162, 1278, 0, 40), + (732, 1531, 764, 1562, 60, 0), + ], + 'bolt_action_rifle_7_62_accesories': [ + (1378, 378, 1526, 422, -160, 0), # scope serial + (1856, 1520, 1930, 1640, 0, 0), # mount numbers (smooth fill + plain steel detail) + (1936, 1816, 2034, 2006, 0, 0), # mount maker code and numbers + ], + 'service_pistol': [ + (80, 840, 198, 894, 250, 0), # issue text on the frame + (1560, 1176, 1652, 1294, 0, 0), # magazine capacity text (smooth fill + clean steel detail, see ABS) + (1292, 1994, 1476, 2047, -200, 0), # serial on the frame bottom + (540, 352, 604, 392, 0, 0), # lettering round a screw head (smooth fill only) + (268, 1898, 330, 2002, 0, -110), # small vertical text + ], +} +ABS = {('service_pistol', 1): (1290, 1480), ('bolt_action_rifle_7_62_accesories', 1): (330, 800), + ('bolt_action_rifle_7_62_accesories', 2): (330, 800)} # absolute source corner for marks whose neighbours carry holes + +def laplace_fill(a, m, iters=600): + """a: HxWxC float, m: HxW bool (True = unknown). Fill unknown pixels smoothly from the known border.""" + out = a.copy() + k = m.copy() + mean = a[~m].mean(axis=0) if (~m).any() else a.mean(axis=(0, 1)) + out[k] = mean + for _ in range(iters): + p = np.pad(out, ((1, 1), (1, 1), (0, 0)), mode='edge') + avg = (p[:-2, 1:-1] + p[2:, 1:-1] + p[1:-1, :-2] + p[1:-1, 2:]) * 0.25 + out[k] = avg[k] + return out + +def blur(a, r=4): + k = 2 * r + 1 + p = np.pad(a, ((r, r), (r, r), (0, 0)), mode='edge') + c = np.cumsum(np.cumsum(p, 0), 1) + c = np.pad(c, ((1, 0), (1, 0), (0, 0))) + return (c[k:, k:] - c[:-k, k:] - c[k:, :-k] + c[:-k, :-k]) / (k * k) + +def soft_mask(h, w, f=6): + y = np.minimum(np.arange(h), np.arange(h)[::-1])[:, None] + x = np.minimum(np.arange(w), np.arange(w)[::-1])[None, :] + return np.clip(np.minimum(y, x) / f, 0, 1) + +def clean(img, marks, set_name, scale): + a = np.asarray(img).astype(np.float32) + H, W = a.shape[:2] + for i, (x0, y0, x1, y1, dx, dy) in enumerate(marks): + x0, y0, x1, y1, dx, dy = [int(round(v * scale)) for v in (x0, y0, x1, y1, dx, dy)] + pad = max(3, int(8 * scale)) + X0, Y0, X1, Y1 = max(0, x0 - pad), max(0, y0 - pad), min(W, x1 + pad), min(H, y1 + pad) + crop = a[Y0:Y1, X0:X1].copy() + m = np.zeros(crop.shape[:2], bool); m[y0 - Y0:y1 - Y0, x0 - X0:x1 - X0] = True + base = laplace_fill(crop, m) + if (set_name, i) in ABS: + sx, sy = [int(v * scale) for v in ABS[(set_name, i)]] + else: + sx, sy = X0 + dx, Y0 + dy + sx = min(max(0, sx), W - (X1 - X0)); sy = min(max(0, sy), H - (Y1 - Y0)) + src = a[sy:sy + (Y1 - Y0), sx:sx + (X1 - X0)] + detail = src - blur(src, max(2, int(4 * scale))) if (dx or dy or (set_name, i) in ABS) else 0.0 + fill = base + detail + w = np.zeros(crop.shape[:2]); w[y0 - Y0:y1 - Y0, x0 - X0:x1 - X0] = soft_mask(y1 - y0, x1 - x0, max(2, int(6 * scale))) + w = np.maximum(w, m * 0.0) + crop = crop * (1 - w[..., None]) + fill * w[..., None] + a[Y0:Y1, X0:X1] = crop + return Image.fromarray(np.clip(a, 0, 255).astype(np.uint8), img.mode) + +def walnut(img): + """Take the scan's saturated orange birch down to a dark oiled walnut: orange texels lose saturation and value, + the grain (local contrast) is kept, and a faint warm red stays in the dark rings.""" + import colorsys + a = np.asarray(img).astype(np.float32) / 255.0 + r, g, b = a[..., 0], a[..., 1], a[..., 2] + mx = a.max(2); mn = a.min(2); sat = (mx - mn) / np.maximum(mx, 1e-4) + hue_orange = (r > g) & (g >= b * 0.9) & (r - b > 0.12) + w = np.clip((sat - 0.30) / 0.2, 0, 1) * hue_orange + lum = 0.30 * r + 0.55 * g + 0.15 * b + base = np.stack([lum * 0.78 + 0.035, lum * 0.52 + 0.022, lum * 0.34 + 0.012], 2) # walnut ramp + out = a * (1 - w[..., None]) + base * w[..., None] + return Image.fromarray(np.clip(out * 255, 0, 255).astype(np.uint8), 'RGB') + +if __name__ == '__main__': + src, dst = sys.argv[1], sys.argv[2] + os.makedirs(dst, exist_ok=True) + for f in sorted(glob.glob(os.path.join(src, '**', 'textures', '*.jpg'), recursive=True)): + b = os.path.basename(f) + set_name = None + for k in sorted(MARKS, key=len, reverse=True): + if b.startswith(k + '_'): set_name = k; break + img = Image.open(f).convert('RGB') + if set_name: + img = clean(img, MARKS[set_name], set_name, img.size[0] / 2048.0) + if b.startswith('bolt_action_rifle_7_62_diff'): + img = walnut(img) + img.save(os.path.join(dst, b.replace('.jpg', '.png'))) + print('cleaned' if set_name else 'copied', b) diff --git a/e63334287a3deaa3/ironveil/tools/weapons/geo.py b/e63334287a3deaa3/ironveil/tools/weapons/geo.py new file mode 100644 index 00000000..b587302f --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/weapons/geo.py @@ -0,0 +1,319 @@ +# Geometry helpers for the Midnight Ops weapons (Blender as a Python module, bpy 4.x/5.x). +# Blender frame for every weapon: barrel along -Y, up +Z, the weapon's right side is -X, metres, +# origin at the right-hand grip. (glTF export turns this into barrel +Z, up +Y.) +import bpy, bmesh, math +from mathutils import Vector, Matrix + +def link(ob): + bpy.context.scene.collection.objects.link(ob) + return ob + +def set_active(ob): + for o in list(bpy.context.scene.objects): + if o is not None: + o.select_set(False) + bpy.context.view_layer.objects.active = ob + ob.select_set(True) + +def mesh_obj(name, verts, faces, smooth=True): + me = bpy.data.meshes.new(name) + me.from_pydata([tuple(v) for v in verts], [], faces) + me.validate() + for p in me.polygons: + p.use_smooth = smooth + return link(bpy.data.objects.new(name, me)) + +def apply_mods(ob): + set_active(ob) + for m in list(ob.modifiers): + bpy.ops.object.modifier_apply(modifier=m.name) + +def tris(ob): + return sum(len(p.vertices) - 2 for p in ob.data.polygons) + +# ------------------------------------------------------------------ primitives +def superellipse(t, e): + c, s = math.cos(t), math.sin(t) + return (math.copysign(abs(c) ** (2.0 / e), c), math.copysign(abs(s) ** (2.0 / e), s)) + +def section_pts(st, n): + """Cross-section of a loft station: dict with zt, zb (top/bottom), wt, wb (widths at top/bottom), + e (exponent, 2 = ellipse, higher = squarer), et/eb optional per half, x (centre offset).""" + zt, zb = st['zt'], st['zb'] + wt, wb = st.get('wt', st.get('w')), st.get('wb', st.get('w')) + mid = (zt + zb) / 2.0 + ht, hb = zt - mid, mid - zb + pts = [] + for k in range(n): + t = 2 * math.pi * k / n + e = st.get('et', st.get('e', 2.6)) if math.sin(t) >= 0 else st.get('eb', st.get('e', 2.6)) + u, v = superellipse(t, e) + z = mid + (ht if v >= 0 else hb) * v + f = (z - zb) / max(1e-6, zt - zb) + hw = (wb + (wt - wb) * f) / 2.0 + pts.append((st.get('x', 0.0) + hw * u, z)) + return pts + +def loft_y(name, stations, n=24, cap0=True, cap1=True): + """Loft along Y through stations (each has 'y' plus the section_pts keys). Stations ordered by y.""" + verts, faces = [], [] + for st in stations: + for x, z in section_pts(st, n): + verts.append((x, st['y'], z)) + m = len(stations) + for i in range(m - 1): + for k in range(n): + a = i * n + k; b = i * n + (k + 1) % n + faces.append([a, b, b + n, a + n]) + if cap0: + c = len(verts); st = stations[0] + verts.append((st.get('x', 0.0), st['y'], (st['zt'] + st['zb']) / 2)) + for k in range(n): + faces.append([c, (k + 1) % n, k]) + if cap1: + c = len(verts); st = stations[-1]; o = (m - 1) * n + verts.append((st.get('x', 0.0), st['y'], (st['zt'] + st['zb']) / 2)) + for k in range(n): + faces.append([c, o + k, o + (k + 1) % n]) + ob = mesh_obj(name, verts, faces) + fix_normals(ob) + return ob + +def sweep(name, path, secs, n=12, up=Vector((0, 0, 1)), cap=True, closed=False): + """Sweep a section along a 3D polyline. secs: one dict per path point (w, h, e) or a single dict. + The section's width runs along 'side' (up x tangent), height along the in-plane normal.""" + P = [Vector(p) for p in path] + if isinstance(secs, dict): + secs = [secs] * len(P) + verts, faces = [], [] + m = len(P) + for i, p in enumerate(P): + if closed: + t = (P[(i + 1) % m] - P[i - 1]).normalized() + else: + t = (P[min(i + 1, m - 1)] - P[max(i - 1, 0)]).normalized() + u = up if abs(t.dot(up)) < 0.98 else Vector((1, 0, 0)) + side = u.cross(t).normalized() + nrm = t.cross(side).normalized() + s = secs[i] + for k in range(n): + a = 2 * math.pi * k / n + s.get('rot', 0.0) + cu, sv = superellipse(a, s.get('e', 2.0)) + verts.append(p + side * (cu * s['w'] / 2) + nrm * (sv * s['h'] / 2)) + rng = m if closed else m - 1 + for i in range(rng): + i2 = (i + 1) % m + for k in range(n): + a = i * n + k; b = i * n + (k + 1) % n + faces.append([a, b, i2 * n + (k + 1) % n, i2 * n + k]) + if cap and not closed: + faces.append(list(range(n))[::-1]) + faces.append([(m - 1) * n + k for k in range(n)]) + ob = mesh_obj(name, verts, faces) + fix_normals(ob) + return ob + +def lathe(name, prof, n=24, axis='Y', center=(0, 0, 0), cap0=False, cap1=False, phase=0.0, sx=1.0, sz=1.0, closed=False): + """Revolve a (radius, position-along-axis) profile. axis 'Y': along -Y forward; 'Z' vertical; 'X' sideways.""" + cx, cy, cz = center + verts, faces = [], [] + for k in range(n): + a = 2 * math.pi * k / n + phase + c, s = math.cos(a), math.sin(a) + for r, t in prof: + if axis == 'Y': + verts.append((cx + c * r * sx, cy + t, cz + s * r * sz)) + elif axis == 'Z': + verts.append((cx + c * r * sx, cy + s * r * sz, cz + t)) + else: + verts.append((cx + t, cy + c * r * sx, cz + s * r * sz)) + m = len(prof) + for k in range(n): + k2 = (k + 1) % n + for j in range(m - 1 + (1 if closed else 0)): + j2 = (j + 1) % m + faces.append([k * m + j, k * m + j2, k2 * m + j2, k2 * m + j]) + if cap0: + faces.append([k * m for k in range(n)]) + if cap1: + faces.append([k * m + m - 1 for k in range(n)][::-1]) + ob = mesh_obj(name, verts, faces) + fix_normals(ob) + return ob + +def cyl(name, r, a, b, axis='Y', c=(0, 0, 0), n=16, r1=None, caps=True, phase=0.0): + """Cylinder of radius r from a to b along axis (positions relative to c).""" + r1 = r if r1 is None else r1 + return lathe(name, [(r, a), (r1, b)], n=n, axis=axis, center=c, cap0=caps, cap1=caps, phase=phase) + +def box(name, c, s, bev=0.0015, seg=2): + bm = bmesh.new() + bmesh.ops.create_cube(bm, size=1.0) + for v in bm.verts: + v.co = Vector((v.co.x * s[0] + c[0], v.co.y * s[1] + c[1], v.co.z * s[2] + c[2])) + if bev > 0: + bmesh.ops.bevel(bm, geom=list(bm.edges), offset=bev, segments=seg, affect='EDGES', profile=0.5) + me = bpy.data.meshes.new(name); bm.to_mesh(me); bm.free() + for p in me.polygons: + p.use_smooth = True + ob = link(bpy.data.objects.new(name, me)) + return ob + +def plate(name, pts, x0, x1, bev=0.0008, seg=1, axis='X'): + """Flat part: side profile pts (y, z) extruded across X from x0 to x1 (axis 'X'), + or top-view pts (x, y) extruded along Z from x0 to x1 (axis 'Z'), or front-view (x, z) along Y (axis 'Y').""" + bm = bmesh.new() + if axis == 'X': + vs = [bm.verts.new((x0, a, b)) for a, b in pts] + elif axis == 'Z': + vs = [bm.verts.new((a, b, x0)) for a, b in pts] + else: + vs = [bm.verts.new((a, x0, b)) for a, b in pts] + f = bm.faces.new(vs) + r = bmesh.ops.extrude_face_region(bm, geom=[f]) + nv = [e for e in r['geom'] if isinstance(e, bmesh.types.BMVert)] + d = x1 - x0 + vec = (d, 0, 0) if axis == 'X' else ((0, 0, d) if axis == 'Z' else (0, d, 0)) + bmesh.ops.translate(bm, verts=nv, vec=vec) + bmesh.ops.recalc_face_normals(bm, faces=bm.faces) + if bev > 0: + bmesh.ops.bevel(bm, geom=list(bm.edges), offset=bev, segments=seg, affect='EDGES', profile=0.5, clamp_overlap=True) + me = bpy.data.meshes.new(name); bm.to_mesh(me); bm.free() + for p in me.polygons: + p.use_smooth = True + return link(bpy.data.objects.new(name, me)) + +def torus(name, R, r, c=(0, 0, 0), axis='X', n=16, m=8, sx=1.0, sy=1.0): + """Ring with major radius R (scaled sx, sy in the ring plane) around the given axis.""" + verts, faces = [], [] + for i in range(n): + a = 2 * math.pi * i / n + for j in range(m): + b = 2 * math.pi * j / m + rr = R + r * math.cos(b) + p = (rr * math.cos(a) * sx, rr * math.sin(a) * sy, r * math.sin(b)) + if axis == 'X': + p = (p[2], p[0], p[1]) + elif axis == 'Y': + p = (p[0], p[2], p[1]) + verts.append((p[0] + c[0], p[1] + c[1], p[2] + c[2])) + for i in range(n): + for j in range(m): + a = i * m + j; b = i * m + (j + 1) % m + a2 = ((i + 1) % n) * m + j; b2 = ((i + 1) % n) * m + (j + 1) % m + faces.append([a, a2, b2, b]) + ob = mesh_obj(name, verts, faces) + fix_normals(ob) + return ob + +def sphere(name, r, c=(0, 0, 0), n=12, m=8, sx=1, sy=1, sz=1): + bm = bmesh.new() + bmesh.ops.create_uvsphere(bm, u_segments=n, v_segments=m, radius=r) + for v in bm.verts: + v.co = Vector((v.co.x * sx + c[0], v.co.y * sy + c[1], v.co.z * sz + c[2])) + me = bpy.data.meshes.new(name); bm.to_mesh(me); bm.free() + for p in me.polygons: + p.use_smooth = True + return link(bpy.data.objects.new(name, me)) + +# ------------------------------------------------------------------ operations +def fix_normals(ob): + bm = bmesh.new(); bm.from_mesh(ob.data) + bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=1e-7) + bmesh.ops.recalc_face_normals(bm, faces=bm.faces) + closed = all(e.is_manifold for e in bm.edges) + if closed and bm.calc_volume(signed=True) < 0: + bmesh.ops.reverse_faces(bm, faces=bm.faces) + bm.to_mesh(ob.data); bm.free() + +def boolean(ob, cutter, op='DIFFERENCE', keep=False): + m = ob.modifiers.new('bool', 'BOOLEAN'); m.operation = op; m.object = cutter + m.solver = 'EXACT' if 'EXACT' in [i.identifier for i in m.bl_rna.properties['solver'].enum_items] else m.solver + apply_mods(ob) + if not keep: + bpy.data.objects.remove(cutter) + return ob + +def bevel(ob, w, seg=2, angle=35): + m = ob.modifiers.new('bev', 'BEVEL'); m.width = w; m.segments = seg + m.limit_method = 'ANGLE'; m.angle_limit = math.radians(angle) + m.harden_normals = False + apply_mods(ob) + return ob + +def transform(ob, M): + ob.data.transform(M); ob.data.update() + return ob + +def move(ob, d): + return transform(ob, Matrix.Translation(Vector(d))) + +def rot(ob, deg, axis, pivot=(0, 0, 0)): + p = Vector(pivot) + return transform(ob, Matrix.Translation(p) @ Matrix.Rotation(math.radians(deg), 4, axis) @ Matrix.Translation(-p)) + +def scale(ob, s, pivot=(0, 0, 0)): + p = Vector(pivot) + S = Matrix.Diagonal((s[0], s[1], s[2], 1.0)) + return transform(ob, Matrix.Translation(p) @ S @ Matrix.Translation(-p)) + +def mirror_x(ob, name=None): + c = ob.copy(); c.data = ob.data.copy(); link(c) + if name: + c.name = name + transform(c, Matrix.Diagonal((-1, 1, 1, 1))) + fix_normals(c) + return c + +def join(obs, name): + obs = [o for o in obs if o is not None] + set_active(obs[0]) + for o in obs: + o.select_set(True) + bpy.ops.object.join() + ob = bpy.context.view_layer.objects.active + ob.name = name; ob.data.name = name + return ob + +def smooth_by_angle(ob, deg=32): + me = ob.data + for p in me.polygons: + p.use_smooth = True + if hasattr(me, 'set_sharp_from_angle'): + me.set_sharp_from_angle(angle=math.radians(deg)) + return ob + +def weighted_normals(ob): + m = ob.modifiers.new('wn', 'WEIGHTED_NORMAL'); m.keep_sharp = True; m.weight = 50 + apply_mods(ob) + return ob + +def set_mat(ob, mat): + ob.data.materials.clear(); ob.data.materials.append(mat) + return ob + +def path_arc(c, r, a0, a1, n, plane='YZ'): + """Points on an arc (degrees) around centre c in the given plane.""" + out = [] + for i in range(n + 1): + a = math.radians(a0 + (a1 - a0) * i / n) + if plane == 'YZ': + out.append((c[0], c[1] + r * math.cos(a), c[2] + r * math.sin(a))) + elif plane == 'XY': + out.append((c[0] + r * math.cos(a), c[1] + r * math.sin(a), c[2])) + else: + out.append((c[0] + r * math.cos(a), c[1], c[2] + r * math.sin(a))) + return out + +def bezier(pts, n): + """Quadratic/cubic Bezier through control points (list of 3 or 4 tuples).""" + P = [Vector(p) for p in pts] + out = [] + for i in range(n + 1): + t = i / n + if len(P) == 3: + q = P[0] * (1 - t) ** 2 + P[1] * 2 * t * (1 - t) + P[2] * t * t + else: + q = P[0] * (1 - t) ** 3 + P[1] * 3 * t * (1 - t) ** 2 + P[2] * 3 * t * t * (1 - t) + P[3] * t ** 3 + out.append(tuple(q)) + return out diff --git a/e63334287a3deaa3/ironveil/tools/weapons/grips.json b/e63334287a3deaa3/ironveil/tools/weapons/grips.json new file mode 100644 index 00000000..035b8972 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/weapons/grips.json @@ -0,0 +1,54 @@ +{ + "rifle": [ + [ + -0.03762373328208923, + 0.07079654932022095, + 0.04415559768676758 + ], + [ + 0.07979588210582733, + 0.010356963612139225, + 0.4671984910964966, + -0.8804833889007568 + ] + ], + "rifleL": [ + [ + 0.0357542410492897, + -0.24063187837600708, + -0.05499231815338135 + ], + [ + 0.2965492010116577, + 0.5771419405937195, + 0.025639934465289116, + 0.7604658603668213 + ] + ], + "pistol": [ + [ + -0.034473538398742676, + 0.042779624462127686, + 0.011927008628845215 + ], + [ + 0.04627012461423874, + 0.021226244047284126, + 0.5680063366889954, + -0.8214483261108398 + ] + ], + "pistolL": [ + [ + 0.07088170945644379, + 0.05433696508407593, + -0.023854970932006836 + ], + [ + 0.1864648163318634, + 0.19839061796665192, + -0.5122721791267395, + 0.8145239353179932 + ] + ] +} \ No newline at end of file diff --git a/e63334287a3deaa3/ironveil/tools/weapons/mats.py b/e63334287a3deaa3/ironveil/tools/weapons/mats.py new file mode 100644 index 00000000..919bec50 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/weapons/mats.py @@ -0,0 +1,626 @@ +# Procedural weapon materials (Cycles nodes), baked to albedo / normal / occlusion-roughness-metal maps. +# Every material reads a pre-baked MASK image (R = convex edges, G = cavities, B = broad occlusion) through the +# 'atlas' UV map, plus the weapon's object-space position, so wear lands where wear happens: +# edges and corners go bright, hands polish and darken, things that slide get scratches along the slide, +# recesses keep dust and a little rust. Metal amount goes out through a value node named METAL. +# Colours are linear RGB. +import bpy, math + +class NB: + def __init__(self, name, mask_img=None): + m = bpy.data.materials.new(name) + m.use_nodes = True + self.m = m; self.nt = m.node_tree; self.nt.nodes.clear() + self.out = self.nt.nodes.new('ShaderNodeOutputMaterial') + self.bsdf = self.nt.nodes.new('ShaderNodeBsdfPrincipled') + self.nt.links.new(self.bsdf.outputs[0], self.out.inputs[0]) + self.P = self.nt.nodes.new('ShaderNodeTexCoord').outputs['Object'] + self.mask = None + if mask_img is not None: + uv = self.nt.nodes.new('ShaderNodeUVMap'); uv.uv_map = 'atlas' + t = self.nt.nodes.new('ShaderNodeTexImage'); t.image = mask_img; t.interpolation = 'Linear' + self.nt.links.new(uv.outputs[0], t.inputs[0]) + s = self.nt.nodes.new('ShaderNodeSeparateColor'); self.nt.links.new(t.outputs[0], s.inputs[0]) + self.mask = s + # ---------------------------------------------------------------- plumbing + def _in(self, sock, v): + if isinstance(v, (int, float)): + sock.default_value = v + elif isinstance(v, tuple): + sock.default_value = v if len(v) == 4 or len(sock.default_value) == 3 else v + (1.0,) + else: + self.nt.links.new(v, sock) + def math(self, op, a, b=None, c=None, clamp=False): + n = self.nt.nodes.new('ShaderNodeMath'); n.operation = op; n.use_clamp = clamp + self._in(n.inputs[0], a) + if b is not None: self._in(n.inputs[1], b) + if c is not None: self._in(n.inputs[2], c) + return n.outputs[0] + def add(self, *a): + r = a[0] + for x in a[1:]: r = self.math('ADD', r, x) + return r + def mul(self, *a): + r = a[0] + for x in a[1:]: r = self.math('MULTIPLY', r, x) + return r + def sub(self, a, b): return self.math('SUBTRACT', a, b) + def inv(self, a): return self.math('SUBTRACT', 1.0, a) + def mx(self, a, b): return self.math('MAXIMUM', a, b) + def clamp(self, a): return self.math('ADD', a, 0.0, clamp=True) + def vmath(self, op, a, b=None, out=0): + n = self.nt.nodes.new('ShaderNodeVectorMath'); n.operation = op + self._in(n.inputs[0], a) + if b is not None: self._in(n.inputs[1], b) + return n.outputs[out] + def mapping(self, v, loc=(0, 0, 0), rot=(0, 0, 0), scale=(1, 1, 1)): + n = self.nt.nodes.new('ShaderNodeMapping') + self._in(n.inputs['Vector'], v) + n.inputs['Location'].default_value = loc + n.inputs['Rotation'].default_value = [math.radians(r) for r in rot] + n.inputs['Scale'].default_value = scale + return n.outputs[0] + def xyz(self, v=None): + n = self.nt.nodes.new('ShaderNodeSeparateXYZ'); self._in(n.inputs[0], v or self.P) + return n.outputs[0], n.outputs[1], n.outputs[2] + def noise(self, v, scale, detail=3.0, rough=0.5, dist=0.0, w=0.0): + n = self.nt.nodes.new('ShaderNodeTexNoise'); n.noise_dimensions = '4D' + self._in(n.inputs['Vector'], v) + n.inputs['Scale'].default_value = scale; n.inputs['Detail'].default_value = detail + n.inputs['Roughness'].default_value = rough; n.inputs['Distortion'].default_value = dist + n.inputs['W'].default_value = w + return n.outputs['Fac'] + def vor(self, v, scale, feature='F1', rnd=1.0, out='Distance'): + n = self.nt.nodes.new('ShaderNodeTexVoronoi'); n.feature = feature + self._in(n.inputs['Vector'], v) + n.inputs['Scale'].default_value = scale; n.inputs['Randomness'].default_value = rnd + return n.outputs[out] + def ss(self, x, a, b): + """smoothstep from a to b (a > b inverts).""" + n = self.nt.nodes.new('ShaderNodeMapRange'); n.interpolation_type = 'SMOOTHSTEP' + self._in(n.inputs['Value'], x) + self._in(n.inputs['From Min'], a); self._in(n.inputs['From Max'], b) + return n.outputs[0] + def lerp(self, f, a, b): + n = self.nt.nodes.new('ShaderNodeMix'); n.data_type = 'FLOAT'; n.clamp_factor = True + self._in(n.inputs[0], f); self._in(n.inputs[2], a); self._in(n.inputs[3], b) + return n.outputs[0] + def mixc(self, f, a, b, mode='MIX'): + n = self.nt.nodes.new('ShaderNodeMix'); n.data_type = 'RGBA'; n.blend_type = mode; n.clamp_factor = True + self._in(n.inputs[0], f) + self._in(n.inputs[6], a if not isinstance(a, tuple) else (a + (1.0,) if len(a) == 3 else a)) + self._in(n.inputs[7], b if not isinstance(b, tuple) else (b + (1.0,) if len(b) == 3 else b)) + return n.outputs[2] + def cmul(self, c, f): + """colour times scalar.""" + return self.mixc(1.0, c, self.gray(f), mode='MULTIPLY') + def gray(self, f): + n = self.nt.nodes.new('ShaderNodeCombineColor') + for i in range(3): self._in(n.inputs[i], f) + return n.outputs[0] + # ---------------------------------------------------------------- masks + def edge(self): return self.mask.outputs[0] if self.mask else 0.0 + def cavity(self): return self.mask.outputs[1] if self.mask else 0.0 + def occl(self): return self.mask.outputs[2] if self.mask else 1.0 + def zone(self, c, r, soft=0.45): + """1 inside an ellipsoid (centre c, radii r) of the weapon frame, fading out over the outer 'soft' part.""" + d = self.vmath('DIVIDE', self.vmath('SUBTRACT', self.P, c), r) + ln = self.vmath('LENGTH', d, out=1) + return self.ss(ln, 1.0, 1.0 - soft) + def scratches(self, scale, stretch, rot, width, density, seed=0.0): + """Thin line fragments: voronoi cell edges of a stretched space, kept where a sparse noise allows. + scale: lines per metre across, stretch: ratio along/across (>1 = long lines), rot: orientation (deg).""" + q = self.mapping(self.P, loc=(seed, seed * 1.7, seed * 0.3), rot=rot) + q = self.mapping(q, scale=(scale, scale / stretch, scale)) + d = self.vor(q, 1.0, 'DISTANCE_TO_EDGE') + line = self.ss(d, width, 0.0) + keep = self.ss(self.noise(self.mapping(self.P, loc=(seed * 3.1, 0, 0)), scale * 0.06, 2.0, 0.5), 1.0 - density, 1.0 - density + 0.12) + return self.mul(line, keep) + def scratch_set(self, axis, amount=1.0, along=1.0, fine=1.0, seed=0.0): + """Directional scratches along the slide axis plus random-direction ones. axis: 'Y' or 'Z'.""" + ar = (0, 0, 0) if axis == 'Y' else (90, 0, 0) + a1 = self.scratches(1400, 30, ar, 0.035, 0.30 * along, seed) + a2 = self.scratches(600, 18, (ar[0] + 3, ar[1], ar[2] + 2), 0.025, 0.22 * along, seed + 5) + r1 = self.scratches(700, 14, (37, 61, 12), 0.03, 0.20 * fine, seed + 11) + r2 = self.scratches(900, 10, (-48, 20, 75), 0.03, 0.16 * fine, seed + 17) + r3 = self.scratches(350, 22, (80, -35, 140), 0.02, 0.10 * fine, seed + 23) + s = self.mx(self.mx(a1, a2), self.mx(r1, self.mx(r2, r3))) + return self.mul(s, amount) + def checker(self, a_axis, b_axis, pitch): + """Diamond checkering height (0..1) on the plane of two axes ('X','Y','Z').""" + x, y, z = self.xyz() + A = {'X': x, 'Y': y, 'Z': z} + k = 2 * math.pi / pitch / 1.4142 + u = self.math('SINE', self.mul(self.add(A[a_axis], A[b_axis]), k)) + v = self.math('SINE', self.mul(self.sub(A[a_axis], A[b_axis]), k)) + h = self.math('MINIMUM', self.math('ABSOLUTE', u), self.math('ABSOLUTE', v)) + return self.ss(h, 0.05, 0.6) + # ---------------------------------------------------------------- output + def finish(self, color, rough, metal, height=None, bump_dist=0.0004, bump_strength=1.0): + self._in(self.bsdf.inputs['Base Color'], color) + self._in(self.bsdf.inputs['Roughness'], self.clamp(rough) if not isinstance(rough, float) else rough) + mv = self.nt.nodes.new('ShaderNodeMath'); mv.operation = 'ADD'; mv.use_clamp = True; mv.name = 'METAL' + self._in(mv.inputs[0], metal); mv.inputs[1].default_value = 0.0 + self._in(self.bsdf.inputs['Metallic'], mv.outputs[0]) + if height is not None: + b = self.nt.nodes.new('ShaderNodeBump'); b.inputs['Strength'].default_value = bump_strength + b.inputs['Distance'].default_value = bump_dist + self._in(b.inputs['Height'], height) + self.nt.links.new(b.outputs[0], self.bsdf.inputs['Normal']) + return self.m + +# ======================================================================================== masks +def mask_material(name): + """R: convex worn edges, G: cavities (tight AO), B: broad occlusion. Baked through an emission shader.""" + m = bpy.data.materials.new(name); m.use_nodes = True + nt = m.node_tree; nt.nodes.clear() + out = nt.nodes.new('ShaderNodeOutputMaterial'); em = nt.nodes.new('ShaderNodeEmission') + nt.links.new(em.outputs[0], out.inputs[0]) + geo = nt.nodes.new('ShaderNodeNewGeometry') + bv = nt.nodes.new('ShaderNodeBevel'); bv.samples = 8; bv.inputs['Radius'].default_value = 0.0011 + dp = nt.nodes.new('ShaderNodeVectorMath'); dp.operation = 'DOT_PRODUCT' + nt.links.new(bv.outputs[0], dp.inputs[0]); nt.links.new(geo.outputs['Normal'], dp.inputs[1]) + e = nt.nodes.new('ShaderNodeMath'); e.operation = 'SUBTRACT'; e.inputs[0].default_value = 1.0 + nt.links.new(dp.outputs['Value'], e.inputs[1]) + er = nt.nodes.new('ShaderNodeMapRange'); er.inputs['From Min'].default_value = 0.004; er.inputs['From Max'].default_value = 0.06 + nt.links.new(e.outputs[0], er.inputs['Value']) + a1 = nt.nodes.new('ShaderNodeAmbientOcclusion'); a1.samples = 12; a1.inputs['Distance'].default_value = 0.006 + a2 = nt.nodes.new('ShaderNodeAmbientOcclusion'); a2.samples = 12; a2.inputs['Distance'].default_value = 0.035 + conv = nt.nodes.new('ShaderNodeMapRange'); conv.inputs['From Min'].default_value = 0.72; conv.inputs['From Max'].default_value = 0.95 + nt.links.new(a1.outputs['AO'], conv.inputs['Value']) + ed = nt.nodes.new('ShaderNodeMath'); ed.operation = 'MULTIPLY' + nt.links.new(er.outputs[0], ed.inputs[0]); nt.links.new(conv.outputs[0], ed.inputs[1]) + cav = nt.nodes.new('ShaderNodeMapRange'); cav.inputs['From Min'].default_value = 0.92; cav.inputs['From Max'].default_value = 0.45 + nt.links.new(a1.outputs['AO'], cav.inputs['Value']) + cc = nt.nodes.new('ShaderNodeCombineColor') + nt.links.new(ed.outputs[0], cc.inputs[0]); nt.links.new(cav.outputs[0], cc.inputs[1]); nt.links.new(a2.outputs['AO'], cc.inputs[2]) + nt.links.new(cc.outputs[0], em.inputs['Color']) + return m + +# ======================================================================================== metals + +def _machining(nb, W, h, r): + """Mill and file marks on machined steel (MACHINING=1, SMG only): fine parallel lines along the receiver, in + patches, raised a hair in the normal map and slightly glossier along each cut.""" + import os + if not os.environ.get('MACHINING') or getattr(W, 'kind', '') != 'smg': return h, r + x, y, z = nb.xyz() + wob = nb.mul(nb.noise(nb.P, 260, 2, 0.5), 2.5) + lines = nb.math('ABSOLUTE', nb.math('SINE', nb.add(nb.mul(z, 2 * math.pi / 0.00042), wob))) + cross = nb.math('ABSOLUTE', nb.math('SINE', nb.add(nb.mul(y, 2 * math.pi / 0.0011), nb.mul(x, 2 * math.pi / 0.0011)))) + patch = nb.ss(nb.noise(nb.P, 16, 3, 0.55, w=31), 0.42, 0.62) + mm = nb.add(nb.mul(nb.ss(lines, 0.15, 0.95), patch), nb.mul(nb.ss(cross, 0.2, 0.95), nb.inv(patch), 0.5)) + return nb.add(h, nb.mul(mm, 0.07)), nb.lerp(nb.mul(mm, 0.35), r, nb.sub(r, 0.10)) +def _hand(nb, W, extra=()): + z = W.zones + h = nb.add(nb.zone(*z['handR']), nb.zone(*z['handL'])) + for e in extra: + h = nb.add(h, nb.zone(*e)) + return nb.clamp(h) + +def _axis(W): + s = W.zones.get('slide', (0, 1, 0)) + return 'Z' if abs(s[2]) > 0.5 else 'Y' + +def blued(name, W, mask, seed=0.0, tint=(0.060, 0.066, 0.082)): + nb = NB(name, mask) + P = nb.P + n1 = nb.noise(P, 14, 4, 0.55, w=seed) + n2 = nb.noise(P, 160, 5, 0.6, w=seed + 3) + n3 = nb.noise(P, 45, 3, 0.5, w=seed + 7) + hand = _hand(nb, W) + edge = nb.edge() + wear = nb.ss(nb.add(nb.mul(edge, nb.add(0.40, nb.mul(n2, 1.2))), nb.mul(hand, edge, 0.6)), 0.34, 0.66) + scr = nb.scratch_set(_axis(W), 1.0, along=1.2, fine=1.1, seed=seed) + cav = nb.cavity() + rust = nb.mul(nb.ss(cav, 0.25, 0.75), nb.ss(nb.noise(P, 70, 4, 0.6, w=seed + 9), 0.50, 0.68)) + pits = nb.ss(nb.vor(nb.mapping(P, scale=(1, 1, 1)), 420, 'F1', 1.0), 0.06, 0.0) + pits = nb.mul(pits, nb.ss(nb.noise(P, 30, 2, 0.5, w=seed + 13), 0.55, 0.72)) + rust = nb.clamp(nb.add(rust, nb.mul(pits, 0.8))) + dust = nb.mul(nb.ss(cav, 0.35, 0.9), nb.ss(nb.noise(P, 90, 3, 0.5, w=seed + 2), 0.35, 0.6), 0.9) + smudge = nb.ss(nb.noise(P, 26, 3, 0.55, w=seed + 4), 0.52, 0.72) + # colour: bluing varies; worn-thin bluing goes plum-grey where hands rub; scratches and edges bright + c = nb.mixc(n1, tint, (tint[0] * 1.5, tint[1] * 1.45, tint[2] * 1.35)) + rub = nb.mul(nb.ss(nb.noise(nb.mapping(P, scale=(3, 0.25, 3)), 30, 3, 0.6, w=seed + 15), 0.52, 0.75), 0.55) + c = nb.mixc(rub, c, (0.13, 0.12, 0.12)) + c = nb.mixc(nb.mul(hand, 0.6, n3), c, (0.21, 0.18, 0.17)) + c = nb.mixc(nb.mul(scr, 0.85), c, (0.42, 0.42, 0.41)) + c = nb.mixc(wear, c, (0.66, 0.65, 0.62)) + c = nb.mixc(rust, c, (0.11, 0.045, 0.020)) + c = nb.mixc(dust, c, (0.20, 0.17, 0.13)) + r = nb.add(0.40, nb.mul(nb.sub(n1, 0.5), 0.18)) + r = nb.lerp(smudge, r, 0.27) # oil sheen + r = nb.lerp(nb.mul(hand, 0.7), r, 0.30) + r = nb.lerp(nb.mul(scr, 0.8), r, 0.24) + r = nb.lerp(wear, r, 0.22) + r = nb.lerp(rust, r, 0.85) + r = nb.lerp(dust, r, 0.92) + metal = nb.clamp(nb.sub(1.0, nb.add(rust, nb.mul(dust, 0.9)))) + h = nb.add(nb.mul(scr, -0.5), nb.mul(pits, -0.6), nb.mul(rust, nb.noise(P, 900, 2, 0.5), 0.5), nb.mul(nb.noise(P, 2500, 1, 0.5), 0.05)) + if 'checkY' in W.zones: # checkered butt plate (face normal along Y) + y0 = W.zones['checkY'] + x, y, z = nb.xyz() + cm = nb.mul(nb.ss(y, y0 - 0.0005, y0 + 0.0008), nb.inv(nb.ss(nb.edge(), 0.1, 0.4))) + ch = nb.mul(nb.checker('X', 'Z', 0.0020), cm, nb.inv(nb.mul(wear, 0.8))) + h = nb.add(h, nb.mul(ch, 0.7)) + h, r = _machining(nb, W, h, r) + return nb.finish(c, r, metal, h, bump_dist=0.00035) + +def parkerized(name, W, mask, seed=0.0, tint=(0.024, 0.025, 0.0235), serr=None): + """Phosphate finish: matte dark grey-green non-metal coat; bare steel shows on worn edges and scratches.""" + nb = NB(name, mask) + P = nb.P + n1 = nb.noise(P, 12, 4, 0.55, w=seed) + n2 = nb.noise(P, 170, 5, 0.6, w=seed + 3) + n3 = nb.noise(P, 40, 3, 0.5, w=seed + 8) + hand = _hand(nb, W) + edge = nb.edge() + wear = nb.ss(nb.add(nb.mul(edge, nb.add(0.30, nb.mul(n2, 1.15))), nb.mul(hand, edge, 0.7)), 0.40, 0.72) + scr = nb.scratch_set(_axis(W), 1.0, seed=seed) + cav = nb.cavity() + rust = nb.mul(nb.ss(cav, 0.30, 0.80), nb.ss(nb.noise(P, 60, 4, 0.6, w=seed + 9), 0.52, 0.70)) + dust = nb.mul(nb.ss(cav, 0.30, 0.85), nb.ss(nb.noise(P, 90, 3, 0.5, w=seed + 2), 0.30, 0.60)) + oil = nb.ss(nb.noise(P, 22, 3, 0.55, w=seed + 4), 0.50, 0.70) + blot = nb.noise(P, 6, 4, 0.65, w=seed + 12) # uneven phosphate + c = nb.mixc(n1, tint, (tint[0] * 1.7, tint[1] * 1.72, tint[2] * 1.6)) + c = nb.mixc(nb.ss(blot, 0.40, 0.70), nb.cmul(c, 0.72), nb.cmul(c, 1.25)) + c = nb.mixc(nb.mul(nb.add(oil, nb.mul(hand, 0.8)), 0.5), c, (tint[0] * 0.65, tint[1] * 0.65, tint[2] * 0.65)) # oiled = darker + c = nb.mixc(nb.mul(n3, hand, 0.35), c, (0.10, 0.10, 0.095)) # rubbed thin + c = nb.mixc(nb.mul(scr, 0.9), c, (0.46, 0.46, 0.45)) + c = nb.mixc(wear, c, (0.60, 0.59, 0.56)) + c = nb.mixc(rust, c, (0.10, 0.042, 0.018)) + c = nb.mixc(dust, c, (0.19, 0.16, 0.12)) + r = nb.add(0.70, nb.mul(nb.sub(n1, 0.5), 0.14)) + r = nb.lerp(nb.mul(oil, 0.8), r, 0.46) + r = nb.lerp(nb.mul(hand, 0.8), r, 0.42) + r = nb.lerp(nb.mul(scr, 0.9), r, 0.30) + r = nb.lerp(wear, r, 0.26) + r = nb.lerp(rust, r, 0.88) + r = nb.lerp(dust, r, 0.93) + metal = nb.clamp(nb.add(nb.mul(scr, 0.9), wear)) + metal = nb.clamp(nb.sub(metal, nb.add(rust, dust))) + h = nb.add(nb.mul(scr, -0.5), nb.mul(nb.noise(P, 1800, 2, 0.6), 0.10), nb.mul(rust, -0.3)) + if serr: # grasping grooves (pistol slide rear): vertical ridges along Y between y0 and y1, above z0 + y0, y1, z0 = serr + x, y, z = nb.xyz() + m = nb.mul(nb.ss(y, y0, y0 + 0.0006), nb.ss(y, y1, y1 - 0.0006), nb.ss(z, z0, z0 + 0.0008)) + g = nb.math('ABSOLUTE', nb.math('SINE', nb.mul(y, 2 * math.pi / 0.00185))) + h = nb.add(h, nb.mul(nb.ss(g, 0.15, 0.7), m, 1.2)) + c = nb.mixc(nb.mul(m, nb.ss(g, 0.5, 0.0), 0.5), c, nb.cmul(c, 0.6)) + h, r = _machining(nb, W, h, r) + return nb.finish(c, r, metal, h, bump_dist=0.00035) + +def steel(name, W, mask, seed=0.0): + """Bright worn steel for bolts, triggers, cocking knobs: heavy scratches along the slide, oil films.""" + nb = NB(name, mask) + P = nb.P + n1 = nb.noise(P, 20, 4, 0.55, w=seed) + n2 = nb.noise(P, 180, 4, 0.6, w=seed + 2) + edge = nb.edge() + scr = nb.scratch_set(_axis(W), 1.0, along=1.6, fine=0.6, seed=seed + 31) + cav = nb.cavity() + oil = nb.ss(nb.noise(nb.mapping(P, scale=(3, 0.6, 3)), 18, 3, 0.55, w=seed + 4), 0.48, 0.70) + grime = nb.mul(nb.ss(cav, 0.55, 1.0), nb.ss(nb.noise(P, 60, 3, 0.5, w=seed + 3), 0.4, 0.7), 0.6) + rust = nb.mul(nb.ss(cav, 0.7, 1.0), nb.ss(nb.noise(P, 80, 4, 0.6, w=seed + 9), 0.62, 0.72)) + c = nb.mixc(n1, (0.30, 0.30, 0.295), (0.40, 0.40, 0.39)) + c = nb.mixc(nb.mul(oil, 0.7), c, (0.21, 0.20, 0.185)) + c = nb.mixc(nb.mul(scr, 0.5), c, (0.56, 0.56, 0.54)) + c = nb.mixc(nb.ss(nb.mul(edge, nb.add(0.4, n2)), 0.3, 0.7), c, (0.70, 0.70, 0.68)) + c = nb.mixc(grime, c, (0.07, 0.06, 0.05)) + c = nb.mixc(rust, c, (0.11, 0.045, 0.02)) + r = nb.add(0.27, nb.mul(nb.sub(n1, 0.5), 0.10)) + r = nb.lerp(oil, r, 0.16) + r = nb.lerp(nb.mul(scr, 0.6), r, 0.36) + r = nb.lerp(grime, r, 0.75) + r = nb.lerp(rust, r, 0.85) + metal = nb.clamp(nb.sub(1.0, nb.add(rust, nb.mul(grime, 0.8)))) + h = nb.add(nb.mul(scr, -0.22), nb.mul(nb.noise(nb.mapping(P, scale=(1, 0.04, 1)), 1800, 1, 0.5), 0.025)) + return nb.finish(c, r, metal, h, bump_dist=0.0002) + +def brass(name, W, mask, seed=0.0): + nb = NB(name, mask) + P = nb.P + n1 = nb.noise(P, 60, 4, 0.6, w=seed) + tarn = nb.ss(nb.add(nb.noise(P, 25, 3, 0.55, w=seed + 2), nb.mul(nb.cavity(), 0.5)), 0.48, 0.75) + scr = nb.scratch_set('Y', 0.8, seed=seed) + c = nb.mixc(n1, (0.62, 0.43, 0.18), (0.74, 0.54, 0.24)) + c = nb.mixc(tarn, c, (0.28, 0.19, 0.08)) + c = nb.mixc(nb.mul(nb.edge(), 0.8), c, (0.85, 0.66, 0.34)) + r = nb.lerp(tarn, 0.26, 0.48) + r = nb.lerp(scr, r, 0.36) + return nb.finish(c, r, 1.0, nb.mul(scr, -0.4), bump_dist=0.0003) + +# ======================================================================================== wood +def wood(name, W, mask, seed=0.0, kind='walnut'): + nb = NB(name, mask) + axis = _axis(W) + q = nb.P if axis == 'Y' else nb.mapping(nb.P, rot=(90, 0, 0)) + q = nb.mapping(q, rot=(4.5 + (seed % 2.0), 0, 1.5)) # grain runs a few degrees off the stock line + if kind == 'walnut': + early, late, pore = (0.058, 0.031, 0.016), (0.030, 0.0155, 0.0080), (0.016, 0.009, 0.005) + ringsPerM, axisOff = 110.0, (0.19, 0.0, -0.33) + else: # beech with a redder oil stain, finer grain, rays + early, late, pore = (0.060, 0.027, 0.012), (0.036, 0.0158, 0.0070), (0.020, 0.009, 0.004) + ringsPerM, axisOff = 140.0, (-0.21, 0.0, -0.28) + warp = nb.add(nb.mul(nb.sub(nb.noise(nb.mapping(q, scale=(9, 0.7, 9)), 1.0, 4, 0.55, dist=0.6, w=seed), 0.5), 0.030), + nb.mul(nb.sub(nb.noise(nb.mapping(q, scale=(40, 2.0, 40)), 1.0, 3, 0.5, w=seed + 1), 0.5), 0.006)) + rel = nb.vmath('MULTIPLY', nb.vmath('SUBTRACT', q, axisOff), (1.0, 0.0, 1.0)) + rad = nb.add(nb.vmath('LENGTH', rel, out=1), warp) + rr = nb.mul(rad, ringsPerM) + # rings wander: lines converge, spread and curve along the length (no two alike, never evenly spaced) + rr = nb.add(rr, nb.mul(nb.noise(nb.mapping(q, scale=(6, 1.3, 6)), 1.0, 3, 0.55, w=seed + 9), 17.0), + nb.mul(nb.noise(nb.mapping(q, scale=(24, 4.0, 24)), 1.0, 2, 0.5, w=seed + 11), 4.0)) + ring = nb.math('FRACT', rr) + rw = nb.noise(nb.mapping(q, scale=(25, 0.5, 25)), 1.0, 2, 0.5, w=seed + 10) # ring sharpness varies + latew = nb.mul(nb.ss(ring, nb.add(0.50, nb.mul(rw, 0.30)), 0.93), nb.ss(ring, 1.0, 0.965)) + latew = nb.mul(latew, nb.add(0.35, nb.mul(nb.noise(nb.mapping(q, scale=(30, 3, 30)), 1.0, 2, 0.5, w=seed + 13), 0.9))) + pores = nb.ss(nb.noise(nb.mapping(q, scale=(1, 0.06, 1)), 1300, 2, 0.5, w=seed + 2), 0.62, 0.72) + pores = nb.mul(pores, nb.add(0.45, nb.mul(latew, 0.55))) + figure = nb.noise(nb.mapping(q, scale=(1, 0.15, 1)), 7, 4, 0.6, w=seed + 3) + tone = nb.noise(q, 4, 2, 0.5, w=seed + 5) + c = nb.mixc(nb.mul(latew, 0.6), early, late) + streak = nb.noise(nb.mapping(q, scale=(60, 1.2, 60)), 1.0, 3, 0.55, w=seed + 14) # long colour streaks along the grain + c = nb.cmul(c, nb.add(0.62, nb.mul(tone, 0.45), nb.mul(nb.sub(figure, 0.5), 0.7), nb.mul(nb.sub(streak, 0.5), 0.5))) + c = nb.mixc(nb.mul(pores, 0.75), c, pore) + scan = _wood_scan(nb, q, kind) + if scan is not None: + # a CC0 scanned walnut (WOOD_SCAN, see CREDITS-weapons.md) replaces the procedural rings: its luminance is + # toned to oiled walnut, its roughness and height maps carry the real grain and pores + lum, srough, sdisp = scan + c = nb.mixc(nb.ss(lum, 0.18, 0.80), (0.022, 0.011, 0.006), (0.115, 0.060, 0.028)) + c = nb.cmul(c, nb.add(0.85, nb.mul(tone, 0.3))) + latew = nb.mul(nb.ss(lum, 0.55, 0.20), 0.6); pores = nb.mul(nb.ss(sdisp, 0.45, 0.25), 0.5) + if kind != 'walnut': + rays = nb.ss(nb.noise(nb.mapping(q, scale=(1, 0.25, 1)), 900, 1, 0.5, w=seed + 6), 0.70, 0.75) + c = nb.mixc(nb.mul(rays, 0.25), c, (0.12, 0.05, 0.022)) + hand = _hand(nb, W) + z = W.zones + worn = nb.clamp(nb.add(nb.zone(*z['butt']), nb.mul(nb.zone(*z['cheek']), 0.8))) + edge = nb.edge() + nE = nb.noise(nb.P, 140, 4, 0.6, w=seed + 7) + edgeW = nb.ss(nb.mul(edge, nb.add(0.3, nb.mul(nE, 1.2))), 0.30, 0.65) + # dents and dings: small round dents plus short gouges + dent = nb.ss(nb.vor(nb.P, 140, 'F1', 1.0), 0.11, 0.03) + dent = nb.mul(dent, nb.ss(nb.noise(nb.P, 14, 2, 0.5, w=seed + 8), 0.62, 0.72)) + gouge = nb.scratches(500, 6, (25, 40, 10), 0.05, 0.16, seed + 3) + scr = nb.scratches(900, 16, (5, 70, -20), 0.03, 0.22, seed + 9) + scr = nb.mx(scr, nb.scratches(700, 12, (-60, 10, 35), 0.03, 0.18, seed + 19)) + cav = nb.cavity() + # finish: oiled; hands darken and polish it; butt and comb worn back to lighter dry wood; edges and dings lighter + c = nb.cmul(c, nb.lerp(hand, 1.0, 0.62)) + c = nb.mixc(nb.mul(worn, nb.add(0.4, nb.mul(nE, 0.6))), c, nb.cmul(nb.mixc(0.35, c, (0.20, 0.15, 0.10)), 1.55)) + c = nb.mixc(nb.mul(edgeW, 0.85), c, nb.cmul(nb.mixc(0.3, c, (0.22, 0.15, 0.09)), 1.7)) + c = nb.mixc(nb.mul(nb.mx(scr, gouge), 0.7), c, nb.cmul(c, 1.9)) + c = nb.mixc(nb.mul(dent, 0.5), c, nb.cmul(c, 0.7)) + c = nb.mixc(nb.mul(nb.ss(cav, 0.2, 0.9), 0.9), c, (0.020, 0.014, 0.010)) + r = nb.add(0.52, nb.mul(nb.sub(tone, 0.5), 0.16), nb.mul(latew, -0.04), nb.mul(pores, 0.08)) + if scan is not None: + r = nb.add(0.40, nb.mul(scan[1], 0.30)) # oiled: 0.40-0.70 from the scan's own roughness + r = nb.lerp(hand, r, 0.34) + r = nb.lerp(nb.mul(worn, 0.8), r, 0.70) + r = nb.lerp(edgeW, r, 0.68) + r = nb.lerp(nb.mx(scr, gouge), r, 0.72) + r = nb.lerp(nb.ss(cav, 0.2, 0.9), r, 0.85) + h = nb.add(nb.mul(latew, -0.10), nb.mul(pores, -0.25), nb.mul(dent, -1.0), nb.mul(gouge, -0.8), nb.mul(scr, -0.35), + nb.mul(nb.noise(nb.mapping(q, scale=(1, 0.06, 1)), 2200, 1, 0.5), 0.06)) + if scan is not None: h = nb.add(h, nb.mul(scan[2], 0.5)) + return nb.finish(c, r, 0.0, h, bump_dist=0.0005) + +def _wood_scan(nb, q, kind): + """Grain-aligned triplanar sampling of a scanned wood set. WOOD_SCAN = folder holding _diff_2k.jpg, + _rough_2k.jpg, _disp_2k.jpg (WOOD_SCAN_NAME, default natural_walnut_veneer). The image grain runs along U, so + every projection puts U along the stock line (q's Y): sides use (Y, Z), top and bottom (Y, X), ends (X, Z). + One image covers WOOD_SCAN_SIZE metres (the scan is 1 m square). Returns (luminance, roughness, height) sockets.""" + import os + d = os.environ.get('WOOD_SCAN') + if not d or kind != 'walnut': return None + name = os.environ.get('WOOD_SCAN_NAME', 'natural_walnut_veneer'); size = float(os.environ.get('WOOD_SCAN_SIZE', 0.6)) + x, y, z = nb.xyz(q) + tc = nb.nt.nodes.new('ShaderNodeTexCoord') + nx, ny, nz = nb.xyz(tc.outputs['Normal']) + w = [nb.math('POWER', nb.math('ABSOLUTE', a), 4.0) for a in (nx, ny, nz)] + tot = nb.add(w[0], w[1], w[2], 1e-4) + w = [nb.math('DIVIDE', a, tot) for a in w] + def uv(u, v): + n = nb.nt.nodes.new('ShaderNodeCombineXYZ') + nb._in(n.inputs[0], nb.mul(u, 1.0 / size)); nb._in(n.inputs[1], nb.mul(v, 1.0 / size)) + return n.outputs[0] + proj = [uv(y, z), uv(x, z), uv(y, x)] # X-facing, Y-facing (end grain), Z-facing + out = [] + for m, col in (('diff', False), ('rough', True), ('disp', True)): + img = bpy.data.images.load(os.path.join(d, '%s_%s_2k.jpg' % (name, m)), check_existing=True) + img.colorspace_settings.name = 'sRGB' if m == 'diff' else 'Non-Color' + acc = None + for wi, pv in zip(w, proj): + t = nb.nt.nodes.new('ShaderNodeTexImage'); t.image = img; t.interpolation = 'Cubic' + nb._in(t.inputs[0], pv) + val = t.outputs[0] + if m == 'diff': + g = nb.nt.nodes.new('ShaderNodeRGBToBW'); nb._in(g.inputs[0], val); val = g.outputs[0] + else: + g = nb.nt.nodes.new('ShaderNodeRGBToBW'); nb._in(g.inputs[0], val); val = g.outputs[0] + term = nb.mul(val, wi) + acc = term if acc is None else nb.add(acc, term) + out.append(acc) + return out + +# ======================================================================================== soft goods and plastics +def leather(name, W, mask, seed=0.0, col=(0.040, 0.024, 0.014)): + nb = NB(name, mask) + P = nb.P + n1 = nb.noise(P, 30, 4, 0.6, w=seed) + crease = nb.math('ABSOLUTE', nb.sub(nb.noise(nb.mapping(P, scale=(0.5, 1, 0.5)), 120, 3, 0.55, w=seed + 2), 0.5)) + crease = nb.ss(crease, 0.06, 0.0) + grain = nb.vor(P, 1100, 'F1', 1.0) + edge = nb.edge() + edgeW = nb.ss(nb.mul(edge, nb.add(0.4, n1)), 0.25, 0.6) + scr = nb.scratches(600, 8, (10, 60, 30), 0.04, 0.2, seed) + c = nb.cmul(col, nb.add(0.75, nb.mul(n1, 0.5))) + c = nb.mixc(nb.mul(crease, 0.6), c, nb.cmul(c, 0.55)) + c = nb.mixc(edgeW, c, (0.11, 0.07, 0.04)) + c = nb.mixc(nb.mul(scr, 0.6), c, (0.10, 0.065, 0.04)) + c = nb.mixc(nb.mul(nb.ss(nb.cavity(), 0.2, 0.9), 0.8), c, (0.03, 0.02, 0.012)) + r = nb.add(0.56, nb.mul(nb.sub(n1, 0.5), 0.2)) + r = nb.lerp(edgeW, r, 0.75) + r = nb.lerp(crease, r, 0.70) + h = nb.add(nb.mul(grain, 0.25), nb.mul(crease, -0.7), nb.mul(scr, -0.4)) + return nb.finish(c, r, 0.0, h, bump_dist=0.0005) + +def canvas(name, W, mask, seed=0.0): + nb = NB(name, mask) + P = nb.P + x, y, z = nb.xyz() + k = 2 * math.pi / 0.0011 + wv = nb.add(nb.math('SINE', nb.mul(y, k)), nb.math('SINE', nb.mul(nb.add(x, z), k))) + n1 = nb.noise(P, 25, 4, 0.6, w=seed) + stain = nb.ss(nb.noise(P, 9, 3, 0.6, w=seed + 3), 0.5, 0.75) + edge = nb.edge() + c = nb.cmul((0.085, 0.072, 0.042), nb.add(0.80, nb.mul(n1, 0.4))) + c = nb.mixc(nb.mul(stain, 0.7), c, (0.075, 0.065, 0.040)) + c = nb.mixc(nb.mul(edge, 0.7), c, (0.24, 0.21, 0.14)) + c = nb.mixc(nb.mul(nb.ss(nb.cavity(), 0.2, 0.9), 0.8), c, (0.04, 0.035, 0.025)) + r = nb.lerp(stain, 0.90, 0.78) + return nb.finish(c, r, 0.0, nb.add(nb.mul(wv, 0.12), nb.mul(n1, 0.2)), bump_dist=0.0004) + +def bakelite(name, W, mask, seed=0.0, col=(0.030, 0.015, 0.008)): + nb = NB(name, mask) + P = nb.P + n1 = nb.noise(P, 40, 5, 0.65, w=seed) + n2 = nb.noise(P, 200, 3, 0.6, w=seed + 1) + hand = _hand(nb, W) + edge = nb.edge() + edgeW = nb.ss(nb.mul(edge, nb.add(0.3, nb.mul(n2, 1.1))), 0.35, 0.7) + scr = nb.scratch_set('Y', 1.0, along=0.4, fine=1.2, seed=seed) + c = nb.cmul(col, nb.add(0.70, nb.mul(n1, 0.6))) + c = nb.mixc(nb.mul(scr, 0.6), c, nb.cmul(col, 2.4)) + c = nb.mixc(edgeW, c, nb.cmul(col, 2.8)) + c = nb.mixc(nb.mul(nb.ss(nb.cavity(), 0.2, 0.9), 0.8), c, (0.05, 0.045, 0.035)) + r = nb.add(0.36, nb.mul(nb.sub(n1, 0.5), 0.15)) + r = nb.lerp(hand, r, 0.26) + r = nb.lerp(nb.mul(scr, 0.8), r, 0.58) + r = nb.lerp(edgeW, r, 0.62) + r = nb.lerp(nb.ss(nb.cavity(), 0.2, 0.9), r, 0.8) + h = nb.add(nb.mul(scr, -0.4), nb.mul(nb.noise(P, 900, 2, 0.5), 0.05)) + if W.kind == 'enemySmg': # moulded grip frame: horizontal grip grooves on the pistol grip + x, y, zz = nb.xyz() + g = nb.math('ABSOLUTE', nb.math('SINE', nb.mul(zz, 2 * math.pi / 0.0045))) + m = nb.mul(nb.ss(zz, -0.012, -0.020), nb.ss(zz, -0.105, -0.098)) + h = nb.add(h, nb.mul(nb.ss(g, 0.2, 0.8), m, nb.inv(nb.mul(hand, 0.4)), 0.8)) + return nb.finish(c, r, 0.0, h, bump_dist=0.0004) + +def checkplastic(name, W, mask, seed=0.0): + """Moulded brown grip panels with diamond checkering, flattened and polished where the palm sits.""" + nb = NB(name, mask) + P = nb.P + n1 = nb.noise(P, 60, 4, 0.6, w=seed) + hand = nb.zone(*W.zones['handR']) + edge = nb.edge() + ch = nb.checker('Y', 'Z', 0.00135) + x, y, z = nb.xyz() + face = nb.ss(nb.math('ABSOLUTE', x), 0.0135, 0.0148) + chm = nb.mul(face, nb.inv(nb.ss(edge, 0.05, 0.3))) + flat = nb.mul(hand, nb.ss(nb.noise(P, 80, 3, 0.5, w=seed + 3), 0.35, 0.6), 0.75) + c = nb.cmul((0.060, 0.026, 0.012), nb.add(0.75, nb.mul(n1, 0.5))) + c = nb.mixc(nb.mul(nb.inv(ch), chm, 0.6), c, (0.022, 0.011, 0.006)) + c = nb.mixc(nb.mul(edge, 0.8), c, (0.11, 0.06, 0.035)) + r = nb.lerp(flat, 0.48, 0.30) + r = nb.lerp(nb.mul(nb.inv(ch), chm), r, 0.62) + h = nb.mul(ch, chm, nb.inv(flat)) + return nb.finish(c, r, 0.0, h, bump_dist=0.00045) + +def leatherstack(name, W, mask, seed=0.0): + """Stacked leather washers: each ring its own shade, lacquered, dark in the grooves, polished by the palm.""" + nb = NB(name, mask) + x, y, z = nb.xyz() + rid = nb.math('FLOOR', nb.mul(nb.sub(y, 0.006), 1 / 0.0093)) + tint = nb.noise(nb.gray(nb.mul(rid, 1.37)), 1.0, 1, 0.5, w=seed) + fib = nb.noise(nb.mapping(nb.P, scale=(1, 0.2, 1)), 700, 3, 0.6, w=seed + 1) + c = nb.mixc(tint, (0.115, 0.052, 0.022), (0.060, 0.028, 0.013)) + c = nb.cmul(c, nb.add(0.8, nb.mul(fib, 0.4))) + c = nb.mixc(nb.mul(nb.ss(nb.cavity(), 0.1, 0.8), 0.9), c, (0.02, 0.012, 0.007)) + c = nb.mixc(nb.mul(nb.edge(), 0.6), c, (0.17, 0.10, 0.05)) + r = nb.lerp(nb.zone(*W.zones['handR']), 0.55, 0.40) + return nb.finish(c, r, 0.0, nb.mul(fib, 0.3), bump_dist=0.0004) + +def leatherette(name, W, mask, seed=0.0): + nb = NB(name, mask) + P = nb.P + peb = nb.vor(P, 650, 'F1', 1.0) + n1 = nb.noise(P, 40, 3, 0.6, w=seed) + edgeW = nb.ss(nb.mul(nb.edge(), nb.add(0.4, n1)), 0.3, 0.6) + c = nb.cmul((0.026, 0.025, 0.024), nb.add(0.85, nb.mul(n1, 0.3))) + c = nb.mixc(edgeW, c, (0.09, 0.085, 0.08)) + r = nb.lerp(edgeW, 0.66, 0.42) + return nb.finish(c, r, 0.0, nb.mul(peb, 0.6), bump_dist=0.0004) + +def paint(name, W, mask, seed=0.0, col=(0.060, 0.066, 0.030), rough=0.62, under='steel'): + """Painted metal: chips on edges and knocks show dark steel (or brass for the black enamel), rust in chips.""" + nb = NB(name, mask) + P = nb.P + n1 = nb.noise(P, 30, 4, 0.6, w=seed) + n2 = nb.noise(P, 220, 4, 0.6, w=seed + 2) + edge = nb.edge() + chips = nb.ss(nb.add(nb.mul(edge, nb.add(0.2, nb.mul(n2, 1.2))), nb.mul(nb.ss(nb.noise(P, 90, 5, 0.7, w=seed + 5), 0.68, 0.74), 0.8)), 0.45, 0.62) + scuff = nb.scratch_set(_axis(W), 0.9, along=0.3, fine=1.0, seed=seed) + rustIn = nb.mul(chips, nb.ss(nb.noise(P, 150, 3, 0.6, w=seed + 7), 0.45, 0.7)) + if under == 'brass': + bare = (0.72, 0.58, 0.36) + else: + bare = (0.42, 0.42, 0.41) + c = nb.cmul(col, nb.add(0.80, nb.mul(n1, 0.4))) + c = nb.mixc(nb.mul(scuff, 0.5), c, nb.cmul(col, 1.8)) + c = nb.mixc(chips, c, bare) + c = nb.mixc(nb.mul(rustIn, 0.8), c, (0.10, 0.042, 0.018)) + c = nb.mixc(nb.mul(nb.ss(nb.cavity(), 0.2, 0.9), 0.85), c, (0.03, 0.028, 0.02)) + r = nb.add(rough, nb.mul(nb.sub(n1, 0.5), 0.12)) + r = nb.lerp(nb.mul(scuff, 0.6), r, rough + 0.12) + r = nb.lerp(chips, r, 0.32) + r = nb.lerp(rustIn, r, 0.85) + metal = nb.clamp(nb.sub(chips, rustIn)) + h = nb.add(nb.mul(chips, -0.6), nb.mul(scuff, -0.3), nb.mul(nb.noise(P, 1500, 2, 0.6), 0.08)) + if W.kind == 'grenade': # pineapple grooves: darker, dirtier + x, y, z = nb.xyz() + th = nb.math('ARCTAN2', y, x) + col_g = nb.math('POWER', nb.math('ABSOLUTE', nb.math('COSINE', nb.mul(th, 4.0))), 18.0) + row_g = nb.math('POWER', nb.math('ABSOLUTE', nb.math('COSINE', nb.mul(nb.add(z, 0.040), 5 * math.pi / 0.0835))), 18.0) + g = nb.mul(nb.mx(col_g, row_g), nb.ss(z, 0.040, 0.036), nb.ss(z, -0.039, -0.035)) + c = nb.mixc(nb.mul(g, 0.7), c, (0.020, 0.020, 0.012)) + h = nb.add(h, nb.mul(g, -1.0)) + return nb.finish(c, r, metal, h, bump_dist=0.0004) + +def blade(name, W, mask, seed=0.0): + """Parkerized blade with a honed bright edge, fine sharpening scratches along the edge.""" + nb = NB(name, mask) + P = nb.P + x, y, z = nb.xyz() + hone = nb.ss(nb.math('ABSOLUTE', x), 0.00085, 0.0004) + n1 = nb.noise(P, 30, 4, 0.55, w=seed) + scr = nb.scratch_set('Y', 1.0, along=1.6, seed=seed) + sharp = nb.mul(hone, nb.ss(nb.scratches(3000, 40, (0, 0, 0), 0.08, 0.6, seed + 4), 0.0, 1.0)) + c = nb.mixc(n1, (0.052, 0.055, 0.050), (0.075, 0.078, 0.072)) + c = nb.mixc(nb.mul(scr, 0.85), c, (0.45, 0.45, 0.44)) + c = nb.mixc(hone, c, (0.60, 0.60, 0.58)) + c = nb.mixc(nb.mul(nb.edge(), 0.8), c, (0.55, 0.55, 0.53)) + r = nb.lerp(hone, 0.66, 0.20) + r = nb.lerp(nb.mul(scr, 0.8), r, 0.30) + metal = nb.clamp(nb.add(hone, nb.mul(scr, 0.9), nb.edge())) + return nb.finish(c, r, metal, nb.add(nb.mul(scr, -0.5), nb.mul(sharp, -0.4)), bump_dist=0.0003) + +def make(t, name, W, mask, seed=0.0): + if t == 'blued': return blued(name, W, mask, seed) + if t == 'park': return parkerized(name, W, mask, seed, serr=W.zones.get('serr')) + if t == 'steel': return steel(name, W, mask, seed) + if t == 'brass': return brass(name, W, mask, seed) + if t == 'wood': return wood(name, W, mask, seed, 'walnut') + if t == 'wood2': return wood(name, W, mask, seed, 'beech') + if t == 'leather': return leather(name, W, mask, seed) + if t == 'canvas': return canvas(name, W, mask, seed) + if t == 'bakelite': return bakelite(name, W, mask, seed, (0.020, 0.011, 0.007) if W.kind == 'mg' else (0.030, 0.015, 0.008)) + if t == 'checkplastic': return checkplastic(name, W, mask, seed) + if t == 'leatherstack': return leatherstack(name, W, mask, seed) + if t == 'leatherette': return leatherette(name, W, mask, seed) + if t == 'paint_od': return paint(name, W, mask, seed, (0.058, 0.064, 0.030), 0.62) + if t == 'paint_grey': return paint(name, W, mask, seed, (0.090, 0.094, 0.086), 0.66) + if t == 'paint_black': return paint(name, W, mask, seed, (0.020, 0.020, 0.021), 0.42, under='brass') + if t == 'blade': return blade(name, W, mask, seed) + raise ValueError(t) diff --git a/e63334287a3deaa3/ironveil/tools/weapons/models.py b/e63334287a3deaa3/ironveil/tools/weapons/models.py new file mode 100644 index 00000000..b840f447 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/weapons/models.py @@ -0,0 +1,804 @@ +# Weapon builders. Each returns a Weapon: named parts (each a list of (object, material type)), empties and +# pivots, in the Blender weapon frame (barrel -Y, up +Z, right side -X, origin at the right-hand grip, metres). +# Shapes follow real period small arms by proportion; no markings of any kind are modelled. +import math +from mathutils import Vector +import geo as G + +class Weapon: + def __init__(self, kind, hi=True): + self.kind = kind; self.hi = hi + self.parts = {} # part name -> [(obj, mat)] + self.pivots = {} # part name -> pivot point (moving parts get an empty there) + self.empties = {} # suffix -> (location, forward vector or None) + self.gripL = (0, -0.3, 0) + self.zones = {} # wear zones for the materials (hand areas, etc.) + self.uvscale = {} # part name -> uv island scale factor + self.gripRoff = (0, 0, 0) # hand-frame nudges (m, Blender frame) found by measuring finger penetration + self.gripLoff = (0, 0, 0) + def add(self, ob, mat, part='body'): + if not self.hi: # reduced models: one mesh (two draw calls with the glass), no moving parts + part = 'body' + self.parts.setdefault(part, []).append((ob, mat)) + return ob + def n(self, hi, lo): + return hi if self.hi else lo + +BORE = 0.020 + +# ===================================================================================================== +def rifle_scoped(hi=True): + """Bolt-action service rifle with a pistol-grip stock and a telescopic sight on a one-piece base + (proportions of the 1903-pattern sniper rifles). Overall 1.09 m.""" + W = Weapon('rifleScoped' if hi else 'rifleScopedLod', hi) + N = W.n + # ---------------- stock (walnut) + S = [ + dict(y=-0.489, zt=0.0085, zb=-0.006, w=0.020, e=2.2), + dict(y=-0.484, zt=0.0115, zb=-0.0135, w=0.029, et=3.2, eb=2.4), + dict(y=-0.40, zt=0.0120, zb=-0.0165, w=0.0315, et=3.4, eb=2.4), + dict(y=-0.30, zt=0.0120, zb=-0.0185, w=0.0335, et=3.4, eb=2.4), + dict(y=-0.225, zt=0.0130, zb=-0.0205, w=0.0355, et=3.4, eb=2.4), + dict(y=-0.190, zt=0.0175, zb=-0.0250, w=0.0395, et=3.4, eb=2.6), + dict(y=-0.140, zt=0.0200, zb=-0.0385, w=0.0410, et=3.4, eb=2.8), + dict(y=-0.060, zt=0.0200, zb=-0.0395, w=0.0410, et=3.4, eb=2.8), + dict(y=-0.025, zt=0.0180, zb=-0.0350, w=0.0385, et=3.0, eb=2.6), + dict(y=0.008, zt=0.0110, zb=-0.0360, w=0.0350, et=2.8, eb=2.4), + dict(y=0.035, zt=0.0045, zb=-0.0500, w=0.0315, et=2.6, eb=2.3), + dict(y=0.060, zt=0.0030, zb=-0.0670, w=0.0325, et=2.6, eb=2.3), + dict(y=0.078, zt=0.0050, zb=-0.0770, w=0.0335, et=2.6, eb=2.4), + dict(y=0.094, zt=0.0120, zb=-0.0735, w=0.0355, et=2.6, eb=2.6), + dict(y=0.112, zt=0.0215, zb=-0.0745, w=0.0375, et=2.6, eb=2.6), + dict(y=0.160, zt=0.0255, zb=-0.0800, w=0.0395, et=2.8, eb=2.6), + dict(y=0.240, zt=0.0280, zb=-0.0900, w=0.0410, et=2.8, eb=2.6), + dict(y=0.330, zt=0.0300, zb=-0.1010, w=0.0420, et=2.9, eb=2.6), + dict(y=0.3515, zt=0.0305, zb=-0.1035, w=0.0425, et=3.0, eb=2.7), + ] + if not hi: + S = [S[i] for i in (0, 1, 3, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18)] + stock = G.loft_y('stock', S, n=N(30, 10)) + W.add(stock, 'wood') + # butt plate (steel, checkered in the material), slightly proud of the wood + last = dict(S[-1]); bp = [] + for dy, grow in ((0.0, 0.0006), (0.0045, 0.0006), (0.0062, -0.0006)): + st = dict(last); st['y'] = last['y'] + dy + st['zt'] += grow + 0.0005; st['zb'] -= grow + 0.0005; st['w'] += 2 * grow + bp.append(st) + W.add(G.loft_y('buttplate', bp, n=N(30, 12)), 'blued') + # hand guard (walnut) over the barrel from the receiver ring to the upper band + HG = [dict(y=-0.468, zt=0.0310, zb=0.0110, w=0.0255, et=2.1, eb=6), + dict(y=-0.455, zt=0.0335, zb=0.0110, w=0.0290, et=2.1, eb=6), + dict(y=-0.205, zt=0.0345, zb=0.0110, w=0.0300, et=2.1, eb=6), + dict(y=-0.192, zt=0.0310, zb=0.0110, w=0.0290, et=2.1, eb=6)] + W.add(G.loft_y('handguard', HG, n=N(22, 10)), 'wood') + # ---------------- barrel (lathe, with crown and bore) + bprof = [(0.0040, -0.700), (0.0040, -0.7275), (0.0052, -0.7305), (0.0078, -0.7305), (0.0083, -0.7290), + (0.0083, -0.700), (0.0088, -0.600), (0.0093, -0.470), (0.0100, -0.330), (0.0108, -0.250), + (0.0118, -0.215), (0.0134, -0.200), (0.0134, -0.170)] + if not hi: + bprof = [(0.0040, -0.71), (0.0040, -0.7305), (0.0083, -0.7305), (0.0093, -0.470), (0.0134, -0.200), (0.0134, -0.170)] + W.add(G.lathe('barrel', bprof, n=N(28, 8), axis='Y', center=(0, 0, BORE), cap0=True, cap1=True), 'blued') + # ---------------- receiver: round body, front ring, rear bridge, open top between them, bolt way + rcv = G.lathe('receiver', [(0.0168, 0.028), (0.0168, -0.130), (0.0178, -0.133), (0.0178, -0.178), (0.0170, -0.180)], + n=N(28, 12), axis='Y', center=(0, 0, BORE), cap0=True, cap1=True) + if hi: + G.boolean(rcv, G.cyl('boltway', 0.0102, 0.04, -0.17, c=(0, 0, BORE), n=24)) + G.boolean(rcv, G.box('cutTop', (-0.012, -0.067, BORE + 0.022), (0.036, 0.110, 0.03), bev=0.0)) + G.boolean(rcv, G.box('cutRight', (-0.018, -0.067, BORE + 0.016), (0.03, 0.110, 0.03), bev=0.0)) + G.boolean(rcv, G.box('cutHandle', (-0.018, 0.0, BORE + 0.010), (0.022, 0.016, 0.03), bev=0.0)) + G.boolean(rcv, G.cyl('thumbcut', 0.010, -0.03, 0.03, axis='X', c=(0.0, -0.075, BORE + 0.026), n=16)) + G.bevel(rcv, 0.0006, seg=1, angle=40) + W.add(rcv, 'blued') + # receiver tang along the wrist top + W.add(G.plate('tang', [(0.020, 0.0020), (0.088, 0.0020), (0.094, 0.0050), (0.088, 0.0065), (0.020, 0.0090)], + -0.0055, 0.0055, bev=0.0008), 'blued') + # ---------------- bolt (moving part): body, extractor, sleeve, cocking piece, safety, bent handle + bolt = [] + bolt.append(G.lathe('boltBody', [(0.0084, -0.118), (0.0088, -0.114), (0.0088, 0.040), (0.0105, 0.042), + (0.0108, 0.072), (0.0080, 0.076), (0.0075, 0.090), (0.0083, 0.093), (0.0083, 0.099), (0.0070, 0.1005)], + n=N(22, 10), axis='Y', center=(0, 0, BORE), cap0=True, cap1=True)) + if hi: + bolt.append(G.box('extractor', (-0.0072, -0.060, BORE + 0.0035), (0.0035, 0.100, 0.0060), bev=0.0007)) + bolt.append(G.plate('safety', [(0.050, 0.0), (0.066, 0.0), (0.066, 0.004), (0.058, 0.008), (0.050, 0.004)], + -0.0015, 0.0015, bev=0.0005)) + G.move(bolt[-1], (-0.006, 0, BORE + 0.0095)) + arm = G.bezier([(-0.0075, 0.004, BORE + 0.001), (-0.034, 0.002, BORE + 0.001), (-0.046, 0.010, BORE - 0.012), (-0.050, 0.019, BORE - 0.021)], N(8, 4)) + bolt.append(G.sweep('boltArm', arm, [dict(w=0.0085, h=0.0070, e=2.4)] * len(arm), n=N(10, 6))) + bolt.append(G.sphere('boltKnob', 0.0090, c=(-0.0515, 0.0205, BORE - 0.0245), n=N(16, 8), m=N(10, 6), sx=1.0, sy=1.05, sz=1.12)) + for o in bolt: + W.add(o, 'steel', 'bolt') + W.pivots['bolt'] = (0, 0, BORE) + # ---------------- trigger guard + floorplate, trigger + W.add(G.plate('floorplate', [(-0.124, -0.0360), (-0.030, -0.0360), (-0.030, -0.0425), (-0.118, -0.0425), (-0.124, -0.040)], + -0.0115, 0.0115, bev=0.0012, seg=2), 'blued') + gp = G.bezier([(0, -0.031, -0.038), (0, -0.026, -0.060), (0, 0.012, -0.062), (0, 0.023, -0.038)], N(12, 6)) + W.add(G.sweep('guardbow', gp, dict(w=0.0034, h=0.0095, e=3.0), n=N(10, 6), up=Vector((1, 0, 0))), 'blued') + if hi: + for y in (-0.118, 0.019): + W.add(G.cyl('gscrew', 0.0032, -0.0435, -0.0445, axis='Z', c=(0, y, 0), n=12), 'blued') + tp = G.bezier([(0, -0.0045, -0.030), (0, -0.0060, -0.044), (0, -0.0030, -0.052), (0, 0.0015, -0.0555)], N(6, 3)) + W.add(G.sweep('trigger', tp, [dict(w=0.0042, h=0.0060, e=3.0)] * (len(tp) - 1) + [dict(w=0.003, h=0.0055, e=3.0)], + n=8, up=Vector((1, 0, 0))), 'steel', 'trigger') + W.pivots['trigger'] = (0, -0.0045, -0.031) + # ---------------- bands, bayonet lug, sling swivels + def band(y0, y1, zt, zb, w, name): + st = [dict(y=y0, zt=zt - 0.0008, zb=zb + 0.0008, w=w - 0.0016, e=3.0), dict(y=y0 + 0.0012, zt=zt, zb=zb, w=w, e=3.0), + dict(y=y1 - 0.0012, zt=zt, zb=zb, w=w, e=3.0), dict(y=y1, zt=zt - 0.0008, zb=zb + 0.0008, w=w - 0.0016, e=3.0)] + return G.loft_y(name, st, n=N(26, 12)) + W.add(band(-0.338, -0.326, 0.0362, -0.0200, 0.0352, 'lowerBand'), 'blued') + W.add(band(-0.4915, -0.455, 0.0350, -0.0180, 0.0335, 'upperBand'), 'blued') + W.add(G.lathe('nose', [(0.0090, -0.4795), (0.0108, -0.4800), (0.0108, -0.4950), (0.0094, -0.4975)], + n=N(20, 10), axis='Y', center=(0, 0, BORE), cap0=False, cap1=False, closed=True), 'blued') + W.add(G.box('bayLug', (0, -0.489, 0.0060), (0.0060, 0.020, 0.0080), bev=0.001), 'blued') + def swivel(y, z, name, part): + base = G.box(name + 'Stud', (0, y, z + 0.003), (0.008, 0.012, 0.006), bev=0.0012) + loop = G.sweep(name + 'Loop', [(-0.016, y, z - 0.002), (-0.017, y, z - 0.012), (-0.012, y, z - 0.015), (0.012, y, z - 0.015), + (0.017, y, z - 0.012), (0.016, y, z - 0.002), (0.0, y, z + 0.001)], + dict(w=0.0034, h=0.0034, e=2.0), n=8, closed=True) + W.add(base, 'blued', part); W.add(loop, 'blued', part) + swivel(-0.466, -0.0185, 'swF', 'body') + # rear swivel: on the butt underside + swivel(0.255, -0.0935, 'swR', 'body') + # ---------------- scope: tube with eyepiece and objective bells, turret saddle, turrets, rings, one-piece base + SZ = 0.0745 + sprof = [(0.0118, 0.1110), (0.0122, 0.1150), (0.0150, 0.1185), (0.0166, 0.1172), (0.0168, 0.0960), (0.0162, 0.0935), + (0.0168, 0.0905), (0.0168, 0.0740), (0.0150, 0.0650), (0.0120, 0.0540), (0.0112, 0.0460), + (0.0112, -0.1640), (0.0118, -0.1700), (0.0144, -0.1880), (0.0150, -0.2060), (0.0155, -0.2085), + (0.0153, -0.2125), (0.0132, -0.2135), (0.0127, -0.2085)] + if not hi: + sprof = [(0.0122, 0.114), (0.0168, 0.1172), (0.0168, 0.074), (0.0112, 0.050), (0.0112, -0.166), (0.0150, -0.206), (0.0153, -0.2125), (0.0127, -0.209)] + W.add(G.lathe('scopeTube', sprof, n=N(36, 8), axis='Y', center=(0, 0, SZ), cap0=True, cap1=True), 'blued') + sad = [dict(y=-0.050, zt=SZ + 0.0118, zb=SZ - 0.0118, w=0.0236, e=2.0), dict(y=-0.046, zt=SZ + 0.0132, zb=SZ - 0.0132, w=0.0262, e=2.6), + dict(y=-0.014, zt=SZ + 0.0132, zb=SZ - 0.0132, w=0.0262, e=2.6), dict(y=-0.010, zt=SZ + 0.0118, zb=SZ - 0.0118, w=0.0236, e=2.0)] + W.add(G.loft_y('saddle', sad, n=N(24, 8)), 'blued') + tur = [(0.0, 0.0), (0.0088, 0.0), (0.0088, 0.0085), (0.0094, 0.0090), (0.0094, 0.0150), (0.0086, 0.0158), (0.0, 0.0158)] + t1 = G.lathe('turretE', [(r, z + 0.0115) for r, z in tur], n=N(24, 10), axis='Z', center=(0, -0.030, SZ)) + t2 = G.lathe('turretW', [(r, -(z + 0.0115)) for r, z in tur], n=N(24, 10), axis='X', center=(0, -0.030, SZ)) + W.add(t1, 'blued'); W.add(t2, 'blued') + def ring(y, name): + if not hi: + W.add(G.box(name, (0, y, SZ - 0.006), (0.030, 0.009, 0.034), bev=0.002), 'blued'); return + r = G.lathe(name, [(0.0112, y + 0.0048), (0.0142, y + 0.0048), (0.0148, y + 0.0030), (0.0148, y - 0.0030), + (0.0142, y - 0.0048), (0.0112, y - 0.0048)], n=N(28, 12), axis='Y', center=(0, 0, SZ), cap0=False, cap1=False, closed=True) + G.fix_normals(r) + W.add(r, 'blued') + W.add(G.box(name + 'Leg', (0, y, 0.0525), (0.0120, 0.0094, 0.0130), bev=0.0012), 'blued') + W.add(G.box(name + 'Ears', (0, y, SZ), (0.0350, 0.0090, 0.0072), bev=0.0014), 'blued') + if hi: + for s in (-1, 1): + W.add(G.cyl(name + 'Screw', 0.0028, 0.0175 * s, 0.0195 * s, axis='X', c=(0, y, SZ), n=10), 'blued') + ring(0.031, 'ringR'); ring(-0.106, 'ringF') + base = [dict(y=-0.170, zt=0.0455, zb=0.0350, w=0.0150, e=3.5), dict(y=-0.165, zt=0.0470, zb=0.0340, w=0.0185, e=4.0), + dict(y=-0.130, zt=0.0470, zb=0.0350, w=0.0185, e=4.0), dict(y=-0.120, zt=0.0470, zb=0.0400, w=0.0160, e=4.0), + dict(y=-0.010, zt=0.0470, zb=0.0400, w=0.0160, e=4.0), dict(y=0.000, zt=0.0470, zb=0.0340, w=0.0200, e=4.0), + dict(y=0.040, zt=0.0470, zb=0.0340, w=0.0200, e=4.0), dict(y=0.044, zt=0.0450, zb=0.0350, w=0.0160, e=3.5)] + W.add(G.loft_y('base', base, n=N(16, 8)), 'blued') + if hi: + for s in (-1, 1): # rear windage screws, one each side of the rear ring + W.add(G.cyl('windScrew', 0.0047, 0.0100 * s, 0.0160 * s, axis='X', c=(0, 0.031, 0.0420), n=14), 'blued') + # lenses (separate nodes, glass) + W.add(G.cyl('lensRear', 0.0121, 0.1112, 0.1104, c=(0, 0, SZ), n=N(28, 12)), 'glass', 'scopeLensRear') + W.add(G.cyl('lensFront', 0.0127, -0.2083, -0.2075, c=(0, 0, SZ), n=N(28, 12)), 'glass', 'scopeLensFront') + # ---------------- sling (leather, 1.25 in), front loop doubled back through a keeper, brass hook + yF, zF = -0.466, -0.0335 + yR, zR = 0.255, -0.1085 + pts = [] + K = N(26, 8) + for i in range(K + 1): + t = i / K + y = yF + (yR - yF) * t + z = zF + (zR - zF) * t - 0.030 * 4 * t * (1 - t) ** 1.3 + pts.append((0.0, y, z)) + sl = [dict(w=0.0030, h=0.0310, e=6.0)] * len(pts) + W.add(G.sweep('sling', pts, sl, n=N(10, 4), up=Vector((1, 0, 0))), 'leather', 'sling') + if hi: + # doubled strap from the front swivel back to the hook + d = [(0.0, yF + 0.002, zF + 0.0035)] + for i in range(1, 9): + t = i / 8 * 0.20 + y = yF + (yR - yF) * t + z = zF + (zR - zF) * t - 0.030 * 4 * t * (1 - t) ** 1.3 + 0.0034 + d.append((0.0, y, z)) + W.add(G.sweep('slingD', d, [dict(w=0.0028, h=0.0300, e=6.0)] * len(d), n=8, up=Vector((1, 0, 0))), 'leather', 'sling') + # keepers + for t in (0.045, 0.16): + y = yF + (yR - yF) * t + z = zF + (zR - zF) * t - 0.030 * 4 * t * (1 - t) ** 1.3 + 0.0017 + ang = math.degrees(math.atan2(zR - zF, yR - yF)) + k = G.loft_y('keeper', [dict(y=y - 0.006, zt=z + 0.0045, zb=z - 0.0045, w=0.0345, e=8), + dict(y=y + 0.006, zt=z + 0.0045, zb=z - 0.0045, w=0.0345, e=8)], n=16) + G.rot(k, ang * 0.9, 'X', (0, y, z)) + W.add(k, 'leather', 'sling') + hy = yF + (yR - yF) * 0.205 + hz = zF + (zR - zF) * 0.205 - 0.030 * 4 * 0.205 * (0.795) ** 1.3 + 0.0042 + hk = G.box('hook', (0, hy, hz), (0.020, 0.010, 0.0032), bev=0.0012) + W.add(hk, 'brass', 'sling') + # ---------------- empties + W.empties['muzzle'] = ((0, -0.7305, BORE), (0, -1, 0)) + W.empties['ejection'] = ((-0.012, -0.066, BORE + 0.010), (-1, 0, 0.6)) + W.empties['scopeEye'] = ((0, 0.118 + 0.080, SZ), (0, -1, 0)) + W.gripL = (0, -0.265, 0.0) + W.zones = dict(handR=((0, 0.050, -0.030), (0.030, 0.050, 0.045)), handL=((0, -0.265, 0.000), (0.030, 0.075, 0.040)), + cheek=((0.02, 0.200, 0.025), (0.025, 0.110, 0.020)), butt=((0, 0.352, -0.035), (0.04, 0.012, 0.09)), + slide=(0, 1, 0)) + W.uvscale = {'bolt': 1.5, 'trigger': 1.2, 'sling': 0.55} + W.gripRoff, W.gripLoff = (0.01, 0, 0), (0.016, 0, -0.016) + return W + + +# ===================================================================================================== +def smg(hi=True): + """.45 submachine gun of the 1942-pattern simplified type: square receiver, horizontal fore-end, plain + barrel, fixed peep sight with protective ears, side cocking knob, 30-round stick magazine. Overall 0.81 m.""" + W = Weapon('smg' if hi else 'smgLod', hi) + N = W.n + B = 0.025 + # upper receiver: square section, rounded corners; hollow with ejection port and cocking slot on the right + R = [dict(y=-0.172, zt=0.0445, zb=0.0005, w=0.0330, e=5.5), dict(y=-0.168, zt=0.0455, zb=0.0, w=0.0345, e=6), + dict(y=0.074, zt=0.0455, zb=0.0, w=0.0345, e=6), dict(y=0.079, zt=0.0440, zb=0.0010, w=0.0330, e=5.5)] + rcv = G.loft_y('receiver', R, n=N(40, 12)) + if hi: + G.boolean(rcv, G.box('inner', (0, -0.04, 0.0230), (0.0260, 0.230, 0.0330), bev=0.0)) + G.boolean(rcv, G.box('port', (-0.016, -0.090, 0.0265), (0.012, 0.050, 0.0190), bev=0.002)) + G.boolean(rcv, G.box('slot', (-0.016, -0.005, 0.0335), (0.012, 0.118, 0.0050), bev=0.0)) + G.boolean(rcv, G.box('topGroove', (0, -0.050, 0.0462), (0.0060, 0.200, 0.0030), bev=0.0)) + G.bevel(rcv, 0.0007, seg=2, angle=40) + W.add(rcv, 'park') + # trigger frame + F = [dict(y=-0.120, zt=0.0020, zb=-0.0240, w=0.0290, e=5), dict(y=-0.116, zt=0.0020, zb=-0.0270, w=0.0310, e=6), + dict(y=0.072, zt=0.0020, zb=-0.0270, w=0.0310, e=6), dict(y=0.077, zt=0.0020, zb=-0.0240, w=0.0290, e=5)] + fr = G.loft_y('frame', F, n=N(36, 10)) + if hi: + G.bevel(fr, 0.0007, seg=2, angle=40) + G.boolean(fr, G.box('magway', (0, -0.088, -0.012), (0.0240, 0.0420, 0.04), bev=0.0)) + W.add(fr, 'park') + gp = G.bezier([(0, 0.012, -0.026), (0, 0.006, -0.050), (0, -0.040, -0.052), (0, -0.056, -0.026)], N(12, 6)) + W.add(G.sweep('guard', gp, dict(w=0.0036, h=0.0105, e=3.0), n=N(10, 6), up=Vector((1, 0, 0))), 'park') + # stock mount plate, buttstock (walnut), butt plate + W.add(G.box('stockMount', (0, 0.082, 0.018), (0.032, 0.008, 0.044), bev=0.0018), 'park') + S = [dict(y=0.0855, zt=0.0400, zb=-0.0040, w=0.0300, e=3.0), dict(y=0.110, zt=0.0390, zb=-0.0150, w=0.0330, e=3.0), + dict(y=0.180, zt=0.0360, zb=-0.0410, w=0.0360, et=2.9, eb=2.7), dict(y=0.270, zt=0.0335, zb=-0.0700, w=0.0385, et=2.9, eb=2.7), + dict(y=0.3575, zt=0.0320, zb=-0.0935, w=0.0400, et=3.0, eb=2.8)] + if hi: + S = [S[0], S[1], dict(y=0.140, zt=0.0375, zb=-0.0270, w=0.0345, e=3.0), S[2], dict(y=0.225, zt=0.0348, zb=-0.0555, w=0.0372, et=2.9, eb=2.7), S[3], dict(y=0.330, zt=0.0326, zb=-0.0860, w=0.0396, et=3.0, eb=2.8), S[4]] + W.add(G.loft_y('stock', S, n=N(44, 12)), 'wood') + last = S[-1]; bp = [] + for dy, g in ((0.0, 0.0006), (0.0045, 0.0006), (0.0060, -0.0005)): + st = dict(last); st['y'] = last['y'] + dy; st['zt'] += g + 0.0005; st['zb'] -= g + 0.0005; st['w'] += 2 * g; bp.append(st) + W.add(G.loft_y('buttplate', bp, n=N(36, 12)), 'park') + if hi: + for z in (0.010, -0.060): + W.add(G.cyl('bpScrew', 0.0034, last['y'] + 0.0060, last['y'] + 0.0072, c=(0, 0, z), n=12), 'park') + W.add(G.cyl('stockBolt', 0.0042, -0.0170, -0.0195, axis='X', c=(0, 0.095, 0.020), n=12), 'park') + # pistol grip (walnut), swept back about 17 degrees + gpath = G.bezier([(0, 0.030, -0.018), (0, 0.040, -0.060), (0, 0.054, -0.100), (0, 0.060, -0.118)], N(10, 5)) + secs = [] + for i in range(len(gpath)): + t = i / (len(gpath) - 1) + secs.append(dict(w=0.044 - 0.004 * t, h=0.0300 + 0.0015 * math.sin(t * math.pi), e=2.5)) + grip = G.sweep('grip', gpath, secs, n=N(32, 10), up=Vector((1, 0, 0))) + W.add(grip, 'wood') + # barrel with collar and crown, front sight blade + bp_ = [(0.0057, -0.420), (0.0057, -0.4385), (0.0072, -0.4410), (0.0098, -0.4410), (0.0105, -0.4395), (0.0105, -0.188), + (0.0138, -0.186), (0.0138, -0.170)] + if not hi: + bp_ = [(0.0057, -0.43), (0.0057, -0.441), (0.0105, -0.441), (0.0105, -0.188), (0.0138, -0.186), (0.0138, -0.170)] + W.add(G.lathe('barrel', bp_, n=N(32, 10), axis='Y', center=(0, 0, B), cap0=True, cap1=True), 'park') + W.add(G.plate('fsight', [(-0.4300, B + 0.0090), (-0.4200, B + 0.0090), (-0.4235, B + 0.0185), (-0.4285, B + 0.0185)], + -0.0012, 0.0012, bev=0.0004), 'park') + W.add(G.plate('fsBase', [(-0.436, B + 0.0080), (-0.414, B + 0.0080), (-0.416, B + 0.0115), (-0.434, B + 0.0115)], + -0.0040, 0.0040, bev=0.0006), 'park') + # fore-end (walnut) under the barrel + FE = [dict(y=-0.3255, zt=0.0120, zb=-0.0060, w=0.0230, e=2.4), dict(y=-0.321, zt=0.0160, zb=-0.0140, w=0.0310, et=3.5, eb=2.4), + dict(y=-0.250, zt=0.0165, zb=-0.0165, w=0.0330, et=3.5, eb=2.4), dict(y=-0.190, zt=0.0170, zb=-0.0150, w=0.0335, et=3.5, eb=2.5), + dict(y=-0.176, zt=0.0160, zb=-0.0080, w=0.0310, et=3.5, eb=2.5)] + W.add(G.loft_y('foreend', FE, n=N(40, 10)), 'wood') + W.add(G.box('feBracket', (0, -0.173, 0.006), (0.030, 0.006, 0.018), bev=0.0012), 'park') + # rear sight: base, two protective ears, aperture blade + W.add(G.box('rsBase', (0, 0.050, 0.0475), (0.0160, 0.024, 0.0040), bev=0.0010), 'park') + for s in (-1, 1): + W.add(G.plate('rsEar', [(0.040, 0.049), (0.062, 0.049), (0.058, 0.0640), (0.050, 0.0660), (0.044, 0.0600)], + s * 0.0055, s * 0.0078, bev=0.0005), 'park') + ap = G.plate('rsBlade', [(-0.0050, 0.049), (0.0050, 0.049), (0.0050, 0.0620), (-0.0050, 0.0620)], 0.0525, 0.0545, bev=0.0004, axis='Y') + if hi: + G.boolean(ap, G.cyl('peep', 0.0011, -0.01, 0.01, axis='Y', c=(0, 0.053, 0.0585), n=10)) + W.add(ap, 'park') + # selector and safety levers, magazine catch (left side, +X) + if hi: + for y, z, a in ((0.030, -0.010, 25), (0.000, -0.012, -20)): + lv = G.plate('lever', [(y - 0.003, z - 0.003), (y + 0.003, z - 0.003), (y + 0.0035, z + 0.004), (y - 0.0025, z + 0.016), (y - 0.006, z + 0.014)], + 0.0155, 0.0180, bev=0.0006) + G.rot(lv, a, 'X', (0, y, z)); W.add(lv, 'park') + W.add(G.cyl('leverPin', 0.0032, 0.0155, 0.0185, axis='X', c=(0, y, z), n=10), 'park') + W.add(G.box('magCatch', (0.0165, -0.060, -0.016), (0.003, 0.010, 0.012), bev=0.0008), 'park') + # bolt (moving) visible through the port, cocked to the rear + W.add(G.box('boltB', (0, -0.012, 0.0235), (0.0245, 0.110, 0.0300), bev=0.0015), 'steel', 'bolt') + W.pivots['bolt'] = (0, -0.012, 0.0235) + # cocking knob (moving with the bolt), right side + W.add(G.cyl('cockStem', 0.0030, -0.0160, -0.0240, axis='X', c=(0, 0.040, 0.0335), n=10), 'steel', 'charging') + W.add(G.lathe('cockKnob', [(0.0, -0.0225), (0.0060, -0.0225), (0.0068, -0.0262), (0.0060, -0.0310), (0.0, -0.0318)], + n=N(16, 8), axis='X', center=(0, 0.040, 0.0335)), 'steel', 'charging') + W.pivots['charging'] = (-0.020, 0.040, 0.0335) + # trigger + tp = G.bezier([(0, -0.0130, -0.024), (0, -0.0140, -0.036), (0, -0.0110, -0.044), (0, -0.0065, -0.0475)], N(6, 3)) + W.add(G.sweep('trigger', tp, dict(w=0.0042, h=0.0062, e=3.0), n=8, up=Vector((1, 0, 0))), 'steel', 'trigger') + W.pivots['trigger'] = (0, -0.013, -0.022) + # 30-round stick magazine + my0, my1 = -0.108, -0.068 + mag = G.loft_y('magBody', [dict(y=my0, zt=0.0, zb=-0.236, w=0.0228, e=8), dict(y=my1, zt=0.0, zb=-0.236, w=0.0228, e=8)], n=N(24, 8)) + if hi: + for sx in (-1, 1): # stamped stiffening ribs on both sides + for yy in (-0.097, -0.079): + rb = G.loft_y('rib', [dict(y=yy - 0.003, zt=-0.030, zb=-0.215, w=0.0010, e=2, x=sx * 0.0114), dict(y=yy + 0.003, zt=-0.030, zb=-0.215, w=0.0010, e=2, x=sx * 0.0114)], n=8) + mag = G.join([mag, rb], 'magBody') + W.add(mag, 'park', 'mag') + W.add(G.box('magFloor', (0, -0.088, -0.2385), (0.0250, 0.0430, 0.0040), bev=0.0012), 'park', 'mag') + W.pivots['mag'] = (0, -0.088, -0.020) + # sling swivels (left side) and canvas sling + for y, z in ((-0.300, 0.000), (0.300, -0.030)): + W.add(G.box('swBase', (0.0195, y, z), (0.004, 0.010, 0.008), bev=0.0010), 'park') + W.add(G.sweep('swLoop', [(0.022, y, z + 0.0), (0.026, y - 0.016, z + 0.002), (0.026, y - 0.016, z - 0.004), (0.022, y, z - 0.002), + (0.026, y + 0.016, z - 0.004), (0.026, y + 0.016, z + 0.002)], dict(w=0.003, h=0.003), n=6, closed=True), 'park') + pts = [] + K = N(40, 9) + for i in range(K + 1): + t = i / K + y = -0.300 + 0.600 * t + z = -0.006 + (-0.034 + 0.006) * t - 0.125 * math.sin(math.pi * t) ** 1.2 + x = 0.0275 + 0.004 * math.sin(math.pi * t) + pts.append((x, y, z)) + W.add(G.sweep('sling', pts, dict(w=0.0030, h=0.0300, e=6.0), n=N(12, 6), up=Vector((0, 0, 1))), 'canvas', 'sling') + if hi: # brass adjusting buckle and the doubled strap end near the rear swivel + i0 = int(K * 0.72); p0 = Vector(pts[i0]); p1 = Vector(pts[i0 + 1]); d = (p1 - p0).normalized() + bk = G.loft_y('buckle', [dict(y=-0.009, zt=0.0030, zb=-0.0030, w=0.0360, e=10), dict(y=0.009, zt=0.0030, zb=-0.0030, w=0.0360, e=10)], n=16) + G.boolean(bk, G.box('bkHole', (0, 0, 0), (0.030, 0.012, 0.02), bev=0.0)) + G.rot(bk, 90, 'Y'); G.rot(bk, 90, 'Y'); G.rot(bk, 90, 'Z'); G.rot(bk, math.degrees(math.atan2(d.z, d.y)), 'X'); G.move(bk, p0) + W.add(bk, 'brass', 'sling') + dbl = [tuple(Vector(q) + Vector((0.0032, 0, 0))) for q in pts[i0:]] + W.add(G.sweep('slingD', dbl, dict(w=0.0028, h=0.0295, e=6.0), n=12, up=Vector((0, 0, 1))), 'canvas', 'sling') + W.empties['muzzle'] = ((0, -0.441, B), (0, -1, 0)) + W.empties['ejection'] = ((-0.019, -0.090, 0.030), (-1, 0, 0.5)) + W.gripL = (0, -0.245, 0.0) + W.zones = dict(handR=((0, 0.045, -0.065), (0.030, 0.035, 0.060)), handL=((0, -0.250, 0.0), (0.030, 0.070, 0.035)), + cheek=((0.02, 0.200, 0.030), (0.025, 0.11, 0.02)), butt=((0, 0.36, -0.03), (0.04, 0.012, 0.08)), slide=(0, 1, 0)) + W.uvscale = {'mag': 0.8, 'sling': 0.5, 'charging': 1.5} + W.gripRoff, W.gripLoff = (0.012, 0, 0.006), (0.012, 0, -0.024) + return W + +# ===================================================================================================== +def pistol(hi=True): + """.45 service pistol of the 1911 pattern: slide with rear grasping grooves, spur hammer, grip safety, + thumb safety, slide stop, checkered grips, arched mainspring housing, lanyard loop. Overall 0.216 m.""" + W = Weapon('pistol', hi) + B = 0.0185 + # slide (moving: 'bolt') + SL = [dict(y=-0.1720, zt=0.0285, zb=0.0050, w=0.0225, et=3.2, eb=10), dict(y=-0.1680, zt=0.0300, zb=0.0045, w=0.0235, et=3.2, eb=10), + dict(y=0.0330, zt=0.0300, zb=0.0045, w=0.0235, et=3.2, eb=10), dict(y=0.0365, zt=0.0290, zb=0.0050, w=0.0225, et=3.2, eb=10)] + slide = G.loft_y('slide', SL, n=40) + G.boolean(slide, G.box('port', (-0.0100, -0.020, 0.0255), (0.012, 0.0300, 0.0140), bev=0.0015)) + G.boolean(slide, G.cyl('muzHole', 0.0072, -0.18, -0.16, c=(0, 0, B), n=20)) + G.boolean(slide, G.cyl('plugHole', 0.0050, -0.18, -0.16, c=(0, 0, 0.0085), n=14)) + G.bevel(slide, 0.0005, seg=1, angle=40) + W.add(slide, 'park', 'bolt') + W.add(G.plate('fSight', [(-0.1640, 0.0295), (-0.1550, 0.0295), (-0.1575, 0.0350), (-0.1620, 0.0350)], -0.0012, 0.0012, bev=0.0003), 'park', 'bolt') + rs = G.box('rSight', (0, 0.0245, 0.0322), (0.0100, 0.0060, 0.0050), bev=0.0006) + G.boolean(rs, G.box('notch', (0, 0.0245, 0.0345), (0.0022, 0.010, 0.004), bev=0.0)) + W.add(rs, 'park', 'bolt') + W.add(G.lathe('bushing', [(0.0060, -0.1700), (0.0080, -0.1700), (0.0080, -0.1745), (0.0060, -0.1745)], n=20, axis='Y', center=(0, 0, B), cap0=False, cap1=False, closed=True), 'park', 'bolt') + W.pivots['bolt'] = (0, 0, B) + # barrel (static) and recoil spring plug + W.add(G.lathe('barrel', [(0.0057, -0.150), (0.0057, -0.1735), (0.0063, -0.1745), (0.0060, -0.1745), (0.0060, -0.150)], + n=20, axis='Y', center=(0, 0, B), cap0=True, cap1=False, closed=True), 'steel') + W.add(G.lathe('barrelHood', [(0.0062, -0.045), (0.0062, -0.0), (0.0, -0.0)], n=16, axis='Y', center=(0, 0, B)), 'steel') + W.add(G.cyl('plug', 0.0044, -0.150, -0.1730, c=(0, 0, 0.0085), n=14), 'park') + # frame: dust cover/rails, grip frame (arched mainspring housing), trigger guard + W.add(G.loft_y('rail', [dict(y=-0.1230, zt=0.0060, zb=-0.0040, w=0.0190, e=2.6), dict(y=-0.1180, zt=0.0060, zb=-0.0080, w=0.0215, e=5), + dict(y=-0.0550, zt=0.0060, zb=-0.0120, w=0.0215, e=8), dict(y=0.0340, zt=0.0060, zb=-0.0120, w=0.0215, e=8)], n=20), 'park') + gf = [(0.0000, -0.0110), (0.0050, -0.0400), (0.0300, -0.1125), (0.0800, -0.1125), (0.0812, -0.1080), (0.0790, -0.0880), + (0.0740, -0.0600), (0.0640, -0.0300), (0.0560, -0.0110), (0.0480, 0.0010), (0.0340, 0.0060), (0.0020, 0.0060)] + W.add(G.plate('gripFrame', gf, -0.0108, 0.0108, bev=0.0016, seg=3), 'park') + gpath = G.bezier([(0, -0.0010, -0.0115), (0, -0.0110, -0.0330), (0, -0.0480, -0.0320), (0, -0.0560, -0.0110)], 10) + W.add(G.sweep('guard', gpath, dict(w=0.0032, h=0.0098, e=3.0), n=12, up=Vector((1, 0, 0))), 'park') + # grip panels (both sides), screws + pan = [(0.0060, -0.0170), (0.0090, -0.0300), (0.0300, -0.1060), (0.0730, -0.1060), (0.0700, -0.0700), (0.0590, -0.0300), (0.0520, -0.0170)] + for s in (-1, 1): + p = G.plate('panel', pan, s * 0.0100, s * 0.0150, bev=0.0018, seg=4) + W.add(p, 'checkplastic') + for y, z in ((0.0140, -0.0260), (0.0430, -0.0960)): + W.add(G.lathe('screw', [(0.0, 0.0), (0.0030, 0.0), (0.0030, 0.0008), (0.0022, 0.0016), (0.0, 0.0017)], n=10, axis='X', + center=(s * 0.0148, y, z), sx=1, sz=1) if s > 0 else + G.lathe('screw', [(0.0, 0.0), (0.0030, 0.0), (0.0030, -0.0008), (0.0022, -0.0016), (0.0, -0.0017)], n=10, axis='X', center=(-0.0148, y, z)), 'park') + # hammer (moving), grip safety tang, thumb safety, slide stop, magazine catch, lanyard loop + hm = G.plate('hammer', [(0.0330, 0.0000), (0.0420, 0.0000), (0.0470, 0.0150), (0.0520, 0.0230), (0.0500, 0.0260), (0.0430, 0.0215), + (0.0360, 0.0120)], -0.0032, 0.0032, bev=0.0006) + W.add(hm, 'steel', 'hammer'); W.pivots['hammer'] = (0, 0.0370, 0.0020) + W.add(G.plate('gsafety', [(0.0480, 0.0010), (0.0700, -0.0010), (0.0720, -0.0050), (0.0640, -0.0110), (0.0560, -0.0300), (0.0500, -0.0300)], + -0.0085, 0.0085, bev=0.0016, seg=2), 'park') + W.add(G.plate('tsafety', [(0.0300, -0.0040), (0.0400, -0.0040), (0.0400, 0.0040), (0.0200, 0.0060), (0.0140, 0.0040), (0.0300, 0.0010)], + 0.0108, 0.0128, bev=0.0005), 'park') + W.add(G.plate('sstop', [(-0.0480, -0.0060), (-0.0260, -0.0060), (-0.0230, 0.0000), (-0.0300, 0.0030), (-0.0480, -0.0010)], + 0.0108, 0.0124, bev=0.0005), 'park') + W.add(G.cyl('sstopPin', 0.0024, -0.0110, -0.0118, axis='X', c=(0, -0.0430, -0.0030), n=10), 'park') + W.add(G.cyl('magCatch', 0.0038, 0.0108, 0.0128, axis='X', c=(0, 0.0045, -0.0175), n=12), 'park') + W.add(G.torus('lanyard', 0.0035, 0.0010, c=(0, 0.0805, -0.1160), axis='X', n=10, m=5), 'park') + # trigger (slides straight back) + W.add(G.plate('trigger', [(-0.0215, -0.0110), (-0.0165, -0.0110), (-0.0160, -0.0240), (-0.0190, -0.0262), (-0.0225, -0.0250)], + -0.0045, 0.0045, bev=0.0006), 'steel', 'trigger') + W.pivots['trigger'] = (0, -0.019, -0.012) + # magazine (moving), mostly hidden in the grip: floor plate shows at the bottom + mg = G.plate('magBody', [(0.0070, -0.0100), (0.0400, -0.0100), (0.0700, -0.1120), (0.0360, -0.1120)], -0.0090, 0.0090, bev=0.0008) + W.add(mg, 'park', 'mag') + W.add(G.plate('magFloor', [(0.0330, -0.1125), (0.0750, -0.1125), (0.0760, -0.1170), (0.0320, -0.1170)], -0.0100, 0.0100, bev=0.0012), 'steel', 'mag') + W.pivots['mag'] = (0, 0.040, -0.060) + W.empties['muzzle'] = ((0, -0.1745, B), (0, -1, 0)) + W.empties['ejection'] = ((-0.012, -0.020, 0.028), (-1, 0, 0.6)) + W.zones = dict(handR=((0, 0.045, -0.060), (0.03, 0.045, 0.060)), handL=((0, 0.030, -0.070), (0.03, 0.04, 0.05)), + cheek=((0, 0, 0), (0.001, 0.001, 0.001)), butt=((0, 0, 0), (0.001, 0.001, 0.001)), slide=(0, 1, 0)) + W.uvscale = {} + W.gripRoff, W.gripLoff = (0.006, 0, -0.006), (0.012, 0, 0.0) + return W + +# ===================================================================================================== +def enemy_rifle(hi=True): + """Short bolt-action rifle of the 1935-pattern carbine type: straight stock with sling slot and disc, turned-down + bolt, tangent rear sight, hooded front sight, nose cap with bayonet lug and cleaning rod. Overall 1.11 m.""" + W = Weapon('enemyRifle', hi) + S = [dict(y=-0.468, zt=0.0110, zb=-0.0130, w=0.0300, et=3.0, eb=2.4), dict(y=-0.400, zt=0.0120, zb=-0.0170, w=0.0320, et=3.2, eb=2.4), + dict(y=-0.220, zt=0.0130, zb=-0.0220, w=0.0350, et=3.2, eb=2.4), dict(y=-0.185, zt=0.0185, zb=-0.0270, w=0.0400, et=3.2, eb=2.6), + dict(y=-0.130, zt=0.0200, zb=-0.0380, w=0.0410, et=3.2, eb=2.8), dict(y=-0.050, zt=0.0200, zb=-0.0390, w=0.0410, et=3.2, eb=2.8), + dict(y=0.005, zt=0.0110, zb=-0.0360, w=0.0350, et=2.8, eb=2.4), dict(y=0.035, zt=0.0045, zb=-0.0480, w=0.0315, et=2.6, eb=2.3), + dict(y=0.065, zt=0.0050, zb=-0.0640, w=0.0330, et=2.6, eb=2.3), dict(y=0.085, zt=0.0120, zb=-0.0700, w=0.0360, et=2.6, eb=2.5), + dict(y=0.120, zt=0.0200, zb=-0.0760, w=0.0380, et=2.7, eb=2.6), dict(y=0.250, zt=0.0250, zb=-0.0960, w=0.0410, et=2.8, eb=2.6), + dict(y=0.3605, zt=0.0280, zb=-0.1120, w=0.0425, et=3.0, eb=2.7)] + stock = G.loft_y('stock', S, n=16) + G.boolean(stock, G.box('slingSlot', (0, 0.230, -0.074), (0.06, 0.030, 0.0085), bev=0.003)) + W.add(stock, 'wood2') + W.add(G.cyl('disc', 0.0120, -0.0205, -0.0225, axis='X', c=(0, 0.250, -0.040), n=14), 'blued') + last = S[-1]; bp = [] + for dy, g in ((0.0, 0.0008), (0.005, 0.0008), (0.0068, -0.0004)): + st = dict(last); st['y'] = last['y'] + dy; st['zt'] += g + 0.0005; st['zb'] -= g + 0.0005; st['w'] += 2 * g; bp.append(st) + W.add(G.loft_y('buttplate', bp, n=16), 'blued') + W.add(G.loft_y('handguard', [dict(y=-0.415, zt=0.0310, zb=0.0110, w=0.0260, et=2.1, eb=6), dict(y=-0.405, zt=0.0330, zb=0.0110, w=0.0290, et=2.1, eb=6), + dict(y=-0.278, zt=0.0335, zb=0.0110, w=0.0295, et=2.1, eb=6), dict(y=-0.270, zt=0.0310, zb=0.0110, w=0.0270, et=2.1, eb=6)], n=12), 'wood2') + W.add(G.lathe('barrel', [(0.0040, -0.725), (0.0040, -0.745), (0.0080, -0.745), (0.0082, -0.700), (0.0092, -0.480), (0.0105, -0.300), + (0.0125, -0.265), (0.0150, -0.255), (0.0150, -0.195), (0.0135, -0.190), (0.0135, -0.170)], + n=14, axis='Y', center=(0, 0, BORE), cap0=True, cap1=True), 'blued') + rcv = G.lathe('receiver', [(0.0165, 0.028), (0.0165, -0.130), (0.0175, -0.133), (0.0175, -0.178), (0.0165, -0.181)], n=16, axis='Y', + center=(0, 0, BORE), cap0=True, cap1=True) + G.boolean(rcv, G.cyl('boltway', 0.0100, 0.04, -0.17, c=(0, 0, BORE), n=14)) + G.boolean(rcv, G.box('cutTop', (-0.010, -0.067, BORE + 0.022), (0.034, 0.110, 0.03), bev=0.0)) + W.add(rcv, 'blued') + W.add(G.plate('tang', [(0.020, 0.0020), (0.090, 0.0020), (0.094, 0.0050), (0.020, 0.0090)], -0.0055, 0.0055, bev=0.0008), 'blued') + bolt = [G.lathe('boltBody', [(0.0085, -0.118), (0.0087, -0.114), (0.0087, 0.040), (0.0108, 0.042), (0.0110, 0.074), (0.0078, 0.080), + (0.0078, 0.094), (0.0060, 0.097)], n=12, axis='Y', center=(0, 0, BORE), cap0=True, cap1=True), + G.plate('wingSafety', [(0.060, 0.0), (0.070, 0.0), (0.070, 0.012), (0.064, 0.014), (0.060, 0.006)], -0.0012, 0.0012, bev=0.0004)] + G.move(bolt[1], (0, 0, BORE + 0.009)) + arm = G.bezier([(-0.0075, 0.003, BORE), (-0.028, 0.003, BORE), (-0.036, 0.006, BORE - 0.016), (-0.038, 0.010, BORE - 0.030)], 4) + bolt.append(G.sweep('boltArm', arm, dict(w=0.0082, h=0.0068, e=2.4), n=6)) + bolt.append(G.sphere('boltKnob', 0.0098, c=(-0.0385, 0.011, BORE - 0.036), n=10, m=7)) + for o in bolt: + W.add(o, 'steel', 'bolt') + W.pivots['bolt'] = (0, 0, BORE) + W.add(G.plate('floorplate', [(-0.124, -0.0365), (-0.030, -0.0365), (-0.030, -0.0425), (-0.118, -0.0425), (-0.124, -0.040)], + -0.0115, 0.0115, bev=0.0012), 'blued') + gp = G.bezier([(0, -0.031, -0.038), (0, -0.026, -0.060), (0, 0.012, -0.062), (0, 0.023, -0.038)], 7) + W.add(G.sweep('guardbow', gp, dict(w=0.0034, h=0.0095, e=3.0), n=6, up=Vector((1, 0, 0))), 'blued') + tp = G.bezier([(0, -0.0045, -0.030), (0, -0.0060, -0.044), (0, -0.0030, -0.052), (0, 0.0015, -0.0555)], 3) + W.add(G.sweep('trigger', tp, dict(w=0.0040, h=0.0058, e=3.0), n=6, up=Vector((1, 0, 0))), 'steel', 'trigger') + W.pivots['trigger'] = (0, -0.0045, -0.031) + # tangent rear sight: base on the barrel, leaf hinged at its front + W.add(G.box('rsBase', (0, -0.228, BORE + 0.0135), (0.0200, 0.048, 0.0080), bev=0.0015), 'blued') + W.add(G.plate('rsLeaf', [(-0.252, 0.0), (-0.200, 0.0), (-0.200, 0.0035), (-0.252, 0.0030)], -0.0085, 0.0085, bev=0.0006), 'blued', 'sightRear') + G.move(W.parts['sightRear'][-1][0], (0, 0, BORE + 0.0175)) + W.pivots['sightRear'] = (0, -0.250, BORE + 0.0175) + # bands, nose cap with bayonet lug, cleaning rod, front sight with hood + def band(y0, y1, zt, zb, w, name, n=16): + st = [dict(y=y0, zt=zt - 0.0008, zb=zb + 0.0008, w=w - 0.0016, e=3.0), dict(y=y0 + 0.0012, zt=zt, zb=zb, w=w, e=3.0), + dict(y=y1 - 0.0012, zt=zt, zb=zb, w=w, e=3.0), dict(y=y1, zt=zt - 0.0008, zb=zb + 0.0008, w=w - 0.0016, e=3.0)] + return G.loft_y(name, st, n=n) + W.add(band(-0.423, -0.410, 0.0350, -0.0190, 0.0340, 'lowerBand'), 'blued') + W.add(G.box('slingBar', (0.0195, -0.416, -0.006), (0.004, 0.026, 0.006), bev=0.0012), 'blued') + W.add(band(-0.505, -0.468, 0.0300, -0.0140, 0.0310, 'nosecap'), 'blued') + W.add(G.box('bayLug', (0, -0.495, -0.0145), (0.0070, 0.040, 0.0070), bev=0.0012), 'blued') + W.add(G.cyl('cleaningRod', 0.0030, -0.505, -0.523, c=(0, 0, -0.0055), n=8), 'steel') + W.add(G.lathe('rodHead', [(0.0, -0.5230), (0.0042, -0.5225), (0.0042, -0.5300), (0.0, -0.5305)], n=8, axis='Y', center=(0, 0, -0.0055)), 'steel') + W.add(G.lathe('fsRing', [(0.0082, -0.705), (0.0105, -0.705), (0.0105, -0.728), (0.0082, -0.728)], n=14, axis='Y', center=(0, 0, BORE), closed=True), 'blued') + W.add(G.plate('fsPost', [(-0.7230, BORE + 0.0090), (-0.7140, BORE + 0.0090), (-0.7175, BORE + 0.0200), (-0.7205, BORE + 0.0200)], -0.0010, 0.0010, bev=0.0003), 'blued') + hood = G.sweep('fsHood', [(0.0115, -0.7165, BORE + 0.006), (0.0118, -0.7165, BORE + 0.020), (0.0, -0.7165, BORE + 0.0285), (-0.0118, -0.7165, BORE + 0.020), (-0.0115, -0.7165, BORE + 0.006)], + dict(w=0.0015, h=0.020, e=8), n=6, up=Vector((0, 1, 0))) + W.add(hood, 'blued') + # leather sling: slot in the butt to the bar on the lower band (left side) + pts = [] + for i in range(13): + t = i / 12 + y = -0.416 + (0.230 + 0.416) * t + z = -0.010 + (-0.074 + 0.010) * t - 0.055 * math.sin(math.pi * t) + pts.append((0.0235 - 0.005 * t, y, z)) + W.add(G.sweep('sling', pts, dict(w=0.0030, h=0.0240, e=6), n=6, up=Vector((0, 0, 1))), 'leather', 'sling') + W.empties['muzzle'] = ((0, -0.745, BORE), (0, -1, 0)) + W.empties['ejection'] = ((-0.012, -0.066, BORE + 0.010), (-1, 0, 0.6)) + W.gripL = (0, -0.290, 0.0) + W.zones = dict(handR=((0, 0.050, -0.030), (0.030, 0.050, 0.045)), handL=((0, -0.290, 0.000), (0.030, 0.075, 0.040)), + cheek=((0.02, 0.200, 0.022), (0.025, 0.110, 0.020)), butt=((0, 0.36, -0.04), (0.04, 0.012, 0.09)), slide=(0, 1, 0)) + W.uvscale = {'sling': 0.5} + W.gripRoff, W.gripLoff = (0.012, 0, 0), (0.016, 0, -0.018) + return W + +# ===================================================================================================== +def enemy_smg(hi=True): + """9 mm submachine gun of the 1940-pattern type: round receiver tube, moulded grip frame, ribbed magazine housing, + underfolding steel stock (extended), barrel rest under the muzzle end, hooded front sight, flip rear sight. 0.83 m.""" + W = Weapon('enemySmg', hi) + B = 0.028 + W.add(G.lathe('tube', [(0.0, 0.036), (0.0160, 0.036), (0.0185, 0.032), (0.0185, -0.168), (0.0200, -0.170), (0.0200, -0.186), (0.0130, -0.190)], + n=18, axis='Y', center=(0, 0, B), cap1=True), 'blued') + W.add(G.lathe('barrel', [(0.0045, -0.395), (0.0045, -0.4100), (0.0085, -0.4100), (0.0090, -0.360), (0.0095, -0.190)], n=14, axis='Y', + center=(0, 0, B), cap0=True, cap1=True), 'blued') + # barrel rest under the barrel + W.add(G.plate('rest', [(-0.236, B - 0.006), (-0.206, B - 0.006), (-0.206, B - 0.0095), (-0.214, B - 0.026), (-0.236, B - 0.026)], + -0.0050, 0.0050, bev=0.0012), 'bakelite') + # front sight with hood + W.add(G.lathe('fsRing', [(0.0088, -0.388), (0.0110, -0.388), (0.0110, -0.404), (0.0088, -0.404)], n=12, axis='Y', center=(0, 0, B), closed=True), 'blued') + W.add(G.plate('fsPost', [(-0.400, B + 0.009), (-0.392, B + 0.009), (-0.3945, B + 0.019), (-0.3975, B + 0.019)], -0.0010, 0.0010, bev=0.0003), 'blued') + W.add(G.sweep('fsHood', [(0.0110, -0.396, B + 0.006), (0.0115, -0.396, B + 0.019), (0.0, -0.396, B + 0.0265), (-0.0115, -0.396, B + 0.019), (-0.0110, -0.396, B + 0.006)], + dict(w=0.0015, h=0.016, e=8), n=6, up=Vector((0, 1, 0))), 'blued') + # grip frame (moulded) with pistol grip, trigger guard + W.add(G.plate('frame', [(-0.075, 0.0120), (0.060, 0.0120), (0.060, -0.0040), (0.040, -0.0140), (-0.075, -0.0080)], -0.0145, 0.0145, bev=0.0025, seg=2), 'bakelite') + gpath = G.bezier([(0, 0.032, -0.006), (0, 0.040, -0.050), (0, 0.050, -0.090), (0, 0.054, -0.108)], 7) + W.add(G.sweep('grip', gpath, [dict(w=0.040, h=0.029, e=2.6)] * len(gpath), n=12, up=Vector((1, 0, 0))), 'bakelite') + gp = G.bezier([(0, 0.016, -0.010), (0, 0.010, -0.034), (0, -0.034, -0.036), (0, -0.046, -0.010)], 7) + W.add(G.sweep('guard', gp, dict(w=0.0034, h=0.0090, e=3.0), n=6, up=Vector((1, 0, 0))), 'blued') + tp = G.bezier([(0, -0.012, -0.010), (0, -0.013, -0.022), (0, -0.010, -0.029), (0, -0.006, -0.032)], 3) + W.add(G.sweep('trigger', tp, dict(w=0.0040, h=0.0058, e=3.0), n=6, up=Vector((1, 0, 0))), 'steel', 'trigger') + W.pivots['trigger'] = (0, -0.012, -0.008) + # magazine housing and magazine + W.add(G.loft_y('magwell', [dict(y=-0.135, zt=0.016, zb=-0.060, w=0.0270, e=7), dict(y=-0.090, zt=0.016, zb=-0.060, w=0.0270, e=7)], n=12), 'blued') + W.add(G.box('magwellLip', (0, -0.1125, -0.0605), (0.0300, 0.0480, 0.0050), bev=0.0012), 'blued') + W.add(G.box('magRelease', (0.0160, -0.1125, -0.040), (0.0050, 0.010, 0.010), bev=0.0012), 'blued') + W.add(G.loft_y('mag', [dict(y=-0.130, zt=-0.040, zb=-0.255, w=0.0225, e=8), dict(y=-0.095, zt=-0.040, zb=-0.255, w=0.0225, e=8)], n=12), 'blued', 'mag') + W.add(G.box('magFloor', (0, -0.1125, -0.2570), (0.0245, 0.0380, 0.0040), bev=0.0012), 'blued', 'mag') + W.pivots['mag'] = (0, -0.1125, -0.050) + # flip rear sight + W.add(G.box('rsBase', (0, -0.020, B + 0.0195), (0.0130, 0.020, 0.0040), bev=0.0010), 'blued') + W.add(G.plate('rsLeaf', [(-0.014, 0.0), (-0.010, 0.0), (-0.011, 0.0110), (-0.014, 0.0110)], -0.0055, 0.0055, bev=0.0004), 'blued', 'sightRear') + G.move(W.parts['sightRear'][-1][0], (0, 0, B + 0.0215)) + W.pivots['sightRear'] = (0, -0.012, B + 0.0215) + # cocking handle on the left, in its slot, cocked to the rear + W.add(G.box('slotRail', (0.0175, -0.065, B + 0.004), (0.0030, 0.150, 0.0060), bev=0.0006), 'park') + W.add(G.cyl('cockStem', 0.0030, 0.0175, 0.0290, axis='X', c=(0, 0.010, B + 0.004), n=8), 'steel', 'charging') + W.add(G.sphere('cockKnob', 0.0062, c=(0.0310, 0.010, B + 0.004), n=10, m=6, sx=1.2), 'steel', 'charging') + W.pivots['charging'] = (0.020, 0.010, B + 0.004) + # underfolding stock, extended: two flat struts and a curved butt plate + for s in (-1, 1): + W.add(G.sweep('strut', [(s * 0.0135, 0.055, 0.004), (s * 0.0140, 0.200, -0.006), (s * 0.0130, 0.352, -0.016)], + dict(w=0.0040, h=0.0110, e=5), n=6, up=Vector((1, 0, 0))), 'blued') + W.add(G.box('stockHinge', (0, 0.058, 0.004), (0.031, 0.012, 0.014), bev=0.002), 'blued') + bpath = G.bezier([(0, 0.356, -0.068), (0, 0.364, -0.030), (0, 0.360, 0.012)], 6) + W.add(G.sweep('buttPad', bpath, dict(w=0.0045, h=0.034, e=6), n=8, up=Vector((1, 0, 0))), 'blued') + W.add(G.box('stockCross', (0, 0.352, -0.016), (0.028, 0.008, 0.012), bev=0.0015), 'blued') + W.empties['muzzle'] = ((0, -0.410, B), (0, -1, 0)) + W.empties['ejection'] = ((-0.019, -0.100, B + 0.006), (-1, 0, 0.4)) + W.gripL = (0, -0.130, -0.040) + W.zones = dict(handR=((0, 0.045, -0.055), (0.030, 0.035, 0.055)), handL=((0, -0.112, -0.040), (0.030, 0.040, 0.040)), + cheek=((0, 0.2, 0.0), (0.001, 0.001, 0.001)), butt=((0, 0.36, -0.03), (0.04, 0.012, 0.05)), slide=(0, 1, 0)) + W.uvscale = {} + W.gripRoff, W.gripLoff = (0.012, 0, -0.006), (-0.012, 0, -0.024) + return W + +# ===================================================================================================== +def mg(hi=True): + """General-purpose belt-fed machine gun of the 1942 type: slotted rectangular barrel jacket with barrel-change port, + muzzle booster, feed cover and tray, moulded stock and grip, folding bipod (folded back along the jacket). 1.22 m.""" + W = Weapon('mg', hi) + B = 0.030 + W.add(G.loft_y('receiver', [dict(y=-0.165, zt=0.058, zb=-0.004, w=0.0480, e=7), dict(y=0.160, zt=0.058, zb=-0.004, w=0.0480, e=7), + dict(y=0.168, zt=0.054, zb=0.000, w=0.0440, e=6)], n=16), 'blued') + # feed cover (hinged at the rear) and feed tray with belt guide on the left + W.add(G.loft_y('cover', [dict(y=-0.150, zt=0.068, zb=0.056, w=0.0440, et=2.6, eb=8), dict(y=-0.140, zt=0.074, zb=0.056, w=0.0460, et=2.6, eb=8), + dict(y=0.035, zt=0.074, zb=0.056, w=0.0460, et=2.6, eb=8), dict(y=0.045, zt=0.066, zb=0.056, w=0.0440, et=2.6, eb=8)], n=14), 'blued', 'cover') + W.pivots['cover'] = (0, 0.040, 0.060) + W.add(G.box('feedTray', (0.034, -0.080, 0.040), (0.026, 0.060, 0.008), bev=0.0015), 'blued') + W.add(G.box('feedTrayR', (-0.030, -0.080, 0.040), (0.014, 0.050, 0.008), bev=0.0015), 'blued') + # rear buffer, stock (moulded) and grip + W.add(G.cyl('buffer', 0.0180, 0.160, 0.190, c=(0, 0, 0.030), n=14), 'blued') + S = [dict(y=0.188, zt=0.0520, zb=0.0050, w=0.0380, e=4), dict(y=0.260, zt=0.0520, zb=-0.0300, w=0.0400, e=4), + dict(y=0.400, zt=0.0500, zb=-0.0700, w=0.0420, e=4), dict(y=0.470, zt=0.0500, zb=-0.0850, w=0.0440, e=4), + dict(y=0.478, zt=0.0480, zb=-0.0830, w=0.0420, e=4)] + W.add(G.loft_y('stock', S, n=14), 'bakelite') + W.add(G.box('triggerHousing', (0, 0.020, -0.012), (0.034, 0.090, 0.018), bev=0.002), 'blued') + gpath = G.bezier([(0, 0.030, -0.018), (0, 0.038, -0.060), (0, 0.048, -0.100), (0, 0.052, -0.118)], 6) + W.add(G.sweep('grip', gpath, dict(w=0.042, h=0.030, e=2.6), n=12, up=Vector((1, 0, 0))), 'bakelite') + gp = G.bezier([(0, 0.016, -0.020), (0, 0.010, -0.044), (0, -0.032, -0.046), (0, -0.044, -0.020)], 6) + W.add(G.sweep('guard', gp, dict(w=0.0036, h=0.010, e=3.0), n=6, up=Vector((1, 0, 0))), 'blued') + tp = G.bezier([(0, -0.010, -0.020), (0, -0.012, -0.032), (0, -0.009, -0.040), (0, -0.005, -0.043)], 3) + W.add(G.sweep('trigger', tp, dict(w=0.0040, h=0.0060, e=3.0), n=6, up=Vector((1, 0, 0))), 'steel', 'trigger') + W.pivots['trigger'] = (0, -0.010, -0.018) + # barrel jacket: hollow, oval cooling slots on top and left, long barrel-change port on the right + J = [dict(y=-0.610, zt=B + 0.024, zb=B - 0.024, w=0.0440, e=5), dict(y=-0.170, zt=B + 0.026, zb=B - 0.026, w=0.0480, e=5)] + jac = G.loft_y('jacket', J, n=16, cap0=True, cap1=True) + G.boolean(jac, G.loft_y('jin', [dict(y=-0.62, zt=B + 0.0215, zb=B - 0.0215, w=0.0395, e=5), dict(y=-0.18, zt=B + 0.0235, zb=B - 0.0235, w=0.0435, e=5)], n=12)) + cut = [] + for i in range(6): + y = -0.225 - i * 0.060 + cut.append(G.sweep('slotT', [(0, y + 0.018, B + 0.03), (0, y - 0.018, B + 0.03)], dict(w=0.020, h=0.03, e=2.0), n=8, up=Vector((0, 0, 1)))) + for z in (B - 0.010, B + 0.010): + cut.append(G.sweep('slotL', [(0.03, y + 0.017, z), (0.03, y - 0.017, z)], dict(w=0.010, h=0.03, e=2.0), n=8, up=Vector((1, 0, 0)))) + cut.append(G.box('port', (-0.03, -0.285, B), (0.03, 0.180, 0.030), bev=0.004)) + cu = G.join(cut, 'cutters') + G.boolean(jac, cu) + W.add(jac, 'blued') + W.add(G.cyl('barrel', 0.0105, -0.172, -0.612, c=(0, 0, B), n=12), 'blued') + W.add(G.lathe('booster', [(0.0045, -0.680), (0.0045, -0.6935), (0.0150, -0.6935), (0.0175, -0.688), (0.0220, -0.640), (0.0225, -0.612), + (0.0245, -0.606)], n=16, axis='Y', center=(0, 0, B), cap0=True, cap1=True), 'blued') + W.add(G.plate('fsight', [(-0.598, B + 0.024), (-0.590, B + 0.024), (-0.592, B + 0.050), (-0.596, B + 0.050)], -0.0012, 0.0012, bev=0.0004), 'blued') + W.add(G.box('rsight', (0, -0.180, B + 0.030), (0.016, 0.040, 0.008), bev=0.0015), 'blued') + W.add(G.plate('rsLeaf', [(-0.196, B + 0.034), (-0.168, B + 0.034), (-0.168, B + 0.037), (-0.196, B + 0.036)], -0.006, 0.006, bev=0.0005), 'blued', 'sightRear') + W.pivots['sightRear'] = (0, -0.196, B + 0.035) + # charging handle on the right + W.add(G.box('chHandle', (-0.030, -0.030, 0.022), (0.014, 0.012, 0.010), bev=0.002), 'steel', 'charging') + W.pivots['charging'] = (-0.025, -0.030, 0.022) + # bipod: clamp on the jacket front, legs folded back under the jacket (rotate about X to deploy) + bip = [G.lathe('clamp', [(0.0270, -0.548), (0.0300, -0.548), (0.0300, -0.566), (0.0270, -0.566)], n=14, axis='Y', center=(0, 0, B), sz=1.0, closed=True)] + for s in (-1, 1): + bip.append(G.sweep('leg', [(s * 0.014, -0.556, B - 0.032), (s * 0.016, -0.400, B - 0.036), (s * 0.017, -0.250, B - 0.038)], + dict(w=0.0110, h=0.0110, e=2.0), n=8)) + bip.append(G.box('foot', (s * 0.017, -0.238, B - 0.040), (0.010, 0.026, 0.008), bev=0.002)) + for o in bip: + W.add(o, 'blued', 'bipod') + W.pivots['bipod'] = (0, -0.556, B - 0.030) + # ammunition belt: rounds side by side in steel links, entering the feed tray from the left and drooping + path = G.bezier([(0.030, -0.080, 0.046), (0.075, -0.080, 0.046), (0.095, -0.080, -0.030), (0.085, -0.080, -0.120)], 40) + L_ = [0.0] + for i in range(1, len(path)): L_.append(L_[-1] + (Vector(path[i]) - Vector(path[i - 1])).length) + pitch, i0 = 0.0127, 0 + for k in range(11): + d0 = 0.012 + k * pitch + j = next((q for q in range(1, len(L_)) if L_[q] >= d0), len(L_) - 1) + p = Vector(path[j]); t = (Vector(path[j]) - Vector(path[j - 1])).normalized() + ang = math.degrees(math.atan2(-t.z, t.x)) + rnd = G.lathe('round', [(0.0, 0.040), (0.0016, 0.0375), (0.0039, 0.022), (0.0040, 0.012), (0.0058, 0.010), (0.0058, -0.020), + (0.0055, -0.034), (0.0058, -0.040), (0.0, -0.040)], n=8, axis='Y', center=(0, 0, 0), closed=False, cap1=False) + G.move(rnd, (0, 0.010, 0)); G.rot(rnd, ang, 'Y'); G.move(rnd, p) + W.add(rnd, 'brass', 'belt') + lk = G.lathe('link', [(0.0064, 0.008), (0.0064, -0.008)], n=8, axis='Y', center=(0, 0, 0), cap0=False, cap1=False) + G.rot(lk, ang, 'Y'); G.move(lk, (p.x, p.y + 0.004, p.z)) + W.add(lk, 'blued', 'belt') + W.empties['muzzle'] = ((0, -0.6935, B), (0, -1, 0)) + W.empties['ejection'] = ((0, -0.060, -0.006), (0, 0, -1)) + W.gripL = (0, 0.090, 0.0) + W.zones = dict(handR=((0, 0.040, -0.065), (0.030, 0.035, 0.060)), handL=((0, 0.300, 0.050), (0.030, 0.090, 0.020)), + cheek=((0.02, 0.3, 0.04), (0.02, 0.1, 0.02)), butt=((0, 0.478, -0.02), (0.05, 0.012, 0.08)), slide=(0, 1, 0)) + W.uvscale = {'belt': 1.0} + W.gripRoff, W.gripLoff = (0.012, 0, 0.006), (-0.012, 0, -0.024) + return W + +# ===================================================================================================== +def knife(hi=True): + """Fighting knife of the 1943 trench-knife type: spear-point blade with false edge, steel guard with a bent tab, + stacked-leather grip, steel pommel. Blade along -Y, guard at y=0.""" + W = Weapon('knife', hi) + # blade: custom lofted section (spine flats, grind to a thin edge) + st = [] + for i in range(13): + t = i / 12.0 + y = -0.170 * t + top = 0.0050 if t < 0.62 else 0.0050 - (t - 0.62) / 0.38 * 0.0090 + bot = -0.0150 + 0.0020 * t if t < 0.70 else -0.0136 + (t - 0.70) / 0.30 * 0.0096 + if t == 1.0: + top = bot = -0.0040 + th = 0.0026 * (1 - 0.55 * t) + st.append((y, top, bot, th)) + V, F = [], [] + for y, top, bot, th in st: + gz = top - (top - bot) * 0.42 + sec = [(th, top), (th, gz), (0.00025, bot), (-0.00025, bot), (-th, gz), (-th, top)] + for x, z in sec: + V.append((x, y, z)) + m = 6 + for i in range(len(st) - 1): + for k in range(m): + a = i * m + k; b = i * m + (k + 1) % m + F.append([a, b, b + m, a + m]) + F.append(list(range(m))[::-1]) + blade = G.mesh_obj('blade', V, F) + G.fix_normals(blade) + G.smooth_by_angle(blade, 25) + W.add(blade, 'blade') + W.add(G.box('guard', (0, 0.003, -0.004), (0.010, 0.006, 0.044), bev=0.0018), 'park') + tab = G.box('tab', (0, -0.001, 0.0185), (0.009, 0.004, 0.010), bev=0.0012) + G.rot(tab, -35, 'X', (0, 0.002, 0.014)); W.add(tab, 'park') + prof = [(0.0100, 0.006)] + k = 0 + y = 0.006 + while y < 0.116: + r = 0.0118 + 0.0012 * math.sin(math.pi * (y - 0.006) / 0.11) + prof += [(r - 0.0006, y + 0.0007), (r, y + 0.0020), (r, y + 0.0072), (r - 0.0006, y + 0.0086)] + y += 0.0093 + prof += [(0.0105, 0.1180)] + W.add(G.lathe('handle', prof, n=10, axis='Y', center=(0, 0, -0.004), sx=0.82, sz=1.0, cap0=True, cap1=True), 'leatherstack') + W.add(G.lathe('pommel', [(0.0, 0.1175), (0.0110, 0.1175), (0.0125, 0.1220), (0.0115, 0.1310), (0.0060, 0.1350), (0.0, 0.1355)], + n=12, axis='Y', center=(0, 0, -0.004), sx=0.85), 'park') + W.empties['muzzle'] = ((0, -0.170, -0.004), (0, -1, 0)) + W.zones = dict(handR=((0, 0.06, -0.004), (0.02, 0.06, 0.02)), handL=((0, 0, 0), (0.001, 0.001, 0.001)), + cheek=((0, 0, 0), (0.001, 0.001, 0.001)), butt=((0, 0, 0), (0.001, 0.001, 0.001)), slide=(0, 1, 0)) + W.uvscale = {} + return W + +def binoculars(hi=True): + """Porro-prism field glasses (6x30 class): objective tubes, covered prism housings, central hinge, focusing eyepieces.""" + W = Weapon('binoculars', hi) + for s in (-1, 1): + W.add(G.lathe('obj', [(0.0150, -0.068), (0.0185, -0.068), (0.0192, -0.064), (0.0185, -0.060), (0.0180, -0.030)], + n=16, axis='Y', center=(s * 0.040, 0, -0.004), cap0=False, cap1=True), 'paint_black') + W.add(G.cyl('objLens', 0.0152, -0.0652, -0.0658, c=(s * 0.040, 0, -0.004), n=16), 'glass') + W.add(G.loft_y('prism', [dict(y=-0.034, zt=0.018, zb=-0.020, w=0.036, e=3.0, x=s * 0.038), dict(y=-0.030, zt=0.024, zb=-0.022, w=0.040, e=3.2, x=s * 0.038), + dict(y=0.024, zt=0.024, zb=-0.016, w=0.038, e=3.2, x=s * 0.035), dict(y=0.030, zt=0.020, zb=-0.010, w=0.032, e=3.0, x=s * 0.034)], n=16), 'leatherette') + W.add(G.lathe('eye', [(0.0110, 0.028), (0.0110, 0.040), (0.0135, 0.041), (0.0135, 0.056), (0.0125, 0.060), (0.0090, 0.061)], + n=14, axis='Y', center=(s * 0.031, 0, 0.012), cap1=False), 'paint_black') + W.add(G.cyl('eyeLens', 0.0090, 0.0598, 0.0592, c=(s * 0.031, 0, 0.012), n=12), 'glass') + W.add(G.box('bridge', (s * 0.012, -0.004, 0.012), (0.016, 0.014, 0.008), bev=0.002), 'paint_black') + W.add(G.cyl('hinge', 0.0085, -0.022, 0.034, c=(0, 0, 0.012), n=12), 'paint_black') + W.add(G.cyl('hingeCap', 0.0060, 0.034, 0.040, c=(0, 0, 0.012), n=10), 'steel') + W.empties['muzzle'] = ((0, -0.068, 0.0), (0, -1, 0)) + W.empties['scopeEye'] = ((0, 0.075, 0.012), (0, -1, 0)) + W.zones = dict(handR=((-0.04, 0.0, 0.0), (0.03, 0.04, 0.04)), handL=((0.04, 0.0, 0.0), (0.03, 0.04, 0.04)), + cheek=((0, 0, 0), (0.001, 0.001, 0.001)), butt=((0, 0, 0), (0.001, 0.001, 0.001)), slide=(0, 1, 0)) + W.uvscale = {} + return W + +def grenade(hi=True): + """Segmented fragmentation hand grenade (pineapple pattern) with striker fuze, lever, pin and ring. Z up.""" + W = Weapon('grenade', hi) + prof = [] + rows = 15 + for j in range(rows + 1): + a = math.pi * j / rows + z = 0.0030 - 0.0440 * math.cos(a) + r = 0.0290 * math.sin(a) ** 0.85 + prof.append((max(r, 0.0), z)) + prof[0] = (0.0, prof[0][1]); prof[-1] = (0.0105, prof[-1][1] - 0.001) + body = G.lathe('body', prof, n=32, axis='Z', center=(0, 0, 0), cap1=True) + me = body.data + for v in me.vertices: + x, y, z = v.co + rr = math.hypot(x, y) + if rr < 1e-5 or z > 0.040 or z < -0.039: + continue + th = math.atan2(y, x) + col = abs(math.cos(4 * th)) # 1 at the 8 column grooves + rowp = abs(math.cos((z + 0.040) / 0.0835 * 5 * math.pi)) # 5 rows + g = max(col ** 30, rowp ** 30) + f = 1.0 - 0.10 * g + v.co.x *= f; v.co.y *= f + W.add(body, 'paint_od') + W.add(G.lathe('neck', [(0.0105, 0.044), (0.0095, 0.050), (0.0090, 0.052)], n=14, axis='Z', cap1=True), 'paint_od') + W.add(G.lathe('fuze', [(0.0, 0.052), (0.0082, 0.052), (0.0085, 0.056), (0.0078, 0.066), (0.0060, 0.0695), (0.0, 0.070)], n=14, axis='Z'), 'park') + spoon = G.sweep('lever', G.bezier([(-0.004, 0, 0.071), (-0.012, 0, 0.070), (-0.028, 0, 0.040), (-0.031, 0, 0.012)], 8), + dict(w=0.0018, h=0.012, e=6), n=8, up=Vector((0, 1, 0))) + W.add(spoon, 'park', 'lever'); W.pivots['lever'] = (-0.006, 0, 0.068) + W.add(G.cyl('pin', 0.0012, -0.012, 0.016, axis='X', c=(0, 0, 0.061), n=6), 'steel', 'pin') + W.add(G.torus('ring', 0.0105, 0.0013, c=(0.0175, 0, 0.051), axis='X', n=16, m=6), 'steel', 'pin') + W.pivots['pin'] = (0.016, 0, 0.061) + W.empties['muzzle'] = ((0, 0, 0.070), (0, 0, 1)) + W.zones = dict(handR=((0, 0, 0), (0.03, 0.03, 0.05)), handL=((0, 0, 0), (0.001, 0.001, 0.001)), + cheek=((0, 0, 0), (0.001, 0.001, 0.001)), butt=((0, 0, 0), (0.001, 0.001, 0.001)), slide=(0, 0, 1)) + W.uvscale = {} + return W + +def stick_grenade(hi=True): + """Stick hand grenade of the 1924 pattern: steel head can, wooden handle, screw cap at the end. Z up, grip at origin.""" + W = Weapon('stickGrenade', hi) + W.add(G.lathe('handle', [(0.0118, -0.070), (0.0125, 0.000), (0.0130, 0.150), (0.0140, 0.205)], n=12, axis='Z', cap0=True, cap1=True), 'wood') + W.add(G.lathe('cap', [(0.0, -0.0830), (0.0110, -0.0830), (0.0140, -0.0805), (0.0140, -0.0700), (0.0128, -0.0680), (0.0120, -0.0680)], n=14, axis='Z', closed=True), 'paint_grey') + W.add(G.lathe('collar', [(0.0142, 0.200), (0.0160, 0.202), (0.0160, 0.214), (0.0120, 0.216)], n=14, axis='Z', closed=True), 'paint_grey') + W.add(G.lathe('head', [(0.0120, 0.214), (0.0330, 0.216), (0.0350, 0.220), (0.0350, 0.282), (0.0335, 0.287), (0.0090, 0.289), (0.0, 0.289)], + n=24, axis='Z', cap0=True), 'paint_grey') + W.add(G.box('clip', (0.0365, 0, 0.250), (0.004, 0.012, 0.050), bev=0.0012), 'paint_grey') + W.empties['muzzle'] = ((0, 0, 0.289), (0, 0, 1)) + W.zones = dict(handR=((0, 0, 0.0), (0.03, 0.03, 0.06)), handL=((0, 0, 0), (0.001, 0.001, 0.001)), + cheek=((0, 0, 0), (0.001, 0.001, 0.001)), butt=((0, 0, 0), (0.001, 0.001, 0.001)), slide=(0, 0, 1)) + W.uvscale = {} + return W + +BUILDERS = {'rifleScoped': rifle_scoped, 'smg': smg, 'pistol': pistol, 'enemyRifle': enemy_rifle, 'enemySmg': enemy_smg, + 'mg': mg, 'knife': knife, 'binoculars': binoculars, 'grenade': grenade, 'stickGrenade': stick_grenade} diff --git a/e63334287a3deaa3/ironveil/tools/weapons/pack.mjs b/e63334287a3deaa3/ironveil/tools/weapons/pack.mjs new file mode 100644 index 00000000..3ce7d626 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/weapons/pack.mjs @@ -0,0 +1,39 @@ +// Pack the exported weapons GLB for the web: occlusion from the ORM map, WebP textures, meshopt geometry. +// usage: GT_MODULES=/path/to/node_modules node pack.mjs rifle.glb smg.glb atlas.glb out.glb (inputs merged into one scene) +// needs: npm i @gltf-transform/core@4 @gltf-transform/extensions@4 @gltf-transform/functions@4 meshoptimizer sharp +import path from 'path'; +const M = process.env.GT_MODULES || path.resolve('node_modules'); +const imp = (p) => import(path.join(M, p)); +const { NodeIO } = await imp('@gltf-transform/core/dist/index.js'); +const { ALL_EXTENSIONS } = await imp('@gltf-transform/extensions/dist/index.js'); +const { dedup, meshopt, textureCompress, mergeDocuments, unpartition } = await imp('@gltf-transform/functions/dist/index.js'); +const { MeshoptEncoder } = await imp('meshoptimizer/index.js'); +const sharp = (await imp('sharp/dist/index.mjs')).default; + +const args = process.argv.slice(2), dst = args.pop(); +await MeshoptEncoder.ready; +const io = new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({ 'meshopt.encoder': MeshoptEncoder }); +const doc = await io.read(args[0]); +for (const more of args.slice(1)) mergeDocuments(doc, await io.read(more)); +const scenes = doc.getRoot().listScenes(), main = scenes[0]; +for (const sc of scenes.slice(1)) { for (const n of sc.listChildren()) main.addChild(n); sc.dispose(); } +doc.getRoot().setDefaultScene(main); +for (const m of doc.getRoot().listMaterials()) { + const orm = m.getMetallicRoughnessTexture(); + if (m.getName().startsWith('wpn_') && orm) { + m.setOcclusionTexture(orm); + m.getOcclusionTextureInfo().setTexCoord(0); + m.setOcclusionStrength(1.0); + } + if (/glass/.test(m.getName())) { m.setAlphaMode('BLEND'); m.setDoubleSided(false); } +} +await doc.transform( + unpartition(), + dedup(), + textureCompress({ encoder: sharp, targetFormat: 'webp', quality: 90, slots: /^(baseColorTexture)$/ }), + textureCompress({ encoder: sharp, targetFormat: 'webp', quality: 92, slots: /^(normalTexture)$/ }), + textureCompress({ encoder: sharp, targetFormat: 'webp', quality: 90, slots: /^(metallicRoughnessTexture|occlusionTexture)$/ }), + meshopt({ encoder: MeshoptEncoder, level: 'high' }) +); +await io.write(dst, doc); +for (const t of doc.getRoot().listTextures()) console.log('texture', t.getName() || t.getURI(), t.getMimeType(), t.getSize(), (t.getImage().byteLength / 1024).toFixed(0) + ' KB'); diff --git a/e63334287a3deaa3/ironveil/tools/weapons/preview.py b/e63334287a3deaa3/ironveil/tools/weapons/preview.py new file mode 100644 index 00000000..da359a42 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/weapons/preview.py @@ -0,0 +1,38 @@ +# Quick geometry check: build weapons with flat colours and export a GLB (no baking). +# usage: python preview.py out.glb kind[,kind...] [lo] +import bpy, sys, os +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import geo as G, models as MD, assemble as AS + +out, kinds = sys.argv[1], sys.argv[2].split(',') +hi = not (len(sys.argv) > 3 and sys.argv[3] == 'lo') +bpy.ops.wm.read_factory_settings(use_empty=True) +COL = {'wood': (0.16, 0.07, 0.03), 'blued': (0.25, 0.26, 0.28), 'steel': (0.5, 0.5, 0.5), 'park': (0.08, 0.08, 0.075), + 'leather': (0.12, 0.06, 0.03), 'brass': (0.7, 0.5, 0.2), 'glass': (0.05, 0.07, 0.08), 'bakelite': (0.05, 0.03, 0.02), + 'canvas': (0.25, 0.22, 0.14), 'paint_od': (0.1, 0.11, 0.06), 'paint_grey': (0.12, 0.12, 0.11), 'paint_black': (0.03, 0.03, 0.03)} +MET = {'blued': 1, 'steel': 1, 'brass': 1} +mats = {} +def mat(t): + if t not in mats: + m = bpy.data.materials.new(t); m.use_nodes = True + b = m.node_tree.nodes['Principled BSDF'] + b.inputs['Base Color'].default_value = COL.get(t, (0.5, 0.5, 0.5)) + (1,) + b.inputs['Metallic'].default_value = MET.get(t, 0); b.inputs['Roughness'].default_value = 0.45 + mats[t] = m + return mats[t] +roots = [] +for k in kinds: + W = MD.BUILDERS[k](hi) + meshes = {} + tot = 0 + for part, lst in W.parts.items(): + obs = [] + for ob, t in lst: + G.set_mat(ob, mat(t)); obs.append(ob) + j = G.join(obs, part) if len(obs) > 1 else obs[0] + G.smooth_by_angle(j, 35) + meshes[part] = j; tot += G.tris(j) + print(W.kind, part, G.tris(j)) + print('TOTAL', W.kind, tot) + roots.append(AS.assemble(W, meshes)) +AS.export(out, roots) diff --git a/e63334287a3deaa3/ironveil/tools/weapons/run.sh b/e63334287a3deaa3/ironveil/tools/weapons/run.sh new file mode 100755 index 00000000..44276a18 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/weapons/run.sh @@ -0,0 +1,17 @@ +#!/bin/bash +# Resumable driver: one Blender process at a time, waits for 5 GB free memory before each. +# usage: run.sh OUT SIZE [sets...] (BPY = python with bpy; default: python3) +set -u +HERE=$(cd "$(dirname "$0")" && pwd); OUT=$1; SIZE=$2; shift 2 +SETS=${*:-rifle smg atlas}; B=${BPY:-python3} +mkdir -p "$OUT" +waitmem() { while [ "$(free -g | awk '/Mem:/{print $7}')" -lt 5 ]; do echo "waiting for memory"; sleep 30; done; } +for S in $SETS; do + if [ ! -f "$OUT/$S.blend" ]; then waitmem; $B "$HERE/build.py" prep "$S" "$OUT" "$SIZE" || exit 1; fi + for K in $(python3 -c "import json;print(' '.join(json.load(open('$OUT/$S.json'))))"); do + n=$(ls "$OUT"/tex/${S}__${K}_{mask,color,metal,rough,normal}.png 2>/dev/null | wc -l) + if [ "$n" -lt 5 ]; then waitmem; $B "$HERE/build.py" bake "$S" "$OUT" "$SIZE" "$K" || exit 1; fi + done + if [ ! -f "$OUT/$S.glb" ]; then waitmem; $B "$HERE/build.py" finish "$S" "$OUT" "$SIZE" || exit 1; fi +done +echo ALLDONE diff --git a/e63334287a3deaa3/ironveil/tools/weapons/scanned.py b/e63334287a3deaa3/ironveil/tools/weapons/scanned.py new file mode 100644 index 00000000..49a3f939 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/weapons/scanned.py @@ -0,0 +1,280 @@ +# The hero's rifle and pistol from Poly Haven scans (CC0, see CREDITS-weapons.md), turned into the node layout the +# game reads (same names and frames as assemble.py), with our sling, the box magazine cut out as a moving part, the +# bolt split into a sliding body and a turning handle, reduced triangle counts and a small third-person LOD. +# usage: python scanned.py +# Blender weapon frame as in models.py: barrel -Y, up +Z, right side -X, origin at the right-hand grip, metres. +import bpy, bmesh, sys, os, math +from mathutils import Vector, Matrix +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import geo as G +import assemble as A + +SRC, TEX, OUT = sys.argv[-3], sys.argv[-2], sys.argv[-1] +os.makedirs(OUT, exist_ok=True) + +def log(*a): print('[scanned]', *a, flush=True) + +class W: # what assemble.assemble() reads + def __init__(self, kind): + self.kind = kind; self.pivots = {}; self.empties = {} + self.gripL = (0, -0.3, 0); self.gripRoff = (0, 0, 0); self.gripLoff = (0, 0, 0) + +def reset(): + bpy.ops.wm.read_factory_settings(use_empty=True) + +def import_set(name): + bpy.ops.import_scene.gltf(filepath=os.path.join(SRC, name, name + '.gltf')) + obs = {o.name: o for o in bpy.data.objects if o.type == 'MESH'} + for o in obs.values(): # bake every transform into the mesh, drop the hierarchy + M = o.matrix_world.copy(); o.parent = None; o.matrix_world = Matrix(); o.data.transform(M) + for o in [o for o in bpy.data.objects if o.type != 'MESH']: + bpy.data.objects.remove(o) + return obs + +def img(path, data): + for suf, px in (('_1k.png', 1024), ('_512.png', 512)): # smaller maps: downscale the cleaned 2k maps + if not os.path.exists(path) and path.endswith(suf): + from PIL import Image + Image.open(path[:-len(suf)] + '_2k.png').resize((px, px), Image.LANCZOS).save(path) + im = bpy.data.images.load(path, check_existing=True) + if data: im.colorspace_settings.name = 'Non-Color' + return im + +def material(name, prefix, size, glass=False, arm=None): + """Principled material from the cleaned maps (ARM: R occlusion, G roughness, B metal).""" + m = bpy.data.materials.new(name) + nt = m.node_tree; N = nt.nodes; Lk = nt.links + bs = N['Principled BSDF'] + if glass: + bs.inputs['Base Color'].default_value = (0.02, 0.025, 0.03, 1) + bs.inputs['Roughness'].default_value = 0.05; bs.inputs['Metallic'].default_value = 0.0 + bs.inputs['Alpha'].default_value = 0.35 + return m + d = N.new('ShaderNodeTexImage'); d.image = img(os.path.join(TEX, '%s_diff_%s.png' % (prefix, size)), False) + a = N.new('ShaderNodeTexImage'); a.image = img(os.path.join(TEX, '%s_arm_%s.png' % (prefix, arm or size)), True) + n = N.new('ShaderNodeTexImage'); n.image = img(os.path.join(TEX, '%s_nor_gl_%s.png' % (prefix, size)), True) + sp = N.new('ShaderNodeSeparateColor'); nm = N.new('ShaderNodeNormalMap') + Lk.new(d.outputs['Color'], bs.inputs['Base Color']) + Lk.new(a.outputs['Color'], sp.inputs['Color']) + Lk.new(sp.outputs['Green'], bs.inputs['Roughness']); Lk.new(sp.outputs['Blue'], bs.inputs['Metallic']) + Lk.new(n.outputs['Color'], nm.inputs['Color']); Lk.new(nm.outputs['Normal'], bs.inputs['Normal']) + # the exporter writes an ORM texture when occlusion is wired through a glTF Material Output group + grp = bpy.data.node_groups.get('glTF Material Output') + if grp is None: + grp = bpy.data.node_groups.new('glTF Material Output', 'ShaderNodeTree') + grp.interface.new_socket('Occlusion', in_out='INPUT', socket_type='NodeSocketFloat') + g = N.new('ShaderNodeGroup'); g.node_tree = grp + Lk.new(sp.outputs['Red'], g.inputs['Occlusion']) + return m + +def set_mats(o, mats): + """Replace the imported materials by ours, matched by the imported material name.""" + for i, slot in enumerate(o.material_slots): + nm = slot.material.name if slot.material else '' + for key, m in mats: + if key in nm: + o.material_slots[i].material = m; break + +def to_frame(obs, origin): + """Imported frame (X = muzzle, Z up, -Y = right side) -> weapon frame (barrel -Y, right side -X), origin moved.""" + R = Matrix.Rotation(-math.pi / 2, 4, 'Z') + M = R @ Matrix.Translation(-Vector(origin)) + for o in obs: o.data.transform(M) + return M + +def decimate(o, ratio): + if ratio >= 1: return + m = o.modifiers.new('dec', 'DECIMATE'); m.ratio = ratio; m.use_collapse_triangulate = True + G.apply_mods(o) + +def split_loose_in_box(o, lo, hi, name): + """Move the loose parts of o whose bounds lie inside the box [lo, hi] into a new object.""" + bm = bmesh.new(); bm.from_mesh(o.data) + bm.verts.ensure_lookup_table() + seen = set(); take = [] + for v in bm.verts: + if v.index in seen: continue + stack = [v]; comp = [] + seen.add(v.index) + while stack: + x = stack.pop(); comp.append(x) + for e in x.link_edges: + y = e.other_vert(x) + if y.index not in seen: seen.add(y.index); stack.append(y) + ok = all(lo[i] <= x.co[i] <= hi[i] for x in comp for i in range(3)) + if ok: take += comp + ids = {v.index for v in take} + bm.free() + new = o.copy(); new.data = o.data.copy(); new.name = name; G.link(new) + for ob, keep in ((o, False), (new, True)): + bm = bmesh.new(); bm.from_mesh(ob.data) + bmesh.ops.delete(bm, geom=[v for v in bm.verts if (v.index in ids) != keep], context='VERTS') + bm.to_mesh(ob.data); bm.free() + return new + +def ring_center(o, axis, pick): + """Centre of the vertices selected by pick(co) in the two other axes.""" + P = [v.co for v in o.data.vertices if pick(v.co)] + c = sum(P, Vector()) / max(1, len(P)) + return c, len(P) + +def sling(name, p0, p1, sag, width=0.032, thick=0.004, uv_rect=(0.02, 0.36, 0.78, 0.44), side=1.0): + """A canvas sling between two attachment points, hanging on the weapon's left side in a shallow curve, + with rolled edges (thickness) and two leather keeper loops. UVs map onto a canvas strip of the accessory set.""" + p0, p1 = Vector(p0), Vector(p1) + n = 36; ring = [] + verts, faces, uvs = [], [], [] + L = (p1 - p0).length + for i in range(n + 1): + t = i / n + p = p0.lerp(p1, t) + Vector((0, 0, -sag * 4 * t * (1 - t))) + # tangent and a normal that keeps the strap flat against the weapon side + tn = (p1 - p0).normalized() + nside = Vector((side, 0, 0)) + up = nside.cross(tn).normalized() + row = [] + for j, (u, o) in enumerate(((-0.5, 0.35), (-0.5, -0.35), (0.5, -0.35), (0.5, 0.35))): + q = p + up * (u * width) + nside * (o * thick) + row.append(len(verts)); verts.append(q) + ring.append(row) + for i in range(n): + a, b = ring[i], ring[i + 1] + for j in range(4): + faces.append((a[j], a[(j + 1) % 4], b[(j + 1) % 4], b[j])) + o = G.mesh_obj(name, verts, faces, smooth=False) + me = o.data; uvl = me.uv_layers.new(name='UVMap') + u0, v0, u1, v1 = uv_rect + for poly in me.polygons: + for li in poly.loop_indices: + vi = me.loops[li].vertex_index + i, j = vi // 4, vi % 4 + uvl.data[li].uv = (u0 + (u1 - u0) * i / n, v0 + (v1 - v0) * (0 if j in (0, 1) else 1)) + return o + +def lod_copy(objs, name, ratio, mats_small): + cs = [] + for o in objs: + c = o.copy(); c.data = o.data.copy(); G.link(c) + c.matrix_world = o.matrix_world.copy() + cs.append(c) + for c in cs: + M = c.matrix_world.copy(); c.parent = None; c.matrix_world = Matrix(); c.data.transform(M) + j = G.join(cs, name) + decimate(j, ratio) + for i, s in enumerate(j.material_slots): + for key, m in mats_small: + if s.material and key in s.material.name: j.material_slots[i].material = m; break + return j + +def tris(objs): + return sum(G.tris(o) for o in objs) + +# ===================================================================================================== +def build_rifle(): + reset() + obs = import_set('bolt_action_rifle_7_62') + name = 'bolt_action_rifle_7_62' + main = obs[name]; scope = obs[name + '_scope'] + bpy.data.objects.remove(obs[name + '_wrap']) # the cloth wrap on the stock read as a stuck-on decal + bolt_a = obs[name + '_bolt_a']; bolt_b = obs[name + '_bolt_b']; trig = obs[name + '_trigger'] + bpy.data.objects.remove(obs[name + '_bullet_54mm']) # display cartridge lying under the gun + # bore axis from the muzzle ring, trigger blade top, scope tube rear + mx = max(v.co.x for v in main.data.vertices) + bore, nb = ring_center(main, 'x', lambda c: c.x > mx - 0.004) + bore_z = bore.z + tz = max(v.co.z for v in trig.data.vertices); tx = sum(v.co.x for v in trig.data.vertices) / len(trig.data.vertices) + sx = min(v.co.x for v in scope.data.vertices) + sc, ns = ring_center(scope, 'x', lambda c: c.x < sx + 0.004) + log('rifle bore z %.4f (n %d), trigger x %.4f top %.4f, scope rear x %.4f centre %s (n %d)' % (bore_z, nb, tx, tz, sx, tuple(round(x, 4) for x in sc), ns)) + # the box magazine is part of the main mesh: cut its loose parts out + mag = split_loose_in_box(main, Vector((tx + 0.06, -0.03, -0.12)), Vector((tx + 0.15, 0.03, bore_z - 0.035)), 'mag') + log('magazine tris', G.tris(mag), 'bounds x', min(v.co.x for v in mag.data.vertices), max(v.co.x for v in mag.data.vertices)) + origin = (tx, 0.0, bore_z - 0.020) + allo = [main, scope, bolt_a, bolt_b, trig, mag] + to_frame(allo, origin) + BORE = 0.020 + # reduce: the scope and bolt carry far more triangles than they show at arm's length + decimate(scope, 0.55); decimate(bolt_a, 0.65); decimate(bolt_b, 0.65); decimate(mag, 0.7) + mats = [('glass', material('wpn_rifle_glass', None, None, glass=True)), + ('accesories', material('wpn_rifle_acc', name + '_accesories', '1k')), + (name, material('wpn_rifle_main', name, '2k', arm='1k'))] + for o in allo: set_mats(o, mats) + # muzzle end in the weapon frame + muz_y = -(mx - origin[0]) + # front and rear sling points: barrel band and the rear stock slot, on the left side (+X) + sl = sling('sling', (0.022, muz_y + 0.47, BORE - 0.030), (0.024, 0.36, -0.050), sag=0.035) + sl.data.materials.append(mats[1][1]) + # weapon description for assemble.py + w = W('rifleScoped') + body = G.join([main, scope], 'body') + w.pivots = {'bolt': (0, 0, BORE), 'boltHandle': (0, 0, BORE), 'trigger': (0, 0.0, tz - origin[2]), + 'mag': (0, -0.10, -0.045), 'sling': (0, 0, 0)} + eye_y = -(sx - origin[0]) + 0.078 + w.empties = {'muzzle': ((0, muz_y, BORE), (0, -1, 0)), + 'ejection': ((-0.006, -0.06, BORE + 0.016), (-0.6, 0.15, 0.78)), + 'scopeEye': ((0, eye_y, sc.z - origin[2]), (0, -1, 0)), + # the sight line for the ADS offset runs through the scope: rear and front lens centres + 'sightRear': ((0, eye_y - 0.078, sc.z - origin[2]), (0, -1, 0)), + 'sightFront': ((0, eye_y - 0.078 - 0.108, sc.z - origin[2]), (0, -1, 0))} + w.gripL = (0, -0.265, -0.012) + meshes = {'body': body, 'bolt': bolt_b, 'boltHandle': bolt_a, 'trigger': trig, 'mag': mag, 'sling': sl} + root = A.assemble(w, meshes) + # the turning handle rides on the sliding bolt: re-parent its empty under the bolt empty + bh = bpy.data.objects['rifleScoped_boltHandle']; bo = bpy.data.objects['rifleScoped_bolt'] + M = bh.matrix_world.copy(); bh.parent = bo; bh.matrix_parent_inverse = Matrix(); bh.matrix_world = M + hi = [o for o in bpy.data.objects if o.type == 'MESH' and o.name.startswith('rifleScoped')] + log('rifleScoped tris', tris(hi), {o.name: G.tris(o) for o in hi}) + # third-person LOD: one mesh, 512 maps + small = [('wpn_rifle_glass', mats[0][1]), ('wpn_rifle_acc', material('wpn_rifle_acc_lod', name + '_accesories', '512')), + ('wpn_rifle_main', material('wpn_rifle_main_lod', name, '512'))] + lw = W('rifleScopedLod') + lb = lod_copy([o for o in hi if 'sling' not in o.name and 'trigger' not in o.name], 'lodbody', 0.16, small) + lw.pivots = {}; lw.empties = dict(w.empties); lw.gripL = w.gripL + lroot = A.assemble(lw, {'body': lb}) + log('rifleScopedLod tris', G.tris(lb)) + A.export(os.path.join(OUT, 'rifle_scan.glb'), [root, lroot]) + meta = {'muzzle_y': muz_y, 'eye_y': eye_y, 'eye_z': sc.z - origin[2], 'tris': tris(hi), 'lod': G.tris(lb)} + log('META', meta) + +def build_pistol(): + reset() + obs = import_set('service_pistol') + n = 'service_pistol' + keep = {n + '_pistol_a': 'body', n + '_slide_a': 'bolt', n + '_hammer_a': 'hammer', n + '_trigger_a': 'trigger', + n + '_magazine_loaded': 'mag'} + for k, o in list(obs.items()): + if k not in keep: bpy.data.objects.remove(o) + P = {keep[k]: obs[k] for k in keep} + # variant a (wooden grips; b has a taped grip) is at the origin, the magazine 0.1 m back beside the gun + for k, o in P.items(): + o.data.transform(Matrix.Translation((0.1 if k == 'mag' else 0, 0, 0))) + body, slide = P['body'], P['bolt'] + mx = max(v.co.x for v in body.data.vertices) + bore, nb = ring_center(body, 'x', lambda c: c.x > mx - 0.003) + tr = P['trigger'] + tx = sum(v.co.x for v in tr.data.vertices) / len(tr.data.vertices); tz = max(v.co.z for v in tr.data.vertices) + log('pistol bore z %.4f (n %d) muzzle x %.4f trigger x %.4f top %.4f' % (bore.z, nb, mx, tx, tz)) + mzmin = min(v.co.z for v in P['mag'].data.vertices); bzmin = min(v.co.z for v in body.data.vertices) + log('pistol mag bottom %.4f grip bottom %.4f' % (mzmin, bzmin)) + origin = (tx - 0.019, 0, bore.z - 0.0185) + to_frame(list(P.values()), origin) + decimate(P['mag'], 0.22) + mats = [('', material('wpn_pistol', n, '2k', arm='1k'))] + for o in P.values(): set_mats(o, mats) + w = W('pistol') + hx = min(v.co.y for v in P['hammer'].data.vertices) + w.pivots = {'bolt': (0, 0, 0.0185), 'hammer': (0, 0.037, 0.002), 'trigger': (0, 0.0, tz - origin[2]), + 'mag': (0, 0.040, -0.060)} + muz_y = -(mx - origin[0]) + w.empties = {'muzzle': ((0, muz_y, 0.0185), (0, -1, 0)), + 'ejection': ((-0.006, -0.02, 0.028), (-0.6, 0.15, 0.78)), + 'sightRear': ((0, 0.040, 0.0335), (0, -1, 0)), 'sightFront': ((0, -0.130, 0.0335), (0, -1, 0))} + root = A.assemble(w, P) + hi = [o for o in bpy.data.objects if o.type == 'MESH'] + log('pistol tris', tris(hi), {o.name: G.tris(o) for o in hi}) + A.export(os.path.join(OUT, 'pistol_scan.glb'), [root]) + +if __name__ == '__main__': + which = os.environ.get('ONLY', 'rifle,pistol').split(',') + if 'rifle' in which: build_rifle() + if 'pistol' in which: build_pistol() diff --git a/e63334287a3deaa3/ironveil/tools/weapons/stats.py b/e63334287a3deaa3/ironveil/tools/weapons/stats.py new file mode 100644 index 00000000..4b615887 --- /dev/null +++ b/e63334287a3deaa3/ironveil/tools/weapons/stats.py @@ -0,0 +1,28 @@ +# Per-weapon triangles, draw calls (primitives) and the texture sets of a packed weapons GLB. +import json, struct, sys, os +path = sys.argv[1] +b = open(path, 'rb').read() +l = struct.unpack(' import(path.join(M, p)); +const { NodeIO } = await imp('@gltf-transform/core/dist/index.js'); +const { ALL_EXTENSIONS } = await imp('@gltf-transform/extensions/dist/index.js'); +const { dedup, meshopt, textureCompress, mergeDocuments, unpartition, prune } = await imp('@gltf-transform/functions/dist/index.js'); +const { MeshoptEncoder, MeshoptDecoder } = await imp('meshoptimizer/index.js'); +const sharp = (await imp('sharp/dist/index.mjs')).default; + +const args = process.argv.slice(2); +// --add '{"smg_sightRear":["smg",[x,y,z]], ...}' adds empty nodes (glTF frame) under existing roots +let ADD = {}; +const ai = args.indexOf('--add'); if (ai >= 0) { ADD = JSON.parse(args[ai + 1]); args.splice(ai, 2); } +const [src, dst, ...news] = args; +await MeshoptEncoder.ready; await MeshoptDecoder.ready; +const io = new NodeIO().registerExtensions(ALL_EXTENSIONS) + .registerDependencies({ 'meshopt.encoder': MeshoptEncoder, 'meshopt.decoder': MeshoptDecoder }); +const doc = await io.read(src); +const main = doc.getRoot().getDefaultScene() || doc.getRoot().listScenes()[0]; +const oldTex = new Set(doc.getRoot().listTextures()); +const newRoots = []; +for (const f of news) { + const d = await io.read(f); + for (const sc of d.getRoot().listScenes()) for (const n of sc.listChildren()) newRoots.push(n.getName()); + mergeDocuments(doc, d); +} +for (const n of main.listChildren()) if (newRoots.includes(n.getName())) { const all = []; n.traverse((c) => all.push(c)); for (const c of all) { const me = c.getMesh(); c.dispose(); if (me) me.dispose(); } } +for (const sc of doc.getRoot().listScenes()) if (sc !== main) { for (const n of sc.listChildren()) main.addChild(n); sc.dispose(); } +doc.getRoot().setDefaultScene(main); +for (const [name, [rootName, t]] of Object.entries(ADD)) { + const r = main.listChildren().find((n) => n.getName() === rootName); + if (!r) { console.warn('no root', rootName); continue; } + const old = r.listChildren().find((n) => n.getName() === name); if (old) old.dispose(); + r.addChild(doc.createNode(name).setTranslation(t)); +} +for (const m of doc.getRoot().listMaterials()) { + const orm = m.getMetallicRoughnessTexture(); + if (m.getName().startsWith('wpn_') && orm && !m.getOcclusionTexture()) { + m.setOcclusionTexture(orm); m.getOcclusionTextureInfo().setTexCoord(0); m.setOcclusionStrength(1.0); + } + if (/glass/.test(m.getName())) { m.setAlphaMode('BLEND'); m.setDoubleSided(false); } +} +const fresh = (t) => !oldTex.has(t); +const newTex = doc.getRoot().listTextures().filter(fresh).map((t) => t.getName() || t.getURI()); +await doc.transform(prune({ keepLeaves: true }), unpartition(), dedup()); +const pat = new RegExp('^(' + newTex.map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|') + ')$'); +if (newTex.length) await doc.transform( + textureCompress({ encoder: sharp, targetFormat: 'webp', quality: +(process.env.QB || 90), pattern: pat, slots: /^(baseColorTexture)$/ }), + textureCompress({ encoder: sharp, targetFormat: 'webp', quality: +(process.env.QN || 92), pattern: pat, slots: /^(normalTexture)$/ }), + textureCompress({ encoder: sharp, targetFormat: 'webp', quality: +(process.env.QO || 90), pattern: pat, slots: /^(metallicRoughnessTexture|occlusionTexture)$/ })); +await doc.transform(meshopt({ encoder: MeshoptEncoder, level: 'high' })); +await io.write(dst, doc); +for (const t of doc.getRoot().listTextures()) console.log('texture', t.getName() || t.getURI(), t.getMimeType(), t.getSize(), (t.getImage().byteLength / 1024).toFixed(0) + ' KB'); +console.log('roots', main.listChildren().map((n) => n.getName()).join(' '));